var isIE = (navigator.userAgent.indexOf("MSIE") != -1);

function isTextValid(text,allowEmpty,minSize,maxSize){
	var txt = new String(text);
	
	if (allowEmpty) {
		if (isTextEmpty(txt)) {return true;}
	} else {
		if (isTextEmpty(txt)) {return false;}
	}
	
	
	if (txt.length < minSize) {return false;}
	if (txt.length > maxSize) {return false;}
	
	return true;
}

function isNumberValid(text,allowEmpty,minSize,maxSize){
	if (!isTextValid(text,allowEmpty,minSize,maxSize)) {return false;}
	var num = parseInt(text);
	if (isNaN(num)) {
		return false;
	} else {
		for (var i = 0; i < text.length; i++){
			switch (text.substr(i,1)){
				case "1":
				case "2":
				case "3":
				case "4":
				case "5":
				case "6":
				case "7":
				case "8":
				case "9":
				case "0":
					// These are acceptable.
					break;
				default:
					// Everything is unacceptable.
					return false;
			}
		}
	}
	return true;
}

function ValidateDate(mo, day, yr, caption){
	if (!((mo.value >= 1) && (mo.value <= 12))) {
		validateAlert("Your " + caption + " month must be between 1 and 12.", mo);
		return false;
	}

	if (isTextEmpty(day.value)){
		validateAlert("You must specify a day for your date of birth.",day);
		return false;
	}
	
	// Do year next because day is dependent on wether it is a leap year or not.
	if (!((yr.value >= 1900) && (yr.value <= 2001))) {
		validateAlert("Your " + caption + " year appears to be invalid.  Please make sure to use four digits to describe the value.", yr);
		return false;
	}
	
	switch (parseInt(mo.value)){
		case 2:
			if ((yr.value % 4) == 0) {
				if (!((day.value >= 1) && (day.value <= 29))) {
					validateAlert("Your " + caption + " day must be between 1 and 29.", day);
					return false;
				}
			} else {
				if (!((day.value >= 1) && (day.value <= 28))) {
					validateAlert("Your " + caption + " day must be between 1 and 28.", day);
					return false;
				}
			}
			break;
			
		case 4:
		case 6:
		case 9:
		case 11:
			if (!((day.value >= 1) && (day.value <= 30))) {
				validateAlert("Your " + caption + " day must be between 1 and 30.", day);
				return false;
			}
			break;
			
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			if (!((day.value >= 1) && (day.value <= 31))) {
				validateAlert("Your " + caption + " day must be between 1 and 31.", day);
				return false;
			}
			break;
	}
	
	return true;
}

function isValidEmail(email){
	var emailStr = new String(email);
	/* The following pattern is used to check if the entered e-mail address
	   fits the user@domain format.  It also is used to separate the username
	   from the domain. */
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special
	   characters.  We don't want to allow special characters in the address. 
	   These characters include ( ) < > @ , ; : \ " . [ ]    */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a 
	   username or domainname.  It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in
	   which case, there are no rules about which characters are allowed
	   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	   is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses,
	   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	   e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of
	   non-special characters.) */
	var atom=validChars + '+'
	/* The following string represents one word in the typical username.
	   For example, in john.doe@somewhere.com, john and doe are words.
	   Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic
	   domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


	/* Finally, let's start trying to figure out if the supplied address is
	   valid. */

	/* Begin with the coarse pattern to simply break up user@domain into
	   different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
	  /* Too many/few @'s or something; basically, this address doesn't
	     even fit the general mould of a valid e-mail address. */
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]

	// See if "user" is valid 
	if (user.match(userPat)==null) {
	    // user is not valid
	    return false
	}

	/* if the e-mail address is at an IP address (as opposed to a symbolic
	   host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
	    // this is an IP address
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
				return false
		    }
	    }
	    return true
	}

	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
	    return false
	}

	/* domain name seems valid, but now make sure that it ends in a
	   three-letter word (like com, edu, gov) or a two-letter word,
	   representing country (uk, nl), and that there's a hostname preceding 
	   the domain or country. */

	/* Now we need to break up the domain to get a count of how many atoms
	   it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>3) {
	   // the address must end in a two letter or three letter word.
	   return false
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   return false
	}

	// If we've gotten this far, everything's valid!
	return true;
}

function isDateValid(yr, mo, dt){
	var res = new Date(yr, mo, dt);
	
	return (!isNaN(res))
}

function isTextEmpty(text){
	var txt = trim(text);
	
	return (txt.length == 0);
}

function trim(text){
	var txt = new String(text);
	
	while (txt.charAt(0) == " ") {
		txt = txt.substring(1, txt.length);
	}
	
	while (txt.charAt(txt.length - 1) == " ") {
		txt = txt.substring(0, txt.length - 1);
	}
	
	return txt;
}

// This is an event handler only.
function IsKeyPressNumeric(e){
	if (navigator.appVersion.indexOf("MSIE") != -1) {
		var chr = e.keyCode;
	} else {
		var chr = e.which;
	}

	switch (String.fromCharCode(chr)){
		case "0":
		case "1":
		case "2":
		case "3":
		case "4":
		case "5":
		case "6":
		case "7":
		case "8":
		case "9":
			return true;
			break;
		default:
			return false;
	}
}

function validateAlert(msg, focusElem){
	if (isIE) {
		focusElem.focus();
	}
	alert(msg);
}

function SalesPriceCalculator(LoanAmount, TaxPercent, TitleFee, LicenseFee, ServiceContract, DownPayment, Term, APR)
{
    var dblLoanAmount;
    var Result;
    var dblStoredPrice;
    var dblTaxPercent;
    var dblServiceContract;
    var dblSvcContractTax;
    var dblTaxAmount;
    var dblTitleFee;
    var dblLicenseFee;
    var dblDownPayment;
    var dblSalesPrice;
    var dblPaymentAmount;
    var dblAPR;
    var dblTerm;
    
    if(isNaN(LoanAmount)){return "Error: Sales Price is not valid.";}
    if(isNaN(TaxPercent)){return "Error: Tax Percent is not valid.";}
    if(isNaN(TitleFee)){return "Error: Title Fee is not valid.";}
    if(isNaN(LicenseFee)){return "Error: License Fee is not valid.";}
    if(isNaN(ServiceContract)){return "Error: Service Contract is not valid.";}
    if(isNaN(DownPayment)){return "Error: Down Payment is not valid.";}
    
    LoanAmount = parseFloat(LoanAmount);
	dblTaxPercent = parseFloat(TaxPercent) * 0.01;
	dblLoanAmount = parseFloat(LoanAmount);
	dblTitleFee = parseFloat(TitleFee);
	dblServiceContract = parseFloat(ServiceContract);
	dblSvcContractTax = (dblServiceContract * dblTaxPercent);
	dblLicenseFee = parseFloat(LicenseFee);
	dblDownPayment = parseFloat(DownPayment);
	dblAPR = parseFloat(APR);
	dblTerm = parseFloat(Term);
	
	dblAPR = parseFloat((APR / 1200))
	dblStoredPrice = 1;
	dblSalesPrice = 0;  
	dblTaxAmount = 0;
		
	while(dblSalesPrice !== dblStoredPrice)
	
		{
		if(dblStoredPrice == 1)
			dblStoredPrice = 0;
	
		else
			
			dblStoredPrice = dblSalesPrice;
				
			dblSalesPrice = dblLoanAmount - dblTaxAmount - dblTitleFee 
			- dblServiceContract - dblSvcContractTax 
			- dblLicenseFee + dblDownPayment;
		
			dblTaxAmount = parseFloat((dblSalesPrice * dblTaxPercent));
		}
		
	
	dblPaymentAmount=pmt(dblAPR, dblTerm, dblLoanAmount, 0, 0);		
	dblTaxAmount = dblTaxAmount + dblSvcContractTax;
		
	Result = new Array(Math.round(dblSalesPrice), dblPaymentAmount, dblTaxAmount);
	return Result;

}


function YourLoanCalc(LoanAmount, PaymentAmount, Term, APR)
{

	var Result;
	var dblAPR;
	
	/*
	if(isNaN(LoanAmount)){return "Error: Loan Amountis not valid.";}
	if(isNaN(PaymentAmount)){return "Error: Payment Amount is not valid.";}
	if(isNaN(Term)){return "Error: Term Amount is not valid.";}	
	if(isNaN(APR)){return "Error: APR Amount is not valid.";}
	*/
	
	dblAPR = parseFloat((APR / 1200))
	
	if(LoanAmount=="")
		PaymentAmount=parseFloat(pmt(dblAPR, Term, parseFloat(PaymentAmount), 0, 0));
	else
		LoanAmount=parseFloat(pv(dblAPR, parseFloat(Term), parseFloat(LoanAmount), 0, 0));
		
	
	Result = new Array(PaymentAmount, LoanAmount);
	
	return Result;
}


function pv(rate, nper, pmt, fv, type){
	if(isNaN(rate)){return "Error: rate is not valid.";}
	if(isNaN(nper)){return "Error: nper is not valid.";}
	if(isNaN(pmt)){return "Error: pmt is not valid.";}
	if(!fv){fv = 0;}
	if(!type){type = 0;}
	if(isNaN(fv)){return "Error: fv is not valid.";}
	if(isNaN(type)){return "Error: type is not valid.";}
	
	var res;
	
	if(rate == 0) {
		res = (-1 * (fv + pmt * nper));
	} else {
		res = (pmt * (1 + rate * type) * (1 - Math.pow((1 + rate), nper)) - rate * fv) / (rate * Math.pow((1 + rate), nper));
	}
	
	res = Math.round(-res);
	
	return res;
}

function pmt(rate, nper, pv, fv, type){
	if(isNaN(rate)){return "Error: rate is not valid.";}
	if(isNaN(nper)){return "Error: nper is not valid.";}
	if(isNaN(pv)){return "Error: pv is not valid.";}
	if(!fv){fv = 0;}
	if(!type){type = 0;}
	if(isNaN(fv)){return "Error: fv is not valid.";}
	if(isNaN(type)){return "Error: type is not valid.";}

	var res;
	
	if(rate == 0) {
		res = (-1 * (fv + pv) / nper);
	} else {
		res = ((rate * (fv + pv * Math.pow((1 + rate), nper))) / ((1 + rate * type) * (1 - Math.pow(1 + rate, nper))));
	}
	
	res = Math.round(-res);
	
	return res;
}

function LoanToValue(SalesPrice, TaxPercent, TitleFee, LicenseFee, ServiceContract, DownPayment, VehicleValue)
{
	var dblTaxValue;
    var dblLoanToValueTotal;
    var dblLoanAmountTotal;
    var Result;
    
    if(isNaN(SalesPrice)){return "Error: Sales Price is not valid.";}
    if(isNaN(TaxPercent)){return "Error: Tax Percent is not valid.";}
    if(isNaN(TitleFee)){return "Error: Title Fee is not valid.";}
    if(isNaN(LicenseFee)){return "Error: License Fee is not valid.";}
    if(isNaN(ServiceContract)){return "Error: Service Contract is not valid.";}
    if(isNaN(DownPayment)){return "Error: Down Payment is not valid.";}
    
    SalesPrice = parseFloat(SalesPrice);
	VehicleValue = parseFloat(VehicleValue);
		    	
	if(isNaN(VehicleValue))
	    {	
		TaxPercent = parseFloat(TaxPercent);
		TitleFee = parseFloat(TitleFee);
		LicenseFee = parseFloat(LicenseFee);
		ServiceContract = parseFloat(ServiceContract);
		DownPayment = parseFloat(DownPayment);	    
		VehicleValue = parseFloat(VehicleValue);
		
		dblTaxValue = parseFloat(((SalesPrice + ServiceContract) / 100) * TaxPercent);
	
		dblLoanAmountTotal = SalesPrice
		dblLoanAmountTotal += dblTaxValue
		dblLoanAmountTotal += TitleFee
		dblLoanAmountTotal += LicenseFee
		dblLoanAmountTotal += ServiceContract
		dblLoanAmountTotal -= DownPayment
		dblLoanToValueTotal = ""
		}	

	else
	
		{
		VehicleValue = parseFloat(VehicleValue);
		dblLoanToValueTotal = parseFloat((SalesPrice / VehicleValue));
		dblTaxValue = ""
		dblLoanAmountTotal = ""
		}


	Result = new Array(dblLoanAmountTotal, dblLoanToValueTotal, dblTaxValue);
	return Result;

}

function MaximumLoanAmount(Value, Term)
{

	var Percent;
	var MaxLoanAmount;
	var Result;
	
	if(isNaN(Value)){return "Error: Vehicle Value is not valid.";}
	if(isNaN(Term)){return "Error: Loan Term is not valid.";}

	if(Term == "")
		{Percent = 0}
	else
		{Percent = 115}

			
	MaxLoanAmount = parseFloat((Value * Percent) /100);
	
	Result = new Array(Percent, MaxLoanAmount);
	return Result;
}

function GetPayment(LoanAmount, Term, APR)
{

	var Result;
	var dblAPR;

	dblAPR = parseFloat((APR / 1200))
	
	LoanAmount = parseFloat(pmt(dblAPR, Term, parseFloat(LoanAmount), 0, 0));
	Result = LoanAmount;
		
	return Result;
}

function GetLoanAmount(PaymentAmount, Term, APR)
{

	var varResult;
	var dblAPR;
	
	dblAPR = parseFloat((APR / 1200))
	PaymentAmount=parseFloat(pv(dblAPR, parseFloat(Term), parseFloat(PaymentAmount), 0, 0));
	Result = PaymentAmount;
	
	return Result;
}

function CheckMinLoan(varVehicleValue, varMinLoanAmount, LTV)
{

	//if(varVehicleValue.length = varMinLoanAmount.length)
	//{
		if(varVehicleValue < ((varMinLoanAmount / LTV) * 100))
			{
			return false;
			}
		else
			{
			return true;
			}
	//}
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	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));
	return (((sign)?'':'-') + '$' + num);
}


