jQuery(document).ready(function(){
	// Para que los links se abran en una ventana nueva
	jQuery(document).ready(function(){jQuery(".external_link").attr("target", "_blank");});
	jQuery("#buscador-boton").click(function(){jQuery("#buscador-form").submit();return false;});
	jQuery("#buscador-form").submit(function(){
		var buscado = trim(jQuery("#buscador-text").val());
		if(buscado.length < 2)
		{
			errorBox ("Debes introducir mínimo 2 Carácteres para iniciar la búsqueda.");
			return false;
		}
		return true;
	});

	jQuery("a[id^='link-anadir-cesta-']").click(function(){
		jQuery.get(jQuery(this).attr('href'), function(data){
			refreshMiniCesta();
		});
		return false;
	});

	jQuery("a.price-filter").click(price_filter);
});
function price_filter(e)
{
	e.preventDefault();
	var id = jQuery(this).data('id');
	var url = document.location.href;
	if(url.indexOf("?") !=-1)
		url = new String().concat(url, "&price_filter=", id);
	else
		url = new String().concat(url, "?price_filter=", id);
	document.location.href = url;
}

function refreshMiniCesta ()
{
  if(refreshPageCarrito)
  {
	storeViewState(jQuery("#compra_form"));
	jQuery("*").css('cursor', 'wait');
  	window.document.location = window.document.location;
  }
  else
  {
  	jQuery("#mini-cesta").slideUp();
		jQuery("#mini-cesta").load("htm/mini-cesta/" + argv_1 + "/" + argv_2 + ".htm", function(){
			jQuery("#mini-cesta").slideDown();
		});
  }
}

function storeViewState(form)
{
	setCookie(jQuery(form).attr('id') + "viewstate", jQuery(form).serialize());	
}

function deleteViewState(form)
{
	setCookie(form + "viewstate", null, 0);
}

function getViewState(formId)
{
	var state = new Object();
	var cookie = getCookie(formId + "viewstate")
	if(cookie != null)
	{		
		var x = cookie.split('&');
		for(var i = 0; i < x.length; i++)
		{
			var y = x[i].split('=');
			state[y[0]] = decodeURIComponent(y[1]);
			state[y[0]] = state[y[0]].replace(/\+/g, ' ');
		}
	}
	return state;
}

function html_entity_decode(str) {
	var ta = document.createElement("textarea");
	ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	toReturn = ta.value;
	ta = null;
	return toReturn
}

function checkEmail(email) {
	var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	return filter.test(email);
}

function errorBox (message,fclose){
	var dialog = jQuery("<div><p><span class='ui-icon ui-icon-circle-close left' style='margin:0 7px 50px 0;'></span><p style='margin-left:22px'>" + message + "</p></p></div>").dialog({
		modal: true,
		buttons: {Ok: function() {jQuery(this).dialog('close');}},
		width:500
	});
	if(fclose != undefined)
		jQuery(dialog).bind( "dialogclose", function(event, ui) {
			fclose();
	});
	return false;
}

function successBox (message, fclose){
	var dialog = jQuery("<div><p><span class='ui-icon ui-icon-circle-check left' style='margin:0 7px 50px 0;'></span><p style='margin-left:22px'>" + message + "</p></p></div>").dialog({
		modal: true,
		buttons: {Ok: function() {jQuery(this).dialog('close');}},
		width:500
	});

	if(fclose != undefined)
		jQuery(dialog).bind( "dialogclose", function(event, ui) {
			fclose();
		});
	return true;
}

function trim (str){ return str.replace(/^\s*|\s*$/g,""); }

function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name,"",-1);
}

function loginfb(userID, signature)
{
	if(jQuery("#uid").length && jQuery("#uid").val() != '')
		return;
	FB.api('/me', function(response) {
		var url = "xml/login-fb.xml?fbid=" + userID + "&signature=" + signature + "&fbemail=" + response.email;
		jQuery.get(url, function(xml){
			if (jQuery(xml).find("error").text() != 0) {
				window.location.href = 'compra-registro/1/general.htm';
			}
			else
				window.location.reload();
		});
	});
}

window.fbAsyncInit = function() {
	FB.init({
	  appId      : '265376000178847', // App ID
	  channelUrl : '//www.tutiendadevideojuegos.com/portal/channel.php', // Channel File
	  status     : true, // check login status
	  cookie     : true, // enable cookies to allow the server to access the session
	  oauth      : true, // enable OAuth 2.0
	  xfbml      : false  // parse XFBML
	});

	// Additional initialization code here
	FB.Event.subscribe('auth.login',
    function(response) {
		if (response.status == "connected") {
			loginfb(response.authResponse.userID, response.authResponse.signedRequest);
		  }
    });
	FB.getLoginStatus(function(response) {
	  if (response.status == "connected") {
		loginfb(response.authResponse.userID, response.authResponse.signedRequest);
	  }
	});
};

(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/es_ES/all.js#xfbml=1&appId=265376000178847";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
