/* 

	RMAB functions:
	---------------------------------------------------------------------------------------------------
	GENERAL FUNCTIONS
		+ setCSS(string division)				- sets CSS for division web
		+ createInitXMLObj() 					- connects to GM application and gets and read XML data
		+ setPageTittle							- sets page title and header
			(string Name, string Region, string Copy, string Year, string Model)
		+ getQueryString(key, default_)			- gets information from URL [not mine]
		+ displayNoResultsText()				- display message if there is no results in carousel
		+ setDivLink()							- sets link in header and footer
		+ openListLink(int Option)				- shopping tools opener 
		+ horizontalTrick()						- makes tabs horizontal align
		+ openListLink(int Option)				- opens Shoppingtools link
		+ reverseWords							- changes word order for french version
			(string Word1, string Word2)			
		+ setCookie								- sets postal code cookie
			(name, value, expires, path, domain, secure)
		+ getCookie(name)						- gets postal code cookie
		+ validatePostalCode()					- checks postal code
		+ siteCatalist(Name)					- site catalist function
		+ fixIE6()								- FIX IE6 problems
	
	OFFER FUNCTIONS
		+ buildOffers()							- function builds an array with all offers in XML file
		+ detailsPage							- read XML and generate details page
			(int offerId, string changeModel)
		+ featuresList							- create two lists of features
			(array featuresList, int howManyFeatures)
		+ leasingRates(int offerId)				- creates leasing rates table
		+ eventBanner()							- generate event banners	
	
	CAROUSEL
		+ createCarousel(int howManyOffers) 	- create carousel object
		+ restoreCarouselFooters()				- restore carousel item footer
	
	TAB
		+ createTabs							- create new tabs object
		(string Model, string Year, int offer, bool changeModel)	
		+ addTab								- add new tab to tabs array
			(string nameOfTab, int offerId, string modelCode, string modelName, bool isActiveTab)
		+ buildTabs(int Index){					- generate tabs layout
		+ nextTab()								- move tabs
	
	PRICING STRATEGIES
		+ pricing								- create pricing strategies div
			(string details, string finance, string lease, string purchase, string cash, string cashpriceor, string purchasePayment)
		+ pricing_finance_rate					- pricing strategies: financing rate
			(string rate, string details)
		+ pricing_purchase_price				- pricing strategies: purchase price
			(string align, string price, string details)
		+ pricing_purchase_lease_rate			- pricing strategies: lease rate
			(string rate, string details)
		+ pricing_purchase_lease_payment		- pricing strategies: lease payment
			(string align, string payment, string term, string downPayment, string details)
		+ pricing_purchase_cash			- pricing strategies: cash purchase
			(string align, string cash, string details)
		+ pricing_finance_payment				- pricing strategies: finance payment
			(string payment, string term, string downPayment, string details)

	---------------------------------------------------------------------------------------------------
*/


/* -------------------------  CONFIGURATION VARS -----------------------------------*/

var lang 				= (document.location.href.indexOf("/french/") != -1) ? "fr" : "en";
var currentOffers		= (document.location.href.indexOf("/current-offers") != -1) ? true : false;
var pageName			= (document.location.href.indexOf("/current-offers") != -1) ? "Current Offers" : "RMAB";
var language			= (lang == "fr") ? "french" : "english";
var Llanguage			= (lang == "fr") ? "French" : "English";
var CarouselObject;

if(currentOffers){
	var division 			= document.location.href.split("/")[6];
	var region 				= document.location.href.split("/")[7];
}else{
	var partURL 			= document.location.href.split("offers/");
	var division 			= partURL[1].split("/")[0];  // "pontiac";	
	var region 				= partURL[1].split("/")[1];  // "ontario";
}

var divisionTitle       = division.substr(0, 1).toUpperCase() + division.substr(1)

var followStrategyOnly 	= (document.location.href.indexOf("followStrategyOnly=true") != -1) ? "true" : "false";
var urlOfferId			= document.location.hash.replace("#", "");
var carousel_list 		= new Array();	// List of items in carousel

var makeCodesArr = new Array();
makeCodesArr["chevrolet"] 	= "1";
makeCodesArr["pontiac"]		= "2";
makeCodesArr["cadillac"] 	= "6";
makeCodesArr["buick"]		= "4";
makeCodesArr["gmc"]			= "G";
makeCodesArr["all"] 		= "1,2,4,G,6";
var makeShortArr 			= new Array();
makeShortArr["chevrolet"] 	= "chev";
makeShortArr["pontiac"] 	= "pont";
makeShortArr["cadillac"] 	= "cadi";
var namePlate = new Array();
namePlate["chevrolet"]		= "MMNAMPLT_7";
namePlate["cadillac"]		= "MMNAMPLT_4";
namePlate["buick"]			= "MMNAMPLT_1";
namePlate["gmc"]			= "MMNAMPLT_2";

var actualYear = "";
var actualModel = "";
var actualPackage = "";

var copy = new Array();
copy["en"] = new Array();
copy["fr"] = new Array();
copy["en_extra"] = new Array();
copy["fr_extra"] = new Array();
copy["en"]["dealers"] = "Dealers";
copy["fr"]["dealers"] = "Concessionnaires";
copy["en"]["takeacloser"] = "Take a closer look at your";
copy["fr"]["takeacloser"] = "Regardez de plus pr&#232;s votre";
copy["en"]["homepage"] = "Homepage";
copy["fr"]["homepage"] = "Page d&#8217;accueil";
copy["en"]["locatevehicle"] = "Locate a Vehicle";
copy["fr"]["locatevehicle"] = "Trouver un v&#233;hicule";
copy["en"]["estimatepayments"] = "Estimate Payments";
copy["fr"]["estimatepayments"] = "Estimateur de paiements";
copy["en"]["checkout"] = "Check out what you`ll get";
copy["fr"]["checkout"] = "Voyez ce que vous obtenez";
copy["en"]["offerdetails"] = "Offer Details";
copy["fr"]["offerdetails"] = "D&#233;tails de l&#8217;offre";
copy["en"]["legal"] = "legal";
copy["fr"]["legal"] = "Avis juridique";
copy["en"]["offerincludes"] = "Offer Includes";
copy["fr"]["offerincludes"] = "L&#8217;offre comprend";
copy["en"]["legal2"] = "Legal";
copy["fr"]["legal2"] = "Avis juridique";
copy["en"]["seetheoffer"] = "See the offer";
copy["fr"]["seetheoffer"] = "Voir cette offre";
copy["en"]["postalcode"] = "Postal Code";
copy["fr"]["postalcode"] = "Code Postal";
copy["en"]["purchaseprice"] = "Purchase Price";
copy["fr"]["purchaseprice"] = "Prix d&#8217;achat";
copy["en"]["leaserate"] = "Lease Rate";
copy["fr"]["leaserate"] = "Taux de location";
copy["en"]["leasepayment"] = "Lease Payment";
copy["fr"]["leasepayment"] = "Paiement de location";
copy["en"]["months"] = "months";
copy["fr"]["months"] = "Mois";
copy["en"]["downpayment"] = "Down Payment";
copy["fr"]["downpayment"] = "Versement";
copy["en"]["cashpurchaseprice"] = "Cash Purchase Price";
copy["fr"]["cashpurchaseprice"] = "Prix d&#8217;achat comptant";
copy["en"]["cashprice"] = "Cash Purchase Price";
copy["fr"]["cashprice"] = "Prix d'achat au comptant";
copy["en"]["financepayment"] = "Purchase Financing Payment";
copy["fr"]["financepayment"] = "Paiement au financement";
copy["en"]["financerate"] = "Purchase Financing Rate";
copy["fr"]["financerate"] = "Taux de financement &#224; l'achat";
copy["en"]["financepayment_smart"] = "Smart Purchase Financing";				// SMART PURCHASE NAMES
copy["fr"]["financepayment_smart"] = "Financement Flexi-Achat";
copy["en"]["financerate_smart"] = "Smart Purchase Financing Rate";
copy["fr"]["financerate_smart"] = "Taux de financement Flexi-Achat";			// --------------------
copy["en"]["shoppingtools"] = "Shopping Tools";
copy["fr"]["shoppingtools"] = "Outils d&#8217;achat";
copy["en"]["buildandprice"] = "Build and Price";
copy["fr"]["buildandprice"] = "Fabriquer et obtenir un prix";
copy["en"]["compare"] = "Compare";
copy["fr"]["compare"] = "Comparer";
copy["en"]["locateyour"] = "Locate your";
copy["fr"]["locateyour"] = "Trouver un";
copy["en"]["locateadealer"] = "Locate a Dealer";
copy["fr"]["locateadealer"] = "Trouver un concessionnaire";
copy["en"]["scheduleatestdrive"] = "Schedule a Test Drive";
copy["fr"]["scheduleatestdrive"] = "Rendez-vous pour un essai routier";
copy["en"]["requestaquote"] = "Request a Quote";
copy["fr"]["requestaquote"] = "Demander une soumission";
copy["en"]["share"] = "Share";
copy["fr"]["share"] = "Partager";
copy["en"]["leasing"] = "Lease Options";
copy["fr"]["leasing"] = "Location";
copy["en"]["freight"] = "Freight";
copy["fr"]["freight"] = "Transport";
copy["en"]["monthly"] = "Monthly";
copy["fr"]["monthly"] = "mensuel";
copy["en"]["weekly"] = "Weekly";
copy["fr"]["weekly"] = "hebdomadaire";
copy["en"]["biweekly"] = "Bi-weekly";
copy["fr"]["biweekly"] = "aux deux semaines";
copy["en"]["apr"] = "APR";
copy["fr"]["apr"] = "TPA";
copy["en"]["msrp"] = "MSRP";
copy["fr"]["msrp"] = "PDSF";

copy["en"]["chevrolet_banner_default"] = "Innovation, quality and value you can count on";
copy["fr"]["chevrolet_banner_default"] = "Innovation, qualit&#233; et valeur dignes de confiance.";
copy["en"]["buick_banner_default"] = "The new class of world class";
copy["fr"]["buick_banner_default"] = "Une nouvelle classe &#224; part.";
copy["en"]["gmc_banner_default"] = "Engineered to take you above and beyond";
copy["fr"]["gmc_banner_default"] = "Con&#231;u pour relever tous vos d&#233;fis.";
copy["en"]["cadillac_banner_default"] = "Dramatic presence. High performance. And 100% pure luxury";
copy["fr"]["cadillac_banner_default"] = "Pr&#233;sence th&#233;&#226;trale. Performance spectaculaire. L&#8217;apog&#233;e du luxe.";

copy["en"]["legalphoto"] = "Photo is example only. Vehicle not exactly as shown";
copy["fr"]["legalphoto"] = "Photo &#224; titre indicatif. Le v&#233;hicule peut diff&#233;rer";

// Regions
copy["en"]["alberta"] 			= "Alberta";
copy["en_extra"]["alberta"] 	= "(also serving Dawson Creek, Fort St. John, Yellowknife and Lloydminster*)";
copy["fr"]["alberta"] 			= "de l'Alberta";
copy["fr_extra"]["alberta"] 	= "(servant &#233;galement Dawson Creek, Fort St. John, Yellowknife et Lloydminster*)";

copy["en"]["bc"] 				= "British Columbia";
copy["en_extra"]["bc"] 			= "(also serving the Yukon Territory*)";
copy["fr"]["bc"] 				= "de Colombie-Britanique";
copy["fr_extra"]["bc"] 			= "(servant &#233;galement le Yukon*)";

copy["en"]["maritime"] 			= "Maritime";
copy["en_extra"]["maritime"] 	= "(also serving parts of Quebec*)";
copy["fr"]["maritime"] 			= "des Maritimes";
copy["fr_extra"]["maritime"] 	= "(servant &#233;galement des r&#233;gions du Qu&#233;bec*)";

copy["en"]["nfld"] 				= "Newfoundland and Labrador";
copy["en_extra"]["nfld"] 		= "(also serving parts of Quebec*)";
copy["fr"]["nfld"] 				= "de T.-N. et du Labrador";
copy["fr_extra"]["nfld"] 		= "(servant &#233;galement des r&#233;gions du Qu&#233;bec*)";

copy["en"]["newfoundland"] 		= "Newfoundland and Labrador";
copy["en_extra"]["newfoundland"]= "(also serving parts of Quebec*)";
copy["fr"]["newfoundland"] 		= "de T.-N. et du Labrador";
copy["fr_extra"]["newfoundland"]= "(servant &#233;galement des r&#233;gions du Qu&#233;bec*)";

copy["en"]["ontario"] 			= "Ontario";
copy["en_extra"]["ontario"]		= "(Including Outaouais*)";
copy["fr"]["ontario"] 			= "de l'Ontario";
copy["fr_extra"]["ontario"]		= "(y compris l'Outaouais*)";

copy["en"]["prairie"] = "Prairie";
copy["en_extra"]["prairie"]		= false;
copy["fr"]["prairie"] = "des Prairies";
copy["fr_extra"]["prairie"]		= false;

copy["en"]["atlantic"] 			= "Atlantic";
copy["en_extra"]["atlantic"]	= "(also serving parts of Quebec*)";
copy["fr"]["atlantic"] 			= "de l'Atlantique";
copy["fr_extra"]["atlantic"]	= "(servant &#233;galement des r&#233;gions du Qu&#233;bec*)";

copy["en"]["alberta_and_prairie"] 		= "Alberta & Prairie";
copy["en_extra"]["alberta_and_prairie"]	= "(also serving Dawson Creek, Fort St. John and Yellowknife*)";
copy["fr"]["alberta_and_prairie"] 		= "de l'Alberta et des Prairies";
copy["fr_extra"]["alberta_and_prairie"]	= "(servant &#233;galement Dawson Creek, Fort St. John, Yellowknife*)";

copy["en"]["quebec"] 			= "Quebec";
copy["en_extra"]["quebec"]		= "(also serving parts of Nunavut & Ontario*)";
copy["fr"]["quebec"] 			= "du Qu&#233;bec";
copy["fr_extra"]["quebec"]		= "(servant &#233;galement des r&#233;gions du Nunavut et de l'Ontario*)";

copy["en"]["or"] = "_or";
copy["fr"]["or"] = "_ou";

var xmlInitial;						// Initial XML created only onLoad, used to retrieve data
var Offers = new Array();			// All offers Array
var Models = new Array();			// Array for carousel
var carouselCount = 1;				// Carousel count

var TabsArray = new Array();		// Array for a tabs
var TabsIndex = 0;					// Index of displayed tabs
var TabsCount = 0;					// Number of all tabs in offer
var _DisplayTabs = 4;				// How many tabs will be displayed

var PostalCodeCookie = "";

var bannerImage = "";
var bannerAlt = "";
var bannerHref = "/gm";

var sitecat_PageName = "";
var sitecat_Prop6 = "";
var sitecat_Prop7 = "";
var sitecat_Channel = "";

		  if((region == "alberta" || region == "prairie") && division == "cadillac"){
		  	copy[lang][region] = copy[lang]["alberta_and_prairie"];
			copy[lang + "_extra"][region] = copy[lang + "_extra"]["alberta_and_prairie"];
		  }

siteCatalist("Homepage");

/* ------------------------- ONLOAD -------------------------------------------- */

$(function(){
		  
		  eventBanner();
		
		 // if(lang == "fr" && division == "chevrolet" && (region == "nfld" || region == "newfoundland"))
		 // 	copy[lang][region] = "de T.-N. et du Labrador";
		
		  setCSS(division);
		  
		  setPageTittle(divisionTitle, copy[lang][region], copy[lang]["dealers"], false, false, copy[lang + "_extra"][region]);

		  setDivLink();		  
		  
			if(lang == "en"){
				if(region == "nfld" || region == "newfoundland")
					$("<div id='regionLegal'>* Dealer marketing areas may cross provincial boundaries, therefore some postal codes may be directed to a region where a customer does not reside. These include, Vieux-Fort, Blanc-Sablon, L'Anse-au-Claire, L'Anse au Loup, West St. Modeste, Red Bay and Barge Bay and other parts of Quebec. Contact your <a href='/gm/english/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=0&cta=blank&lang=en'>local dealer</a> for further assistance.</div>").appendTo("#wrap");
				else
					$("<div id='regionLegal'>* Dealer marketing areas may cross provincial boundaries, therefore some postal codes may be directed to a region where a customer does not reside. Contact your <a href='/gm/english/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=0&cta=blank&lang=en'>local dealer</a> for further assistance.</div>").appendTo("#wrap");
			}else{
				if(region == "nfld" || region == "newfoundland")
					$("<div id='regionLegal'>* Les zones de commercialisation des concessionnaires peuvent franchir des fronti&#232;res provinciales, par cons&#233;quent, certains codes postaux de client peuvent &#234;tre associ&#233;s &#224; une r&#233;gion autre que celle o&#249; le client r&#233;side. Il peut s'agir notamment de Vieux-Fort, de Blanc-Sablon, de L'Anse-au-Clair, de L'Anse au Loup, de West St. Modeste, de Red Bay et Barge Bay ou d'autres r&#233;gions du Qu&#233;bec. Communiquez avec votre <a href='/gm/french/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=0&cta=blank&lang=fr'>concessionnaire local</a> pour obtenir de l'aide.</div>").appendTo("#wrap");
				else
					$("<div id='regionLegal'>* Les zones de commercialisation des concessionnaires peuvent franchir des fronti&#232;res provinciales, par cons&#233;quent, certains codes postaux de client peuvent &#234;tre associ&#233;s &#224; une r&#233;gion autre que celle o&#249; le client r&#233;side. Communiquez avec votre <a href='/gm/french/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=0&cta=blank&lang=fr'>concessionnaire local</a> pour obtenir de l'aide.</div>").appendTo("#wrap");
			}
		  //SET UP LOCATE A DEALER FORM FIELDS
		  $("#f_nameplate").val(makeCodesArr[division]).attr("name",namePlate[division]);
		  $("#f_nav").val(makeCodesArr[division]);
		  $("#f_cmb").val(makeCodesArr[division]);
		  
		  $(".langToggle").click(function(){
		 	 if(document.location.href.indexOf("french") != -1) {
				document.location.href = document.location.href.replace(/french/g,"english");
		  	} else {
				document.location.href = document.location.href.replace(/english/g,"french");	
		  	}
		  	return false;
		  });
		  
		  // setting variables to load in flash container using the swfobject technique
			var flashvars = {
					lang: lang,
					listName: "list1",
					filePath: "/media/financing/offers/rmab/media/vehicles/" + division + "/" // path to media assets
			};
			var params = {
					wmode: "transparent",
					scale: 'noscale',
					salign: 'TL'
			};
			swfobject.embedSWF("/media/financing/offers/rmab/Player.swf", "promo", "990", "420", "9.0.0", "", flashvars, params);
			
			if(getCookie("pc"))
				PostalCodeCookie = getCookie("pc");
			else
				PostalCodeCookie = copy[lang]["postalcode"];
				
			$("#pc").val(PostalCodeCookie);
			
			
			// SCRIPT FOR CURRENT OFFERS - HIDE SHOPPING TOOLS
			$('#SiteMapBTN').hover(function () {
					$("#shoppingTools").css('display','none');
					$("#shoppingTools").css('visibility','hidden');
												}, function () {});
			
			$('#CloseSiteMap').click(function () {
					$("#shoppingTools").css('display','block');	
					$("#shoppingTools").css('visibility','visible');
												});
			
			$('#GlobalNav').hover(function () {
											$("#shoppingTools").css('display','none');
											$("#shoppingTools").css('visibility','hidden');
											},
					function ()
					{
						$("#shoppingTools").css('display','block');
						$("#shoppingTools").css('visibility','visible');
					}
			);
			
			//createInitXMLObj();		// Loads initial xml file, creating XML obj
			
			jQuery('#carCarousel').jcarousel({
				initCallback: createInitXMLObj,
				scroll: 4
			});
			
			$("#loading").css("display","none");
			$("#headerMain, #content, #carousel, #footerContent, #regionLegal").css("display","block");
			
		  
});


/* -------------------------  XML OFFERS INIT -----------------------------------*/

function createInitXMLObj(carousel){	// connects to GM application and gets and read XML data

	CarouselObject = carousel;

	var regionReal 		= region;
	if (region == 'nfld') {regionReal = "newfoundland";}
	$.ajax({
		type: "GET",
		url: "/gm/" + language + "/rmab/offers/search?makes=" + makeCodesArr[division] + "&regions=" + regionReal + "&followStrategyOnly=" + followStrategyOnly,
		//url: "/js/offers/rmab_new_ps.xml",
		dataType: ($.browser.msie) ? "text" : "xml",
		async: true,
		error: function(xhr, ajaxOptions, thrownError){
			displayNoResultsText();
		},
		beforeSend: function(){
			// Loading state
		},
		complete: function(){
			//
		},
		success: function(xml){
			//work around for IE

			var tempXML;
			if (typeof xml == "string") {
			   tempXML = new ActiveXObject("Microsoft.XMLDOM");
			   tempXML.async = false;
			   tempXML.loadXML(xml);
			   xml = tempXML;
			}

			xmlInitial = xml;
			var numOffers = $(xmlInitial).find("recordCount").text();
			
			if (numOffers == 0) { // If there are no results returned
				displayNoResultsText();
				return; //exit
			}else{
				$("#ajax_loading").css('display', 'none');	
			}
			
			buildOffers();
			
			
			if(urlOfferId){
				detailsPage(urlOfferId);
			}

		}
	});
}

/* -------------------------  CREATE CAROUSEL -----------------------------------*/

function createCarousel(){

		//var offersCount = carouselCount-1;
		var i = 1;
		
		$.each(Models, function(i, value){
			var offerItem = value.split("|");
			vehModel = offerItem[0];
			vehYear = offerItem[1];
			vehCode = Offers[value][0]["vehCode"];
			offerId = Offers[value][0]["ID"];
			CarouselObject.add(i+1, "<div class='carousel_item'><div class='carousel_item_header'>" + reverseWords(vehYear, "<b>" + vehModel + "</b>") + "</div><a href='#' onclick=\"detailsPage(" + offerId + ", true); s.tl(this,'o','" + region + " " + division + " DEALERS - " + vehModel + " - CTA OFFER DETAILS'); s.tl(this,'o','" + region + " " + division + " DEALERS - CTA OFFER DETAILS');\"><img src='/images/vehicles/showroom/vehicles/" + vehCode + "_med.jpg' height='78' alt='" + reverseWords(vehYear, vehModel) + "' /></a><div id='carousel_footer_" + vehModel + vehYear + "' class='carousel_item_footer'><a href='#' onclick=\"detailsPage(" + offerId + ", true); s.tl(this,'o','" + region + " " + division + " DEALERS - " + vehModel + " - CTA OFFER DETAILS'); s.tl(this,'o','" + region + " " + division + " DEALERS - CTA OFFER DETAILS');\" class='carousel_item_footer_button'>" + copy[lang]["seetheoffer"] + "</a></div></div>");
		});

		CarouselObject.size(carouselCount-1);
		var changeWidth = (carouselCount-1)*226;
		$("#carCarousel").css("width", changeWidth);
		CarouselObject.reload();
		
}

function restoreCarouselFooters(){			// Restore carousel item footer
	
	$(".carousel_item_footer_active").attr("class", "carousel_item_footer");
	
}

/* -------------------------  BUILD OFFERS -----------------------------------*/

function buildOffers(){		// Function builds an array with all offers in XML file

	var offersArray = new Array();

	$(xmlInitial).find("offers offer").each(function(){			// Get all offers from XML file
		var offer = new Array();
		offer["ID"]			= $(this).children("offerID").text();
		offer["Title"]		= $(this).children("offertitle").text();
		offer["vehModel"]	= $(this).children("modelNameDesc").text();	
		offer["vehYear"]	= $(this).children("modelYear").text();
		offer["vehCode"]	= $(this).children("modelyearcode").text();

		var Key = offer["vehModel"] + "|" + offer["vehYear"];
		if(offersArray[Key]){
			offersArray[Key].push(offer);
		}else{
			offersArray[Key] = new Array();
			Models.push(Key);
			carouselCount++;
			offersArray[Key].push(offer);
		}
	});
	
	Models.sort();
	
	$.each(Models, function(i, value){
		Offers[value] = new Array();
		Offers[value] = offersArray[value];	
	});
	
	createCarousel();		

	return true;

}

/* -------------------------  DEATILS PAGE -----------------------------------*/

function detailsPage(offerId, changeModel){

	var details 			= new Array();
	var featuresArr 		= new Array();
	var featuresArrCount 	= 0;
	
	// GET ALL OFFER DATA
	$(xmlInitial).find("offer:has(offerId:contains(" + offerId + "))").each(function(){
				vehModelDesc	= $(this).children("modelNameDesc").text();
				offerTitle		= $(this).children("offertitle").text();
				modelDesign		= $(this).children("modeldesignator").text();
				optionCode		= $(this).children("optioncode").text();
				vehModel		= $(this).children("modelNameDesc").text();	
				vehModelName	= $(this).children("modelName").text();	
				vehYear 		= $(this).children("modelyear").text();
				vehOption 		= $(this).children("optioncode").text();
				vehCode			= $(this).children("modelyearcode").text();
				vehHomePage		= $(this).children("modeloverviewlink").text();
				
				finance			= $(this).children("displaysectionfinance").text();
				lease			= $(this).children("displaysectionlease").text();
				purchaseprice	= $(this).children("displaysectionpurchaseprice").text();
				payment			= $(this).children("finance").children("displaypayment").text();
				cashprice		= $(this).children("displaysectioncashprice").text();
				cashpriceor		= $(this).children("displaysectioncashpriceor").text();
				lease_payment	= $(this).children("lease").children("displayPayment").text();
				msrp			= $(this).children("displaySectionMsrp").text();
				smart			= $(this).children("displayAsSmartPurchaseFinance").text();

				details["advertisedrate"] 		= $(this).children("finance").children("advertisedrate").text();
				details["finance_detailcopy"] 	= $(this).children("finance").children("detailcopy").text();
				details["payment"] 				= $(this).children("finance").children("payment").text();
				details["term"] 				= $(this).children("finance").children("term").text();
				details["downpayment"] 			= $(this).children("finance").children("downpayment").text();
				details["cashprice"] 			= $(this).children("purchase").children("cashprice").text();
				details["purchase_detailcopy"]	= $(this).children("purchase").children("detailcopy").text();
				details["includeFreight"]		= $(this).children("purchase").children("includeFreight").text();
				details["freightamount"]		= $(this).children("purchase").children("freightamount").text();
				
				details["lease"] = new Array();
				details["lease"]["advertisedrate"] 			= $(this).children("lease").children("advertisedrate").text();
				details["lease"]["payment"] 				= $(this).children("lease").children("payment").text();
				details["lease"]["term"] 					= $(this).children("lease").children("term").text();
				details["lease"]["downpayment"] 			= $(this).children("lease").children("downpayment").text();
				details["lease"]["displayAdvertisedRate"] 	= $(this).children("lease").children("displayAdvertisedRate").text();
				details["lease"]["displayPayment"] 			= $(this).children("lease").children("displayPayment").text();
				details["lease"]["effectiveRate"] 			= $(this).children("lease").children("effectiveRate").text();
				details["lease"]["paymentType"] 			= $(this).children("lease").children("paymentType").text();
				details["lease"]["displayPayment"] 			= $(this).children("lease").children("displayPayment").text();	
				details["lease"]["legal"] 					= $(this).children("lease").children("legal").text();	
				details["lease"]["paymentCopy"] 			= $(this).children("lease").children("detailcopy").text();
				details["lease"]["rateCopy"] 				= $(this).children("lease").children("rateDetailCopy").text();
				
				details["finance"] = new Array();
				details["finance"]["displayAdvertisedRate"] = $(this).children("finance").children("displayAdvertisedRate").text();
				details["finance"]["effectiveRate"] = $(this).children("finance").children("effectiveRate").text();
				details["finance"]["paymentType"] = $(this).children("finance").children("paymentType").text();
				
				pricing_display = pricing(details, finance, lease, purchaseprice, cashprice, cashpriceor, payment, msrp, smart);
				if(lease_payment == "true")
					leasing = "<div class='leasingDiv'><a href='#leasingWindow' class='leasingButton'>" + copy[lang]["leasing"] + "</a></div><div style='clear:both'></div>";
				else
					leasing = "";
				
				legal			= $(this).children("legals").children("legal").text();
				
				$(this).children("features").children("feature").each(function(){
					featuresArr.push( $(this).text() );
					featuresArrCount++;
				});
				
	});
	
	document.location.hash = offerId;
	
	
	
	actualModel = modelDesign;
	actualPackage = optionCode;
	actualYear = vehYear;
	
	var Template = [
				   	"<div id='tabs'>",	// ------------------------------------------------------------------------------------------- TABS DECLARATION
				   		"<ul id='offer-tabs'></ul>",	
						"<a href='#' class='tab_right_arrow' onclick='nextTab()'></a>",
					"<div style='clear:both'></div>",											
					"<a href='#' class='tab_left_arrow' onclick='prevTab()'></a>",
					"<div id='main'>",	// ------------------------------------------------------------------------------------------- MAIN CONTENT
						"<div id='offer-left'>", // ---------------------------------------------------------------------------------- LEFT SIDE
								"<div id='banner'></div>",
								"<div id='pricingStrategies'>" + pricing_display + leasing + "</div>",
								"<div id='take_a_look'>",
									"<span>" + copy[lang]["takeacloser"] + " " + vehModelDesc + "</span>",
								"</div>",
								"<div id='offer-buttons'>",
									"<a href='" + vehHomePage + "' class='offer-left-button offer-left-button1' onClick=\"s.tl(this,'o','" + region + " " + division + " DEALERS - " + vehModelDesc + " - CTA OVP'); s.tl(this,'o','" + region + " " + division + " DEALERS - CTA OVP');\">" + reverseWords(vehModelDesc, copy[lang]["homepage"]) + "</a>",
									"<a href='/gm/" + language + "/hostredirect?host=http://apps.gm.ca/app/GMCanada/NewVehicleLocatorCriteria.do&lang=" + lang + "&nav=" + makeCodesArr[division] + "&cta=blank&search_year=" + vehYear + "&search_model_designator="+ modelDesign + "&search_nameplate=1&search_url=&search_pkgcd=" + optionCode + "&search_mktcd=' class='offer-left-button offer-left-button2' onClick=\"s.tl(this,'o','" + region + " " + division + " DEALERS - " + vehModelDesc + " - CTA LOCATE A VEHICLE'); s.tl(this,'o','" + region + " " + division + " DEALERS - CTA LOCATE A VEHICLE');\">" + copy[lang]["locatevehicle"] + "</a>",
									"<a href='/gm/" + language + "/payment-estimator/calculator?year=" + vehYear + "&modelCode=" 
										+ modelDesign + "&packageCode=" + vehOption + "&postalCode=' class='offer-left-button offer-left-button3' onClick=\"s.tl(this,'o','" + region + " " + division + " DEALERS - " + vehModelDesc + " - CTA ESTIMATE PAYMENTS'); s.tl(this,'o','" + region + " " + division + " DEALERS - CTA ESTIMATE PAYMENT');\">" + copy[lang]["estimatepayments"] + "</a>",
								"</div>",
								"<div class='findDealer-line'></div>",
						"</div>",
						"<div id='offer-right'>",	// ------------------------------------------------------------------------------ RIGHT SIDE
								"<img src='/apps/offersearch/" + language + "/vehicles/large/" + vehYear + modelDesign + ".jpg' width='392' alt='" + reverseWords(vehYear, vehModel) + "' />",
								"<div class='legalPhoto'>" + copy[lang]["legalphoto"] + "</div>",
								"<div id='right-footer'>",
									"<div class='sign'>" + copy[lang]["checkout"] + "</div>",
									"<a href='#featuresWindow' class='featuresButton'>" + copy[lang]["offerdetails"] + "</a>",
									"<a href='#legalWindow' class='legalButton'>" + copy[lang]["legal"] + "</a></div><div style='clear:both'>",
								"</div>",
						"</div>",
						"<div style='clear:both'>&nbsp;</div>",
						"<div>", // -------------------------------------------------------------------------------------------------- FIND DEALER
							"<div class='findDealer_box'>",
								"<form id='postalCodeForm' onsubmit='return validatePostalCode()' action='http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do?' method='get'>",
                    				"<input id='f_nav' type='hidden' value='" + makeCodesArr[division] + "' name='nav' />",
									"<input id='f_cta' type='hidden' value='blank' name='cta' />",
									"<input id='f_lang' type='hidden' value='" + lang + "' name='lang' />",
									"<input id='f_nameplate' type='hidden' value='" + makeCodesArr[division] + "' name='" + namePlate[division] + "' />",
                       				"<input type='text' id='pc' name='POSTLCD' value='" + PostalCodeCookie + "' onclick='this.value=\"\"' />",
									"<input id='f_cmb' type='hidden' value='1' name='cmb_brand' />",
                        			"<input id='f_service' type='hidden' value='Optional' name='SELECTED_SERVICE' />",
									"<input type='submit' class='searchButton' value='' />",
                    			"</form>",
							"</div>",
						"</div>",
						"<select name='shopping_tools' id='shoppingTools' onchange='openListLink(this.value)'>", // ------------------------------------------------------ SHOPING TOOLS AND ICONS 
								"<option value='0' selected='selected'>" + copy[lang]["shoppingtools"] + "</option>",
								"<option value='1'>" + copy[lang]["buildandprice"]  + "</option>",
								"<option value='2'>" + copy[lang]["estimatepayments"] + "</option>",
								"<option value='3'>" + copy[lang]["compare"] + " " + vehModel + "</option>",
								"<option value='4'>" + copy[lang]["locateyour"] + " " + vehModel + "</option>",
								"<option value='5'>" + copy[lang]["locateadealer"] + "</option>",
								"<option value='6'>" + copy[lang]["scheduleatestdrive"] + "</option>",
								"<option value='7'>" + copy[lang]["requestaquote"] + "</option>",
						"</select>",
						"<a id='pageToolsShare' rel='nofollow' href='http://www.addthis.com/bookmark.php?v=250&amp;pub=gmcanada' onmouseover='return addthis_open(this, \"\", location.href + \"#" + offerId + "\" , \"" + offerTitle + "\")' onmouseout='addthis_close()' onclick='return false' class='iconShare'>",
								"<span>" + copy[lang]["share"] + " <span style='font-size: 108%'>+</span></span>",
						"</a>",
						"<a href='#' onclick='print(); return false'>",
								"<img src='/images/financing/offers/rmab/divisions/chevrolet/icon_print.gif' class='iconPrint' border='0' alt='print' />",
						"</a>",
					"</div>"							
				   ];
	
	$("#content").html(Template.join(''));
	
	document.getElementById("main").className = "details";
	$(".findDealer_box").css("background-image","url(/images/financing/offers/rmab/divisions/" + division + "/find_dealer_" + lang + ".png)");
	if(lang == "fr"){
		$("#shoppingTools").css("left","690px");	
		$(".iconPrint").css("right","74px");
	}

	createTabs(vehModel, vehYear, offerId, changeModel);
	restoreCarouselFooters();

	document.getElementById("carousel_footer_" + vehModel + vehYear).className = "carousel_item_footer_active";
	
	// WINDOWS
	
				$("#featuresWindow").html("<div class='windowTag'>" + offerTitle + "</div><div class='featuresTag'>" + copy[lang]["offerincludes"] + ":</div><img src='/apps/offersearch/english/vehicles/large/" + vehYear  + modelDesign + ".jpg' class='windowCarPresentation' height='170' alt='" + offerTitle + "' /><div class='featuresList'><ul id='featuresListLeft'></ul></div><div class='featuresList'><ul id='featuresListRight'></ul></div><a href='#' class='windowClose'>&nbsp;</a>");
				$("#legalWindow").html("<div class='windowTag'>" + offerTitle + "</div><img src='/apps/offersearch/english/vehicles/large/" + vehYear  + modelDesign + ".jpg' class='windowCarPresentation' height='170' alt='" + offerTitle + "' /><br/><br/><p class='windowText'><span class='windowTextTag'>" + copy[lang]["legal2"] + ":</span><br/>" + legal + "</p><a href='#' class='windowClose'>&nbsp;</a>");
				
				featuresList(featuresArr, featuresArrCount-1);	// Generates list data divided into two columns
				
				$('.featuresButton').click(function(){ 						// Generate action on click to open features window
					$.openDOMWindow({ 
						loader:1, 
						loaderImagePath:'animationProcessing.gif', 
						loaderHeight:16, 
						loaderWidth:17, 
						windowSourceID:'#featuresWindow', 
						width:740,
						//height:'auto'
						height:400
					}); 
					return false; 
				}); 
				
				$('.legalButton').click(function(){ 						// Generate action on click to open legal window
					$.openDOMWindow({ 
						loader:1, 
						loaderImagePath:'animationProcessing.gif', 
						loaderHeight:16, 
						loaderWidth:17, 
						windowSourceID:'#legalWindow', 
						width:740,
						//height:'auto'
						height:490
					}); 
					return false; 
				}); 
				
				if(lease == "true"){
					html = leasingRates(offerId, details["lease"]["legal"]);
				
					$("#leasingWindow").html("<div class='windowTag'>" + offerTitle + "</div><img src='/apps/offersearch/english/vehicles/large/" + vehYear  + modelDesign + ".jpg' class='windowCarPresentation' height='170' alt='" + offerTitle + "' /><br/><br/><p class='windowText'><br/>" + html + "</p><a href='#' class='windowClose'>&nbsp;</a>");
				
					$('.leasingButton').click(function(){ 						// Generate action on click to open leasing window
						$.openDOMWindow({ 
							loader:1, 
							loaderImagePath:'animationProcessing.gif', 
							loaderHeight:16, 
							loaderWidth:17, 
							windowSourceID:'#leasingWindow', 
							width:740,
							//height:'auto'
							height:490
						}); 
						return false; 
					}); 
				
				}
				
				$('.windowClose').click(function(){
					$.closeDOMWindow();				
					return false;
				});
				
		// BANNER LOAD
		$("#banner").html("<img src='" + bannerImage + "' alt='" + bannerAlt + "' />");
		
		//SC
		siteCatalist('', vehModelDesc);
		
		if ($.browser.msie && $.browser.version.substr(0,1)<7) {
			fixIE6();
		}
		
		setPageTittle(divisionTitle, copy[lang][region], copy[lang]["dealers"], vehYear, vehModel, copy[lang + "_extra"][region]);	// Set new page tittle
		
		return false;
	
}

/* -------------------------  PRICING STRATEGIES -----------------------------------*/

// FINANCE RATE ----------------------------------------------------------------------
function pricing_finance_rate(Rate, Details, APR, ChangeFontSize, SmartPurchase){
	EffectiveAPR = (APR) ? " (" + APR + " " + copy[lang]["apr"] + ")" : ""; 
	fontSize = (ChangeFontSize) ? "smaller" : "big";
	Smart = (SmartPurchase == "true") ? "_smart" : "";
	return 	"<b>" + copy[lang]["financerate" + Smart] + putSpace() + ":</b><br/> <span class='" + fontSize + "'>" + Rate + EffectiveAPR + "</span><br/><span class='small'>" + Details + "</span>";
}

// PURCHASE PRICE --------------------------------------------------------------------
function pricing_purchase_price(Align, Price, Details){
	if(Align == "left")
		return 	"<span class='big'>" + Price + "</span> <b>" + copy[lang]["purchaseprice"] + "</b><br/><span class='small'>" + Details + "</span>";
	else
		return 	"<b>" + copy[lang]["purchaseprice"] + putSpace() + ":</b> <span class='big'>" + Price + "</span><br/><span class='small'>" + Details + "</span>";
}

// PURCHASE PRICE RIGHT SIDE ----------------------------------------------------------
function pricing_msrp(Price, Details){
	return 	"<b>" + copy[lang]["msrp"] + putSpace() + ":</b> <span class='big'>" + Price + "</span><br/><span class='small'>" + Details + "</span>";
}

// LEASE RATE ------------------------------------------------------------------------
function pricing_purchase_lease_rate(Rate, Details, APR, ChangeFontSize){	
	EffectiveAPR = (APR) ? " (" + APR + " " + copy[lang]["apr"] + ")" : "";  
	fontSize = (ChangeFontSize) ? "smaller" : "big";
	return 	"<b>" + copy[lang]["leaserate"] + putSpace() + ":</b><br/> <span class='" + fontSize + "'>" + Rate + EffectiveAPR + "</span><br/><span class='small'>" + Details + "</span>";
}

function pricing_purchase_lease_payment(Align, Payment, Details, Term, downPayment, IncludeFreight, Freight, Type){	// LEASE PAYMENT
	
	Months = copy[lang]["months"];
	if(Details) Details += "<br/>";
	if(Months) Months += "<br/>";
	
	switch(Type){
		case "":  paymentType = copy[lang]["monthly"];
				  break;
		case "1": paymentType = copy[lang]["monthly"];
				  break;
		case "2": paymentType = copy[lang]["biweekly"];
				  break;
		case "4": paymentType = copy[lang]["weekly"];
				  break;
	}
	
	if(Align == "right")
		return "<span class='big'>" + Payment + "</span> <b>" + reverseWords(paymentType, copy[lang]["leasepayment"])  + "</b> <br/><span class='small'>" + Details + Term + " " + Months + downPayment + " " + copy[lang]["downpayment"] + "</span>";
	else
		return "<b>" + reverseWords(paymentType, copy[lang]["leasepayment"]) + putSpace() + ":</b><br/><span class='big'>" + Payment + "</span><br/><span class='small'>" + Details + Term + " " + Months + downPayment + " " + copy[lang]["downpayment"] + "</span>";
	
}

function pricing_purchase_cash(Align, Cash, Details){		// CASH PRICE LEFT
	if(Align == "left")
		return "<b>" + copy[lang]["cashpurchaseprice"] + putSpace() + ":</b><br/><span class='big'>" + Cash + "</span><br/><span class='small'>" + Details + "</span>";
	else
		return "<b>" + copy[lang]["cashprice"] + putSpace() + ":</b><br/><span class='big'>" + Cash + "</span><br/><span class='small'>" + Details + "</span>";
}

function pricing_cash(Cash, Details){		// CASH PRICE LEFT
	return "<b>" + copy[lang]["cashprice"] + putSpace() + ":</b> <span class='big'>" + Cash + "</span><br/><span class='small'>" + Details + "</span>"
}

function pricing_finance_payment(Align, Payment, Term, downPayment, IncludeFreight, Freight, Type, SmartPurchase){	// FINANCE PAYMENT

	switch(Type){
		case "":  paymentType = copy[lang]["monthly"];
				  break;
		case "1": paymentType = copy[lang]["monthly"];
				  break;
		case "2": paymentType = copy[lang]["biweekly"];
				  break;
		case "4": paymentType = copy[lang]["weekly"];
				  break;
	}

	if(IncludeFreight == "true" && Freight)
			FreightHTML = "<br/>" + Freight + " " + copy[lang]["freight"];
	else
			FreightHTML = "";

	Smart = (SmartPurchase == "true") ? "_smart" : "";

	if(Align == "right")
		return "<span class='big'>" + Payment + "</span> <b>" + reverseWords(paymentType, copy[lang]["financepayment" + Smart]) + "</b> <br/><span class='small'>" + Term + " " + copy[lang]["months"] + "<br/>" + downPayment + " " + copy[lang]["downpayment"] + FreightHTML + "</span>";
	else
		return "<b>" + reverseWords(paymentType, copy[lang]["financepayment" + Smart]) + putSpace() + ":</b> <span class='big'>" + Payment + "</span><br/><span class='small'>" + Term + " " + copy[lang]["months"] + "<br/>" + downPayment + " " + copy[lang]["downpayment"] + FreightHTML + "</span>";
}

function pricingStrategyTemplateTwo(Box1, Box2, OrLine, Strategy){

	return "<table width='500' class='psTemplate'><tr><td height='160' width='250' class='psTwo'>" + Box1 + "</td><td width='13' height='160' class='psTwo'><img height='61' alt='|' src='/images/financing/offers/rmab/divisions/" + division + "/pricing_vertical_div" + OrLine + ".gif'></td><td width='250' class='psTwo'>" + Box2 + "</td></tr></table>";

}
function pricingStrategyTemplate(Type, Box1, Box2, Box3, Box4, h1, h2, v, Strategy){
	
	sp = Type.split("/");
	
	var html = "";
	html += "<table width='500' class='psTemplate'><tr>";
	
	if(sp[1]){
		sp_top = sp[0].split("+");					// Top line
		if(sp[1]) sp_bottom = sp[1].split("+");		// Bottom line
		span_top = (!sp_top[1] && sp_bottom[1]) ? " colspan='3'" : "";
		span_bottom = (sp_bottom[1]) ? "" : " colspan='3'";
		span_div = (sp_top[1] || sp_bottom[1]) ? " colspan='3'" : "";
		
		top_first_width = (sp_top[1]) ? "250" : "500";
		bottom_first_width = (sp_bottom[1]) ? "250" : "500";
		
		html += "<td height='80' style='text-align:" + sp_top[0] + "; vertical-align:middle'" + span_top + " width='" + top_first_width + "'>" + Box1 + "</td>";
		if(sp_top[1]) html += "<td width='13' class='verticalAlign'><img src='/images/financing/offers/rmab/divisions/" + division + "/pricing_vertical_div" + h1 + ".gif' height='61' alt='|' /></td><td style='text-align:" + sp_top[1] + "; vertical-align:middle;' width='250'>" + Box2 + "</td>";
		
		if(sp[1]){ 
			html += "</tr><tr><td " + span_div + "><img src='/images/financing/offers/rmab/divisions/" + division + "/pricing_horizontal_div" + v + ".gif' width='500' height='13' alt='-' /></td></tr><tr><td height='80' style='text-align:" + sp_bottom[0] + "; vertical-align:middle'" + span_bottom + " width='" + bottom_first_width + "'>" + Box3 + "</td>";
			if(sp_bottom[1]) html += "<td width='13' class='verticalAlign'><img src='/images/financing/offers/rmab/divisions/" + division + "/pricing_vertical_div" + h2 + ".gif' height='61' alt='|' /></td><td style='text-align:" + sp_bottom[1] + "; vertical-align:middle;' width='250'>" + Box4 + "</td>";
		}
	}else{
		html += "<td height='160' style='text-align:" + Type + "; vertical-align:middle'>" + Box1 + "</td>";
	}
		
	
	html += "</tr></table><!--" + Strategy + "-->";
	
	return html;
	
}

function pricing(details, f, l, p, c, cashpriceor, pp, msrp, smart){	// create pricing strategies div

	//alert("finance = " + f + ", lease = " + l + ", purchaseprice = " + p + ", cashprice = " + c + ", cashpriceor = " + cashpriceor + ", pp = " + pp);
	
	var strategy = 0;				// strategy #
	var top_left = "";				// top left box
	var top_right = "";				// top right box
	var bottom_left = "";			// bottom left box
	var bottom_right = "";			// bottom right box
	
	if(f == "true" && 	l == "false" && p == "false" && c == "false" && pp == "false" && details["finance"]["displayAdvertisedRate"] == "true"){					// strategy #2
		strategy = 2;
		box1 = pricing_finance_rate(details["advertisedrate"], details["finance_detailcopy"], details["finance"]["effectiveRate"]);
		return pricingStrategyTemplate("center", box1, "" , "" , "" , "", "", "", strategy);
	}
		
	if(f == "false" && 	l == "false" && 	p == "true" && 		c == "false"){
		strategy = 3;
		box1 = pricing_purchase_price("right", details["cashprice"], details["purchase_detailcopy"]);				// strategy #3
		return pricingStrategyTemplate("center", box1, "" , "" , "" , "", "", "", strategy);
	}
	
	if(f == "true" && 	l == "false" && 	p == "true" && 		c == "false" && pp == "false"){									// strategy #9
		strategy = 9;
		box1 = pricing_finance_rate(details["advertisedrate"], details["finance_detailcopy"], details["finance"]["effectiveRate"]);
		box2 = pricing_purchase_price("right", details["cashprice"], details["purchase_detailcopy"]);
		return pricingStrategyTemplateTwo(box1, box2, "", strategy);
	}
		
	if(f == "false" && 	l == "true" && 		p == "false" && 	c == "false" && details["lease"]["displayPayment"] == "false"){									// strategy #13
		strategy = 13;
		box1 = pricing_purchase_lease_rate(details["lease"]["advertisedrate"], details["lease"]["rateCopy"], details["lease"]["effectiveRate"]);
		return pricingStrategyTemplate("center", box1, "" , "" , "" , "", "", "", strategy);
	}
		
	if(f == "false" && 	l == "true" && 		p == "true" && 		c == "false" 	&& 	details["lease"]["displayAdvertisedRate"] == "false"){									// strategy #14
		
		strategy = 14;
		box1 = pricing_purchase_lease_payment("left", details["lease"]["payment"], details["lease"]["paymentCopy"], details["lease"]["term"], details["lease"]["downpayment"], details["includeFreight"], details["freightamount"], details["lease"]["paymentType"]);
		box2 = pricing_purchase_price("right", details["cashprice"], details["purchase_detailcopy"]);
		return pricingStrategyTemplateTwo(box1, box2, "", strategy);
	}
	
		
		
	if(f == "false" && 	l == "true" && 		p == "false" && 	c == "false" && details["lease"]["displayPayment"] == "true"){									// strategy #15
		strategy = 15;
		box1 = pricing_purchase_lease_payment("left", details["lease"]["payment"], details["lease"]["paymentCopy"], details["lease"]["term"], details["lease"]["downpayment"], details["includeFreight"], details["freightamount"], details["lease"]["paymentType"]);
		box2 = pricing_purchase_lease_rate(details["lease"]["advertisedrate"], details["lease"]["rateCopy"], details["lease"]["effectiveRate"]);
		return pricingStrategyTemplateTwo(box1, box2, "", strategy);
	}
	
	/*
		!! CONFLICT WITH 28
		if(f == "true" && 	l == "false" && 	p == "false" && 	c == "true"){								// strategy #17
			strategy = 17;
			top_left = pricing_finance_rate(details["advertisedrate"], details["finance_detailcopy"]);
			bottom_right = pricing_purchase_cash("right", details["cashprice"], details["purchase_detailcopy"]);
			separator["h"] = "_or";
	}*/ 
		
	if(f == "false" && 	l == "false" && 	p == "false" && 	c == "true"){									// strategy #19
		strategy = 19;
		box1 = pricing_purchase_cash("left", details["cashprice"], details["purchase_detailcopy"]);
		return pricingStrategyTemplate("center", box1, "" , "" , "" , "", "", "", strategy);
	}
	

	if(f == "false" && 	l == "true" && 		p == "false" && 	c == "true" && details["lease"]["payment"] == ""){	// strategy #20
		strategy = 20;
		box1 = pricing_purchase_lease_rate(details["lease"]["advertisedrate"], details["lease"]["rateCopy"], details["lease"]["effectiveRate"]);
		box2 = pricing_purchase_cash("left", details["cashprice"], details["purchase_detailcopy"]);
		return pricingStrategyTemplateTwo(box1, box2, copy[lang]["or"], strategy);
	}

	if(f == "true" && 	l == "true" && 		p == "false" && 		c == "false" && details["lease"]["displayAdvertisedRate"] == "true" && details["lease"]["displayPayment"] == "false" && details["finance"]["displayAdvertisedRate"] == "true" ){									// strategy #21
		strategy = 21;
		box1 = pricing_purchase_lease_rate(details["lease"]["advertisedrate"], details["lease"]["rateCopy"], details["lease"]["effectiveRate"]);
		box2 = pricing_finance_rate(details["advertisedrate"], details["finance_detailcopy"], details["finance"]["effectiveRate"], true);
		return pricingStrategyTemplateTwo(box1, box2, copy[lang]["or"], strategy);
	}
			
	if(f == "true" && 	l == "true" && 		p == "false" && 	c == "true" && details["lease"]["payment"] == ""){									// strategy #22
		strategy = 22;
		box1 = pricing_purchase_lease_rate(details["lease"]["advertisedrate"], details["lease"]["rateCopy"], details["lease"]["effectiveRate"], true);
		box2 = pricing_finance_rate(details["advertisedrate"], details["finance_detailcopy"], details["finance"]["effectiveRate"], true);
		box3 = pricing_purchase_cash("right", details["cashprice"], details["purchase_detailcopy"]);
		return pricingStrategyTemplate("left+right/left", box1, box2 , box3 , "" , copy[lang]["or"], "", copy[lang]["or"], strategy);
	}
	
		
	if(f == "true" && 	l == "true" && 		p == "true" && 		c == "false" && details["lease"]["payment"] == ""){									// strategy #23
		strategy = 23;
		box1 = pricing_purchase_lease_rate(details["lease"]["advertisedrate"], details["lease"]["rateCopy"], details["lease"]["effectiveRate"], false);
		box2 = pricing_finance_rate(details["advertisedrate"], details["finance_detailcopy"], details["finance"]["effectiveRate"], true);
		box3 = pricing_purchase_price("left", details["cashprice"], details["purchase_detailcopy"]);
		return pricingStrategyTemplate("left+right/left", box1, box2 , box3 , "" , copy[lang]["or"], "", copy[lang]["or"], strategy);
	}
		
	if(f == "false" && 	l == "true" && 		p == "true" && 		c == "false" && details["lease"]["displayAdvertisedRate"] == "true" && details["lease"]["displayPayment"] == "true"){									// strategy #24
		strategy = 24;
		box1 = pricing_purchase_lease_payment("right", details["lease"]["payment"], details["lease"]["paymentCopy"], details["lease"]["term"], details["lease"]["downpayment"], details["includeFreight"], details["freightamount"], details["lease"]["paymentType"]);
		box2 = pricing_purchase_lease_rate(details["lease"]["advertisedrate"], details["lease"]["rateCopy"], details["lease"]["effectiveRate"], false);
		box3 = pricing_purchase_price("left", details["cashprice"], details["purchase_detailcopy"]);
		return pricingStrategyTemplate("left+right/left", box1, box2 , box3 , "" , "", "", copy[lang]["or"], strategy);
	}
		
	if(f == "true" && 	l == "true" && 		p == "false" && c == "true" && details["lease"]["payment"] != ""){									// strategy #25
		strategy = 25;
		box1 = pricing_purchase_lease_payment("right", details["lease"]["payment"], details["lease"]["paymentCopy"], details["lease"]["term"], details["lease"]["downpayment"], details["includeFreight"], details["freightamount"], details["lease"]["paymentType"]);
		box2 = pricing_purchase_lease_rate(details["lease"]["advertisedrate"], details["lease"]["rateCopy"], details["lease"]["effectiveRate"], true);
		box3 = pricing_finance_rate(details["advertisedrate"], details["finance_detailcopy"], details["finance"]["effectiveRate"], true);
		box4 = pricing_purchase_cash("right", details["cashprice"], details["purchase_detailcopy"]);
		return pricingStrategyTemplate("left+right/left+right", box1, box2 , box3 , box4 , "", copy[lang]["or"], copy[lang]["or"], strategy);
	}
		
	if(f == "true" && 	l == "true" && 		p == "false" && 	c == "false" && msrp == "true"){									// strategy #26
		strategy = 26;
		box1 = pricing_purchase_lease_payment("right", details["lease"]["payment"], details["lease"]["paymentCopy"], details["lease"]["term"], details["lease"]["downpayment"], details["includeFreight"], details["freightamount"], details["lease"]["paymentType"]);
		box2 = pricing_purchase_lease_rate(details["lease"]["advertisedrate"], details["lease"]["rateCopy"], details["lease"]["effectiveRate"], true);
		box3 = pricing_msrp(details["cashprice"], details["purchase_detailcopy"]);
		box4 = pricing_finance_rate(details["advertisedrate"], details["finance_detailcopy"], details["finance"]["effectiveRate"], true);
		return pricingStrategyTemplate("left+right/left+right", box1, box2 , box3 , box4 , "", copy[lang]["or"], copy[lang]["or"], strategy);
	}
	
	if(f == "false"&& 	l == "true" && 		p == "false" && 	c == "true"	&& details["lease"]["payment"] != "" && details["lease"]["displayAdvertisedRate"] == "false"){									// strategy #27
		strategy = 27;
		box1 = pricing_purchase_lease_payment("left", details["lease"]["payment"], details["lease"]["paymentCopy"], details["lease"]["term"], details["lease"]["downpayment"], details["includeFreight"], details["freightamount"], details["lease"]["paymentType"]);
		box2 = pricing_purchase_cash("left", details["cashprice"], details["purchase_detailcopy"]);
		return pricingStrategyTemplateTwo(box1, box2, copy[lang]["or"], strategy);
	}
	
	if(f == "true" && 	l == "false" && 	p == "false" && 	c == "true"  && pp == "false"){									// strategy #28
		strategy = 28;
		box1 = pricing_purchase_cash("right", details["cashprice"], details["purchase_detailcopy"]);
		box2 = pricing_finance_rate(details["advertisedrate"], details["finance_detailcopy"], details["finance"]["effectiveRate"]);
		return pricingStrategyTemplateTwo(box1, box2, copy[lang]["or"], strategy);
	}
	
	if(f == "true" && 	l == "false" && 	p == "false" && 	c == "false" && pp == "true" && details["finance"]["displayAdvertisedRate"] == "true"){					// strategy #29 OR #35
		strategy = (smart == "true") ? 35 : 29;
		
		box1 = pricing_finance_rate(details["advertisedrate"], details["finance_detailcopy"], details["finance"]["effectiveRate"], false, smart);
		box2 = pricing_finance_payment("left", details["payment"], details["term"], details["downpayment"], details["includeFreight"], details["freightamount"], details["finance"]["paymentType"], smart);
		return pricingStrategyTemplateTwo(box1, box2, copy[lang]["or"], strategy);
	}

	if(f == "true"&& 	l == "false" && 	p == "true" && 	c == "false" && pp == "true" && details["finance"]["displayAdvertisedRate"] == "false"){					// strategy #30
		strategy = 30;
		box1 = pricing_purchase_price("right", details["cashprice"], details["purchase_detailcopy"]);
		box2 = pricing_finance_payment("left", details["payment"], details["term"], details["downpayment"], details["includeFreight"], details["freightamount"], details["finance"]["paymentType"]);
		return pricingStrategyTemplateTwo(box1, box2, "", strategy);
	}

	if(f == "true" && 	l == "false" && 	p == "true" && 		c == "false" && pp == "true" && details["finance"]["displayAdvertisedRate"] == "true"){					// strategy #31 OR #36
	
		strategy = (smart == "true") ? 36 : 31;
		
		financingAlign = (smart == "true") ? "left" : "right";
		
		box1 = pricing_purchase_price("right", details["cashprice"], details["purchase_detailcopy"]);
		box3 = pricing_finance_payment(financingAlign, details["payment"], details["term"], details["downpayment"], details["includeFreight"], details["freightamount"], details["finance"]["paymentType"], smart);
		box4 = pricing_finance_rate(details["advertisedrate"], details["finance_detailcopy"], details["finance"]["effectiveRate"], true, smart);
		return pricingStrategyTemplate("right/left+right", box1, "" , box3 , box4 , "", "", "", strategy);
	}
	
	if(f == "true" && 	l == "false" && 	p == "false" && 	c == "true" && pp == "true" && details["finance"]["displayAdvertisedRate"] == "false"){					// strategy #32
		strategy = 32;
		box1 = pricing_cash(details["cashprice"], details["purchase_detailcopy"]);
		box2 = pricing_finance_payment("left", details["payment"], details["term"], details["downpayment"], details["includeFreight"], details["freightamount"], details["finance"]["paymentType"]);
		return pricingStrategyTemplateTwo(box1, box2, copy[lang]["or"], strategy);
	}
	
	if(f == "true" && 	l == "false" && 	p == "false" && 	c == "false" && pp == "true" && details["finance"]["displayAdvertisedRate"] == "false"){					// strategy #33
		strategy = 33;
		box1 = pricing_finance_payment("left", details["payment"], details["term"], details["downpayment"], details["includeFreight"], details["freightamount"], details["finance"]["paymentType"]);
		return pricingStrategyTemplate("right", box1, "" , "" ,"" , "", "", "", strategy);
	}
	
	if(f == "true" && 	l == "false" && 	p == "false" && 	c == "true" && pp == "true" && details["finance"]["displayAdvertisedRate"] == "true"){					// strategy #34 OR #37

		strategy = (smart == "true") ? 37 : 34;
		
		financingAlign = (smart == "true") ? "left" : "right";
		
		box1 = pricing_cash(details["cashprice"], details["purchase_detailcopy"]);
		box3 = pricing_finance_payment(financingAlign, details["payment"], details["term"], details["downpayment"], details["includeFreight"], details["freightamount"], details["finance"]["paymentType"], smart);
		box4 = pricing_finance_rate(details["advertisedrate"], details["finance_detailcopy"], details["finance"]["effectiveRate"], true, smart);
		return pricingStrategyTemplate("right/left+right", box1, "" , box3 ,box4 , "", "", copy[lang]["or"], strategy);
	}
	


	return "";
	
}

/* -------------------------  TABS CREATOR -----------------------------------*/

function buildTabs(Index){									// Generate tabs layout

	$("#offer-tabs").html("");
	
	$(".tab_left_arrow").css("display","block");
	$(".tab_right_arrow").css("display","block");
	
	if(Index == 0)
		$(".tab_left_arrow").css("display","none");
	
	if(Index+_DisplayTabs >= TabsCount)
		$(".tab_right_arrow").css("display","none");
	
	for(x=Index;x<Index+_DisplayTabs;x++){

		count = x+ 1 - Index;
		if(TabsArray[x]){
			if(TabsArray[x].active == true){
				ActiveCss = " class='active'";
				CornerActive = "_up";
			}else{
				ActiveCss = " class='item_" + count + "'";
				CornerActive = "";
			}
			
			Title = TabsArray[x].name.substr(5);
			Name = TabsArray[x].name.replace(Title, "<b>" + Title + "</b>");

			$("<li><a href='#' onclick='return detailsPage(" + TabsArray[x].id + ")' " + ActiveCss + "><img src='/images/financing/offers/rmab/divisions/" + division + "/tab" + CornerActive + "_crl.gif' class='cr_left' alt=''><div>" + Name + "</div><img src='/images/financing/offers/rmab/divisions/" + division + "/tab" + CornerActive + "_crr.gif' class='cr_right' alt=''></a></li>").appendTo("#offer-tabs");
			
		}
	
	}
	
	horizontalTrick();	
	
}

function addTab(Name, offerId, Code, Model, Active){		// Add new tab to tabs array
	TabsArray.push({
					name: Name,
					id: offerId,
					code: Code,
					model: Model,
					active: Active
				   });
	
	TabsCount++;
	
}

function createTabs(Model, Year, offer, changeModel){				// Create new tabs object
	
	TabsArray = new Array();
	TabsCount = 0;

	if(changeModel == true)
		TabsIndex = 0;
	
	$.each(Offers[Model + "|" + Year], function(i, value){	
		if(offer == value["ID"])	
			Active = true;
		else 
			Active = false;
		addTab(value["Title"], value["ID"], value["vehCode"], value["vehModel"], Active);
	});
		
	buildTabs(TabsIndex);
	
}

function nextTab(){
	TabsIndex++;
	buildTabs(TabsIndex);
	return 0;
}

function prevTab(){
	TabsIndex--;
	buildTabs(TabsIndex);
	return 0;
}

/* -------------------------  LEASING -----------------------------------*/

function leasingRates(offerId, Legal){
	
	var count = 0;
	$(xmlInitial).find("offer:has(offerId:contains(" + offerId + ")) row:first col").each(function(){
			count++;																					   
	});
	
	var table = "<table class='leasingTable'><thead><tr>";
	var width = Math.round(660 / count);
	if(width > 500) width = 200;
	
	$(xmlInitial).find("offer:has(offerId:contains(" + offerId + ")) row:first col").each(function(){
		table += "<td width='" + width + "'>" + $(this).text() + "</td>";																						   
	});
	table += "</tr></thead><tbody><tr>";
	
	i = 0;
	$(xmlInitial).find("offer:has(offerId:contains(" + offerId + ")) row:gt(0) col").each(function(){
		table += "<td>" + $(this).text() + "</td>";
		i++;
		if(i == count){
			table += "</tr><tr>";
			i = 0;
		}
	});
	
	table += "</tr></table><br/><span class='windowText'>" + Legal + "</span>";

	return table;
	
}

/* ------------------------------------------------------------------------------------------------
   EVENT BANNERS FUNCTION
   ------------------------------------------------------------------------------------------------ */
   
function eventBanner(){
	$.ajax({
		url: "/images/financing/offers/rmab/banners/xml/" + division +  ".xml",
		dataType: ($.browser.msie) ? "text" : "xml",
		async: true,
		cache: true,
		error: function(xhr, ajaxOptions, thrownError){
					bannerImage = "/images/financing/offers/rmab/banners/new/" + division + "_default_" + lang + ".jpg";
					bannerAlt = copy[lang][division + "_banner_default"];
					
		},		
		success: function(xmlBanners){
					//work around for IE
					
					var tempXMLBanners;
					if (typeof xmlBanners == "string") {
					   tempXMLBanners = new ActiveXObject("Microsoft.XMLDOM");
					   tempXMLBanners.async = false;
					   tempXMLBanners.loadXML(xmlBanners);
					   xmlBanners = tempXMLBanners;
					}
		
					xmlInitialBanners = xmlBanners;		
					count = 0;
					$(xmlInitialBanners).find("regions " + region + " item").each(function(){
						bannerImage = $(this).children("image[@lang=" + lang + "]").text();	
						bannerHref = $(this).children("link[@lang=" + lang + "]").text();
						count++;
					});
					if(count == 0){
						bannerImage = "/images/financing/offers/rmab/banners/new/" + division + "_default_" + lang + ".jpg";
						bannerAlt = copy[lang][division + "_banner_default"];
					}
			}
		});	
	
}


/* ------------------------------------------------------------------------------------------------
   SITE CATALIST
   ------------------------------------------------------------------------------------------------ */
   
function siteCatalist(Name, Model){
	
	if(divisionTitle == "Gmc")
				divisionTitle = divisionTitle.toUpperCase();
	
	if(pageName == "RMAB")
		sitecat_Prop7 = (Model) ? Model : division.toUpperCase();
		
	sitecat_Prop6 = divisionTitle;
	
	Name = (Name && Name != '') ? " - " + Name : "";
	Model  = (Model) ? " - " + Model : "";
	
	if(pageName == "RMAB"){
		sitecat_PageName 	= copy["en"][region] + " " + divisionTitle + " " + copy["en"]["dealers"] + Name + Model;
		sitecat_Channel 	= copy["en"][region] + " " + divisionTitle + " " + copy["en"]["dealers"] + " Site";
	}else{
		sitecat_PageName 	= "Offer Search - " + divisionTitle + " - " + copy["en"][region] + " - " + Llanguage + Model;
		sitecat_Channel		= "Offers & Programs";
	}
	
	if(Model){
	
		s.pageName=sitecat_PageName;
		s.server="gm.ca";
		s.channel=sitecat_Channel;
		s.prop2=Llanguage;
		s.prop3="";
		s.prop4="";
		s.prop5="";
		s.prop6=sitecat_Prop6;
		s.prop7=sitecat_Prop7;
		s.eVar1="";
		s.products="";
		s.eVar3="";
		s.eVar10="";
		s.events="";
		
		s.t();
	}
	
}


/* -------------------------  OTHER STAFF -----------------------------------*/

function setCSS(division){			// Sets CSS for division web
	
	if(division != "chevrolet" && division != "buick" && division != "cadillac" && division != "gmc" && division != "pontiac"){
		document.location = "/gm";
		return false;
	}
	
	filename = "/css/financing/offers/rmab_div_" + division + ".css";
	var ref=document.createElement("link");
	ref.setAttribute("rel", "stylesheet");
	ref.setAttribute("type", "text/css");
	ref.setAttribute("href", filename);
	document.getElementsByTagName("head")[0].appendChild(ref)
	
	$(".findDealer_box").css("background-image","url(/images/financing/offers/rmab/divisions/" + division + "/find_dealer_" + lang + ".png)");

}

function setPageTittle(Name, Region, Copy, Year, Model, ExtraCopy){		// Sets page title and header
	
	var RMAB = (!currentOffers) ? "RMAB " : "";

	if(Region == undefined)
		Region = "";
	
	var AddExtraCopy = (ExtraCopy) ? "<br/><div class='extraHeaderCopy'>" + ExtraCopy + "</div>" : "";
	
	if(lang == "en"){
		if(Year && Model)
			ModelTitle = " - " + Year + " " + Model;
		else
			ModelTitle = "";
			
		$("#headerMain h1").html(Region + " " + Name + " " + Copy + AddExtraCopy);
		document.title = RMAB + Region + " " + Name + " " + Copy + ModelTitle;
	}else{
		if(Year && Model)
			ModelTitle = " - " + Model + " " + Year;
		else
			ModelTitle = "";
		
		if(currentOffers == true && region == "alberta" && division == "cadillac")
			$("#headerMain h1").html("<span style='font-size:24px'>" + Copy + " " + Name + " " + Region + "</span>" + AddExtraCopy);
		else
			$("#headerMain h1").html(Copy + " " + Name + " " + Region + AddExtraCopy);
			
		document.title = RMAB + Copy + " " + Name + " " + Region.replace("&#233;","\u00E9") + ModelTitle;
	}
	
	//if(currentOffers == true)
	//		$("#rmabTitle").html($("#rmabTitle").html() + "*");
	

}

function featuresList(list, count){		// Create two lists of features
	var div = Math.floor(count / 2);
	var activeList = "#featuresListLeft";
	x = 0;

	while(list[x]){
		if(x > div && count > 7)	
			activeList = "#featuresListRight";
		$("<li>" + list[x] + "</li>").appendTo(activeList);
		x++;
		
	}
}

// Return query string value, given the key
// If no default is given, it will return empty string
function getQueryString(key, default_) {
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
} 

function displayNoResultsText() {		// Display message if there is no results in carousel

	// Try to match the correct region
	var myPath = "services/goodwrench/offers" // General
	if (region == "ontario") { myPath = "maintenance/goodwrench/gwspecials/gw_on_offer01"; } // Ontario
	else if (region == "bc") { myPath = "maintenance/goodwrench/gwspecials/gw_bc_offer01"; } // BC
	else if (region == "maritime") { myPath = "maintenance/goodwrench/gwspecials/gw_atlantic_offer01"; } // Maritime

	if (lang == "fr") {
		var txt = '<p>Nous sommes en train de mettre &#224; jour les offres dans ce code postal. Veuillez <a href="http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do?nav=' + makeCodesArr[division] + '&' + namePlate[division] + '=' + makeCodesArr[division] + '&cta=blank&lang=fr"> contacter votre concessionaires</a> pour les offres les plus r&#233;centes.<br/><br/>';
		txt += 'Vous avez besoin de service? Voyez nos offres de <a href="/gm/french/'+myPath+'">service Goodwrench</a>.</p>';
	} else {
		var txt = '<p>We are updating our offers. Please <a href="http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do?nav=' + makeCodesArr[division] + '&' + namePlate[division] + '=' + makeCodesArr[division] + '&cta=blank&lang=en">contact your dealer</a> for the latest available offers.<br/><br/>';
		txt += 'Need Service? See our <a href="/gm/english/'+myPath+'">Goodwrench offers</a>.</p>';
	}

	$("#ajax_loading").html(txt);
}

function setDivLink(){		// Sets link in header and footer
	switch(division){
		case "chevrolet":
							$(".divLink").html("chevrolet.ca");
							$(".divLink").attr("href","/gm/" + language + "/vehicles/chevrolet/");
							break;
		case "cadillac":
							$(".divLink").html("cadillac.ca");
							$(".divLink").attr("href","/gm/" + language + "/vehicles/cadillac/");
							break;
		case "buick":
							$(".divLink").html("buick.ca");
							$(".divLink").attr("href","/gm/" + language + "/vehicles/buick/");
							break;
		case "gmc":
							$(".divLink").html("gmc.gm.ca");
							$(".divLink").attr("href","/gm/" + language + "/vehicles/gmc/");
							break;
	}
}

function openListLink(Option){
	
	switch(Option){
		case "1":		document.location = "/gm/" + language + "/hostredirect?host=http://apps.gm.ca/app/mygm/GetUserInfo.do&request=access,lastsavedconfig&goto=http%3A%2F%2Fconfigurator%2Eautodata%2Egm%2Eca%2FGMCanada%2FmodelSelect%2Ehtml%3Flang%3D" +lang + "%26model%3D" + actualModel + "%26package%3D" + actualPackage +"%26brand%3D" + makeCodesArr[division] + "%26year%3D" + actualYear;
						break;
		case "2":		document.location = "/gm/" + language + "/payment-estimator/calculator?year=" + actualYear + "&modelCode=" + actualModel + "&packageCode=" + actualPackage + "&postalCode=";
						break;
		case "3":		document.location = "/gm/" + language + "/hostredirect?host=http://compare.autodata.gm.ca/compare/main.asp&lang=" + lang + "&model=" + actualModel + "&package=" + actualPackage +"&brand=" + makeCodesArr[division] + "&year=" + actualYear;
						break;
		case "4":		document.location = "/gm/" + language + "/hostredirect?host=http://apps.gm.ca/app/GMCanada/NewVehicleLocatorCriteria.do&lang=" + lang + "&nav=" + makeCodesArr[division] + "&cta=blank&search_year=" + actualYear + "&search_model_designator=" + actualModel + "&search_nameplate=" + makeCodesArr[division] + "&search_url=&search_pkgcd=" + actualPackage +"&search_mktcd=";
						break;
		case "5":		document.location = "/gm/" + language + "/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=" + makeCodesArr[division] + "&cta=blank&lang=" + lang + "&" + namePlate[division] + "=" + makeCodesArr[division];
						break;
		case "6":		document.location = "javascript:openSRAQ('/gm/" + language + "/hostredirect?host=https://apps.gm.ca/app/GMCanada/ContactADealer.do&lang=" + lang + "&raqSource=scheduleTestDrive&scheduleSubSource=new&year=" + actualYear  + "&modelDesignator=" + actualModel + "&nav=" + makeCodesArr[division] + "&nameplate=" + makeCodesArr[division] + "')";
						break;
		case "7":		document.location = "javascript:openSRAQ('/gm/" + language + "/hostredirect?host=https://apps.gm.ca/app/GMCanada/ContactADealer.do&lang=" + lang + "&raqSource=scheduleTestDrive&scheduleSubSource=new&year=" + actualYear  + "&modelDesignator=" + actualModel + "&nav=" + makeCodesArr[division] + "&nameplate=" + makeCodesArr[division] + "')";
						break;
	}
	
}

function horizontalTrick(){				// ------------ Makes tabs horizontal align
		$("#offer-tabs li div").each(function(){
			if(this.clientHeight < 24 && this.clientHeight > 0)
				this.className = "horizontal";
		});
}

function reverseWords(Word1, Word2){
	if(lang == "fr")
		return Word2 + " " + Word1;
		
	return Word1 + " " + Word2;
}


function setCookie(name, value, expires, path, domain, secure) {
		domain = location.toString();
		if (domain.indexOf('.gm.ca') != -1){
			if(navigator.appName.indexOf('Microsoft') != -1)
				domain = "";
			else{
				domain = ".gm.ca";
			}
		}
		else if(domain.indexOf('.mminteractive.com') != -1){
			if(navigator.appName.indexOf('Microsoft') != -1)
				domain = "";
			else{
				domain = ".mminteractive.com";
			}
		}
		else{
			domain ="";
		}
		var curCookie = name + '=' + escape(value) + ((expires) ? '; expires=' + expires.toGMTString() : '') + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '') + ((secure) ? '; secure' : '');
		document.cookie = curCookie;
}

function getCookie(name) {
	// There is something very flakey with this function. Probably explains why at some unknown time some unknown person created the function get_cookie to be found later in this file.  Why they didn't document this decision makes baby Jesus cry. It cost me a couple of hours of work but that is besides the point.  I'm not trashing this function because I think it does work in certain contexts and is probably being used, but it doesn't seem to function predictably. I wouldn't use it if I were you. <3 JRB
	// I think I have fixed this flakeyness, seems fine now - PJ
	
	var dc = document.cookie;

	// find beginning of cookie value in document.cookie
	var prefix = name + "=";
	
	var begin = dc.indexOf("; " + prefix);
	//alert(begin);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	}
	else begin += 2;

	// find end of cookie value
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) end = dc.length;

	// return cookie value
	return unescape(dc.substring(begin + prefix.length, end));
}

function validatePostalCode() {

	var postalCode = $("#postalCodeForm input[type=text]").get(0).value.toUpperCase().replace(/\s/,''); // get postal code input, strip whitespace

	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));

	var pcRegExp = /(^\D{1}\d{1}\D{1}\s?\d{1}\D{1}\d{1}$)/;

	if (pcRegExp.test(postalCode)) {

		$("#postalCodeForm input[type=text]").get(0).value = postalCode;

		setCookie("pc",postalCode, cookieExpiresDate, "/");
		
		document.getElementById("postalCodeForm").submit();

		return true;

	} 

	else {

		if(lang == "fr") {
			alert("D\u00E9sol\u00E9! Le code postal vous avez entr\u00E9 n'est pas valide. Veuillez re-entrez votre code postal et essayez encore. (Un code postal canadien valide doit inclure des lettres (a) et des nombres (#) dans l'ordre suivant : a#a #a#)");
		} else {
			alert("Sorry!The postal code you have entered is not valid. Please re-enter your postal code and try again.(A valid Canadian postal code includes letters (A) and numbers (#) in the following sequence: A#A #A#)");
		}
		
		return false;

	}

}

function putSpace(){
	if(lang == "fr")
		return " ";
	else
		return "";
}

function fixIE6(){
		switch(division){
			case "chevrolet":
								$(".details").css("height", "364px");
								$(".offer-left").css("height", "364px");
								$("#pricingStrategies").css("height", "176px");
								break;
			case "buick":
								$(".details").css("height", "371px");
								$(".offer-left").css("height", "364px");
								$("#pricingStrategies").css("height", "185px");
								break;
			case "cadillac":
								$(".details").css("height", "364px");
								$(".offer-left").css("height", "364px");
								$("#pricingStrategies").css("height", "184px");
								break;
			case "gmc":
								$(".details").css("height", "387px");
								$(".offer-left").css("height", "364px");
								$("#pricingStrategies").css("height", "195px");
								break;
		}
}
