/* Utility Functions */

function arrayContains( anArray, anObject ) {
	if ( ( typeof(anArray) == "undefined" ) || ( anArray == null ) ) return false;
	for ( var i=0; i<anArray.length; i++) {
		if ( anArray[i] == anObject ) return true;
	}
	return false;
}

function defaultCurrencyFormat( num ) {
	return currencyFormatWithCents(num, true);
}

function currencyFormat( num ) {
	if (isNaN(num)) num = 0;
	var numFormat = "";

	num = Math.round(num);

	if ( ( typeof(num) != undefined ) && ( num != null ) ) {
		num = "" + num;
		for (var i=num.length; i - 3 >= 0; i -= 3) {
			numFormat = num.substring(i-3,i) + numFormat;
			if ( i - 3 > 0 ) numFormat = "," + numFormat;
		}
		if ( i > 0 ) numFormat = num.substring(0,i) + numFormat;
	}
	return "$" + numFormat;
}

function currencyFormatWithCents( num, ignoreZeroCents  ) {
	if (isNaN(num)) num = 0;

	var sign = "";
	var cents = "00";

	if ( num != 0 ) {
		cents = "" + Math.round( Math.abs(num) * 100 );
		cents = cents.substring(cents.length-2);
	}
	if ( ( cents == "00" ) && ignoreZeroCents ) cents = "";

	num = "" + Math.floor(num);

	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
		num = num.substring(0,num.length-(4*i+3))+',' + num.substring(num.length-(4*i+3));
	}

	if ( num < 0 ) sign = "-";
	if ( cents != "" ) num += "." + cents;

	return sign + '$' + num;
}

function setHtml( pageItem, value ) {
	if ( ( typeof(pageItem) == "undefined" ) ||
		( pageItem == null ) ||
		( typeof(pageItem.innerHTML) == "undefined" ) )
	{
		return;
	}
	if ( value == null ) return;
	pageItem.innerHTML = value;
}

function setImgSrc( image, src ) {
	if ( typeof(image) == "undefined" ) return;
	if ( ( image == null ) || ( src == null ) ) return;
	image.src = src;
}

function openShowDealersWindow(url) {
	if ( typeof(url) == "undefined" ) url = "about:blank";
	return openWindow(url, "showDealers", "width=500,height=700");
}

function openWindow(url, windowName, windowProperties) {
	var newWindow = window.open(url, windowName, windowProperties);
	if ( newWindow != null ) {
		newWindow.focus();
	}
	return newWindow;
}


/**
* getCurrentAccessories() is a utility that returns the list of currently selected accessories from the accessoryMap object
*
*/
function getCurrentAccessories()
{
	var currentAccessories = [];
	for (var accessoryId in accessoryMap) {
		var accessory = accessoryMap[accessoryId];
		if ( accessory.selected ) {
			currentAccessories.push(accessory);
		}
	}
	return currentAccessories;
}

/**
* setAccessoryMonthlyPaymentValuesFromService() is a utility that sets the monthlyPayment attributes for all of the accessories in the accessoryMap, following a request from the PE service.
* see getPaymentEstimatorRate()
*
*/
function setAccessoryMonthlyPaymentValuesFromService()
{
	var peAccessoryData = paymentEstimatorData.result.accessory;
	for (var accessoryId in accessoryMap) {
		var accessory = accessoryMap[accessoryId];
		for(i=0; i< peAccessoryData.length; i++)
		{
			if(accessory.code == peAccessoryData[i].id)
			{
				accessory.monthlyPayment = peAccessoryData[i].incr;
				break;
			}
		}
	}
}

/**
* getPaymentEstimatorRate() makes the AJAX request to the PE service for the main configurator page
*
*/
function getPaymentEstimatorRate(creditRating, termPeriod) {
	if ( ( vehicle.loanRate <= 0 ) || ( vehicle.loanTerm == -1 ) ) return -1;
	
	var servicePath = "/PE/service/rest/bys";
	var requestDataString = setupPERequest(creditRating, termPeriod);
			
	// make the AJAX request
	$.ajax({
	   async: false,
	   type: "POST",	
	   url: servicePath,
	   contentType: 'application/json', 
	   data: requestDataString,
	  
	   success: function(response)
	   {
			//alert('buy, ajax response success: ' + response);
			var result = eval('('+response+')');
			paymentEstimatorData = result;
			var calculatorState =  window.calculatorState;
			var duration = 60;
			var creditRating = 0;
			var rateIsManual = false;
			var APR = "undefined";
			var down = 0;
			var trade = 0;
			var owed = 0;
			
			if(calculatorState.duration != undefined) duration = calculatorState.duration;
			if(calculatorState.creditRating != undefined) creditRating = calculatorState.creditRating;
			if(calculatorState.rateIsManual != undefined) rateIsManual = calculatorState.rateIsManual;
			if(calculatorState.APR != undefined) APR = calculatorState.APR;
			if(calculatorState.down != undefined) down = calculatorState.down;
			if(calculatorState.trade != undefined) trade = calculatorState.trade;
			if(calculatorState.owed != undefined) owed = calculatorState.owed;
			
			setAccessoryMonthlyPaymentValuesFromService();
			window.vehicle.monthlyPayment = result.result.monthlyPay;
			var displayMonthlyPayment = defaultCurrencyFormat( Math.ceil(result.result.monthlyPay) );
			calculatorUpdate(displayMonthlyPayment, duration, creditRating, rateIsManual, APR, down, trade, owed);
	   },
	   error: function(XMLHttpRequest, textStatus, errorThrown)
	   {
	   		// handle PE Service unavailable or other critical failure
	   		isPaymentEstimatorServiceAvailable = false;
	   		document.getElementById("empLabel").style.display = "none";
	   		document.getElementById("financeNote").style.display = "none";
	   		document.getElementById("monthlyPayment").style.display = "none";
	   		document.getElementById("customizeMonthlyPaymentButton").style.display = "none";
	   }
	   
	});
}


function getPaymentEstimatorRateFromCalculator(creditRating, termPeriod) {
	if ( ( vehicle.loanRate <= 0 ) || ( vehicle.loanTerm == -1 ) ) return -1;
	
	var servicePath = "/PE/service/rest/bys";
	var requestDataString = setupPERequest(creditRating, termPeriod);
			
	// make the AJAX request
	$.ajax({
	   async: false,
	   type: "POST",	
	   url: servicePath,
	   contentType: 'application/json', 
	   data: requestDataString,
	  
	   success: function(response)
	   {
			//alert('buy, ajax response success: ' + response);
			var result = eval('('+response+')');
			paymentEstimatorData = result;
			var calculatorState =  window.calculatorState;
			var duration = 60;
			var creditRating = 0;
			var rateIsManual = false;
			var APR = "undefined";
			var down = 0;
			var trade = 0;
			var owed = 0;
			
			window.vehicle.monthlyPayment = result.result.monthlyPay;
			setAccessoryMonthlyPaymentValuesFromService();

	   },
	   error: function(XMLHttpRequest, textStatus, errorThrown)
	   {
	   		isPaymentEstimatorServiceAvailable = false;
	   		// do nothing else... this should be handled in getPaymentEstimatorRate()
	   }
	   
	});
}

/**
* Generates the data string for submission to the PE service
*
*/
function setupPERequest(creditRating, termPeriod)
{
	var baseAmountFinanced = 0;
	// create the accessories string 
	var accessoriesString = "";
	for (var accessoryId in accessoryMap) {
		var accessory = accessoryMap[accessoryId];
		accessoriesString += '{"accessoryCode":"' + accessory.code + '","amount":"' + accessory.msrp + '"},';
	}
	// crop off the trailing comma - ","
	accessoriesString = accessoriesString.substr(0, accessoriesString.length-1);

	// calculate the baseAmountFinanced
	var tmpDownPayment = 0;
	var tmpTradeInValue = 0;
	var tmpOwedOnTrade = 0;
	var tmpApr = 0;
	var rateIsManual = false;
	
	var calculatorState =  window.calculatorState;
	if(calculatorState.loanRate != undefined) tmpApr = calculatorState.loanRate;
	if(calculatorState.down != undefined) tmpDownPayment = calculatorState.down;
	if(calculatorState.trade != undefined) tmpTradeInValue = calculatorState.trade;
	if(calculatorState.owed != undefined) tmpOwedOnTrade = calculatorState.owed;
	if(calculatorState.rateIsManual != undefined) rateIsManual = calculatorState.rateIsManual;
	
	baseAmountFinanced = this.baseMsrp - ( tmpDownPayment + tmpTradeInValue - tmpOwedOnTrade );
	
	// compile the data as a string for relaying to the app via AJAX
	// finished version should look something like this:
	// ' { getItInputTO : { "zipCode": "90210", "financingOption":"B", "make": "Scion", "accessoriesList":[ {"accessoryCode":"ExT","amount":"76.0"}, {"accessoryCode":"EF","amount":"69.0"} ], 
	//		"baseAmountFinanced":"12000", "modelYear":"2010", "trimCode":"6221", "baseMSRP":"15000" } } '
	var requestDataString = '{ bysInputTO : { "zipCode": "' + this.zipCode + '"' +
		', "financingOption":"B", "make": "Scion", "accessoriesList":[ ' + accessoriesString +
		' ], "baseAmountFinanced":' + baseAmountFinanced.toString() + 
		', "modelYear":' + this.modelYear +
		', "trimCode":' + this.modelCode +
		', "creditRating":' + creditRating +
		', "termPeriod":' + termPeriod +
		', "totalMSRP":' + baseMsrp;
	
	if ((typeof(mailerApr) != "undefined") && (mailerApr > 0))
	{
		// set mailerapr above other options
		tmpApr = mailerApr;
		requestDataString += ', "aprRate":' + tmpApr;
	} else if(tmpApr != 0 && rateIsManual) {
		// use manualApr if set and mailerapr doesn't trump it
		requestDataString += ', "aprRate":' + tmpApr;
	}
	
	// finish up the requestDataString format
	requestDataString += ' } }';
	
	return requestDataString;
}


/* Vehicle Info Box Functions - see vehicleObject.jsp */

function Vehicle( basePrice, deliveryFee, docFee, accessoriesPrice, loanRate, loanTerm ) {

	function totalPrice() {
		if ( this.basePrice == null ) return 0;
		return this.basePrice + this.deliveryFee + this.docFee + this.accessoriesPrice;
	}

	function initDisplay() {
		this.display = new VehicleDisplay( this );
		this.display.update();
	}

	function updateVehicle( updateObject ) {
		for ( var x in updateObject ) {
			if ( typeof(this[x]) != "undefined" ) this[x] = updateObject[x];
		}
		if (this.display == null) { initVehicleDisplay(); }
		if ( ( typeof(this.display) != "undefined" ) && ( this.display != null ) ) {
			this.display.update();
		}
	}

	this.basePrice = basePrice;
	this.deliveryFee = deliveryFee;
	this.docFee = docFee;
	this.accessoriesPrice = accessoriesPrice;
	this.loanRate = loanRate;
	this.loanTerm = loanTerm;

	this.modelImageSrc = null;

	this.display = null;

	this.totalPrice = totalPrice;
	this.initDisplay = initDisplay;
	this.update = updateVehicle;

	return this;
}

function VehicleDisplay( vehicleObject ) {

	function updateDisplay() {
		setHtml( this.basePrice, defaultCurrencyFormat( this.vehicle.basePrice ) );
		setHtml( this.deliveryFee, defaultCurrencyFormat( this.vehicle.deliveryFee ) );
		setHtml( this.docFee, defaultCurrencyFormat( this.vehicle.docFee ) );
		setHtml( this.accessoriesPrice, defaultCurrencyFormat( this.vehicle.accessoriesPrice ) );
		setHtml( this.totalPrice, defaultCurrencyFormat( this.vehicle.totalPrice() ) );
	
		var monthlyPayment = this.vehicle.monthlyPayment;
		if ( this.vehicle.loanRate > 0 ) {
			var currentAccessories = getCurrentAccessories();
			for(i=0; i<currentAccessories.length; i++)
			{
				var price = parseFloat(currentAccessories[i].monthlyPayment);
				monthlyPayment += price;
			}
			monthlyPayment = Math.ceil(monthlyPayment);
		}
		else {
			monthlyPayment = "";
		}

		var displayMonthlyPayment = defaultCurrencyFormat( monthlyPayment );
		setHtml( this.monthlyPayment, displayMonthlyPayment );

		setImgSrc( this.vehicleImage, this.vehicle.modelImageSrc );
	}

	this.vehicle = vehicleObject;
	this.basePrice = document.getElementById("vehicleBasePrice");
	this.deliveryFee = document.getElementById("vehicleDeliveryFee");
	this.docFee = document.getElementById("vehicleDocFee");
	this.accessoriesPrice = document.getElementById("vehicleAccessoriesPrice");
	this.totalPrice = document.getElementById("vehicleTotalPrice");
	this.monthlyPayment = document.getElementById("monthlyPayment");
	this.update = updateDisplay;

	this.vehicleImage = document.images["vehicleImage"];

	return this;
}

function vehicleDisplayInitialized() {
	if ( typeof(vehicle) != "undefined" && vehicle == null &&
	     typeof(vehicle.display) != "undefined" || vehicle.display != null )
	{
		return true;
	}
	return false;
}

function initVehicleDisplay() {
	if ( typeof(vehicle) != "undefined" ) {
		vehicle.initDisplay();
	}
}

