var v=parseInt(navigator.appVersion);
var NS4=(document.layers) ? true : false;
var IE4=((document.all)&&(v>=4))?true:false;
var ver4 = (NS4 || IE4) ? true : false;


function ShowLayer(){return}
function HideLayer(){return}

function floor(number)
{
  return Math.floor(number*Math.pow(10,2))/Math.pow(10,2);
}



//=================================================================//
// this is the main function.
//=================================================================//



function showme(){

     RentVSBuy();
  	
}

function onChange(){
    	document.calc.cRent.value = formatCurrency(document.calc.cRent.value);
	document.calc.pPrice.value = formatCurrency(document.calc.pPrice.value);
	document.calc.iRate.value = formatPercent(document.calc.iRate.value);
	document.calc.PropTax.value = formatPercent(document.calc.PropTax.value);
	document.calc.loanLength.value = document.calc.loanLength.value;
	document.calc.stayLength.value = document.calc.stayLength.value;
	document.calc.homeAppreciate.value = formatPercent(document.calc.homeAppreciate.value);
	document.calc.downPay.value = formatPercent(document.calc.downPay.value);
}


function showAll(){
	showme();
	ShowLayer("BuyVsRentResult"); 
	document.calc.getResult.value = "Recalculate";
        if (NS4==false){
            window.scrollTo(0,200);		
         }	
        else{
            window.scrollTo(0,150);		
         }	
 
}

function RentVSBuy(){

	paymentOfRent();
	paymentOfBuy();

}

function RemovePercentage(InStr) {

	var iChk, sSrch;
	var sTemp = InStr;
	var Delmtr = new Array("%", " ");	
	
	for (i=0; i<Delmtr.length; i++){
		sSrch = Delmtr[i];
		iChk = sTemp.lastIndexOf(sSrch);
		
		while (iChk != -1){
			sTemp = sTemp.replace(sSrch, "");
			iChk = sTemp.lastIndexOf(sSrch);
		}
	}	
	
	return sTemp;
}




//=================================================================//
// the function is to control the loan term not greater than 30 years.
//=================================================================//

function checkNum(thisNum){
var temp;
temp = thisNum;
	if(temp > 30 && temp == document.calc.loanLength.value){
			alert ("'Length of Loan Term' must be equal to or less than 30 years.");	
			temp = 30;	
			document.calc.loanLength.value = 30;
			}	
return temp;
}


//=================================================================//
// the function is to calculate the buying home facts.
//=================================================================//
//=================================================================//
function paymentOfBuy(){
	var i;

// calculate payment    
	var downPayPercent = replacePercent(document.calc.downPay.value);

	var loanAmount = replaceChars(document.calc.pPrice.value);
	
	var pPrice = loanAmount;

	loanAmount = loanAmount*(100-downPayPercent)/100
	var newDownPay = replacePercent(document.calc.downPay.value);
	var newPropTax = replacePercent(document.calc.PropTax.value);

	var IncInPricePercent = replacePercent(document.calc.homeAppreciate.value);

	var interestRate = replacePercent(document.calc.iRate.value)/100;
	
	var yearLoan = checkNum(document.calc.loanLength.value);

	var aRate = 1 + (interestRate/12);

	var payment 
        payment = (loanAmount * (aRate-1) * Math.pow(aRate,yearLoan*12)) / (Math.pow(aRate,yearLoan*12)-1);

	payment = parseInt(payment);
	
	
 

// find home value after year of owning 
	
	var yearOwn = checkNum(document.calc.stayLength.value);

	var homeValAfterOwnYears = 0;	
	var incAmount = 0;
	homeValAfterOwnYears = pPrice;
	var pp = 1+IncInPricePercent/(100);

	homeValAfterOwnYears = pPrice * Math.pow(pp,yearOwn);

	homeValAfterOwnYears = parseInt(homeValAfterOwnYears);


// find the remain balance

	var monthlyInterest = interestRate/12;

	var loanMonths = yearLoan * 12;
	var ownPayMonths = yearOwn * 12;
	
	var PayOff = loanAmount;
	var interestDue = 0;
	var pricipalCredit=0;

	if (parseInt(yearOwn) < parseInt(yearLoan)){		
	for (i=0;i<ownPayMonths;i++) {
		interestDue = PayOff * monthlyInterest;
		pricipalCredit = payment - interestDue;
		PayOff = PayOff - pricipalCredit;
		}

		PayOff = Math.round(PayOff);
	}
	else{
		PayOff = 0;
	}



// find the total interest 

	var totalInterest=0;
	    principalCredit = 0;

	var intDue=0;
	var remLoanAmount = loanAmount;

	if (parseInt(yearOwn) <= parseInt(yearLoan)){
		for (i=0;i<ownPayMonths;i++) {	
			intDue = loanAmount * monthlyInterest;
			principalCredit = payment - intDue;
			remLoanAmount = remLoanAmount - principalCredit;
			totalInterest = totalInterest + intDue;		
		}
	}
	else {
		for (i=0;i<loanMonths;i++) {	
			intDue = loanAmount * monthlyInterest;
			principalCredit = payment - intDue;
			remLoanAmount = remLoanAmount - principalCredit;
			totalInterest = totalInterest + intDue;		
		}
	}

totalInterest = parseInt(totalInterest);




// find equity

	var equity = 0;
	equity = homeValAfterOwnYears - PayOff;
	equity = parseInt(equity);

// find total property tax 

	var loanTimePropertyTax = newPropTax*pPrice * yearLoan/100;
	var TPropertyTax = newPropTax*pPrice * yearOwn/100;


// find total tax saving. assume personal tax rate is 28%.   
	
	var TTSaving = 0;
	if (parseInt(yearOwn)<=parseInt(yearLoan)) {

		TTSaving = parseInt((totalInterest + TPropertyTax)* 28 / 100);
		}
	else { 
		TTSaving = parseInt((totalInterest + loanTimePropertyTax)*28/100);
		}
		


	
// Total mortgage payment. Assume mortgage insurence rate 0.52%. 
// Assume loan closing cost rate 0.5%,  
// Home owning insurence .15%. 

	var mortgagePayment = payment * 12;

	var mortgageIns = (0.52/100)*loanAmount;
	var loanClosingCost = loanAmount * (0.5/100);
	var homeOwnInsurence = pPrice * (0.15/100);

	var totalMortgagePayment = parseInt((mortgagePayment+mortgageIns));


	if (parseInt(yearOwn) <= parseInt(yearLoan)){	
		totalMortgagePayment = totalMortgagePayment * yearOwn + homeOwnInsurence*yearOwn +TPropertyTax+loanClosingCost;
		}
	else {
		totalMortgagePayment = totalMortgagePayment * yearLoan + homeOwnInsurence*yearOwn +TPropertyTax+loanClosingCost;		
		
		}



// total cost of buying a home. Assume selling home cost 6%, 

	var costOfSellingHome = homeValAfterOwnYears*6/100;

	var downPay = parseInt(newDownPay)/100 * pPrice;
	var totalCost = 0;



	totalCost = parseInt((downPay+totalMortgagePayment+PayOff+costOfSellingHome)-(TTSaving+homeValAfterOwnYears));
	if (totalCost < 0) totalCost = 0;



// monthly cost

	var monthlyCost = 0;
	monthlyCost = parseInt(totalCost/yearOwn/12);		

	


// to display all 

	var totalSaving; 
	var string;



	if (paymentOfRent()>totalCost){
	    totalSaving	= parseInt(paymentOfRent()) - parseInt(totalCost);	
	    string = "Buying: ";
		}
	else{
	    totalSaving	= parseInt(totalCost) - parseInt(paymentOfRent());	
  	    string = "Renting: ";
		}
	string = string + formatCurrency(totalSaving);

	var doc;
	if (NS4 == false){
		doc = document.frmHidePart;
		}
	else {
		doc = document.layers[0].document.frmHidePart;
		}

		doc.r17.value = formatCurrency(PayOff);
		doc.r18.value = formatCurrency(homeValAfterOwnYears);
		doc.r20.value = formatCurrency(monthlyCost);
		doc.r22.value = formatCurrency(totalCost);
		doc.r23.value = string;
		doc.r24.value = formatCurrency(TTSaving);
		doc.r25.value = formatCurrency(equity);
		doc.getYear.value = document.calc.stayLength.value;
}



//=================================================================//
// the function is to calculate the payment of renting.
//=================================================================//

function paymentOfRent(){

	var yearOwn = document.calc.stayLength.value;
	var totalRent = 0;

	var rent = replaceChars(document.calc.cRent.value);

	var rentNew = Math.pow(1.0228,(yearOwn - 1));  
	var newRent = (rentNew) + (rentNew * rent);

	var monthlyRent = (parseInt((newRent - rent)/2) + parseInt(rent));	
	
	var totalRent = monthlyRent * yearOwn * 12;	

	var doc
	if (NS4 == false){
		doc = document.frmHidePart
		}
	else {
		doc = document.layers[0].document.frmHidePart
		}

	doc.r21.value = formatCurrency(totalRent); 
	doc.r19.value = formatCurrency(monthlyRent);
	
	return totalRent;
}



function replaceChar(entry) {
	out = "$"; 
	add = ""; 
	temp = "" + entry;
	while (temp.indexOf(out)>-1) {
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + out.length), temp.length));
	}
	return temp;
}


//=================================================================//
// the function is to eliminate the '%' simbol.
//=================================================================//

function replacePercent(entry) {
	out = "%"; 
	add = ""; 
	temp = entry;
	 
	while (temp.indexOf(out)>-1) {
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add +
		temp.substring((pos + out.length), temp.length));
		}

	if (temp<0){	
		alert ("The value you entered must be a possitive number.");												
		temp = 0;				
		}		

	return temp;
}	



//=================================================================//
// the function is to put back the '%' simbol.
//=================================================================//


function formatPercent(theNumber){
	//theNumber = replacePercent(theNumber);
	theNumber = RemovePercentage(theNumber);
	if (theNumber == replacePercent(document.calc.iRate.value) && theNumber == 0){
		alert ("The 'Interest Rate' cannot be zero. The value is returned to 7.5%.");
		theNumber = 7.5;
	}
	  theNumber = Math.round(theNumber * 1000) / 1000;

	  return(theNumber + "%");	

}



//=================================================================//
// the function is to eliminate the ',' and '$' from the entry.
//=================================================================//
	
function replaceChars(entry) {
	out = ","; 
	add = ""; 
	temp = "" + entry;

	outVal = "$"; 	
	

// to get rid of charactor ",". 

	if (temp.indexOf(out)>-1){
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + out.length), temp.length));
		}
// to eliminate the '$'.
	if (temp.indexOf(outVal)>-1){
		pos= temp.indexOf(outVal);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + outVal.length), temp.length));
		}

	return temp;
}


//=================================================================//
// the function is to re-format the number of currency to us dollar.
//=================================================================//
function formatCurrency(thisnum) {		
		num=replaceChars(thisnum);
		
//		num = num.toString().replace(/\$|\,/g,'');
			if(isNaN(num)) num = "0";
			num = Math.floor(num).toString();	
		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 ('$' + num );		
	
}



function addPct(pct) {
			pct=replacePercent(pct);
			pct=parseFloat(pct);		
		if (checkForm(pct));
	{
			return (pct + '%');
		}
}

function checkForm(toCheck) {
	isNum = true;
	for (j = 0; j < toCheck.length; j++) {
	if ((toCheck.substring(j,j+1) < "0") && (toCheck.substring(j,j+1) != ".") || (toCheck.substring(j,j+1) > "9")) {
      isNum = false;
      }
    }
  if ((isNum == false) || (toCheck.length == 0) || (toCheck == null)) {

  return false;
  }
  else {
  return true;
  }
}


//=======================================================================//
//=======================================================================//


var iPageX, iPageY;
var ScrnHeight = screen.availHeight;

if (ScrnHeight > 700){
        iPageX = 670; iPageY = 133;
} else {
	if (NS4) iPageX = 625;	
	else iPageX = 590;			
	iPageY = 130;
}


function getIndex(n) {
    inx = null;
    for (i=0; i<document.layers.length; i++) {
        aLay = document.layers[i];
        if (aLay.id == n) { inx = i; break;}}
    return inx;
}

function arrange(aInx) {
	document.layers[aInx].pageX = iPageX;
	document.layers[aInx].pageY = iPageY;
}

function ShowLayer(n) {
    if (!ver4) return;
    if (IE4) {
	aLay = eval(n);
	aLay.style.display = "block";
	} 
    else {
    	var aInx = getIndex(n);
    	document.layers[aInx].visibility = "show";
	}
}



function HideLayer(n) {if (!ver4) return;
    if (IE4) {
    aLay = eval(n);
    aLay.style.display = "none";
	} 
    else {
	var aInx = getIndex(n);
        document.layers[aInx].visibility = "hide";
	}
}



with (document) {
    write("<STYLE TYPE='text/css'>");
    if (NS4){
       	if (ScrnHeight > 700){
		write(".inner {position:relative; visibility:hidden;}");
	}
	else write(".inner {position:relative; visibility:hidden;}");
    } else {
    if (ScrnHeight > 700){
		write(".inner {position:relative; display:none;}");
	}
	else {	
		write(".inner {position:relative; display:none;}");
	}
		
        write(".inner {display:none}")
    }
    write("</STYLE>");
}
