var v=parseInt(navigator.appVersion);

var agt=navigator.userAgent.toLowerCase();
var t = agt.charAt(82);
var is_major=parseInt(navigator.appVersion);
var is_minor=parseFloat(navigator.appVersion);

// code rewritten Jan 2007 for better browser recognition and support (begin)
//var is_nav=((agt.indexOf('mosilla')!=-1) && (agt.indexOf('spoofer')==-1)
//	&& (agt.indexOf('compatible')==-1) && (agt.indexOf('opera')==-1)
//	&& (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
//var is_nav6 = (is_nav && (is_major >= 5));

//var bn = navigator.appName;
//var bv = navigator.appVersion;

//var NS4=(document.layers) ? true : false;
//var IE4=((document.all)&&(v>=4))?true:false;
//var ver4 = (NS4 || IE4) ? true : false;
   browser = navigator.appName;
   if (browser == "Netscape"){
      if(navigator.userAgent.indexOf("Firefox")!=-1){
        var versionindex=navigator.userAgent.indexOf("Firefox")+8
        browser = "Firefox";
// for FireFox, the version goes all the way to the end of userAgent, so no second
// argument is given for substring (meaning take everything from versionindex to the end)
        version = navigator.userAgent.substring(versionindex);
      }
   }
   if (browser == "Microsoft Internet Explorer"){
      var versionindex=navigator.userAgent.indexOf("MSIE ")+5
// for Internet Explorer, the version goes up to the first semicolon 
      tmp_version = navigator.userAgent.substring(versionindex);
      var semicolonindex=tmp_version.indexOf(";")
      if (semicolonindex > -1){
         version = tmp_version.substring(0,semicolonindex);
      } else {
         version = tmp_version;
      }   
   }
   if (browser == "Netscape"){
      var isNetscape = false;
      var testcharindex=navigator.userAgent.indexOf("Netscape")+8
      if (testcharindex > -1){
         isNetscape = true;
         testchar = navigator.userAgent.charAt(testcharindex);
         if (testchar == "6"){
            var versionindex=navigator.userAgent.indexOf("Netscape6/")+10
//          version = parseInt(navigator.userAgent.charAt(versionindex));
// for Netscape, the version goes up to the first blank or all the way to the end of userAgent, 
// whichever comes first.
            tmp_version = navigator.userAgent.substring(versionindex);
            var blankindex=tmp_version.indexOf(" ")
            if (blankindex > -1){
                version = tmp_version.substring(0,blankindex);
            } else {
                version = tmp_version;
            }   
         }
         if (testchar == "/"){
            var versionindex=navigator.userAgent.indexOf("Netscape/")+9
//          version = parseInt(navigator.userAgent.charAt(versionindex));
// for Netscape, the version goes up to the first blank or all the way to the end of userAgent, 
// whichever comes first.
            tmp_version = navigator.userAgent.substring(versionindex);
            var blankindex=tmp_version.indexOf(" ")
            if (blankindex > -1){
                version = tmp_version.substring(0,blankindex);
            } else {
                version = tmp_version;
            }   
         }
         
         if (!isNetscape){
            browser = "other"
         }   

      } // 
   }
// change this to no longer support Netscape 4   
   if (browser == "Netscape" && version >= "4"){
      NS4 = true;
   } else {
      NS4 = false;
   }
   if (browser == "Netscape" && version >= "6"){
      NS6 = true;
// the following line is a very, very important change.
// if Netscape 6 is mis-identified as Netscape 4, it causes code for Netscape 4 to be used to hide
// and reveal the calculator results.  this code does not work with Netscape 6.
      NS4 = false;
   } else {
      NS6 = false;
   }
   if (browser == "Microsoft Internet Explorer" && version >= "4"){
      IE4 = true;
   } else {
      IE4 = false;
   }
   if (browser == "Firefox" && version >= "1"){
      FF1 = true;
   } else {
      FF1 = false;
   }
   browser_version = browser + " " + version;
   
// change this to no longer support Netscape 4   
//var ver4 = (NS4 || IE4 || FF1) ? true : false;
var ver4 = (NS6 || IE4 || FF1) ? true : false;

if (browser == "Netscape"){
   var is_nav = true;
   if (version >= "6"){
      var is_nav6 = true;
   } else {
      var is_nav6 = false;
   }
} else { 
   var is_nav = false;      
}

var bn = browser;
var bv = version;

t = version;
// code rewritten Jan 2007 for better browser recognition and support (end)

function checkIt(str){
	var p = agt.indexOf(str)  + 1;
	return p;
}

//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;
// code rewritten Jan 2007 for better browser recognition and support (begin)
//	if (NS4 == false){
//		doc = document.frmHidePart;
//		}
//	else {
//		doc = document.layers[0].document.frmHidePart;
//		}
    doc = document.frmHidePart;
// code rewritten Jan 2007 for better browser recognition and support (end)

		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;

// capture browser type and version and put in hidden fileds on form.
// this helps support resolving problems based on browser type (begin)
   app_browser = "unknown";
   if (IE4){
      app_browser = "IE4";
   }
   if (NS4){
      app_browser = "NS4";
   }
   if (NS6){
      app_browser = "NS6";
   }
   if (FF1){
      app_browser = "FF1";
   }
}


//=================================================================//
// 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
// code rewritten Jan 2007 for better browser recognition and support (begin)
//	if (NS4 == false){
//		doc = document.frmHidePart
//		}
//	else {
// the following line causes an error in any version of Netscape after version 4
//      doc = document.layers[0].document.frmHidePart
//		}
    doc = document.frmHidePart
// code rewritten Jan 2007 for better browser recognition and support (end)

	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 positive number.");												
		temp = 0;				
		}		

	return temp;
}	



//=================================================================//
// the function is to put back the '%' simbol.
//=================================================================//


function formatPercent(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);		
			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 ScrnHeight = screen.availHeight;

// change this to no longer support Netscape 4 (begin)  
//function getIndex(n) {
//  inx = null;
// the following line causes an error in Netscape and Firefox
//  for (i=0; i<document.layers.length; i++) {
//      aLay = document.layers[i];
//      if (aLay.id == n) { inx = i; break;}}
//  return inx;
//}
// change this to no longer support Netscape 4 (end)  

function ShowLayer(n) {
//      if (bn=='Netscape' && t < 8) {alert ('Please use Netscape version 8 or higher or Internet Explorer for this calculator.'); return false; }

//    if (!ver4) { alert("Please use Netscape4.7 and below \nto see your result \nor, please use IE. \nThank you");return;}
// change this to no longer support Netscape 4 (begin)  
//  if (IE4) {
//	aLay = eval(n);
//	aLay.style.display = "block";
//  } 
//  else {
//    	var aInx = getIndex(n);
//    	document.layers[aInx].visibility = "show";
//	}
// the following line has problem in Netscape 7 ("BuyVsRentResult" is not defined)
// the following line has problem in Netscape 8, see below: 
//Warning: Element referenced by ID/NAME in the global scope. Use W3C standard document.getElementById() instead.
//	aLay = eval(n);
  	aLay = document.getElementById(n)
  	if (NS6){
       aLay.style.display = "block"; 
       aLay.style.visibility = "visible"; 
    } else {   
  	   aLay.style.display = "block";
    } 
// change this to no longer support Netscape 4 (end)  
}

// the code in HideLayer isn't right, but it is never called
//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";
//	 }
//}

// this code hides the calculator results layer when the page is first loaded
with (document) {
    write("<STYLE TYPE='text/css'>");
    if (NS4){
       write(".inner {position:relative; visibility:hidden;}");
    } else {
       write(".inner {position:relative; display:none;}");		
       write(".inner {display:none}")
    }
    write("</STYLE>");
}

