//set up global variables
var divisionalArray = ["bu","ca","ch","gc","om","pg","sb","sa","hm"];
var vehicleArray = new Array();

function brandFiles(name, cssFile, mastheadFile) {
	this.name = name;
	this.cssFile =cssFile;
	this.mastheadFile = mastheadFile;
}

var makeArray = new Array();
makeArray["bu"] = new brandFiles("Buick", "default", "bu");
makeArray["ca"] = new brandFiles("Cadillac", "default", "ca");
makeArray["ch"] = new brandFiles("Chevrolet", "default", "ch");
makeArray["gc"] = new brandFiles("GMC", "gc", "gc");
makeArray["om"] = new brandFiles("Oldsmobile", "default", "default");
makeArray["pg"] = new brandFiles("Pontiac", "pg", "pg");
makeArray["sb"] = new brandFiles("Saab", "sb", "sb");
makeArray["sa"] = new brandFiles("Saturn", "default", "sa");
makeArray["hm"] = new brandFiles("HUMMER", "default", "default");

makeArray["bp"] = new brandFiles("", "bp", "bp");
makeArray["oc"] = new brandFiles("", "default", "default");
makeArray["os"] = new brandFiles("", "default", "default");
makeArray["fc"] = new brandFiles("", "default", "fc");
makeArray["gw"] = new brandFiles("", "default", "default");
makeArray["fl"] = new brandFiles("", "default", "default");
makeArray["gm"] = new brandFiles("", "gm", "gm");
makeArray["oo"] = new brandFiles("", "default", "default");
makeArray["ps"] = new brandFiles("", "default", "default");
makeArray["ld"] = new brandFiles("", "ld", "ld");

var isDivisional = false;
var updateYear = false;

function setYear() {
	updateYear = true;
	
}

function getYear(state) {
	year = document.vehicleSelect.year.options[document.vehicleSelect.year.selectedIndex].value;

	if(!isDivisional) {
		make = document.vehicleSelect.make.options[document.vehicleSelect.make.selectedIndex].value;
	}
	
	if(year!="") {
		getMake(state);
	}
	
}

function getMake(state) {	
	year = document.vehicleSelect.year.options[document.vehicleSelect.year.selectedIndex].value;
	if(year=="") year="2006";
	vehicleArray = eval("vehicleArray"+year+state);
	var vehicleMakeArray = new Array();
	var makeCount = 0;
	var make = "";
	var tempMake = "";
	var temp = "";
	
	//check to see if the model dropdown has a selected value.  This means it was selected. Store for later use
	make = document.vehicleSelect.make.options[document.vehicleSelect.make.selectedIndex].value;
	if(make == "" && pagename == "RESULTS") { 
		make = selectedMake;
		setStyle = true;
	}	
	
	//loop the array and extract the make based on the year
	for(x=0;x<vehicleArray.length;x++){				
			vehicleMakeArray[makeCount] = vehicleArray[x].make;	
			makeCount++;
	}//end for loop

	vehicleMakeArray.sort();

	//create the dropdowns, eliminate dups
	makeCount = 1;
	
	document.vehicleSelect.make.options.length = 1;	
	
	for(x=0;x<vehicleMakeArray.length;x++) {
		tempMake = vehicleMakeArray[x];
		if(temp != tempMake) { //don't want to display dups
			
			document.vehicleSelect.make.options[makeCount] = new Option(tempMake,tempMake);
			//if the make matches the temp make, select it
			

			if(tempMake == make) { 
				if(pagename == "RESULTS" && updateYear == true) {
					document.vehicleSelect.make.options[0].selected='true';
					selectedModel = "";
					selectedStyle = "";
				}else{
					document.vehicleSelect.make.options[makeCount].selected='true';
				}
			}
			makeCount++;
		}
		temp= tempMake;
	}
	
	
		//determine if divisional or cross-divisional site is linking to us	
	for(x=0;x<divisionalArray.length;x++) {
		if(brandId == divisionalArray[x]) { //brandId is divisional 
			isDivisional = true;
			break;		
		}	
	}//end for divisionalArray
	//if we are divisional, we need to include the make text, otherwise display the dropdown
	if(displaySearch) {
		if(isDivisional) {
			make = vehicleMakeArray[brandId].name;		
			document.vehicleSelect.make.options[1].value = make;
			document.vehicleSelect.make.options[1].selected = true;
		}else{
			//document.getElementById("makeDropdownBlock").style.display = 'block';
		}
		getModels(state);
	}//end if displaySearch
	

}//end function getMake

//populates the model dropdown based on make
function getModels(state){
	//alert("getModels()");
	year = document.vehicleSelect.year.options[document.vehicleSelect.year.selectedIndex].value;
	if(year=="") year="2006";
	vehicleArray = eval("vehicleArray"+year+state);
	var model = "";
	var tempModel="";
	var tempMake = "";
	var temp = "";
	var modelArray = new Array();
	var modelCount = 0;
	var setStyle = false;
	//check to see if the model dropdown has a selected value.  This means it was selected. Store for later use
	make = document.vehicleSelect.make.options[document.vehicleSelect.make.selectedIndex].value;
	model = document.vehicleSelect.modelsubmodel.options[document.vehicleSelect.modelsubmodel.selectedIndex].value;
	if(model == "" && pagename == "RESULTS") { 
		model = selectedModel;
		setStyle = true;
		pagename="SEARCH";
	}	
	//set the options so only the first entry remains
	document.vehicleSelect.modelsubmodel.options.length = 1;	
	//document.vehicleSelect.typestyle.options.length = 1;
	if(!isDivisional){//if non divisonal obtain the value of the 'make' select box	
		make = document.vehicleSelect.make.options[document.vehicleSelect.make.selectedIndex].value;
	}
	//loop the array and extract the model based on the make
	for(x=0;x<vehicleArray.length;x++){				
		tempMake=vehicleArray[x].make;
		//if the tempMake matches the selected make
		if(tempMake.toLowerCase().indexOf(make.toLowerCase()) != -1) {
			//add to the model arrays so we can sort and filter for dups
			tempModel = vehicleArray[x].modelsubmodel;	
			modelArray[modelCount] = tempModel;	
			modelCount++;	
		}//end if tempMake equals make
	}//end for loop
	modelArray.sort();
	//create the dropdowns, eliminate dups
	modelCount = 1;
	for(x=0;x<modelArray.length;x++) {
		tempModel = modelArray[x];
		if(temp != tempModel) { //don't want to display dups
			document.vehicleSelect.modelsubmodel.options[modelCount] = new Option(tempModel,tempModel);
			//if the model matches the temp model, select it
			if(tempModel == model) { 
				if(pagename == "RESULTS" && updateYear == true) {
					document.vehicleSelect.modelsubmodel.options[0].selected='true';
					selectedModel = "";
					selectedStyle = "";
					pagename="SEARCH";
				}else{
					document.vehicleSelect.modelsubmodel.options[modelCount].selected='true';
					setStyle = true;
				}
			}
			modelCount++;
		}
		else{
			setStyle = true;
		}
		temp= tempModel;
	}
	
	if(!isDivisional && document.vehicleSelect.make.selectedIndex == 0){
		document.vehicleSelect.modelsubmodel.options[0].selected = 'true';
	}
	
	//dont call getStyles if the make has changed on the results page.  This means that the model/style needs to be recalculated.
	//if(setStyle && selectedMake == make){ getStyles(); toggleStyle();}
	//if(selectedMake != make) { document.vehicleSelect.typestyle.options[0].selected='true'; }
	updateYear = false;
}//end getModels

function getStyles() {
	//alert("getStyles()");
	//get the value of the selected model
	var model = document.vehicleSelect.modelsubmodel.options[document.vehicleSelect.modelsubmodel.selectedIndex].value;
	var tempModel = "";
	var tempStyle = "";	
	var styleArray = new Array();	
	var styleCount = 0;	
	var make = "";
	var tempMake = "";
	var temp = "";
	var pvcId = "";
	//loop the array and extract the styles based on the model
	for(x=0;x<vehicleArray.length;x++){				
		tempModel=vehicleArray[x].modelsubmodel;
		//if the tempModel matches the selected model
		if(tempModel == model) {
			//add to style array so we can sort and filter for dups.		
			tempStyle = vehicleArray[x].typestyle;
			//don't include if there is no style
			if(tempStyle.length > 0) { 
				styleArray[styleCount] = tempStyle; 
				styleCount++; 
			}			
			//set the make/pvc of the vehicle based on the model selected
			make = vehicleArray[x].make;
			//set the pvc in case we need it later
			pvcId = vehicleArray[x].pvcId;	
		}//end if tempModel and model match		
	}//end for vehicleArray
	
	//set the make as selected if non divisional and model is selected
	if(!isDivisional && document.vehicleSelect.modelsubmodel.selectedIndex != 0){				
		for(x=0;x<document.vehicleSelect.make.options.length;x++){
			tempMake = document.vehicleSelect.make.options[x].value; 
										
			if(tempMake.toLowerCase().indexOf(make.toLowerCase()) != -1){ //if they match select it
				document.vehicleSelect.make.options[x].selected='true';
			}						
		}//end for
	}//end if make dropdown exists becuase we are non divisional
	

	
	//if there is no style, we must set the PVC based on model/submodel, otherwise wait for the sytle to be selected
	if(styleArray.length == 0) { document.vehicleSelect.pvcId.value = pvcId; }
	//call get models before creating the style list so that the list is limited to the models based on make
	//getModels();
	
	if(make == "Saab" && year == "2005") {
		styleArray.sort(decendingSort);
	}else{
		styleArray.sort();
	}
	//populate the styles options
	styleCount = 1;
	for(x=0;x<styleArray.length;x++) {
		tempStyle = styleArray[x];
		if(temp != tempStyle) { //don't display dups
			document.vehicleSelect.typestyle.options[styleCount] = new Option(tempStyle,tempStyle);
			if(tempStyle == selectedStyle) { 
				document.vehicleSelect.typestyle.options[styleCount].selected='true';
				getPvc();
			}
			styleCount++;
		}
		temp = tempStyle;
	}	
	// remove previous array elements.
	document.vehicleSelect.typestyle.options.length=styleCount;
	return styleArray;	
}//end getStyles	

function getSubbrand() {
	var submodel = document.vehicleSelect.modelsubmodel.options[document.vehicleSelect.modelsubmodel.selectedIndex].value;
	var make = document.vehicleSelect.make.options[document.vehicleSelect.make.selectedIndex].value;
	
	var tempMake = "";
	
	//set the make as selected if non divisional and model is selected
	if(!isDivisional && document.vehicleSelect.make.selectedIndex == 0){	
					
		// get make for model selected
		for(var x=0;x<vehicleArray.length;x++){				
			//get the first match and set form var.
			if(vehicleArray[x].modelsubmodel == submodel) {
				make = vehicleArray[x].make;
				break;
			}
		}//end for vehicleArray

		// set make pulldown
		for(var x=0;x<document.vehicleSelect.make.options.length;x++){
			tempMake = document.vehicleSelect.make.options[x].value; 
										
			if(tempMake.toLowerCase().indexOf(make.toLowerCase()) != -1){ //if they match select it
				document.vehicleSelect.make.options[x].selected='true';
				getModels(state);
			}						
		}//end for
	}//end if make dropdown exists becuase we are non divisional
	
	
	for(z=0;z<vehicleArray.length;z++){				
		//get the first match and set form var.
		if(vehicleArray[z].modelsubmodel == submodel && vehicleArray[z].make == make) {
			document.vehicleSelect.subbrandId.value = vehicleArray[z].subbrandId;
			document.vehicleSelect.modelId.value = vehicleArray[z].modelId;
			break;
		}
	}//end for vehicleArray
}

function getPvc(){
	var model = document.vehicleSelect.modelsubmodel.options[document.vehicleSelect.modelsubmodel.selectedIndex].value;
	var style = document.vehicleSelect.typestyle.options[document.vehicleSelect.typestyle.selectedIndex].value;
	var tempStyle = "";
	//match on model and style and get the pvc
	for(z=0;z<vehicleArray.length;z++){				
		tempModel=vehicleArray[z].modelsubmodel;
		tempStyle=vehicleArray[z].typestyle;
		//if the tempModel and tempStyle matches the selected model/style
		if(tempStyle == style && tempModel == model) {
			pvcId = vehicleArray[z].pvcId;
			document.vehicleSelect.pvcId.value = pvcId;
		}
	}//end for vehicleArray
}//end getPvc

function validate(lang, pagename, brandId) {
	if(document.vehicleSelect.subbrandId.value == "" || document.vehicleSelect.modelId.value == "") 
	{
		getSubbrand();
	}
	var errorMsg = "";
	var returnStatus = true;
	//if divisional site, there won't be a make dropdown
	//if(isDivisional) { 		
			//if((document.vehicleSelect.modelsubmodel.options[document.vehicleSelect.modelsubmodel.selectedIndex].value == "") ||
			//   (document.vehicleSelect.typestyle.options[document.vehicleSelect.typestyle.selectedIndex].value == "")) {
			//		if(lang == "es")
			//   			errorMsg = "Selecciona un modelo y estilo";
			 //  		else
			//			errorMsg = "Please select a Model and Trim";    
			//}//end if model or style is empty			
	//}else{//if not divisional
			
			
			
			// check if valid zip code
			if( ! isNumber(document.vehicleSelect.zip.value) ){
				errorMsg = retreiveError();	
			}
			// check if valid milesPerYear
			else if( ! isNumber(stripCommas(document.vehicleSelect.milesPerYear.value)) ){
				errorMsg = retreiveError();
			}
			else if( stripCommas(document.vehicleSelect.milesPerYear.value).length > 5){
				errorMsg = retreiveError(2);
			}
			else if((document.vehicleSelect.make.options[document.vehicleSelect.make.selectedIndex].value == "") ||
		   	   (document.vehicleSelect.modelsubmodel.options[document.vehicleSelect.modelsubmodel.selectedIndex].value == "") ||
		   	   //(document.vehicleSelect.typestyle.options[document.vehicleSelect.typestyle.selectedIndex].value == "") || 
		   	   (document.vehicleSelect.zip.value == "") || 
		   	   (document.vehicleSelect.milesPerYear.value == ""))		   	   
		   	   {
					errorMsg = retreiveError();
			   }//end if make, model or style is empty			
	//}//end else not divisional
	if(errorMsg.length > 0) { 
		alert(errorMsg); 
	}else{
		// Omniture
		s_linkType='o';
		if(pagename == "SEARCH") {
			s_linkName="Select Vehicle Submit";
		}
		else{
			s_linkName="Search for Another Vehicle"+ " | " + brandId;
		}
		s_lnk=s_co(this);s_gs("gmleopromo");
		// end Omniture
		
		if(surveyFlag == 1)
		{
			if (lang = "es") {
				popUp("fuel_survey","http://www.gmsurveys2.com/external/987587a.htm","720","500");
			}
			else {
				popUp("fuel_survey","http://www.gmsurveys2.com/external/9bb2a1b.htm","720","500");
			}
		}
		
		document.vehicleSelect.submit();
	}
}//end validate()

function resortStyle(styleArray) {

	if(document.vehicleSelect.make.options[document.vehicleSelect.make.selectedIndex].value == "Saab" && year == "2005") {
		styleArray.sort(decendingSort);
		document.vehicleSelect.typestyle.options.length = 1;
		for(i=0; i<styleArray.length; i++) {
			document.vehicleSelect.typestyle.options[i+1] = new Option(styleArray[i],styleArray[i]);
		}
	}else{
		styleArray.sort(); 
	}
}
	
function decendingSort(a, b) {
	var x = a.toLowerCase();
   	var y = b.toLowerCase();
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}



function vehicleList(make, model, style, pvcId, makeId, modelId, subbrandId){	
	this.make = make; 
	this.modelsubmodel = model; 
	this.typestyle = style;
	this.pvcId = pvcId;
	this.makeId = makeId;
	this.modelId = modelId;
	this.subbrandId = subbrandId;
}

function learnMoreList(model, modelId) {
	this.model = model;
	this.modelId = modelId
}

function redirectAndClose(url) {
	if(window.opener) {
		window.opener.location.href = url;
		window.close();
		window.opener.focus();
	}else{
		window.location.href=url;
	}
}	


function popWin(url, width, height) { 
	var attributes = "width=" + width + ",height=" + height + ",resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=";
attributes += ((navigator.appName.indexOf("Internet Explorer") != -1) && ((navigator.userAgent.indexOf("Mac") != -1))) ? "yes" : "no";
	window.open(url, "", attributes);
}

function popWinWithMenu(url, width, height) { 
	var attributes = "width=" + width + ",height=" + height + ",resizable=yes,scrollbars=yes,toolbar=yes,location=no,directories=no,status=no,menubar=yes";
	window.open(url, "", attributes);
}
	
function popWinCloseParent (url, width, height) { 
	var attributes = "width=" + width + ",height=" + height + ",resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=";
	attributes += ((navigator.appName.indexOf("Internet Explorer") != -1) && ((navigator.userAgent.indexOf("Mac") != -1))) ? "yes" : "no";
	window.open(url, "", attributes);
	window.opener = top;
	window.close();
}
	
function backToParent(url) {
	if (window.opener) {
		window.opener.location.href = url;
		window.opener.focus();
	} else {
		popWin(url, 800, 600);
		//window.location.href=url;
	}
}	


function isNumber(value){
	var tmp = parseFloat(value).toString();
	
	if (tmp.length == value.length && tmp != "NaN") {return true;} 
	else {return false;}
		
}


function stripCommas(value){
	 var re = /,/g;
    	 return value.replace(re,"");
}

function retreiveError(errorNo){
	var msg = "";
	if(lang == "es"){
		if(errorNo == 2){
			msg = "Las Millas estimadas por ano no pueden exceder las 99,999";
		
		} else {
			msg = "Ingrese su cdigo postal y Millas por ano y seleccione una Marca y Modelo";
		}
		
	}else{
		if(errorNo == 2){
			msg = "Estimated Miles Driven per Year can not exceed 99,999 miles";
		
		} else {
			msg = "Please enter Zip code and Miles Per Year and select a Make and Model";
		}
	}
	
	return msg;
}