//Finding the language in Live or preview mode
var mlang=langShort;

function afterIntialLoad()
{
	// setting variables to load in flash container using the swfobject technique
	var flashvars = {
					lang: mlang,
					listName: "list1",
					filePath: "/media/home/media/mainpage" + window.homeQuebecFilePath + "/" // path to media assets
	};
	var params = {
					wmode: "transparent",
					scale: 'noscale',
					salign: 'TL'
	};
	swfobject.embedSWF("/media/home/home_player.swf", "flashDiv", "990", "525", "9.0.0", "", flashvars, params);              
}

function loadDelay()
{
var t;
clearTimeout(t);
t = setTimeout("afterIntialLoad()", 100);
}

$(document).ready(function() {
	
	var myPC = getCookie("pc");
	if(myPC) {
	//alert("pc cookie exists!")
	}
	
	else {
	var thisURL = location.toString();
	
	if (thisURL.indexOf('french') != -1){
			$('#pc').val("CODE POSTAL");
	}
		else {
				$('#pc').val("POSTAL CODE");
			}
	}
	
	//alert(document.cookie);
	
	
	if (( $('#pc').val()) != "POSTAL CODE" && ( $('#pc').val()) != "CODE POSTAL" && ( $('#pc').val()) != "")  { /*alert ("we have a cookie!")*/ }
	
	else {getVal();}
	
	
	
	//window.alert( $('#foo').val() );

	
	
	// Check Postal Code format
	$("#pc").change(getVal);
	$("#pc").blur(getVal);
	
	function getVal() { 
	
			//alert("the value is " + ( $('#pc').val()) );
	
			if(validatePC($('#pc').val() )) {
			//alert($(this).val());
			//$.cookie("pc", $(this).val(), {path: '/'} );
			
			// Attempting to fix weird bug by using the cookie algo from the gmcl.js
			// - appeared to be 2 different cookies with same name, but different HOST values, not sure why/how
			
			var today = new Date();
			today.setTime(today.getTime());
			
			//Get 1 day in milliseconds
			var one_day=1000*60*60*24

			
			var cookieExpiresDate = new Date (today.getTime() + (30 * one_day));
			
			//alert("attempting to set cookie " + ( $('#pc').val()) + " until " + cookieExpiresDate);
			
			var homeCook = ( $('#pc').val());
			//alert ("the home cookie= " + homeCook);
			
			setCookie("pc",homeCook, cookieExpiresDate, "/");
			
			$(this).removeClass("error");
		 	} else {
		  	//alert('fail');
			$(this).addClass("error");
		 	}
	};
	
	
	// Validate Postal Code
	function validatePC(el) {
	 if (( $('#pc').val()) != "POSTAL CODE" && ( $('#pc').val()) != "CODE POSTAL" && ( $('#pc').val()) != "") {
	//alert("attempting to validate " + el)
	
	//var pc = $(el).val();
	var pcRegExp = /(^\D{1}\d{1}\D{1}\s?\d{1}\D{1}\d{1}$)/;
	if (pcRegExp.test(el)) {
		// Save value to cookie
		//$.cookie("pc",pc, {path: '/'});
		// Attempting to fix weird bug by using the cookie algo from the gmcl.js
		// - appeared to be 2 different cookies with same name, but different HOST values, not sure why/how
		/*
		var today = new Date();
		today.setTime(today.getTime());
		var cookieExpiresDate = new Date (today.getTime() + (30 * 24 * 60));
		setCookie("pc",pc, cookieExpiresDate, "/");
		*/
		//alert ("valid!")
		return true;
		
	} else {
		if(location.href.indexOf("french")!= -1) {
			alert("Le code postal n'est pas valide. Veuillez inscrire un code postal canadien valide.");
		} else {
			alert("Postal code invalid. Please enter a valid Canadian Postal code.");
		}
		return false;
		};
	}
}
	
	
	$(".hoverItem").fadeTo(1, 0.2);
	getText = $("#pc.postal").val();
	if ((getText != "POSTAL CODE") && (getText != "CODE POSTAL")){
		 $("#pc.postal").attr('maxlength',6);
		 	 
	}
 
	// effect for top nav bottom brandItem menus
	$('ul.topNavItems').superfish({ 
		delay: 100, 
		speed:"normal"
	});
	
	$('ul#brandItems').superfish({ 
		delay: 100, 
		speed:"fast"
	}); 
	
	//IE6 fix to show dropdown after reload
	$('ul.topNavItems .topNavItemTitle').hover(function(){
		$(this.id).addClass("sfHover");
	 },
	 function(){
		$(this.id).removeClass("sfHover");
	 }
	);
		
	// set initial states for browse bars
	$("#browseVehicleOpen").hide();
	$("#browseBrandClosed").hide();
	$("#currentOffersOpen").hide();
	
	// hide all the brand panels and selected states in the browse brand bar
			
	$(".brandPanel").css("visibility","visible");
	$(".brandPanel").hide();
	$("#brandPanels").css("visibility","visible");
	$("#brandPanels").hide();
		
	// user clicks on browse vehicle
	$(".runVehicleAnimation").click(function(){
		$(".hoverItem").hide();
		$("div#currentOfferWrapper").css("position", "absolute");
		if (!$("#browseBrandOpen").is(":animated") && !$("#browseVehicleOpen").is(":animated") && !$("#currentOffersOpen").is(":animated")){
			$("#closeButton").hide();
			$(".brandPanel").fadeOut("500");
			$("#brandPanels").fadeOut("500");
			$(".brandItem").show();
			if ( $("#browseBrandOpen").is(":visible") ){
				$("#browseBrandOpen").hide("clip", { direction: "horizontal" }, 500, function(){		
					$("#browseVehicleClosed").hide();
					$("#browseBrandClosed").show();
					$("#browseVehicleOpen").show("clip", { direction: "horizontal" }, 500);
				});
			} else {
				$("#currentOffersOpen").hide("clip", { direction: "horizontal" }, 500, function(){		
					$("#browseVehicleClosed").hide();
					$("#browseBrandClosed").show();
					$("#currentOffersClosed").show();
					$("#browseVehicleOpen").show("clip", { direction: "horizontal" }, 500);
				});				
			}
		}
	});	
	
	
	
	
	// user clicks on browse brands
	$(".runBrandAnimation").click(function(){
		$(".hoverItem").hide();
		$("div#currentOfferWrapper").css("position", "absolute");
		if (!$("#browseBrandOpen").is(":animated") && !$("#browseVehicleOpen").is(":animated") && !$("#currentOffersOpen").is(":animated")){
			$(".brandPanel").fadeOut("500");
			$("#brandPanels").fadeOut("500");
			$(".brandItem").show();
			if ( $("#browseVehicleOpen").is(":visible") ){
				$("#browseVehicleOpen").hide("clip", { direction: "horizontal" }, 500, function(){		
					$("#browseBrandClosed").hide();
					$("#browseVehicleClosed").show();
					$("#browseBrandOpen").show("clip", { direction: "horizontal" }, 500);
				});		
			} else {
				$("#currentOffersOpen").hide("clip", { direction: "horizontal" }, 500, function(){		
					$("#browseBrandClosed").hide();
					$("#currentOffersClosed").show();
					$("#browseBrandOpen").show("clip", { direction: "horizontal" }, 500);
				});						
			}	
		}
	});	
	
	$("#closeButton").click(function(){
		$("#brandPanels").show();
		$(".brandPanel").fadeOut(200);
		$(".hoverItem").hide();
		$(".brandItem").show();
		$("#brandPanels > *").fadeOut(200);
		$("#closeButton").hide();
		$("#brandPanels").fadeOut(200);
	});
	
	$("#pc.postal").click(function(){
		getText = $("#pc.postal").val();
		if ((getText == "POSTAL CODE") || (getText == "CODE POSTAL")){
			$("#pc.postal").val("");
			 $("#pc.postal").attr('maxlength',6);			 
		}
	});
		
	$(".brandItem").hover(function(){
		if (!$("#browseBrandOpen").is(":animated") && !$("#browseVehicleOpen").is(":animated")){
				//getId = this.id;
				getId = $(this).parent().attr("id");
				getId= getId.replace(/Item/, "");
				showBrandPanel(getId+'Item',getId+'ItemSelected',getId+'Panel');
			}
		},
		 function(){
		  
		 }
	);
	
	$("#browseVehicleClosed").hover(function(){
		//if (!$("#browseBrandOpen").is(":animated") && !$("#browseVehicleOpen").is(":animated")){
				$("#vehicleOverlay").show();
		//	}
		 },
		 function(){
			$("#vehicleOverlay").hide();
		 }
	);
	
	$("#browseBrandClosed").hover(function(){
		//if (!$("#browseBrandOpen").is(":animated") && !$("#browseVehicleOpen").is(":animated")){
				$("#brandOverlay").show();
		//	}
		 },
		 function(){
			$("#brandOverlay").hide();
		 }
	);


	
	// from the browse brand bar user opens a brand panel and rolls over the vehicle links
	// NOTE : naming convention is [DIVISION CODE]_[SOMETHING]_panel_rollover - first loaded image (off state) must always use "init" as the "SOMETHING" (ex. chev_init_panel_rollover.jpg)
	$(".brandRollovers").hover(
		 function(){
			toSplit = this.id.split('-');
			//console.log(this.id);
			swapObject = getRef(toSplit[0] + "NavRollovers");
			//console.log("swapObject.src=" + swapObject.src);
			imgSrc = swapObject.src;
			if (mlang=="en"){
				imgSrc = imgSrc.replace("init",toSplit[1]);
			}
			else{
				imgSrc = imgSrc.replace("init",toSplit[1]);
				imgSrc = imgSrc.replace("_fr.jpg",".jpg");
			}
			//console.log(imgSrc);
			swapObject.src = imgSrc;
		 },
		 function(){
			imgSrc = swapObject.src;
			if (mlang=="en"){
				imgSrc = imgSrc.replace(toSplit[1],"init");
			}
			else{
				imgSrc = imgSrc.replace(toSplit[1],"init");
				imgSrc = imgSrc.replace(".jpg","_fr.jpg");
			}
			swapObject.src = imgSrc;
			//console.log("imgSrc=" + imgSrc);
		 }

	);	
	
	$(".corpBrandRollovers").hover(
		 function(){
			toSplit = this.id.split('-');
			swapObject = getRef(toSplit[0] + "NavRollovers");
			swapObject.src = swapObject.src.replace("init",toSplit[1]);
		 },
		 function(){
			swapObject.src = swapObject.src.replace(toSplit[1],"init");
		 }

	);	
	
	$("#segmentItems li").hover(  function () {
		if (!$("#browseBrandOpen").is(":animated") && !$("#browseVehicleOpen").is(":animated") && !$("#currentOffersOpen").is(":animated")){
			thisSegment = "#"+this.id;
			//$(".hoverItem").hide();
			$(thisSegment + " .hoverItem").show();
		}
      }, 
      function () {
        $(".hoverItem").hide();
      }
    );
	
	// ie fix for ul hover
	$(".topNavItemTitle").hover(
		 function(){
		  topNavItem = "li#"+this.id;
		  cssObj = {
	        backgroundColor: "#185FAE",
	        color: "#fff",
			backgroundImage: "url(/images/home/top_nav_item_bg.gif)", 
			backgroundPosition: "top left"
	      }
		  $(topNavItem).css(cssObj);
		  $("#"+this.id+" div a,#"+this.id+" div").css("color", "#fff");
		 },
		 function(){
		  topNavItem = "li#"+this.id;
		  cssObj = {
			backgroundColor: "",
	        color: "#666",
			backgroundImage: "none" 
	      }
	      $(topNavItem).css(cssObj);
		  $("#"+this.id+" div a,#"+this.id+" div").css("color", "#666");
		 }
	);

	//change visibility first. stops IE7 from flickering
	$("div#bottomNav").fadeIn(100,function(){
		loadDelay();
	});

	$(window).load(function(){
		afterIntialLoad();
	})

  $("#innerWrapper").hover(function(){
    // do nothing
    }, function(){
	  //TODO: REMOVED FOR WORKING - PUT BACK FOR PRODUCTION
      $("#brandPanels").hide();
  })


});

function loadBrandPanelBG(){
	$("#corpPanel").css("backgroundImage", "url(/images/home/corp_brand_panel_bg.jpg)");
	$("#chevPanel").css("backgroundImage", "url(/images/home/chev_brand_panel_bg_"+mlang+"_CA.jpg)");
	$("#pontPanel").css("backgroundImage", "url(/images/home/pont_brand_panel_bg_"+mlang+".jpg)");
	$("#buicPanel").css("backgroundImage", "url(/images/home/buic_brand_panel_bg_"+mlang+"_CA.jpg)");
	$("#gmcPanel").css("backgroundImage", "url(/images/home/gmc_brand_panel_bg_"+mlang+"_CA.jpg)");
	$("#satuPanel").css("backgroundImage", "url(/images/home/satu_brand_panel_bg_"+mlang+"_CA.jpg)");
	$("#cadiPanel").css("backgroundImage", "url(/images/home/cadi_brand_panel_bg_"+mlang+"_CA.jpg)");
	$("#hummPanel").css("backgroundImage", "url(/images/home/humm_brand_panel_bg_"+mlang+"_CA.jpg)");
	$("#saabPanel").css("backgroundImage", "url(/images/home/saab_brand_panel_bg_"+mlang+"_CA.jpg)");
}

// user opens a panel in the browse brand bar
function showBrandPanel(hideThis,showSelected,showPanel){	
	$(".hoverItem").hide();
	$("#" + hideThis + " .hoverItem").show();
	// TODO: added this... !$("#" + showPanel).is(":visible") &&  - make sure it works okay and then remove this comment!
	if (!$("#" + showPanel).is(":visible") && !$("#" + hideThis).is(":animated") && !$("#" + showPanel).is(":animated") && !$("#" + showSelected).is(":animated") && !$(".brandPanel").is(":animated")){
		$("#brandPanels").fadeIn(200);
		$(".brandPanel").hide();
		$("#" + showPanel).fadeIn(200); 
		$("#closeButton").show();
		if ($("#" + showPanel).css("backgroundImage") == "none"){
			loadBrandPanelBG();
		}
		
	}
	else{
		$("#brandPanels").show();
		$(".brandPanel").hide();
		$("#" + showPanel).show(); 
		$("#closeButton").show();
	}
}

