/*ordenar*/
function go(pagina,value){
window.location.href=pagina+value; //pagina incluye todos los gets y &variable=
}

function borra(ref,reload){
		dataString="ref="+ref+"&reload="+reload;
		$.ajax({
		type: "GET",
		url: "/borra.php",
		data: dataString,
		cache: false,
		error: function(html){
		$("#errores").html('<img src="/Imagenes/warning.gif" alt="ajax-loader" width="50" height="50" /><p><small>Error. Vuelva a intentar. </small></p>');
		},
		success: function(html){
		$("#ajaxcontent").html(html);
		}
		});
}

function cambiapais(pais,retri){
window.location.href= "checkout.php?pais="+pais+"&retri="+retri;

}

/* Destruye Sesión */
function destruyesesion(){
	
 	
		$.ajax({
		type: "GET",
		url: "/logout.php",
		data: 'nothing=nothing',
		cache: false,
		error: function(html){
		$("#errores").fadeIn(400).append('<img src="/Imagenes/warning.png" alt="ajax-loader" width="50" height="50" style="vertical-align: middle" /><small>Error. Vuelva a intentar. </small>');
		},
		success: function(html){
		$("#errores").fadeIn(400).append(html);
		}
		});
}


$(document).ready(function(){
imagePreview();


/* Grey OUT */	
$(".registra_submit").click(function(){
		
	$('#screen').css({	"display": "block", opacity: 0.7, "width":$(document).width(),"height":$(document).height()});
	$('#box').css({"display": "block"});
	$.scrollTo('#container',800);
	return false;
});
/* Cambiar Imagen portada */
  $('.change').bind('mouseover',function(){  
       var imgPreview = $(this).attr('rel');
       var link=  $(this).attr('href');
      $('#imagenes img').attr('src',imgPreview);
      $('#imagenes a').attr('href',link)  
   });  

/* Inicia Sesión */
	$(".iniciasesion").click(function(){
		var email=$('#email').val();
		var passwd=$('#passwd').val();
		
		if (email=='' || passwd=='' || email.length<4 || passwd.length<4 ){
		    alert("Por favor rellene bien los campos de email y contraseña. Gracias.");
			return false;
		}
		
		$("#respuestalogin").css({"display": "block"});
		$.ajax({
		type: "GET",
		url: "/login.php",
		data: 'email='+email+'&passwd='+passwd,
		cache: false,
		error: function(html){
		$("#respuestalogin").html('<img src="/Imagenes/warning-white.gif" style="vertical-align:middle" alt="ajax-loader" width="30" height="29" />Error. Vuelva a intentar.');
		},
		success: function(html){ 		

		$("#respuestalogin").html(html);
		}
		});
		
	});

/* Recuerda Contraseña */
	$(".recuerda").click(function(){
		var email=$('#email').val();
		
		if (email=='' ||  email.length<4  ){
		    alert("Por favor introduzca su email correctamente. Gracias.");
			return false;
		}
		
		$("#respuestalogin").css({"display": "block"});
		$.ajax({
		type: "GET",
		url: "/recordatorio.php",
		data: 'email='+email,
		cache: false,
		error: function(html){
		$("#respuestalogin").html('<img src="/Imagenes/warning-white.gif" style="vertical-align:middle" alt="ajax-loader" width="30" height="29" />Error. Vuelva a intentar.');
		},
		success: function(html){ 		

		$("#respuestalogin").html(html);
		}
		
		});
	return false;	
	});

/* Ajax y formularios */
	$(".add_submit").click(function(){
		var element = $(this);
		var Id = element.attr("id");
		Id =Id.substring(1); // eliminamos la letra añadida para cumplir el standar.
		
		var numcolors= $("#numcolores"+Id).val(); //Cuantos colores
		var pack = $("#pack"+Id).val();
		var portes = $("#portes"+Id).val()
		
		dataString='';
		
		
		talla=$("#talla"+Id).val();
		actualiza=$("#actualiza"+Id).val();
		for (i=0;i<numcolors;i++)
		{
			var color= $("#color"+i+Id).attr("name");
			var uds= $("#color"+i+Id).val();
			
				// Comprobacion Packs (Lotes de X unidades)
			if (pack > 1)
			{
				faltan = pack - (uds % pack);
				multiplo = pack * Math.ceil(uds/pack);
				if (faltan != 0 && uds >0)
				{
					alert("Se ha auto-añadido " + faltan +" unidades para completar el pack de "+pack);
					uds = faltan + parseInt(uds);
				}
			}
		
			
			if (uds>0 || actualiza==1)
			dataString +=color+'='+uds+'&'; //'rojo=2&'
		}
		
			
		if (dataString=='') //no se han añadido productos. notificar al usuario
		  alert('Por favor, seleccione cuantas unidades quiere de la Referencia: '+Id);
		else
		{	
			dataString ="actualiza="+actualiza+"&talla="+talla+"&ref="+Id+"&"+dataString; //No cambiar orden! PHP get desde 3
			//Cargando...
			$("#ajax"+Id).fadeIn(400).html('<img src="/Imagenes/ajax-loader.gif" alt="ajax-loader" width="32" height="32" /><p> Cargando...</p>');
		
		//alert(dataString);
		$.ajax({
		type: "GET",
		url: "/actualiza_carrito.php",
		data: dataString,
		cache: false,
		error: function(html){
		$("#ajax"+Id).html('<img src="/Imagenes/warning.gif" alt="ajax-loader" width="50" height="50" /><p><small>Error. Vuelva a intentar. </small></p>');
		},
		success: function(html){
		$("#ajaxcontent").html(html);
		}
		});
		}
	return false;})

/* Menu drop */
	//$("ul.subnav").parent().append("<span class=trigger2></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)

	$("#navlist li.trigger span").click(function() { //When trigger is clicked...
		//Following events are applied to the subnav itself (moving subnav up and down)
		$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click
		$(this).parent().hover(function() {
		}, function(){
			$(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
		});

		//Following events are applied to the trigger (Hover events for the trigger)
		}).hover(function() {
			$(this).addClass("subhover"); //On hover over, add class "subhover"
		}, function(){	//On Hover Out
			$(this).removeClass("subhover"); //On hover out, remove class "subhover"
	});


});

/*
 * Image preview script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 * modificado para que muestre la imagen segun indica name y no href.
 */
 
this.imagePreview = function(){	
	/* CONFIG */
		
		xOffset = 10;
		yOffset = 30;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.preview").hover(function(e){
		$("body").append("<p id='preview'><img src='/Imagenes/Productos/Zoom/"+ this.name +"' alt='Image preview' /><br />Haga Click para ver aún más grande</p>");								 
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		$("#preview").remove();
    });	
	$("a.preview").mousemove(function(e){
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};


/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
