// JavaScript Document

var sbtSelectedCarData = new Object();
sbToolsCookies = new Array();
sbtBrandName = "GMFLEET"; // Update for every brand
mmcValue = 0;
var styleValue = "";

// Used for the MMC search
found  = false;
yearFound = false;

sbtCookiesNames = new Array(
	"mySelectedYear",
	// Cookies for Dealer Search Parameters
	"sbtZipCode",
	"sbtZipProximity",
	"sbtCityName",
	"sbtCityState",
	"sbtCityProximity",
	"sbtSearchDealerName",
	"sbtCityNameDealer",
	"sbtCityStateDealer",
	"sbtSearchCountry", 
	"sbtSearchType", 
	//Cookies for multibrand, GMC and Chevrolet sites
	"sbtDealerTypeCode",
	"sbtAgreementTypeCode",
	"sbtProgramCode",
	"sbtProgramICON",
	"sbtSelectedBrand",
	"sbtSelectedGMFleetProgram",
	// Cookies for Trim Package
	"mySelectedStyle",
	"sbtMsrPrice",
	"sbtTrimName",
	"sbtStyle",
	// Cookies for Vehicle Selection
	"mySelectedType", 
	"sbtModelDesignator",
	"mySelectedBrand", 
	"sbtBrand",
	"sbtModelCode", 
	"sbtSubModelCode", 
	"sbtCabType", 
	"sbtBoxType", 
	"sbtDriveType", 
	"sbtModel", 
	"sbtPrice", 
	"sbtImage",
	// Cookies for Selected Dealer
	"sbtBAC",
	"sbtDealerName",
	"sbtDealerDistance",
	"sbtGmbpManager",
	"sbtDealerStreet",
	"sbtDealerCity",
	"sbtDealerState",
	"sbtDealerPostalCode",
	"sbtDealerPhone",
	"sbtDealerFax",
	"sbtDealerWebsite",
	"sbtDealerMap",
	"sbtDealerDirections",
	"sbtDealerWd",
	// Cookies compatible with Comparator
	"mySelectedModel",
	// Cookies for omniture
	"setionOmni"
);

function readSBTCookie(sbtCookieName) {
	var arrayName = sbtCookieName.toLowerCase();
	if (sbToolsCookies[arrayName] == null)
		sbToolsCookies[arrayName] = readCookie(sbtCookieName);
	return sbToolsCookies[arrayName];
}

function createSBTCookie(sbtCookieName, sbtCookieValue, lifeTime) {
	var arrayName = sbtCookieName.toLowerCase();
	sbtCookieValue = getValidString(sbtCookieValue);
	sbToolsCookies[arrayName] = sbtCookieValue;
	createCookie(sbtCookieName, sbToolsCookies[arrayName], lifeTime);
}

function updateSBTCookie(sbtCookieName, sbtCookieValue, lifeTime) {
	var arrayName = sbtCookieName.toLowerCase();
	sbtCookieValue = getValidString(sbtCookieValue);
	sbToolsCookies[arrayName] = sbtCookieValue;
	eraseCookie(sbtCookieName);
	createCookie(sbtCookieName, sbToolsCookies[arrayName], lifeTime);
}

function eraseSBTCookie(sbtCookieName) {
	var arrayName = sbtCookieName.toLowerCase();
	sbToolsCookies[arrayName] = null;
	cookieErase(sbtCookieName);	
}

function readAllSBToolsCookies() {
	for (var i = 0; i < sbtCookiesNames.length; i++) {
		readSBTCookie(sbtCookiesNames[i]);
		if (sbToolsCookies[sbtCookiesNames[i].toLowerCase()] == null)
			sbToolsCookies[sbtCookiesNames[i].toLowerCase()] = "";
	}
	loadSelectedComparatorCarData();
}

function saveAllSBTStoredCookies() {	
	for (var i = 0; i < sbtCookiesNames.length; i++) {
		var arrayName = sbtCookiesNames[i].toLowerCase();
		if (sbToolsCookies[arrayName] != null && sbToolsCookies[arrayName] != "")
			updateSBTCookie(sbtCookiesNames[i], sbToolsCookies[arrayName], 30);
	}
}

function eraseAllSBTStoredCookies() {	
	for (var i = 0; i < sbtCookiesNames.length; i++) {
		if(sbtCookiesNames[i] != "setionOmni" && sbtCookiesNames[i] != "sbtZipCode"){
			eraseSBTCookie(sbtCookiesNames[i]);	
		}		
	}
}

function eraseTrimCookies() {
	eraseSBTCookie("mySelectedStyle");
	eraseSBTCookie("sbtMsrPrice");
	eraseSBTCookie("sbtTrimName");
}

function eraseCarCookies() {
	eraseSBTCookie("mySelectedType"); 
	eraseSBTCookie("sbtModelDesignator");
	eraseSBTCookie("mySelectedBrand"); 
	eraseSBTCookie("sbtModelCode"); 
	eraseSBTCookie("sbtSubModelCode"); 
	eraseSBTCookie("sbtCabType"); 
	eraseSBTCookie("sbtBoxType"); 
	eraseSBTCookie("sbtDriveType"); 
	eraseSBTCookie("sbtModel"); 
	eraseSBTCookie("sbtPrice"); 
	eraseSBTCookie("sbtImage");
	eraseSBTCookie("sbtStyle");//ADDED
}


function loadSelectedComparatorCarData() { 
	if (!carCookiesPresent()) {
		var year = sbToolsCookies["myselectedyear"];
		var submodel = sbToolsCookies["myselectedmodel"].split(",")[1];
		var mmc = sbToolsCookies["myselectedtype"];
		var pvc = sbToolsCookies["myselectedstyle"];
	
		// If the whole data truly exists
		if (!isEmptyString(year) && !isEmptyString(submodel) && !isEmptyString(mmc) && !isEmptyString(pvc)) {			
			loadCarData(sbtBrandName, year , submodel , mmc , pvc);
			updateSBTCookie("sbtModelDesignator", sbtSelectedCarData["mmc"], 30);
			updateSBTCookie("mySelectedBrand", sbtSelectedCarData["description"], 30);
			updateSBTCookie("sbtModelCode", sbtSelectedCarData["modelcode"], 30);
			updateSBTCookie("sbtSubModelCode", sbtSelectedCarData["submodelcode"], 30);
			updateSBTCookie("sbtCabType", sbtSelectedCarData["cabtype"], 30);
			updateSBTCookie("sbtBoxType", sbtSelectedCarData["boxtype"], 30);
			updateSBTCookie("sbtDriveType", sbtSelectedCarData["drivetype"], 30);
			updateSBTCookie("sbtModel", sbtSelectedCarData["model"], 30);
			updateSBTCookie("sbtPrice", sbtSelectedCarData["msrp"], 30);
			updateSBTCookie("sbtImage", sbtSelectedCarData["imagelocation"], 30);
			updateSBTCookie("sbtSearchCountry", "US", 30);
			updateSBTCookie("sbtSearchType", "0", 30);
			updateSBTCookie("sbtModel", sbtSelectedCarData["model"], 30);
			updateSBTCookie("sbtMsrPrice", sbtSelectedCarData["msrp"], 30);
			updateSBTCookie("sbtTrimName", sbtSelectedCarData["style"], 30);
		}
	}
}

function carCookiesPresent() { 
	var allPresent = true;
	
	allPresent &= (sbToolsCookies["myselectedtype"] != null && sbToolsCookies["myselectedtype"] != "");
	allPresent &= (sbToolsCookies["sbtmodeldesignator"] != null && sbToolsCookies["sbtmodeldesignator"] != "");
	allPresent &= (sbToolsCookies["myselectedbrand"] != null && sbToolsCookies["myselectedbrand"] != "");
	allPresent &= (sbToolsCookies["sbtmodelcode"] != null && sbToolsCookies["sbtmodelcode"] != "");
	allPresent &= (sbToolsCookies["sbtsubmodelcode"] != null && sbToolsCookies["sbtsubmodelcode"] != "");
	allPresent &= (sbToolsCookies["sbtcabtype"] != null);
	allPresent &= (sbToolsCookies["sbtboxtype"] != null);
	allPresent &= (sbToolsCookies["sbtdrivetype"] != null && sbToolsCookies["sbtdrivetype"] != "");
	allPresent &= (sbToolsCookies["sbtmodel"] != null && sbToolsCookies["sbtmodel"] != "");
	allPresent &= (sbToolsCookies["sbtprice"] != null && sbToolsCookies["sbtprice"] != "");
	allPresent &= (sbToolsCookies["sbtimage"] != null && sbToolsCookies["sbtimage"] != "");
	allPresent &= (sbToolsCookies["sbtsearchcountry"] != null && sbToolsCookies["sbtsearchcountry"] != "");
	allPresent &= (sbToolsCookies["sbtsearchtype"] != null && sbToolsCookies["sbtsearchtype"] != "");
	
	return allPresent;
}

function trimCookiesPresent() {
	var allPresent = true;
	
	allPresent &= (sbToolsCookies["myselectedstyle"] != null && sbToolsCookies["myselectedstyle"] != "");
	allPresent &= (sbToolsCookies["sbtmsrprice"] != null && sbToolsCookies["sbtmsrprice"] != "");
	allPresent &= (sbToolsCookies["sbttrimname"] != null && sbToolsCookies["sbttrimname"] != "");
	
	return allPresent;
}

function dealerCookiesPresent() {
	var allPresent = true;
	
	allPresent &= (sbToolsCookies["sbtbac"] != null && sbToolsCookies["sbtbac"] != "");
	allPresent &= (sbToolsCookies["sbtdealername"] != null && sbToolsCookies["sbtdealername"] != "");
	allPresent &= (sbToolsCookies["sbtdealerdistance"] != null && sbToolsCookies["sbtdealerdistance"] != "");
	allPresent &= (sbToolsCookies["sbtgmbpmanager"] != null);
	allPresent &= (sbToolsCookies["sbtdealerstreet"] != null && sbToolsCookies["sbtdealerstreet"] != "");
	allPresent &= (sbToolsCookies["sbtdealercity"] != null && sbToolsCookies["sbtdealercity"] != "");
	allPresent &= (sbToolsCookies["sbtdealerstate"] != null && sbToolsCookies["sbtdealerctate"] != "");
	allPresent &= (sbToolsCookies["sbtdealerpostalcode"] != null && sbToolsCookies["sbtdealerpostalcode"] != "");
	allPresent &= (sbToolsCookies["sbtdealerphone"] != null);
	allPresent &= (sbToolsCookies["sbtdealerfax"] != null);
	allPresent &= (sbToolsCookies["sbtdealerwebsite"] != null);
	allPresent &= (sbToolsCookies["sbtdealermap"] != null);
	allPresent &= (sbToolsCookies["sbtdealerdirections"] != null);
	
	return allPresent;
}

function getValidString(text) {
	if (text == null || text == "undefined")
		return "";
	else
		return text.replace("\r\n", "");
}

function isEmptyString(text) {
	return (text == null || text == "");
}

//required to format the price
function formatPrice(price){
	var ret;
	if (price != '999999.00' && price != '999,999.00' && price != " N"){
		var fixedPrice = price.replace(/,/g,"");
		decimalPos = fixedPrice.indexOf('.');
		//if the price has decimal, just in case
		if (decimalPos >= 0)
			ret  = fixedPrice.substring(0,fixedPrice.length-6) + ","+   fixedPrice.substring((fixedPrice.length-6),fixedPrice.length)
	}else{
		ret = 'N/A';
	}
	return ret; 
}


/******************************************
Following functions retrieve the full
vehicle data selected from different tools
*******************************************/

/********************************************************************/
/***********   Load the XML file   *************/
/********************************************************************/
function loadCarData(brand , year , submodel , mmc , pvc){				
	if (window.ActiveXObject){
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		xmlDoc.onreadystatechange = function () {
			if (xmlDoc.readyState == 4)OnCarDataLoaded(brand , year , submodel , mmc , pvc);
		};
		xmlDoc.load("/xml/brandInfo.xml");
	}
	else if (document.implementation && document.implementation.createDocument){ 
		xmlDoc = new XMLHttpRequest();
		xmlDoc.onreadystatechange = function () {
			if (xmlDoc.readyState == 4)OnCarDataLoaded(brand , year , submodel , mmc , pvc);
		};
		if (xmlDoc != null) {
			xmlDoc.open("GET","/xml/brandInfo.xml", false);
			xmlDoc.send(null);
		}
	}
}

/********************************************************************/
/***********   Load the first elements of the XML file   *************/
/********************************************************************/
function OnCarDataLoaded(brand , year , submodel , mmc , 	pvc){ 
		
	//fist elemets of the XML file	
    allBrandsNode = (window.ActiveXObject) ? xmlDoc.documentElement  :  xmlDoc.responseXML.documentElement;

    //values to search for
	ids 	  = new Array(brand , year , submodel , mmc , pvc);
	
	//index of the attributes to compare with the values
	attrIndex = new Array('0'   , '0'  , '4'   , '3' , '1');	
	
	//go through all the elements
	goToElements(0 ,  ids ,  allBrandsNode);
}


/********************************************************************/
/***********   go for each elemet of the XMl file    ****************/
/********************************************************************/
function goToElements(index , ids , Elements){ 
		//stop then there is no more values to compare with
		if (index < 5){
			    var i = 0;
				while (i < Elements.childNodes.length){
							if (Elements.childNodes[i].nodeType == 1){ // This get rides of #text belonging to "whitespaces" for FF
								if (ids[index] == Elements.childNodes[i].attributes[attrIndex[index]].value)
								{	
									//go to the next element
									goToElements( ++index ,  ids ,   Elements.childNodes[i]);
									
									//get the values of the attributes
									getCarValues(Elements.childNodes[i].attributes);
									
									break;
								}					
							}
					i++;
				}
		}
}

/********************************************************************/
/*******  go for each attribute of the XML file and get its value  **/
/********************************************************************/
function getCarValues(attributes){ 
	var j = 0;
	
	//for each attribute get te value 
	while (j < attributes.length){
		sbtSelectedCarData[attributes[j].nodeName.toLowerCase()] = attributes[j].nodeValue;
		j++;
	}
}

/******************************************
Following functions retrieve the MMC code
using the PVC for a given vehicle
*******************************************/
function getRequest() { 
    var xmlhttp=false;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    // JScript gives us Conditional compilation, we can cope with old IE versions.
    // and security blocked creation of the objects.
     try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
      try {
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
       xmlhttp = false;
      }
     }
    @end @*/
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') { 
        try { 
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            xmlhttp=false;
        }
    }
    if (!xmlhttp && window.createRequest) { 
        try {
            xmlhttp = window.createRequest();
        } catch (e) {
            xmlhttp=false;
        }
    }

    return xmlhttp;
}

/********************************************************************/
/***********   Load the XML file   *************/
/********************************************************************/
function loadXML() { 
	var request = getRequest();
    request.open("get", "/xml/brandInfo.xml", false);
    request.send(null);
	xmlDoc = request.responseXML;
}


/******************************************
Following functions retrieve the MMC code
using the PVC for a given vehicle
*******************************************/

/********************************************************************/
/***********   Load the XML file   *************/
/********************************************************************/

function getMMCFromPVC(pvc , year){	

	
	if (window.ActiveXObject){
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		xmlDoc.onreadystatechange = function () {
			if (xmlDoc.readyState == 4)OnMMCXMLLoaded(pvc , year);
		}
			xmlDoc.load("/xml/brandInfo.xml");
	}
	else if (document.implementation && document.implementation.createDocument){
		xmlDoc = new XMLHttpRequest();
		xmlDoc.onreadystatechange = function () {
			if (xmlDoc.readyState == 4)OnMMCXMLLoaded(pvc , year);
		};
		if (xmlDoc != null) {
			xmlDoc.open("GET","/xml/brandInfo.xml", false);
			xmlDoc.send(null);
		}
	}
}


/********************************************************************/
/***********   Load the first elements of the XML file   *************/
/********************************************************************/
function OnMMCXMLLoaded(pvc , year){ 
	//fist elemets of the XML file	
    //allBrandsNode = (window.ActiveXObject) ? xmlDoc.documentElement  :  xmlDoc.responseXML.documentElement;
		allBrandsNode = '';
	
	// keep the mmc value
	mmcValue = 0;
	
	//flag to know when the pvc is found
	found  = false;
	
	//year to search in
	yearFound = false;
	
	// search for the element that have mmc values
	getMMC(pvc , allBrandsNode , year)
}


function searchByPCV(pvc , year){
	//fist elemets of the XML file	
    allBrandsNode = xmlDoc.documentElement;
	
	// keep the mmc value
	mmcValue = 0;
	
	//flag to know when the pvc is found
	found  = false;
	
	//year to search in
	yearFound = false;
	
	// search for the element that have mmc values
	getMMC(pvc , allBrandsNode , year)
}

/********************************************************************/
/***********   go for each elemet of the XMl file    ****************/
/********************************************************************/
function getMMC(pvc ,  Elements , year){ 
		var i = 0;	
		
		//stop when the pvc was found
		if (!found){	    
				while ((i < Elements.childNodes.length) && (!found)){
							if (Elements.childNodes[i].nodeType == 1){ // This get rides of #text belonging to "whitespaces" for FF
								//if we are in the correct year
								if (isTheYear(Elements , year))
								{	
										if (hasMMC(Elements.childNodes[i].attributes))
										{	
											//compare all the pvc with the one we are searching for
											ComparePVC(pvc , Elements.childNodes[i])
										}else{
											getMMC(pvc ,  Elements.childNodes[i]  , year);
										}
								}else{
										getMMC(pvc ,  Elements.childNodes[i]  , year);
									}
							}
					i++;
				}	
		}
}

/********************************************************************/
/******* set the flag yearFound to know if we are looking in the right year ***/
/********************************************************************/
function isTheYear(node , year){
 ret = yearFound;		
  if (!ret){  
		if (node.tagName == "Year"){
			if (node.attributes[0].value == year)
			{
				yearFound = ret = true
			}
		}
		else{
			   yearFound = ret = false;
		}
   }
	return ret;		
}

/********************************************************************/
/******* if the element has a mmc value  **/
/********************************************************************/
function hasMMC(attributes , year){
	if (!found){
		var j = 0;
		
		//for each attribute get the mmc value
		while (j < attributes.length){
			if (attributes[j].nodeName == "mmc"){
					mmcValue =  attributes[j].nodeValue;
					return true;
			}
			j++;
		}
    }
	return false;
}


/********************************************************************/
/*******Compare if the pvc is the one we are looking for  **/
/********************************************************************/
function ComparePVC(pvc , Elements){	
	var  i  = 0;
	while (i < Elements.childNodes.length){
				if (Elements.childNodes[i].nodeType == 1){ 
					//if the pvc is the the same we set the "found" flag to true and break the search
					if (pvc == Elements.childNodes[i].attributes[1].value){
							found = true;
							styleValue = Elements.childNodes[i].attributes[6].value;
							//alert("This is the optionCode value: " + styleValue);
							break;
						}
				}
		i++;
	}
	
	//clean the mmcValue if the pvc was not found
	mmcValue = (found) ? mmcValue : 0;	
}
