/** LIBRERIA ENCARGADA DE LA INTERFACE DEL SITIO  **/

function lanikaiInterface() {
	
	this.start = function () {
		// init carrousel	
		$('#carouselChicos').jcarousel({
			scroll:6,
			animation:"slow"
		});
		$('#carouselChicas').jcarousel({
			scroll:6,
			animation:"slow"
		});
		
		$('#carouselRelacionados').jcarousel({
			scroll:6,
			animation:"slow"
		});
		
		$('#carouselMarcas').jcarousel({
			scroll:12,
			animation:"slow"
		});

		// init menu
		$("#nav ul ").css({display: "none"});
		$("#nav li").hover(function(){
			$(this).find('ul:first:hidden').css({visibility: "visible",display: "none"}).show();},
		function() {
			$(this).find('ul:first').hide();
		});

		//init Slide News
		$(function(){
			$("ul#ticker01").liScroll();
		}); 
		
		$('.jqzoom').jqzoom({
            zoomType: 'standard',
            lens:true,
            preloadImages: false,
            alwaysOn:false
        });
		
		$("a.jqzoom").fancybox();
		
	};

	
	/** CAMBIA LA ORIENTACION DEL SLIDESHOW **/
	this.starDetectPositionScreen = function(doTime) {
		function screenPosition() {
			if($("body").width() < $("body").height()) {
				$(".idBlockImgSLideshowMovilHorizontal").css("display","none");
				$(".idBlockImgSLideshowMovilVertical").css("display","block");
			} else {
				$(".idBlockImgSLideshowMovilVertical").css("display", "none");
				$(".idBlockImgSLideshowMovilHorizontal").css("display", "block");
			}
			setTimeout(function() { 
				screenPosition();
			},doTime);
		}
		screenPosition();
	};
	
	/*****************************************************************/
	/* Bloque de funciones de evento "click", se ejecutan segun el   */
	/* atributo rel del enlace relacionado.                          */
	/* Por ej:                                                       */
	/* <a onclick="lanikaiInterface.genericClickFunctions($(this));" */
	/* href="javascript://" rel="anadiralcarro" >link</a>            */
	/*****************************************************************/
	
	this.genericClickFunctions = function(e) {
		if(e.attr("rel")) {
			switch(e.attr("rel")) {
				//Clicks generales
				case "loginuser":
					e.parent().parent("form").submit();
				break;
				
				case "cerrarpopup":
					$("#idBlockDetallePedido").fadeOut("slow");
					//$("#idBlockPopUpWindow").remove();
				break;
				
				//Clicks dashboard
				case "verpedido":
					var idpedido=e.parent().prevAll("td:last").html();
					this.returnInfoByAjax(_JS_CALLACTION+"ecommerce/getDetailPedido/", "GET","idpedido="+idpedido, "#idBlockDetallePedido", "cargaDetalleDePedido");
					$("#idBlockDetallePedido").fadeIn("slow");
				break;
				
				case "verfactura":
					var idfactura=e.parent().prevAll("td:last").html();
					$.ajax({
						type: "POST",
						data: "idfactura="+idfactura,
						url: _JS_CALLACTION+"ecommerce/getDetailFactura/",
						success: function(msg){
							var position = $(".maxContent").position();
							$("#idBlockDetalleFactura").css("left",position.left+3)
							$("#idBlockDetalleFactura").fadeIn("slow",function(){
								$("#idBlockDetalleFactura").html(msg);
							});
						}
					});
				break;

				case "cerrarFactura":
					$("#idBlockDetalleFactura").fadeOut("fast");
				break;
				
				//Clicks referentes al carro de compras
				case "anadiralcarro":
					//$("#idBlockFrmCarrito").submit();
					if ($("#idSelectColor").val() != 'Color' && $("#idSelectTallas").val() != '' && $("#idSelectCantidad").val() != ''){
						if(e.parent().parent().parent().parent().get(0).tagName=="FORM") {
							e.parent().parent().parent().parent().submit();
						} else if (e.parent().parent().parent().get(0).tagName=="FORM") {
							e.parent().parent().parent().submit();
						}
					} else {
						alert ("Seleccione color, talla y cantidad para su producto.");
						$(".colorText").css("background","#FFE2E2");
					}

				break;
				case "imprimircesta":
					$('.contentCart').printElement();
				break;
				case "realizarpedido":
					if(e.prev("form").length) {
						if($("#idBlockShippingAmount").val()!="") {
							e.prev("form").submit();							
						} else {
							alert("Debe seleccionar un metodo de envio.");
						}
					} else {
						alert("No hay productos cargados en la cesta, no puede realizar el pedido.");
					}
				break;
				case "borraritem":
					if(e.parent().parent().parent().get(0).tagName=="FORM") {
						e.parent().parent().parent("form").submit();
					} else {
						e.parent().parent().parent().parent("form").submit();	
					}
				break;
			}
		}
	};
	
	this.returnInfoByAjax = function(sUrl, sMethod, sParams, blockOfContent, sFunction, aParameters) {
		$.ajax({
			url: sUrl,
			type: sMethod,
			data: sParams,
			success: function(returnData) {
				return doActionByParameters(sFunction, blockOfContent, returnData, aParameters);
			}
		});
		
		function doActionByParameters(sFunction, blockOfContent, returnData, aParameters) {
			switch(sFunction) {
				case "cargaDetalleDePedido":
					$(blockOfContent).html(returnData);
				break;
				case "cargaGrillaDeProductos":
					limitGrill = parseInt($("#idBlockContProds").html());
					$(blockOfContent).append(returnData);
					limitGrill = limitGrill + 21;
					$("#idBlockContProds").html(limitGrill);
				break;
				case "cargaColumnaDeProductos":
					$(blockOfContent).append(returnData);
				break;
				default:
					alert("No existe una funcion relacionada");
				break;
			}
		}
		
	};
	
	/*****************************************************************/
	/* Bloque que valida passwords.                                  */
	/*****************************************************************/
	this.validatePasswords = function(formElement) {
		$(formElement).submit(function(){
			if($('#pass1').val()) {
				if($('#pass1').val()==$('#pass2').val())
					{
						return true;
					} else {
						alert("Las claves son distintas.");
						return false;
					}
			} else {
				alert("La clave esta vacia.");
				return false;
			}
		});
	};
	
	this.showOrHideUserDataForms = function(divElement, bMyAccount) {
		if(divElement.val()=="diferente") {
			if(bMyAccount) {
				divElement.attr("value", "igual");
				$(".divClassAviso").hide();
			}
			$("#idBlockInfoEnvio").attr("value", "diferente");
			if(!bMyAccount) {
				$("#idBlockLoginForm1").hide();
			}
			$("#idBlockLoginForm2").show();
		} else {
			if(bMyAccount) {
				divElement.attr("value", "diferente");
				$(".divClassAviso").show();
			}
			$("#idBlockInfoEnvio").attr("value", "igual");
			if(!bMyAccount) {
				$("#idBlockLoginForm1").show();
			}
			$("#idBlockLoginForm2").hide();
		}
	};
	
	this.changeImageProductDetail = function(ruta) {
		$(".productDetailsImageBig").attr("src",ruta);
		$("#idBlockImageZoom").attr("href",ruta);
	};
	
	/*****************************************************************/
	/* Bloque del carro que arma el selector de destinos, y hace     */
	/* diferentes cosas.                                             */
	/*****************************************************************/
	this.cartDestinationDropDown = function(divElement) {
		$(divElement).mouseover(function(){
			$("#idBlockDestination").show();
			$(this).children().children().mouseover(function(){
				addRemoveSelectorClass($(this));
			});
		}).mouseleave(function(){
			$("#idBlockDestination").hide();
		});
	
		$(".destinationBlock").click(function(){
			addRemoveSelectorClass($(this));
			var destinationName=$(this).children(".nombreDestino").html();
			destinationName=(destinationName.length>8 ? destinationName.substring(0,8)+"..." : destinationName);
			
			var shipping=parseFloat($(this).attr("id"));
			shipping=shipping.toFixed(2);
			$(this).parent().parent().next("h1").html(shipping+"&nbsp;&euro;&nbsp;-&nbsp;("+destinationName+")");
			var totalTotal=parseFloat($(this).attr("id"))+parseFloat($("#idBlockTotal").attr("class"));
			totalTotal=totalTotal.toFixed(2); 
			$("#idBlockTotal").html(totalTotal+"&nbsp;&euro;");
			$("#idBlockShippingAmount").attr("value",shipping);
			$("#idBlockTotalAmount").attr("value",totalTotal);
			$("#idBlockDestination").hide();
		});
	
		function addRemoveSelectorClass(element) {
			$(".destinationBlock").each(function(){
				$(this).children(".nombreDestino").removeClass("nombreDestinoSelected");
				$(this).children(".precioDestino").removeClass("precioDestinoSelected");
			});
			element.children(".nombreDestino").addClass("nombreDestinoSelected");
			element.children(".precioDestino").addClass("precioDestinoSelected");
		}
	};
	
	
	/*****************************************************************/
	/* Bloque de funciones de evento "click" en la busqueda de       */
	/* portada                                                       */
	/*****************************************************************/
	
	this.searchSimpleByParam = function (elem) {
		window.location = $("option:selected",elem).val();
	};

	this.searchFastFunction = function(event,element) {
		if (event){
			if(event.keyCode == 13) {
				if (element.val()){
					actionForm = $("#idBlockBuscar").attr("action")+element.val()+"/";
					$("#idBlockBuscar").attr("action",actionForm);
					$("#idBlockBuscar").submit();	
				}else{
					alert (_JS_ALERTFASTSEARCHERROR);
					return false;
				}
			}
		}else{
			if (element.val()){
				actionForm = $("#idBlockBuscar").attr("action")+element.val()+"/";
				$("#idBlockBuscar").attr("action",actionForm);
				$("#idBlockBuscar").submit();	
			}else{
				alert (_JS_ALERTFASTSEARCHERROR);
			}
		}
	};
	
	this.moreResultsGrillSection = function () {
		limitGrill = parseInt($("#idBlockContProds").html());
		limitGrillAux = parseInt($("#idBlockContProds").html());
		productos = parseInt($(".itemProduct").length);
		$.ajax({
			type: "GET",
			data: "limitGrill="+limitGrill,
			url: _JS_CONTROLLERMOREPRODUCTS,
			success: function(msg){
				$(".grillContent").append(msg);

				limitGrill = limitGrill + 21;
				$("#idBlockContProds").html(limitGrill);
				
				productosAux = parseInt($(".itemProduct").length);
				valueProducts=limitGrillAux-productosAux;
				valueProducts=(valueProducts<0 ? (valueProducts*-1): valueProducts);
				productsQuantity=Math.ceil((valueProducts)/7);
				/*
				if (valueProducts <= 18 && productsQuantity>0) {
					finLimitCol = $(".itemProduct").length;
					iniLimitCol = $(".contItemColumnInside").length;
					$.ajax({
						type: "POST",
						data: "finLimitCol="+finLimitCol+"&iniLimitCol="+iniLimitCol,
						url: _JS_CONTROLLERLEFTCOL+"/"+productsQuantity,
						success: function(msg) {
							$(".contentColumn").append(msg);
						}
					});
				}
				*/
			}
		});
		
		
	};	

	/*****************************************************************/
	/* Bloque de funciones de manejo de colores en detalle de	     */
	/* productos                                                       */
	/*****************************************************************/
	
	this.showBlockColors = function (element) {
		element.next().slideDown();
	};
	
	this.hideBlockColors = function (elem) {
		var nameColor = elem.attr("name");
		elem.parent().prev("input[type=text]").attr("value",nameColor);
		var idColor = elem.attr("id").replace("imagen_","");
		elem.parent().prev().prev("input[type=hidden]").attr("value",idColor);
		if (elem.parent().prev().prev("input[type=hidden]").val() != 'Color'){
			$(".colorText").css("background","#FFF");
		}
		elem.parent().slideUp();
	};

	/*****************************************************************/
	/* Bloque de funciones para el manejo favoritos			         */
	/*****************************************************************/
	
	// agregar a la lista de favoritos
	this.addToFavorites = function (idProduct) {
		var favoritos = "-";
		if($.cookie("favoriteList")) {
			favoritos = $.cookie("favoriteList");
		}
		favoritos = favoritos+idProduct+"-";
		$.cookie("favoriteList",null);
		$.cookie("favoriteList",favoritos, { path: '/' });
		alert(_JS_ALERTADDFAVORITE);
	};
	
	// quitar de lista de favoritos
	this.removeFavorites = function (idProduct) {
		var newFavoritos = "-";
		if($.cookie("favoriteList")) {
			var favoritos = $.cookie("favoriteList");
			favoritos = favoritos.split("-");
			for (var i=0;i<favoritos.length;i++)
				{
				 	if(favoritos[i] != idProduct && favoritos[i] != "")
				 		{
				 			newFavoritos = newFavoritos + favoritos[i] + "-";
				 		}
				}
			$.cookie("favoriteList",null);
			$.cookie("favoriteList",newFavoritos, { path: '/' });
			window.location.reload();
		}
	};
	
	/*****************************************************************/
	/* Bloque de cambio de lenguaje	                    	         */
	/*****************************************************************/
	
	this.changeLanguage = function (elem) {
		window.location.href = _JS_HOSTDOMINIO + elem.val() + "/";
	};
	
	this.accionBotonFooter = function (category,e) {
		if (e.attr("rel") == "on") {
			$.ajax({
				type: "POST",
				data: "busqueda="+category,
				url: _JS_CONTROLLERBUTTONFOOTERMOVIL,
				success: function(msg){
					/*
					$(".contentResults .inactive").fadeOut();
					$(".active").addClass("inactive");
					$(".inactive").removeClass("active");
					$(".inactive").attr("rel","on");
					
					e.addClass("active");
					*/
					//e.fadeIn();
					//e.parent().css("display","none");
					if (e.parent().is(".itemResults")){
						e.parent().parent().html(msg);
						e.parent().parent().fadeIn("fast");
					} else {
						e.next().html(msg);
						e.next().fadeIn("fast");
					}
					e.attr("rel","off");
				}
			});
		} else {
			e.next().fadeOut("fast");
			e.attr("rel","on");
		}
	};
	
	this.changeStockSizes = function (e) {
		var idproducto = $("#idBlockIdProducto").val();
		var id = e.val();
		$.ajax({
			type: "POST",
			data: "id="+id+"&idproducto="+idproducto,
			url: _JS_CONTROLLERCHANGESTOCKSIZES,
			success: function(msg){
				$("#idBlockStockSizes").fadeOut("fast",function(){
					$("#idBlockStockSizes").html(msg);					
				}).fadeIn("fast");
			}
		});
	};
	
	this.changeProductColor = function (e) {
		var args = e.val().split('-');
		var idcolor = args[0];
		var idproducto = args[1];
		window.location = _JS_PRODUCTDETAILS+"product/"+idproducto+"/"+idcolor;
	};
	
	this.changeImageProductMovil = function (e) {
		$(".productDetailsImageBig").attr("src",e.attr("rel"));
	};
	
}

