/*

######################## NOTES

This file is called from these themes:
_microbeadcarcoverscom_ and 
_mrzaccessoriescom_
mstateofninecom_

Make sure to update all of them.

*/

var searchGlobals = {
	"jsonFileDate":{"carcover":"20110609","floormat":"20110906","grille":"20110830","sunshade":"20110607","spoiler":"20110616"},
	"hasUniques":false
	}
//hasUniques is used so it is known after a model is selected whether uniques are present or not. need this for validation.


function zStdErr(e)	{
	if(typeof console != 'undefined')
		console.log(e);
	}


/*
tried loading the json via ajax and ran into all sorts of cross-domain issues. This solution works.
can't set a script id='bob' and load the src into it each time a new set of models is loaded because the var $models doesn't reset each time

this function will create a new script tag in the head element and load the json source.
*/

function loadJSON(url) {
	var headID = document.getElementsByTagName("head")[0];         
	var newScript = document.createElement('script');
		newScript.type = 'text/javascript';
		newScript.src = url;
	headID.appendChild(newScript);
	}




//loads in the makes json file. function is run after a 'category' is selected or on category pages onload.
//safeid would be a part type, such as 'carcover' or 'floormat'.
function loadMakeJSON(safeid)	{
//	alert(filename);
	fn = jsonFileDir+safeid+'_allmakes_'+searchGlobals['jsonFileDate'][safeid]+'.json';
	zStdErr('make file: '+fn);
	loadJSON(fn);
	makeSelect = $('vehicleMake');
	makeSelect.options.length=0;  //remove any existing year options.
	selOption = document.createElement("option");  //change prompt to 'loading...' to indicate something is happening.
	selOption.innerHTML = 'loading...';
	makeSelect.appendChild(selOption);
	setTimeout ( "renderMakeMenu()", 1500 );  //pause a moment while script element (json) loads.
	}


//executed 'onchange' for the make list.
//if this function is executed, the make was either initially selected or changed. hide all select lists 'below' the models and make sure models is visible.
function loadModelJSON(make)	{
	
	$('vehicleYear').style.display = 'block';
	$('vehicleModel').style.display = 'none';
	$('vehicleUnique').style.display = 'none';
	
	fn = jsonFileDir+jsonFileCat+'_'+make.toLowerCase().split(' ').join('_')+'_'+searchGlobals['jsonFileDate'][jsonFileCat]+'.json';
	zStdErr('model file: '+fn);
	loadJSON(fn);

	yearSelect = $('vehicleYear');
	yearSelect.options.length=0;  //remove any existing year options.
	selOption = document.createElement("option");  //change prompt to 'loading...' to indicate something is happening.
	selOption.innerHTML = 'loading...';
	yearSelect.appendChild(selOption);
	setTimeout ( "renderYearMenu('"+make+"')", 1500 );  //pause a moment while script element loads.
	}



//gets run after a category is selected. generates the first menu in the dropdown.
function renderMakeMenu()	{
	if($makes == '')	{
		zStdErr('makes is not ready. try again in 2.5');
		setTimeout ( "renderMakeMenu()", 2500 );
		}
	else	{
		$('makeModelYearContainer').style.display = 'block'; //search is hidden by default.
//any time the make is changed, the unique and model should disappear.	
		$('vehicleUnique').style.display = 'none';
		$('vehicleModel').style.display = 'none';
		
		makeSelect = $('vehicleMake');
		makeSelect.options.length=0;  //remove default (loading...) option
		selOption = document.createElement("option");  //add a 'please choose' option (selected and disabled)
		selOption.innerHTML = 'Vehicle Make';
		selOption.setAttribute('value', "");
		makeSelect.appendChild(selOption);	
		for(key in $makes)	{
			selOption = document.createElement("option");  //add a 'please choose' option (selected and disabled)
			selOption.innerHTML = key.replace("_"," ");
			with(selOption)	{
				setAttribute('value', key);
				setAttribute('id', 'vehicleMake_'+key);
				}
			makeSelect.appendChild(selOption);			
			}
		makeSelect.disabled = false;
		makeSelect.disabled = "";  //IE was not disabling the disable when set to false. strange.
		makeSelect.focus(); //move the cursor to this field.
		}
	}





//update the year menu with make-specific set of years.  'make' needs to match id of json file.
function renderYearMenu(make)	{

	yearSelect = $('vehicleYear');
	
	
	yearSelect.options.length=0;  //remove any existing year options.
	selOption = document.createElement("option");  //add a 'please choose' option (selected and disabled)
	selOption.innerHTML = 'Vehicle Year';
	with(selOption)	{
		setAttribute('value', "");
//		setAttribute('disabled', 'disabled'); //setting this to disabled makes the chooser still look like it can't be changed. 
		setAttribute('selected', 'selected');
		}
	yearSelect.appendChild(selOption);

	for(key in $models)	{
//the last entry in the json is a list of years, which we don't need here.
		if(key != 'year')	{
//http://www.w3schools.com/jsref/met_select_add.asp			
//https://developer.mozilla.org/en/DOM/HTMLSelectElement#add%28%29
			y=document.createElement('option');
			y.text = key;
			y.id = 'vehicleYear_'+key;
			try	{
				yearSelect.add(y,yearSelect[1]); // standards compliant
				}
			catch(ex){
				yearSelect.add(y); // IE only
				}
			}
		}
	yearSelect.disabled = false;
	yearSelect.focus(); //move the cursor to this field.
	}



function renderModelsMenu(year)	{

	$('vehicleModel').style.display = 'block';//make sure menu is visible.
	$('vehicleUnique').style.display = 'none'; //when a new model menu is output, uniques should be hidden.
	
	vehicleModelSelect = $('vehicleModel');
	vehicleModelSelect.options.length=0;  //remove any existing year options.
	selOption = document.createElement("option");  //add a 'please choose' option (selected and disabled)
	selOption.innerHTML = "Vehicle Model";
	selOption.setAttribute('value', "");
	selOption.setAttribute('selected', 'selected');

	vehicleModelSelect.appendChild(selOption);
	
//loops through array and adds an option to the models select list for each model.
	for(var index in $models[year]['model'])	{
		selOption = document.createElement("option");  
		selOption.innerHTML = index.replace(/_/g," ");
		selOption.setAttribute('value', index);
		selOption.setAttribute('id', 'vehicleModel_'+index);

		vehicleModelSelect.appendChild(selOption);
		}
	vehicleModelSelect.disabled = false;
	vehicleModelSelect.focus(); //move the cursor to this field.

	}

function renderUniqueSelect(selectedModel)	{

//	$models['1986']['model']['Integra'].length   ### PATH to data
	vehicleUniqueSelect = $('vehicleUnique');
	selectedYear = $('vehicleYear').getValue()
	vehicleUniqueSelect.options.length=0;  //remove any existing year options.

//check if there are any uniques. If so, show select list and generate options. if not, hide select list and end.


	if(typeof $models[selectedYear]['model'][selectedModel] == 'undefined')	{
		searchGlobals['hasUniques'] = false;
		zStdErr('uniques is undefined');
		vehicleUniqueSelect.style.display = 'none'; //make sure menu is invisible.
		}
//this is an else if instead of part of the if above to appease the IE gods. 
//It was having issues if the node didn't exist.
	else if($models[selectedYear]['model'][selectedModel][0] == null)	{
		searchGlobals['hasUniques'] = false;
		zStdErr('uniques is null');
		vehicleUniqueSelect.style.display = 'none'; //make sure menu is invisible.
		}
	else if($models[selectedYear]['model'][selectedModel][0] == '')	{
		searchGlobals['hasUniques'] = false;
		zStdErr('uniques is blank');
		vehicleUniqueSelect.style.display = 'none'; //make sure menu is invisible.
		}
	else	{
		searchGlobals['hasUniques'] = true;
		vehicleUniqueSelect.style.display = 'block'; //make sure menu is visible.
		//reset dropdown and add new values	
		selOption = document.createElement("option");  //add a 'please choose' option (selected and disabled)
		selOption.innerHTML = "Vehicle Unique Identifier";
		selOption.setAttribute('value', "");
		selOption.setAttribute('selected', 'selected');

		vehicleUniqueSelect.appendChild(selOption);
		numUniqueAttributes = $models[selectedYear]['model'][selectedModel].length

		zStdErr('length of uniques = '+numUniqueAttributes);

		for(i = 0; i < numUniqueAttributes; i++)	{
			unique = $models[selectedYear]['model'][selectedModel][i];
//only proceed if unique has a value. keeps blanks from being added.
			if(unique != '')	{
				selOption = document.createElement("option");  
				selOption.innerHTML = unique.replace(/_/g," ");
				selOption.setAttribute('value', unique);
				selOption.setAttribute('id', 'vehicleUnique_'+unique);
		
				vehicleUniqueSelect.appendChild(selOption);
				}
			}
		vehicleUniqueSelect.disabled = false;	
		vehicleUniqueSelect.focus(); //move the cursor to this field.
		}
	}









//when form is submitted, put the various input values into the correct order for the 'tag' and add to hidden 'keywords' input.
//correct order is make-model-value followed by 'type' if set.
//also validates to make sure if a make is set, so is a model and value.  checks to make sure a make and/OR a part type is set.

function compileNSubmitMMY()	{
	var valid = true;  //set to true or false based on whether or not all the form values are set.
	var errors = '';  //used to hold errors generated in the form validation.
	var query = '';  //used to build the query, which is added to the keywords field in the form.
	var make;
//make, model and year are all required. If 'unique' is present, it is required too.
	if($('vehicleMake').getValue() == "")
		errors += '<li>Vehicle Make<\/li>';
	if($('vehicleYear').getValue() == "")
		errors += '<li>Vehicle Year<\/li>';
	if($('vehicleModel').getValue() == "")
		errors += '<li>Vehicle Model<\/li>';
	if(searchGlobals['hasUniques'] == true && $('vehicleUnique').getValue() == "")
		errors += '<li>Vehicle Unique Identifier<\/li>';
		
	if(errors != '')	{
		$('searchErrors').innerHTML = 'Oops! It appears a few required fields were left blank: <ul>'+errors+'<\/ul>';
		valid = false;
		}
	else	{
/*
2011-09-28
looks like items are getting tagged with spaces. hhmm.. hopefully this doesn't break anything (return more results than desired). I have a nasty feeling that some items were created with dashes and some with spaces. blech.
changed: $('vehicleModel').getValue().replace(/\s+/g, '-')
to: $('vehicleModel').getValue()

*/
		if(jsonFileCat && jsonFileCat == 'sunshade')
			make = $('vehicleModel').getValue().replace(/\s+/g, '-')
		else
			make = $('vehicleModel').getValue()

		query = $('vehicleMake').getValue()+'-'+make+'-'+$('vehicleYear').getValue();

		if(searchGlobals['hasUniques'] == true)
			query += '-'+$('vehicleUnique').getValue()
		if(jsonFileCat)
			query += '+'+jsonFileCat;  //adds a 'type' to the end to make sure either only carcovers, floormats, etc are returned
			
		$('partFinderKeywords').value = query;
		if(typeof PleaseTrackClick == 'function') { 
			PleaseTrackClick('ADVSEARCH','parttype" '+jsonFileCat+'| make: '+$('vehicleMake').getValue()+'| model: '+$('vehicleModel').getValue()+'| year: '+$('vehicleYear').getValue()+'| page: '+this.location); 
			}

		}

	return valid;
//	document.partFinderFrm.submit();
	}
	
	


function PreselectMyItem(itemToSelect,formField)	{
// Get a reference to the drop-down
	var myDropdownList = formField;
//	zStdErr(myDropdownList);
//	alert(formField);
// Loop through all the items
	for (iLoop = 0; iLoop < myDropdownList.options.length; iLoop++)	{    
		if (myDropdownList.options[iLoop].id == itemToSelect)	{
// Item is found. Set its selected property, and exit the loop
			myDropdownList.options[iLoop].selected = true;
			break;
			}
		}
	}
	
	
	
