/**
 * Common AutoSys Utility Functions
 */

/**
 * Add 'in_array' method to Array class
 *
 * @return boolean 
 * @param object obj The object to check for in the given instance of an Array
 * @access public
 */
Array.prototype.in_array = function ( obj ) {
	var len = this.length;
	
	for ( var x = 0 ; x <= len ; x++ ) {
		if ( this[x] == obj ) {
			return true;
		}
	}  
	
	return false;
}   

/**
 * Swap the fullsize image with the thumbnail
 * @param string url The URL to swap into the fullsize view
 * @access public
 */
function autosysImageSwap(url)
{
	var oPhoto = document.getElementById('autosysfullsize');
	var oPhotoLink = document.getElementById('autosysfullsizelink');
	
	oPhotoLink.href = url;
	oPhoto.src = url;
}

/**
 * Truncate text to a predetermined length
 * @param string sTag The HTML tag element to look for
 * @param string sClass The class to match against
 * @param integer nLength The maximum length of the HTML
 * @access public
 */
function autosysTruncateText(sTag, sClass, nLength)
{
	if (!document.getElementByTagName) {
		return;
	}
	
	var allTags=document.getElementsByTagName(sTag);
	for (i=0; i < allTags.length; i++) {
		if (allTags[i].className==sClass) {
			var sData = allTags[i].innerHTML;
			if (sData.length > nLength) {
            	allTags[i].innerHTML = sData.substring(0, nLength) + " &hellip;";
        	}
    	}
	}
}

/**
 * Show option in a 'make' list
 * @return void
 * @param eID string The ID of the combo box to populate
 */
function showOptions(eID, defaultID)
{
	if(ele = document.getElementById(eID)) {
	
		for (i = ele.options.length - 1; i > 0; i--) {
			ele.options[i] = null;
		}
		
		for (tempID in aMake) {
			sName = aMake[tempID]['name'];
			if(!aMake[tempID]['count']) {
				continue;
			}
			
			if(displayFlag[tempID] == 1) {
				if (tempID == defaultID) {
					ele.options[ele.options.length] = new Option(sName, tempID, false, true);
				} else {
					ele.options[ele.options.length] = new Option(sName, tempID);
				}
			}
		}
	}
}

/**
 * Save vehicle ID to a cookie
 * @return void
 * @param integer VehID The unique ID of a vehicle
 */
function saveVehicle(VehID)
{
	sName = 'veh_' + VehID;
	
	createCookie(sName,VehID,1);
	
	newField = document.createElement("input");
	newField.type =  "hidden";
	newField.name =  "cart[]";
	newField.value = VehID;
	document.addvehicle.appendChild(newField);
	document.addvehicle.submit();
}

/**
 * Thoggle a vehicle.
 * @return void
 * @param string sID The object id string identifier.
 * @param boolean nToggle The boolean value to toggle the option or not.
**/

function toggle_vehicle(sId, nToggle)
{
    var oElement;
    
    if (document.all && document.all[sId])
       oElement = document.all[sId];
    else if (document.getElementById(sId))
       oElement = document.getElementById(sId);
       
    if (oElement)
       oElement.style.display = (nToggle) ? 'block' : 'none';
}

/**
  * Creates and erases a cookie, based on the vehcile added to the list.
  *
  * @return void
  * @param integer VehID The vehicle ID to set the cookie to.
  * @param string boxID The ID of the box element
  *
**/
function doAction(VehID,boxID)
{
	sName = 'veh_' + VehID;

	if(ele = document.getElementById(boxID))
	{
		if(ele.checked == 1)
		{
			createCookie(sName,VehID,1);
		}
		else
		{
			eraseCookie(sName);
		}
	}
}

/**
  * Checks the check box if the vehicle is in the cookie or not.
  *
  * @return void
  * @param string VehID The vehicleID.
  * @param string bogID The ID of the check boxes.
**/
function checkValue(VehID,boxID)
{
	sName = 'veh_' + VehID;
	if(readCookie(sName))
	{
		if(ele  = document.getElementById(boxID))
		{
			ele.checked = 1;
		}
		else
		{
			ele.checked = 0;
		}
	}

}

/**
  * Saves the vehicles that one checked or unchecked on the form.
  *
  * @return void
**/
function saveVehicles()
{
	cookStr = document.cookie;
	kVeh = cookStr.split(';');
	for(i=0; i<kVeh.length; i++)
	{
		aData = kVeh[i].split('=');
		sTest = "veh_";
		var reg_exp = new RegExp(sTest);	
		if(reg_exp.test(aData[0]))
		{
			newField = document.createElement("input");
			newField.type =  "hidden";
			newField.name =  "cart[]";
			newField.value = aData[1];
			newField.checked = 1;
			document.result.appendChild(newField);
		}
	}

    document.result.submit();
}

/**
  * Broadens the search for a vehicle by the zip code.
  * @return void
  *
**/
function broaden()
{
	oQS = new Querystring();
	if(nDist = oQS.get("pxdist"))
	{ 
		sDist = 50 + parseInt(nDist);
        sUrl = "results.php?<<QUERY_STRING>>&pxdist=" + sDist;
	}
	else
	{
		sUrl = "results.php?<<QUERY_STRING>>";
	}							
	location.href = sUrl;
}

/**
  * Toggles a vehicle visually.
  * @param string sID the element ID to change.
  * @param boolean nToggle is if it should be toggled or not.
  * @return void
**/
function toggle_vehicle(sId, nToggle)
{
    var oElement;
    if (document.all && document.all[sId])
         oElement = document.all[sId];
    else if (document.getElementById(sId))
         oElement = document.getElementById(sId);
    if (oElement)
         oElement.style.display = (nToggle) ? 'block' : 'none';
}

function delVehicle()
{
	with(document.result)
	{
		if(oneVal = document.result.cart.value)
		{
             sName = 'veh_' + oneVal;
             eraseCookie(sName);
             newField = document.createElement("input");
             newField.type =  "hidden";
             newField.name =  "cart[]";
             newField.value = oneVal;
             document.remove.appendChild(newField);
		}
		else
		{
			for(i=0; i<cart.length; i++)
			{
				if(cart[i].checked)
				{
					sName = 'veh_' + cart[i].value;
					eraseCookie(sName);
    		        newField = document.createElement("input");
                    newField.type =  "hidden";
               		newField.name =  "cart[]";
	                newField.value = cart[i].value;
	                document.remove.appendChild(newField);
				}
			}
		}
	}
	document.remove.submit();
}

/**
  * Rounds a given value to the precision required.
  *
  * @return integer nLen The rounded value.
  * @param integer nVal The original value.
  * @param integer nPrecision The number of decimal places.
**/
function round(nVal, nPrecision) {
	nDiv = Math.pow(10, nPrecision + 1);
	sRound = (Math.round(nVal * nDiv) / nDiv).toString();
	nLen = Math.round(nVal).toString().length;

	return sRound.substring(0, nLen + nPrecision + 1);
}

/**
  * Resets the values for the loan information (reset button)
  *
  * @return void
  * @param string mnths The ID of the months input type.
  * @param string intr The ID for the interest input type.
  * @param string amt The ID for the amount input type.
  * @param string res The ID for the results area.
**/
function reset_loan(mnths, intr, amt, res) {
	document.getElementById(mnths).value="";
	document.getElementById(intr).value="";
	document.getElementById(amt).value="";
	document.getElementById(res).innerHTML="";
}

/**
  * Calculates, and sets the display of a loan payment amount per month.
  *
  * @return void
  * @param integer mnths The # of months this would be paid over.
  * @param integer intr The interest of the loan itself.
  * @param integer amt The total amount of the loan
**/
function calc_loan(mnths, intr, amt)  {
	if(!document.getElementById(mnths).value || !document.getElementById(intr).value || !document.getElementById(amt).value) {
		return;
	}
			
	var nMonths = document.getElementById(mnths).value;
	var nInterest = document.getElementById(intr).value;
	var nAmount = document.getElementById(amt).value;
	nAmount.replace(',', '');
	nAmount.replace('$', '');
			
	var nPayment = calcPayment(nMonths, nInterest, nAmount);
	var nIntAmt = round((nMonths * nPayment) - nAmount, 2);
				
	var tTextAroo = "<p class='result-text'>Monthly Payment: <span>$" + nPayment + "</span></p>" +"<p class='result-text'>Total Interest Paid: <span>$" + nIntAmt + "</span></p>";
			
	document.getElementById('l-results').innerHTML = tTextAroo;
						
}
	
/**
  * Calculates the loan payment (Internal javascript function)
  *
  * @return float Payment per month rounded to the 2nd decimal place.
  * @param integer nMonths The months that this loan would be going for.
  * @param float nInterest The interest rate of this loan.
  * @param integer nAmount The total amount of the loan.
**/ 		
function calcPayment(nMonths, nInterest, nAmount) {
	nInterest /= 1200;
	var nPayment = nAmount * nInterest / (1 - Math.pow(1 + nInterest, -nMonths));
		
	return round(nPayment, 2);
}


function vin_validate(vin)
{
	var weight = 8;
	var total = 0;
	var length = 17;
	var final_value;

	var x = "12345678012345070923456789";

	if(!vin.length) {
		return false;
	}

	if (vin.length != length) {
		return false;
	}

	for (var t = 0; t < length; t++ ){
		switch (vin.charAt(t)) {
			case 'I':
			case 'O':
			case 'Q':
			  return false;
		}
		// if NOT alphanumeric
		if( ((vin.charCodeAt(t) < 48) || (vin.charCodeAt(t) > 90)) || ((vin.charCodeAt(t) < 57) && (vin.charCodeAt(t) > 65)) ) {
			return false;
		}
	}

	//add the first 8 digits of the VIN to total
	for (var i = 0; i < 7; i++) {
		if  ((vin.charCodeAt(i) - "A".charCodeAt(0)) <  0)
			total+= (vin.charCodeAt(i)-"0".charCodeAt(0))*weight--;
		else
			total+= (x.charAt(vin.charCodeAt(i)-"A".charCodeAt(0)))*weight--;
	}

	//add 8th position and takes into account that the weight factor is 10
	if  ((vin.charCodeAt(7) - "A".charCodeAt(0)) <  0)
		total+= (vin.charCodeAt(7)-"0".charCodeAt(0))*10;
	else
		total+= (x.charAt((vin.charCodeAt(7)-"A".charCodeAt(0))))*10;

	weight = 9;	//sets weight for calcultions of the second half of the VIN

	//add the second half of the VIN to total
	for(i = 9; i < length; i++) {
		if  ((vin.charCodeAt(i) - "A".charCodeAt(0)) <  0)
			total+= (vin.charCodeAt(i)-"0".charCodeAt(0)) * weight--;
		else
			total+= (x.charAt(vin.charCodeAt(i)-"A".charCodeAt(0))) * weight--;
	}

	final_value = total % 11;
	var tmp;

	if (vin.charCodeAt(8) == 'X')
		tmp = 10;
	else
		tmp = vin.charCodeAt(8) - "0".charCodeAt(0);

	// If final_value = the 9th position(the check digit) in the vin then it's a
	// valid VIN
	
	return ( final_value == tmp );
}