var WROOT;
var WLANG;
var LLANG;
var siteLoaded = false;
var MAPA;

/****  STORE LOCATOR *****/
var geocoder;
var iconimage;
var STORELIST = Array();
var STOREMARKERS = Array();
var tmpLatLng;
var infoWindow;
var pb = progressBar();
/*********************/

function initSite(wr,lang){
	LLANG = lang;
	WROOT = wr;
	WLANG = wr+LLANG+"/";
	if($.browser.msie && parseFloat($.browser.version) < 8){
		$("#ie6").slideDown(600);
	}else{$("#ie6").remove();}
	//IE6-7 Png Transparents
	//$('body').supersleight({shim: WROOT+'css/blank.gif'});
	$(".language li a").fadeTo(0,.45);
	$(".language li a."+LLANG).fadeTo(0,1);
	$(".language li a").each(function(){
		$(this).hover(function(){
			$(this).fadeTo(0,1);
		},function(){
			if(!$(this).hasClass(LLANG)){$(this).fadeTo(0,.45);}
		});
	})
	HeaderShopCartHover();
	$(document).scroll(function(){
		$("#site_prefooter .toparrow").show();
	});
	linksFadeEffect();
	$(window).load(function(){doSiteLoaded();});
	setTimeout("doSiteLoaded()",4000);
	hoverFade();
	//IE last-child corrections
	if($.browser.msie && parseFloat($.browser.version) < 9){$("#site_header ol.menuPrincipal li:last").css("padding-right","0px").css("margin-right","0px");}
	if($("a.fancybox").length > 0){
		$("a.fancybox").fancybox({
			'transitionIn'	:	'elastic',
			'transitionOut'	:	'elastic',
			'speedIn'		:	400, 
			'speedOut'		:	400
		});
	}
	
}

function doSiteLoaded(){
	if(!siteLoaded){
		siteLoaded = true;
		if($.browser.msie){$('#site_content').stop(true,true).show();}
		else{$('#site_content').stop(true,true).fadeTo(150,1);}	
	}
}

function linksFadeEffect(){
	$("a[href]:not(a.nolink)").not("a[href^='http']").not(".fancybox").click(function(){
		$.scrollTo('#siteOut',200);
		if(!$.browser.msie && !$.browser.safari){$("#site_content").stop(true,true).fadeTo(150,0,"swing");}
	});
}

function SHCAddArticle(cod_articulo){
	loadingShopCart();
	var qty = $("#productQuantity").val();	
	var size = $("#productSize").val();
	
	if(size == "compact"){
		cod_articulo += "C";	
	}
	
	var url = WLANG+"shopcart/addArticle/"+cod_articulo+"/qty/"+qty+"/";
	$.ajax({
			type: "POST",
			url: url,
			success: function(response){
				loadShopCart(true)
			},
			error:function(response){
				alert("Connection to BD refused");
			}
	});
	return true;
}

function changeQuantityProduct(cod_articulo,num){
	$(".shopcartDiv .mainZone").fadeTo(100,.25);
	
	var url = WLANG+"shopcart/changeArticle/"+cod_articulo+"/qty/"+num+"/";
	$.ajax({
			type: "POST",
			url: url,
			success: function(response){
				window.location.reload();
			},
			error:function(response){
				window.location.reload();
			}
	});	
}


function SHCRemoveArticle(url,reloadpage){
	loadingShopCart();	
	$.ajax({
			type: "POST",
			url: url,
			success: function(response){
				loadShopCart(true);
				if(reloadpage){window.location.reload();}
			},
			error:function(response){
				alert("Connection to BD refused");
			}
	});
	return true;
}

function loadingShopCart(){
	$("#HcheckoutDiv > a,#HcheckoutDiv > span,#HcheckoutDiv > div,#HcheckoutDiv > img").fadeTo(100,.5);
}

function loadShopCart(fromIn){
	$("#HcheckoutDiv").load(WLANG+"ajax/headercheckout/",function(){
		if(!fromIn){
			$("#HcheckoutDiv > a,#HcheckoutDiv > span,#HcheckoutDiv > div,#HcheckoutDiv > img").fadeIn(130);
		}else{
			$("#HcheckoutDiv > a,#HcheckoutDiv > span,#HcheckoutDiv > div,#HcheckoutDiv > img").show();
		}
		HeaderShopCartHover();
	});	
}

function HeaderShopCartHover(){
	$("#HcheckoutDiv .items").hover(
		function(){
			$(this).find(".itemsList").stop(true,true).fadeIn(100);
		},function(){
			$(this).find(".itemsList").stop(true,true).fadeOut(150);
	});
}

function hoverFade(x){
	$(x).hover(function(){
		$(this).stop(true,true).fadeTo(80,.85);
	},function(){
		$(this).stop(true,true).fadeTo(150,1);
	})
}

function productFacebookLike(url,width,lo,sf){
	var w = width ? parseInt(width) : 450;
	var layout = lo ? lo : "button_count";
	var showfaces = sf ? sf : "true";
	$("#productFacebookLike").append('<fb:like href="'+url+'" layout="'+layout+'" show_faces="'+showfaces+'" width="'+w+'" font=""></fb:like>');	
}

function homeInit(){
	$(".promos > ul > li").addClass("thirdsize");
	$(".promo").each(function(){hoverFade(this);});
	$("ul.promo li").addClass("thirdsize");
	$(".promos > a").each(function(){hoverFade(this);});	
	
	$(".promos ul.promo").each(function(i){
		$(this).find("li:first").addClass("active");
		if($(this).find("li").length > 1){slidePromo(i);}		
	});
	
	$(".hnews.promo").find("li:first").addClass("active");
	//if($(".hnews.promo li").length > 1){slideHomeNews();}		
}

function slidePromo(x){
	var tl = $(".promos ul.promo");
	var mt;
	tl.hover(function(){tl.addClass("hhover");},function(){tl.removeClass("hhover");})
	var list = $(tl)[x];
	var time2change = parseInt($(list).attr("rel"));
	if(time2change == 0){
		var aleatorio = Math.floor(Math.random()*($("li",list).length+1));
		//$("li",list).hide();
		$("li:eq("+aleatorio+")",list).addClass("active").show();
		$("li:eq("+aleatorio+")",list).find('span').css("width",parseInt($("li:eq("+aleatorio+")",list).width()-9)+"px").css("margin-top",parseInt($("li:eq("+aleatorio+")",list).height()-23)+"px");
	}else{
		var interv;
		interv = setInterval(function(){
			if(!tl.hasClass("hhover")){						  
				$(list).find('li:eq(1)').show();
				mt = parseInt($(list).find('li:eq(1)').height()-23)
				if(mt < 154){
					$(list).find('li:eq(1) span').css("width",parseInt($(list).find('li:eq(1)').width()-6)+"px").css("margin-top","154px");
				}else{
					$(list).find('li:eq(1) span').css("width",parseInt($(list).find('li:eq(1)').width()-6)+"px").css("margin-top",mt+"px");
				}
				
				$(list).find('li:first').fadeOut(function(){
					$(list).find('li:eq(1)').addClass("active");
					$(this).removeClass("active").appendTo(list);
				});
			}
		},time2change*1000);
	}
}

function slideHomeNews(){
	var list;
	var tl = list = $(".hnews.promo");
	tl.hover(function(){tl.addClass("hhover");},function(){tl.removeClass("hhover");})
	var time2change = parseInt($(list).attr("rel"));
	if(time2change == 0){
		var aleatorio = Math.floor(Math.random()*($("li",list).length+1));
		//$("li",list).hide();
		$("li:eq("+aleatorio+")",list).addClass("active").show();
	}else{
		var interv;
		interv = setInterval(function(){
			if(!tl.hasClass("hhover")){						  
				$(list).find('li:eq(1)').show();
				$(list).find('li:first').fadeOut(function(){
					$(list).find('li:eq(1)').addClass("active");
					$(this).removeClass("active").appendTo(list);
				});
			}
		},time2change*1000);
	}
}

/***** MAPS *********/

function loadGoogleMap(latlng,initZoom){
	var varcenter = latlng ? latlng : new google.maps.LatLng(41.3952,2.1694);
	var varzoom =  initZoom ? initZoom : 4;
	
	var myOptions = {
      zoom: varzoom,
      center: varcenter,
      mapTypeId: google.maps.MapTypeId.TERRAIN
    };
	
	MAPA = new google.maps.Map(document.getElementById("gmap"), myOptions);
	MAPA.controls[google.maps.ControlPosition.RIGHT].push(pb.getDiv());
	geocoder = new google.maps.Geocoder();
	infoWindow = new google.maps.InfoWindow();
	google.maps.event.addListener(MAPA, 'click', closeInfoWindow);	
}


closeInfoWindow = function() {
	infoWindow.close();
};

openInfoWindow = function(marker,html) {
	var markerLatLng = marker.getPosition();
	var setHtml = html ? html : ['<b>Marker position is:</b><br/>',markerLatLng.lat(),', ',markerLatLng.lng()].join('');
	infoWindow.setContent(setHtml);
	infoWindow.open(MAPA, marker);
}


function loadMarkers() {
    for (var i = 0; i < STORELIST.length; i++) {
      setTimeout(function() {
        addMarker();
      }, (4*i)+(2000 * Math.random()));
    }
  }

  function addMarker() {
	  var ii = iterator;
	  var iii = STORELIST[ii][0]
    STOREMARKERS.push(new Array(iii,new google.maps.Marker({
      position: STORELIST[ii][1],
      map: MAPA,
      draggable: false,
	  icon: iconimage
    })));
	
	google.maps.event.addListener(STOREMARKERS[ii][1], 'click', function(){
		openInfoWindow(STOREMARKERS[ii][1],$("#STORE"+iii).html());
	});
    iterator++;
	if(iterator == STORELIST.length){pb.hide();}
	pb.updateBar(1);
  }

function loadHQ(latlng){
	var HQmarker = new google.maps.Marker({
		//maxWidth: 200,
		position: latlng, 
		map: MAPA, 
		title:"Bubel Headquarters",
		icon: iconimage
	});
	
	google.maps.event.addListener(HQmarker, 'click', function() {
		openInfoWindow(HQmarker,$("#HQinfo").html());
	});
	setTimeout(function(){openInfoWindow(HQmarker,$('#HQinfo').html())},1000);
}

function searchStates(){
	$(".locator .storelocator form .loading").show();
	
	var ttmp = $("#searchCountry").val().split(";");
	var country =  ttmp[0];
	
	centerMaps(false,ttmp[1],ttmp[2]);	
	
	
	$("#searchState").empty();
	$("#searchState").append('<option value="0">Loading...</option>');
	$("#searchState").parent().hide();
	$("#searchCity").empty();
	$("#searchCity").append('<option value="0">Loading...</option>');
	$("#searchCity").parent().hide();
	
	if(country != "0"){
		$.ajax({
			type: "POST",
			url: WLANG+"ajax/searchStates/",
			data:"value="+country,
			dataType:"json",
			success: function(response){
				$("#searchState").empty();
				if(response.length > 0){
					if(response.length > 1 || response[0].cautonoma.length > 0){
						$("#searchState").append('<option value="0">Select a state</option>');
						$("#searchState").parent().show();
						$(response).each(function(){
							if(this.cautonoma.length < 1){
								$("#searchState").append('<option value="">-</option>');
							}else{
								$("#searchState").append('<option value="'+this.cautonoma+'">'+this.cautonoma+'</option>');
							}
							
						})
						$(".locator .storelocator form .loading").hide();
					}else{
						$("#searchState").parent().hide();
						searchCities();	
					}
				}else{
					$("#searchState").parent().hide();
					searchCities();					
				}
			},
			error:function(response){
				alert("Connection to BD refused");
				$(".locator .storelocator form .loading").hide();
			}
		});		
	}	
}

function searchCities(){
	$(".locator .storelocator form .loading").show();
	
	var ttmp = $("#searchCountry").val().split(";");
	var country =  ttmp[0];
	var state = $("#searchState").val();
	$("#searchCity").empty();
	$("#searchCity").append('<option value="0">Loading...</option>');
	$("#searchCity").parent().hide();
	
	if(country != "0"){

		$.ajax({
			type: "POST",
			url: WLANG+"ajax/searchCities/",
			data:"c="+country+"&s="+state,
			dataType:"json",
			success: function(response){
				$("#searchCity").empty();

				if(response.length && response[0].city.length > 0){
					$("#searchCity").append('<option value="0">Select a city</option>');
					$("#searchCity").parent().show();
					$(response).each(function(){
						$("#searchCity").append('<option value="'+this.city+'">'+this.city+'</option>');
					})
				}else{
					$("#searchCity").parent().hide();				
				}
				$(".locator .storelocator form .loading").hide();
			},
			error:function(response){
				alert("Connection to BD refused");
				$(".locator .storelocator form .loading").hide();
			}
		});		
	}	
}

function searchStores(){
	$(".locator .storelocator form .loading").show();
	$("#storesResult").empty();
	var s = $("#searchStore").val();
	var ttmp = $("#searchCountry").val().split(";");
	var country =  ttmp[0];
	var state = $("#searchState").val();
	var city = $("#searchCity").val();
	$.ajax({
			type: "POST",
			url: WLANG+"ajax/searchStores/",
			data:"value="+s+"&c="+country+"&s="+state+"&cy="+city,
			dataType:"json",
			success: function(response){
				listStores(response);
				$(".locator .storelocator form .loading").hide();
			},
			error:function(response){
				alert("Connection to BD refused");
				$(".locator .storelocator form .loading").hide();
			}
	});
	return true;	
}

function listStores(list){
	var HTML = "";
	$("#storesResult").empty();
	$(list).each(function(){
		HTML = '<li>';
		HTML += '<span><a class="name" href="javascript:void(0)" onclick="centerMaps('+this.id+','+this.lat+','+this.lng+')">'+this.name+'</a></span>';
		HTML += '<span>'+this.address+'</span>';
		HTML += '<span>'+this.cp+' '+this.city+' ('+this.province+')</span>';
		if(this.tel.length){
			HTML += '<span>t. '+this.tel+'</span>';}
		if(this.email.length){
			HTML += '<span>e. <a href="mailto:'+this.email+'">'+this.email+'</a></span>';}
		HTML += '</li>';
		
		$("#storesResult").append(HTML);
	})
	if(list.length < 1){
		$("#storesResult").html('<li class="vacio">No results</li>')	
	}
}

function centerMaps(id,lat,lon){
	var pos = new google.maps.LatLng(lat,lon);
	$.scrollTo('#site',50);
	if(id){
		MAPA.setZoom(14);
		MAPA.panTo(pos);
		var t=false;
		var i=0;
		do{
			if(STOREMARKERS[i][0] == id){
				t=true;	
				openInfoWindow(STOREMARKERS[i][1],$("#STORE"+STOREMARKERS[i][0]).html());
			}
			i++;
		}while(t==false && i < STOREMARKERS.length);
	}else{
		MAPA.panTo(pos);	
	}
}


function validateform(){
	var validate = true;
	if($("#fnombre").length < 1 || $("#fnombre").val() == $("#fnombre").next().html()){validate = false;alert("Error "+$("#fnombre").next().html());}
	else if($("#fapellidos").length < 1 || $("#fapellidos").val() == $("#fapellidos").next().html()){validate = false;alert("Error "+$("#fapellidos").next().html());}
	else if($("#fasunto").length < 1 || $("#fasunto").val() == $("#fasunto").next().html()){validate = false;alert("Error "+$("#fasunto").next().html());}
	else if(!checkMail($("#femail").val())){validate = false;alert("Error "+$("#femail").next().html());}
	else if($("#ftext").length < 1 || $("#ftext").val() == $("#ftext").next().html()){validate = false;alert("Error CONTENT MESSAGE");}
	
	if(validate){$(".contact form").submit();}
}

function showUpLine(code,x){
	$('.bubelsShow li.'+code).clone().prependTo('.bubelsShow');
	$('.bubelsShow li.'+code+":last").remove();
	$(".bubelsShow li:first .bubelitem").hover(function(){
		//$(".details",this).fadeIn(60);
		$(this).addClass("back2");
	},function(){
		//$(".details",this).fadeOut(100);
		$(this).removeClass("back2");
	})
	if(x){
		$(".bubelsCollectionDiv .lines li a").not(x).removeClass("activo");
		$(x).addClass("activo");
	}
	$(".banda").remove();
	$(".bandaDiv").append('<span class="banda '+LLANG+'">&nbsp;</span>');
}

function initBubelsShow(co){
	if(co.length > 0){
		for(var i=0;i<co.length;i++){
			showUpLine(co[i]);
		}
	}
	$(".bubelsShow .line").each(function(){$(".bubelitem:last",this).css("margin-right","0px");}) 
	var ml1 = parseInt((940 - $(".bubelsCollectionDiv .collections").width())/2);
	$(".bubelsCollectionDiv .collections").css("margin-left",ml1+"px")
	var ml2 = parseInt((940 - $(".bubelsCollectionDiv .lines").width())/2);
	$(".bubelsCollectionDiv .lines").css("margin-left",ml2+"px")
	$(".bubelitem").hover(function(){
		//$(".details",this).fadeIn(60);
		$(this).addClass("back2");
	},function(){
		//$(".details",this).fadeOut(100);
		$(this).removeClass("back2");
	});
	$(".banda").remove();
	$(window).load(function(){$(".bandaDiv").append('<span class="banda '+LLANG+'">&nbsp;</span>');});
}

function productChangeSizePriceShow(cod_articulo){
	var size = $("#productSize").val();
	$(".bubelProductShow .zonad .shippingtime > div").not(":last").not("."+size).addClass("hide");
	
	$(".bubelProductShow .zonad .shippingtime > div."+size).removeClass("hide");
	$.ajax({
			type: "POST",
			url: WLANG+"ajax/getPricebyCod/",
			data:"cod="+cod_articulo+"&size="+size,
			success: function(response){
				$("#itemprice").html(response);
			},
			error:function(response){
				alert("Connection to BD refused");
			}
	});
}

function initTabs(){
	$(".tab_content").hide(); //Hide all content
	$("ul.tabs li:first").addClass("active").show(); //Activate first tab
	$(".tab_content:first").show(); //Show first tab content

	//On Click Event
	/*$("ul.tabs li").click(function() {

		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content

		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).fadeIn(100); //Fade in the active ID content
		return false;
	});*/
}

function addToCart(cod){
	$(".bubelProductShow").hide();
	$(".bubelProduct2Cart").show();
	$("#cartprice").html($("#itemprice").html());
	$("#cartsize").html($("#productSize").val());
	SHCAddArticle(cod);
}

function shcIDvalidateInputs(){
	var validate=true;
	
	/*primer comprobacion. rapida*/
	$("#checkout1 input").each(function(){
		if($(this).val().length < 2){
			validate=false;
			$(this).prev().addClass("txterror");
			$(this).addClass("error");
		}else{
			$(this).prev().removeClass("txterror");
			$(this).removeClass("error");
		}
	})	
	if(validate){
		/*primer comprobacion. telefono y email*/
		if(!checkMail($("#femail").val())){
			validate=false;
			$("#femail").prev().addClass("txterror");
			$("#femail").addClass("error");
		}else{
			$("#femail").prev().removeClass("txterror");
			$("#femail").removeClass("error");
		}
		if($("#ftel").val().length < 9){
			validate=false;
			$("#ftel").prev().addClass("txterror");
			$("#ftel").addClass("error");
		}else{
			$("#ftel").prev().removeClass("txterror");
			$("#ftel").removeClass("error");
		}
		
		if(validate){
			
			$(".shopcartDiv .mainZone").fadeTo(100,.25);
			$("#checkout1").submit();	
		}
		
		return false;
	}
}

function showTech(what){
	$(".tecnical_descs div").fadeOut(120);
	$(".tecnical_descs div."+what).fadeIn(100);
}

function hideTech(){
	$(".tecnical_descs div").fadeOut(120);
}


function techPropertiesInit(movement){
	$(".techpropertiesDiv li > span").each(function(){
		$(this).hover(function(){
		techPropertiesShow($(this).parent(),movement);
	},function(){
		techPropertiesHide($(this).parent(),movement);
	})
	
	})
}

function techPropertiesShow(obj,movement){
		if(movement){
			$(obj).find("div").stop(true,false).animate({
				'margin-top': '-115px',
				height: '115px',
				width: '250px'
			  }, 400,"swing", function() {
				$(obj).find("div").css("overflow","visible");
				$(obj).find("div span").stop(true,true).fadeIn(100);
			 
			});
		}else{
			$("div span",obj).stop(true,true).fadeIn(100);
		}
}


function techPropertiesHide(obj,movement){
	
	$("div span",obj).stop(true,true).hide();
	
	if(movement){
	$("div",obj).css({width:'57px'}).stop(true,false).animate({
		marginTop: '-41px',
		height: '41px'
	  }, 600,"swing", function() {
		// Animation complete.
			$("span",obj).fadeIn(100);
	 });
	}else{
		
	}
}

function aboutInit(){
	$(".historia area").each(function(i){
		$(this).hover(function(){
			$(".historia li:eq("+i+")").show();
			slideAbout(i);
		},function(){
			$(".historia li:eq("+i+")").hide();
		});
		
		$(this).click(function(){
			slideAbout(i);
		})
	});
}

function slideAbout(ul){
	if($(".historia li:eq("+ul+")").is(':visible')){
		var list = $(".historia ul.slideshow:eq("+ul+")");
		var act = $("li.act",list);		
		if($("li.act",list).next().length > 0){
			$("li.act",list).fadeOut(100);
			$("li.act",list).next().fadeIn(100,function(){
				$("li.act",list).removeClass("act");
				$(this).addClass("act");
			});
		}else{
			$("li.act",list).fadeOut(100)
			$("li:first",list).fadeIn(100,function(){
				$("li.act",list).removeClass("act");
				$(this).addClass("act");
			});
		}
	}
}
