/*****************************************************************************************************
*********	search/master.js -- javascript functions commonly used on search page only
*************************************************************************************************** */

//Globals
var xmlhttp;
var firstPaymentRefresh = true;

function change_tab(tab_id, tab){
	
	//purpose: tab control system for containers
	
	//Reset all tab classes as off
	document.getElementById('search_tab').className = 'tab_wrapper not_selected';
	document.getElementById('shopByPayment_tab').className = 'tab_wrapper not_selected';
	if( $j('#shopByMPG_tab').length > 0 )
		document.getElementById('shopByMPG_tab').className = 'tab_wrapper not_selected';
	document.getElementById('newArrivals_tab').className = 'tab_wrapper not_selected';
	document.getElementById('advanced_tab').className = 'tab_wrapper not_selected';
	if( $j('#virtualgarage_tab').length > 0 )
		document.getElementById('virtualgarage_tab').className = 'tab_wrapper not_selected';
	
	//Reset all content areas as off
	document.getElementById('tab_search_default_content').style.display = 'none';
	document.getElementById('tab_search_advanced_content').style.display = 'none';
	document.getElementById('tab_shop_by_payment_content').style.display = 'none';
	if( $j('#tab_mpg_content').length > 0 )
		document.getElementById('tab_mpg_content').style.display = 'none';
	document.getElementById('tab_NewArrivals_content').style.display = 'none';
	if( $j('#virtualgarage_tab').length > 0 )
		document.getElementById('tab_virtualgarage_content').style.display = 'none';
	
	//Turn on current tab needed
	document.getElementById(tab_id).style.display = '';
	document.getElementById(tab).className = 'tab_wrapper_selected selected';
	
	//Check if payment calculator tab is opening to draw the carousel from the ajax version which has the correct counts
	if (tab == 'shopByPayment_tab') {
		recompute('update');
	}
	
}  

function validate() {

	var validationErrorString = "";
	
	if (isNaN(document.getElementById("vehiclePriceInput").value))
		validationErrorString += "Vehicle Price must be a number.\n";
	
	if (isNaN(document.getElementById("downPaymentInput").value))
		validationErrorString += "Down Payment / Trade must be a number.\n";
		
	if (isNaN(document.getElementById("aprInput").value))
		validationErrorString += "Interest Rate must be a number.\n";

	if (isNaN(document.getElementById("termInput").value))
		validationErrorString += "Term must be a number.\n";
		
	if (validationErrorString.length > 0){
		alert("There are problems with the input values.  Please correct them to compute a monthly payment.\n\n" + validationErrorString);
		return false;
	}
	else {
		return true;
	}
	
}
	
function calculateMonthlyPayment(loanAmount, apr, term) {
	var aprAsDecimal = apr;
	if(aprAsDecimal > 1.0)
		aprAsDecimal = aprAsDecimal / 100.0;

	aprAsDecimal = aprAsDecimal / 12.0;

	var pow = 1.0;
	for(var i= 0; i < term; i++){
		pow = pow * (1 + aprAsDecimal);
	}

	return (loanAmount * pow * aprAsDecimal) / (pow - 1);
}

function submit_search(targetParent) {

	// purpose: submit the make and model search to the browse page
	
	var openInParent = (typeof targetParent == 'boolean' && targetParent === true) ? true : false;
	// Get the parameters from the select boxes.
	var make = $j('#search_make').val();
	var model = $j('#search_model').val();
	var type;
	if( $j('form.search-criteria-section input[name="type"]:checked').length )
		type = $j('form.search-criteria-section input[name="type"]:checked').val();
	else
		type = $j('#searchVehicleType').val();
	
	//build url
	var url = 'browse/view_detailed/';
	
	if( type != '' ){
		url += 'type_' + type + '/';
	}
	if (make != '') {
		url += 'make_' + SpaceToUscore(make) + '/';
	}
	if (model != '') {
		url += 'model_' + SpaceToUscore(model) + '/';
	}
	
	// Redirect.
	if (openInParent === true)
		parent.location = escapeForSearch(url);
	else
		location.href = escapeForSearch(url);
}

function recompute(status) {
	
	// Get payment calculator data
	var sPriceRange = document.getElementById("vehiclePriceInput").value;
	var sCashTradeDown = document.getElementById("downPaymentInput").value;
	var sAPR = document.getElementById("aprInput").value;
	var sTerm = document.getElementById("termInput").value;
	var type = document.getElementById("searchVehicleType").value;
	
	// Update the affordable monthly price box
	try {document.getElementById("monthlyPaymentInput").value = calculateMonthlyPayment(sPriceRange - sCashTradeDown, sAPR, sTerm).toFixed(2); }
	catch(expaycalc) {}
	
	// If price range adjusted we need to update matching affordable vehicles
	if (status == 'update') {
		
		try {
			// Get settings needed to pass in
			var bwUrl = document.getElementById("bwUrl").innerHTML;
			var bwReseller = document.getElementById("bwResellerFolder").innerHTML;
			
			// Format the request
			var requestPage = "/InventoryHosting2/Search/js/displayCarousel.ajax.asp";
			var requestParams = "rnd=" + encodeURIComponent(timestamp()) + "&vehicleprice=" + encodeURIComponent(sPriceRange) + 
								"&bwurl=" + encodeURIComponent(bwUrl) + "&reseller=" + encodeURIComponent(bwReseller) + 
								"&type=" + encodeURIComponent(type);
			var serverContent = new ajaxObject(requestPage);
			serverContent.callback = function(responseText) {
				//Update carousel div content to new pulled content based on price
				document.getElementById('monthlypriceCarousel').innerHTML = responseText;
				// Redraw and animate the new carousel code
				loadPaymentCarousel();
				// Update status for user
				if (!firstPaymentRefresh) {
					inlineMsg('CarouselMatching', 'Affordable Vehicles have been updated', '3');
				}
				//If first time refreshing from first payment tab click make sure we dont do it again since unnecessary
				firstPaymentRefresh = false;
				// Loader image - was brief and need to re-add id for this
				//document.getElementById("showLoadImage").innerHTML = '<img style="padding-left:5px;" src="/InventoryHosting2/search/images/smLoader.gif">';
			}
			serverContent.update(requestParams);
		}
		catch(ex) {}
	}
	
}

function openTerms()
{
	if(document.getElementById("terms").style.display == "none")
		document.getElementById("terms").style.display = "";
	else
		document.getElementById("terms").style.display = "none";
}

function populate_makes_search() {
	
	// purpose: initial population only upon page load of the make and model drop box search
	
	//Disable models by default until make it picked
	document.getElementById("search_model").disabled = true;
	var make;
	//var selected_make = "";
	var selected_index = -1;
	add_list_item(document.getElementById("search_make"),"","- Select Make -");
	for (i=0; i<vehicles.length; i++){
		//Assign the value of the first element in each array (make name) to a temp variable.
		make = vehicles[i][0];
		add_list_item(document.getElementById("search_make"),make,make);
		//if (make.toLowerCase() == selected_make){
			//selected_index = i;
		//}
	}
	if (selected_index >= 0) {
		document.getElementById("search_make").selectedIndex = selected_index + 1;
		make_changed_search();
	}
}
		
function make_changed_search(){

	// purpose: refresh the values in the make and model search

	// Get the new value in the make drop.
	var make = document.getElementById("search_make").value;

	if (make != "") {
		// Clear the model list.
		empty_list(document.getElementById("search_model"));
		
		// Add the first item back to the model list.
		add_list_item(document.getElementById("search_model"),"","- Select Model -");
		
		// Get the additional values of this particular make array and add them to the model list.
		var veh_index = document.getElementById("search_make").selectedIndex - 1;
		var upper_bound = vehicles[veh_index].length
		
		//var selected_model = "";
		var selected_index = 0; 
					   
		for (i=1; i<upper_bound; i++){
			add_list_item(document.getElementById("search_model"),vehicles[veh_index][i],vehicles[veh_index][i]);
			//if (vehicles[veh_index][i].toLowerCase() == selected_model){
				//selected_index = i;
			//}                    
		}

		if (selected_index > 0) {
			document.getElementById("search_model").selectedIndex = selected_index;
		}                
		
		// Enabled the model drop box.
		document.getElementById("search_model").disabled = false;
		
	}else{
		document.getElementById("search_model").selectedIndex = 0;
		document.getElementById("search_model").disabled = true;
	}
}

