function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}


function doCalc() {
doCalcOnForm(document.forms["calculateThis"]);
}

function clearColumn(form, nColumn) {
        form[("down_payment" + nColumn)].value = "";
        form[("first_mortgage" + nColumn)].value = "";
        form[("cmhc" + nColumn)].value = "";
        form[("total_financing" + nColumn)].value = "";
        form[("monthly_payment" + nColumn)].value = "";
        form[("expenses" + nColumn)].value = "";
        form[("total_payment" + nColumn)].value = "";
        form[("income_required" + nColumn)].value = "";
}

function clearResults(form) {
        var nCounter = 0;
        for (nCounter = 1; nCounter <=3; nCounter++) {
                clearColumn(form, nCounter);
        }
}

function checkForm(form) {
        var nCounter = 0;
        var sResult = 0;
        var nResult = -1;
        var nIndex = 0;
        for (nCounter = 1; nCounter <= 3; nCounter++) {
                if ((form[("percent_down" + nCounter)].options[form[("percent_down" + nCounter)].selectedIndex].value == "") || 
                        (form[("percent_down" + nCounter)].options[form[("percent_down" + nCounter)].selectedIndex].value == "other")) {
                        while ((nResult < 5) || (nResult > 100)) {
                                sResult = prompt(decodeMsg("DOWNPAYMENT_PERCENT"), "5");
                                if (sResult == null) {
                                        alert("DOWNPAYMENT_REQUIRED");
                                        sResult = "0";
                                } else {
                                        if (sResult.indexOf(".") > 0) sResult = sResult.substring(0, sResult.indexOf(".") + 3);
                                        nResult = Number(filterNum("0" + sResult));
                                        if ((nResult < 5) || (nResult > 100)) {
                                                alert("INVALID_DOWNPAYMENT")
                                        }
                                }
                        }
        
                        if (form[("percent_down" + nCounter)].options[form[("percent_down" + nCounter)].selectedIndex].value == "other") {
                                nIndex = form[("percent_down" + nCounter)].selectedIndex + 1;
                        } else {
                                nIndex = form[("percent_down" + nCounter)].selectedIndex;
                        }
                        form[("percent_down" + nCounter)].options[nIndex].value = nResult;
                        form[("percent_down" + nCounter)].options[nIndex].text = nResult + "%";
                        form[("percent_down" + nCounter)].selectedIndex = nIndex;
                }
        }
        validateNum(form.io_price,0,1000,9999999,true);
        validateNum(form.io_interest,3,1,100);
        validateNum(form.io_heating,0,0,99999,true);
        validateNum(form.io_taxes,0,0,99999,true);
        validateNum(form.io_condo,0,0,99999,true);
        validateNum(form.io_gds,2,1,100);

        if ((form.io_price.value != "") &&
                (form.io_interest.value != "") &&
                (form.io_gds.value != "")) {
                return true;
        } else {
                return false;
        }
}

function CMHCRate(PercentDown, Amortization) {

var PercentFinanced = 0;
PercentFinanced = Number(100 - Number(PercentDown));


var total_rate = 0.0;
total_rate = 0;



if (Amortization == 40)
	total_rate = .6;
else if (Amortization == 35)
	total_rate = .4;
else if (Amortization == 30)
	total_rate = .2;

        if (PercentFinanced <= 80)
                total_rate = 0;
        else if (PercentFinanced <= 85)
                total_rate = total_rate + 1.75;
        else if (PercentFinanced <= 90)
                total_rate = total_rate + 2.0;
        else if (PercentFinanced <= 95)
                total_rate = total_rate + 2.75;
        else if (PercentFinanced <= 100)
                total_rate = total_rate + 3.1;
	return total_rate;

}

function mortgagePayment(nAmount, nRate, nAmort) {
        var nAmortMonths = nAmort * 12;
        var nPaymentsPer6Months = 6;    

        return (nAmount / ( (1 / ( Math.pow((1 + nRate / 200), (1 / nPaymentsPer6Months ))  - 1) ) * (1 - Math.pow((1 + nRate / 200), (-nAmortMonths / nPaymentsPer6Months)) ) ) );     
}

function currencyString(nNumber) {
        nNumDec = 2;
        if (nNumber > 999999) nNumDec = 0;
        var str = "" + Math.round(nNumber * Math.pow(10,nNumDec));
        while (str.length <= nNumDec) {
                str = "0" + str;
        }
        var decpoint = str.length - nNumDec;
        var result = commaFmt(str.substring(0,decpoint) + "." + str.substring(decpoint,str.length));
        if (result.charAt(result.length - 1) == ".") result = result.substring(0, result.length - 1);
        return result;


}

function doCalcOnForm(form) {
        var bCMHCAlert = true;
        var nDownPayment = 0;
        var nFirstMortgage = 0;
        var nCMHCPremium = 0;
        var nTotalFinancing = 0;
        var nPayment = 0;
        var nExpenses = 0;
        var nTotal = 0;
        var nIncome = 0;
        if (checkForm(form)) {
                var nCounter = 0;
                for (nCounter = 1; nCounter <= 3; nCounter++) {

                        nDownPayment = (filterNum(form.io_price.value)) * (Number(form[("percent_down" + nCounter)].options[form[("percent_down" + nCounter)].selectedIndex].value) / 100);
                        form[("down_payment" + nCounter)].value = currencyString(nDownPayment);
                        // calculate first mortgage value
                        nFirstMortgage = (filterNum(form.io_price.value) - nDownPayment);
                        form[("first_mortgage" + nCounter)].value = currencyString(nFirstMortgage);

                        nCMHCPremium = (CMHCRate(Number(form[("percent_down" + nCounter)].options[form[("percent_down" + nCounter)].selectedIndex].value), form.io_amortization.options[form.io_amortization.selectedIndex].value)) * (nFirstMortgage) / 100;
                        form[("cmhc" + nCounter)].value = currencyString(nCMHCPremium);
                        nTotalFinancing = nFirstMortgage + nCMHCPremium;
                        form[("total_financing" + nCounter)].value = currencyString(nTotalFinancing);
                        nPayment = mortgagePayment(nTotalFinancing, Number(form.io_interest.value), (Number(form.io_amortization.options[form.io_amortization.selectedIndex].value)));
                        form[("monthly_payment" + nCounter)].value = currencyString(nPayment);
                        nExpenses = ( (Number(filterNum(form.io_heating.value)) + Number(filterNum(form.io_taxes.value)) ) /12 + Number(filterNum(form.io_condo.value))/12 );
                        form[("expenses" + nCounter)].value = currencyString(nExpenses);
                        nTotal = nExpenses + nPayment;
                        form[("total_payment" + nCounter)].value = currencyString(nTotal);
                        nIncome = nTotal * 12 / (Number(form.io_gds.value) / 100);
                        form[("income_required" + nCounter)].value = currencyString(nIncome);
                }
        } else {
                clearResults(form);
        }
}

function formatRealNum(theNum,decplaces) {
	var str = Math.round(parseFloat(filterNum(theNum.value)) * Math.pow(10,decplaces));
	str = ""+str;
	while (str.length <= decplaces) {
		str = "0" + str;
	}
	var decpoint = str.length - decplaces;
	return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
}

function formatInteger(theNum) {
	var str = Math.round(parseFloat(filterNum(theNum.value)));
	str = ""+str;
	return str;
}

function formatNum(theNum,decplaces,addcommas) {

	var str = ""+theNum.value;
	if ((str == "") || (str == "null")) {
		theNum.value = "";
		return false;
	}
	if (decplaces == 0) {
		var fmtdnum = formatInteger(theNum,decplaces);
	} else {
		var fmtdnum = formatRealNum(theNum,decplaces);
	}
	if (addcommas) {
		fmtdnum = commaFmt(fmtdnum);
	}
	theNum.value = fmtdnum;
	return true
}

function popupIsEmpty(theMenuObj) {
	var theSelection = theMenuObj.selectedIndex;
	if (theSelection <= 0) {
		return true;
	} else {
		return false;
    }
}

function scrub_RollNum(theNum,otherAllowed,minWildcardPosition) {
	var result = "";
	var allowed = "";
	otherAllowed +="";
	if (otherAllowed == 'undefined')
		otherAllowed = "";
	allowed = "0123456789"+ otherAllowed;

	result = scrub_String(theNum,allowed);
	
	for(i=result.length-1; i>=0; i--) {
		if(result.charAt(i) != ",")
			break;
		result = result.substring(0,i);
	}

	if (minWildcardPosition)
		result = parse_Wildcards (result,minWildcardPosition);

	return result;
}

function scrub_String(theStr,charsAllowed,charsAllowedOnce) {
	var result = "";
	var specialCharAt = -1;
	var specialChar = "";
	for(i=0;i<=theStr.length;i++) {
		theChar = theStr.charAt(i);
		if (charsAllowed.indexOf(theChar) != -1)
 			result +=theChar;
 		else if (charsAllowedOnce){
 			specialCharAt = charsAllowedOnce.indexOf(theChar);
 		 	if (specialCharAt != -1) {
 				result += theChar;
				charsAllowedOnce = charsAllowedOnce.substring(0,specialCharAt) 
					+ charsAllowedOnce.substring(specialCharAt+1,charsAllowedOnce.length);
 			}
 		}
	}
	return result;
}

function filterNum(theNum) {
	var minusStr = "";
	var result = "";

	if (theNum.indexOf("-") != -1)
		minusStr = "-";

 	result = scrub_String(theNum,"0123456789",".")

 	if (result == "")
 		return "";
	else
		return minusStr + result;
}

function commaFmt(numEle) {
	var tempStr = ""+numEle;
	
	var charCheck = tempStr.indexOf(",");
	if ((charCheck+0) >= 0) {
		return numEle;
	}

	var decStr = "";
	var decInt = tempStr.indexOf(".");
	if (decInt!=-1) {
		decStr = tempStr.substring(decInt,tempStr.length);
		tempStr = tempStr.substring(0,decInt);
	}

	var isNeg = false;
	if (tempStr.indexOf("-")!=-1) {
		isNeg=true;
        tempStr=tempStr.substring(1,tempStr.length);
	}

	if (tempStr.length<=3) { 
		return numEle;
	}

	var newStr = "";
	var jInt = 0;
	for (var iInt=tempStr.length-1;iInt>=0;iInt--) {
		jInt++;
		newStr = tempStr.charAt(iInt) + newStr;
		if (jInt%3==0) {
			if (iInt-1>=0) {
				newStr = ","+newStr;
			}
		}
	}

	if (decInt!=-1)
		newStr = newStr + decStr;
	if (isNeg)
		newStr = "-"+newStr;

	return newStr;
}

function format_Real(theNum,decplaces) {
	var str = filterNum(theNum);
	str = Math.round(parseFloat(str) * Math.pow(10,decplaces));
	str = ""+str;
	while (str.length <= decplaces) {
		str = "0" + str;
	}
	var decpoint = str.length - decplaces;
	return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
}

function format_Integer(theNum) {
// FORMAT AN INTEGER
	var str = filterNum(theNum);
	str = Math.round(parseFloat(str));
	return ""+str;
}

function format_Number(theNum,decplaces,addcommas) {
	var str = ""+theNum;
	if ((str == "") || (str == "null"))
		return "";

	if (decplaces == 0)
		var fmtdnum = format_Integer(str,decplaces);
	else
		var fmtdnum = format_Real(str,decplaces);
		
	if (addcommas) 
		fmtdnum = commaFmt(fmtdnum);
return fmtdnum;
}

function validateNum(theNum,decplaces,min,max,addcommas) {
	var str = filterNum(theNum.value);
	
	if ((str == "") || (str == "null")) {
		theNum.value = "";
		return false;
	}
	var tmpFloat = parseFloat(filterNum(theNum.value));
	
	if (tmpFloat < min || tmpFloat > max) {
		alert("Please enter a number between " + min + " and " + max + ".");
		theNum.value = "";
		theNum.focus();
		return false;
	}
	if (decplaces == 0) {
		var fmtdnum = formatInteger(theNum,decplaces);
	} else {
		var fmtdnum = formatRealNum(theNum,decplaces);
	}
	if (addcommas) {
		fmtdnum = commaFmt(fmtdnum);
	}
	theNum.value = fmtdnum;
	return true
}

function validatePrice(theNum,min,max,addcommas) {
	var str = filterNum(theNum.value);
	if ((str == "") || (str == "null")) {
		theNum.value = "";
		return false;
	}
	var tmpFloat = parseFloat(filterNum(theNum.value));
	
	if (tmpFloat < min || tmpFloat > max) {
		alert("Please enter a number between " + min + " and " + max + ".");
		theNum.value = "";
		theNum.focus();
		return false;
	}
	if (tmpFloat < 100) {
		decplaces = 2;
	} else {
		decplaces = 0;
	}
	
	if (decplaces == 0) {
		var fmtdnum = formatInteger(theNum,decplaces);
	} else {
		var fmtdnum = formatRealNum(theNum,decplaces);
	}
	if (addcommas) {
		fmtdnum = commaFmt(fmtdnum);
	}
	theNum.value = fmtdnum;
	return true
}


function str_Empty (theFormObj){
	if (theFormObj.value+"" == "null")
		return true;
	else if (theFormObj.value == "")
		return true;
	return false;
}



function popup_Empty(theMenuObj) {
	var theSelection = theMenuObj.selectedIndex;
	if (theSelection == -1)
		return true;
	else if (theMenuObj.options[theSelection].value == '')
		return true;
	else
		return false;
}



function field_Empty (theFormObj){
	if (!theFormObj) {
		return false;
	}

	var theType = theFormObj.type;
	if (theType.indexOf('select') != -1)
		return popup_Empty(theFormObj)
	else
		return str_Empty (theFormObj)
}



function list_Empty(theMenuObj) {
	var isEmpty = true;
	for(i=1;i<theMenuObj.length;i++) {
		if (theMenuObj.options[i].selected)
			isEmpty = false;
	}
	return isEmpty;
}



function numberRange_OK(fromNumObj,toNumObj)
{
	if (fromNumObj.value == "" || toNumObj.value == "")
		return true;
		
	var tmpFromFloat = parseFloat(filterNum(fromNumObj.value));
	var tmpToFloat = parseFloat(filterNum(toNumObj.value));
	if (tmpToFloat < tmpFromFloat) {
		alert(toNumObj.name+"  is greater than  "+toNumObj.name+"   Please re-enter");
		fromNumObj.value = "";
		toNumObj.value = "";
		fromNumObj.focus();
		return false;
	}
	return true;
}



function wildcard_Alert () {
	alert('Wildcard Search Enabled\n  "?" - Searches for any single character.\n'
		+ '  "*" - Searches for any characters of any length.');
}



function scrub_multi_value_field(fieldContents,minWildcardPosition) {
	var result = "";
	if (fieldContents == "" || fieldContents=='undefined')
		return "";
	if (minWildcardPosition == "" || minWildcardPosition=='undefined')
		minWildcardPosition = 0;

	fieldContents = scrub_Text (fieldContents,true);
	if (fieldContents.indexOf(",") == -1) {
			result = parse_Wildcards (fieldContents,minWildcardPosition);
	}
	else {
		var fieldContents_Array = fieldContents.split(",");
	
		for(var sc_x=0;sc_x < fieldContents_Array.length; sc_x++) {
	  		if (fieldContents_Array[sc_x] == "") 
	  			continue;
	  		if(fieldContents_Array[sc_x].charAt(0) == " ")
				fieldContents_Array[sc_x] = fieldContents_Array[sc_x].substring(1,fieldContents_Array[sc_x].length);
	  		if(fieldContents_Array[sc_x].charAt(fieldContents_Array[sc_x].length - 1) == " ")
				fieldContents_Array[sc_x] = fieldContents_Array[sc_x].substring(0,fieldContents_Array[sc_x].length - 1);
			result = result + parse_Wildcards (fieldContents_Array[sc_x],minWildcardPosition);
			result = result + ",";
		}
		// remove commas from the end of the string
		for(sc_i=result.length-1; sc_i>=0; sc_i--) {
			if(result.charAt(sc_i) != ",")
				break;
			result = result.substring(0,sc_i);
		}
	}
	return result;
}


function scrub_select_mult(elem, maxn) { 
	var valid = true;
	var cnt = 0;
	for (var i=0; i<elem.options.length; i++) {
		if (valid) {
			if (elem.options[i].selected) { 
				cnt ++;
				if (cnt > maxn) { 
					valid = false;
					alert("You can select only " + maxn + " items in the list"); 
					elem.options[i].selected = false; 
				}
			}
		} else {
			elem.options[i].selected = false; 
		}
	}
	return valid; 
}



function isNum(inString)  {
	if(inString.length!=1) 
		return false;
	var refString="1234567890";
	if (refString.indexOf(inString,0) == -1) 
		return false;
	return true;
}



function isChar(inString)  {
	if(inString.length!=1) 
		return false;
	var refString="abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ";
	if (refString.indexOf(inString,0) == -1) 
		return false;
	return true;
}

function replace_Char (unwantedChar,wantedChar,theStr) {
	while ((x=theStr.indexOf(unwantedChar)) != -1) {
		theStr = theStr.substring(0,x) + wantedChar 
			+ theStr.substring(x+unwantedChar.length,theStr.length);
	}	
	return theStr;
}

function scrub_String_Unwanted(theStr,charsUnwanted) {
	var result = "";
	var theChar = "";
	var ok = true;
	var i = 0;
	for(i=0;i<=theStr.length;i++) {
		theChar = theStr.charAt(i);
		if (theChar == '"')
			result += "`"
		else if (theChar == "'")
			result += "`"
		else if (charsUnwanted.indexOf(theChar) == -1)
 			result += theChar;
	}
	return result;
}

function parse_Wildcards (theStr,minWildcardPosition) {
	theStr = scrub_String_Unwanted(theStr,"%_");
	if (minWildcardPosition == 0) {
		if (theStr.indexOf("*") != -1 || theStr.indexOf("?") != -1 ) {
			alert("Wildcards are not allowed in this field.");
			theStr = replace_Char("*","",theStr);
			theStr = replace_Char("?","",theStr);
		}
	} else {
		var tmpStr = theStr.substring(0,minWildcardPosition);
		if (tmpStr.indexOf("*") != -1 || tmpStr.indexOf("?") != -1 ) {
			alert("A wildcard can only be used after character " + minWildcardPosition 
				+ " in this field.");
			theStr = replace_Char("*","",theStr);
			theStr = replace_Char("?","",theStr);
		} else {
			var x = theStr.indexOf("*");
			if (x != -1) {
				tmpStr = theStr.substring(x+1,theStr.length);
				if (tmpStr.indexOf("*") != -1 ) {
					alert("Only one * wildcard is allowed in this field.");
					theStr = replace_Char("*","",theStr);
					theStr = replace_Char("?","",theStr);
				}
			}
		}
	}
	return theStr;
}



function scrub_Text (theStr,makeUpper,minWildcardPosition,allowQuotes) {
	theStr += "";
	if (theStr == "null" || theStr == "")
		return "";
	for(var i=0; i<theStr.length; i++) {
		if(theStr.charAt(0) != " ")
			break;
		theStr = theStr.substring(1,theStr.length);
	}
	for(i=theStr.length-1; i>=0; i--) {
		if(theStr.charAt(i) != " ")
			break;
		theStr = theStr.substring(0,i);
	}

	var perc = "";
	if (makeUpper) {
		theStr = theStr.toUpperCase();
		perc = "%_";
	}
	if (allowQuotes != 'true')
		theStr = scrub_String_Unwanted(theStr,perc);

	if (minWildcardPosition && minWildcardPosition > '')
		theStr = parse_Wildcards (theStr,minWildcardPosition);

	return theStr;
}



function numberFilter (s) {
filteredValues = "1234567890";  
var i;
var returnString = "";
for (i = 0; i < s.length; i++) { 
var c = s.charAt(i);
if (filteredValues.indexOf(c) != -1) returnString += c;
}
	return returnString;
}

function calculate(){
	price = numberFilter(document.calculator.price.value);
	leftt = price;
	total_tax = 0;
	toronto_tax = 0;


	if (price > 55000){
		tmp_tax = 55000 * 0.005;
		total_tax += tmp_tax;
		price -= 55000;
	} else {
		tmp_tax = price * 0.005;
		total_tax += tmp_tax;
		price = 0;
	}


	if (price > 195000){
		tmp_tax = 195000 * 0.01;
		total_tax += tmp_tax;
		price -= 195000;
	} else {
		tmp_tax = price * 0.01;
		total_tax += tmp_tax;
		price = 0;
	}


	if (price > 150000){
		tmp_tax = 150000 * 0.015;
		total_tax += tmp_tax;
		price -= 150000;
	} else {
		tmp_tax = price * 0.015;
		total_tax += tmp_tax;
		price = 0;
	}

	if (price > 0){
		tmp_tax = price * 0.02;
		total_tax += tmp_tax;
		price = 0;
	}

	if (document.calculator.firsttimehomebuyer.checked==true){
		if (total_tax > 2000)
			total_tax = total_tax - 2000;
		else
			total_tax = 0;
	}
	total_tax = Math.round(total_tax);
	if (document.calculator.torontopurchase.checked==true){
		if (leftt > 55000){
			toronto_tax = 275;
			leftt = leftt - 55000;
		} else {
			toronto_tax = leftt * .005;
			leftt = 0;
		}


		if (leftt > 345000){
			toronto_tax = toronto_tax + 3450;
			leftt = leftt - 345000;
		} else {
			toronto_tax = toronto_tax + (leftt * .01);
			leftt = 0;
		}

		if (document.calculator.firsttimehomebuyer.checked==true)
			toronto_tax = 0;

		if (leftt > 0){
			toronto_tax = toronto_tax + (leftt * .02);
		}
		toronto_tax = Math.round(toronto_tax);
		total_tax = total_tax + toronto_tax;
	}

	document.calculator.tax.value = total_tax;

}
