/*******************************************************
LTV - Loan to Value
EHV - Estimated Home Value
1MB - 1st Mortgage balance
2MB - 2nd Mortgage Balance
Cashout , Additional Cash to Borrow and Total Amount of Debt you wish to Consolidate are all similar terms
calculated as follows: 120% of EHV - 1MB - 2MB

********************************************************/
	//Loan to Value <= 100% for 1st Mortgage Balance	
	var LTV = .95;
	//Loan to Value <= 120% for Additional Cash To Borrow
	var LTV2 = 1;
	//Loan to Value <= 120% for 2MB
	var LTV2MB = 1;	
	
	//Additional Cash To Borrow field will be hidden until Available Equity > 0 is confirmed
	// (Available Equity = (120% X Estimated Home Value) - 1st mortgage balance - 2nd mortgage balance)
	var visibleCashout = false;
	var noEquityOptions = new Array();
	//Available Equity is less than 2500 (no cash out option)
	var noCashoutOptions = new Array();
	
	//Available Equity is greater than 2500, but less than 5000, dropdown has only 2 values 0 & 2500 (short cash out options)
	var shortCashoutOptions = new Array();
	
	//Available equity is greater than 5000, dropown options from 0 to Available Equity in $5000 increments (full cash out options)
	var fullCashoutOptions = new Array();
	
	//1st mortgage balance dropdown options (upper limit -> 100% of EHV)
	var mb1Options = new Array();
	
	//2nd mortgage balance dropdown options (upper limit -> 125% of EHV)
	var mb2Options = new Array();
	
	//The RangeEntry object - defines one option eg: 1st Mortgage balance - 5,000-10,000 lo:5000, hi:10000 value:7500 label:5,000-10,000
						   //another eg: Additional Cash to Borrow: 2500 lo:2500 hi:4999 value:2500 label:2500
	function rangeEntry(hi, lo, value, label) {
	    this.hi = hi;
	    this.lo = lo;
	    this.value = value;
	    this.label = label;
	}
	
	function getInteger(vNum) {
    vNum = getIntegerString(vNum.toString());
    if (vNum == "") {
        vNum = 0;
    }
    return Number(vNum);
}
	function getIntegerString(strIn) {
    return strIn.replace(/[^0-9]/g, "");
}
	
	//format the range label with commas
	function hiloRangeLabel(hi, lo) {
	    return addCommasToNumString(lo.toString())+" - "+addCommasToNumString(hi.toString());
	}
	function addCommasToNumString(strIn) {
    var arrTemp = strIn.split("");
    var i = strIn.length - 4;
    var iPoint = strIn.indexOf(".");
    if (iPoint > -1) {
        i -= (strIn.length - iPoint);
    }
    for (i; i >= 0; i -= 3) {
        arrTemp[i] += ",";
    }
    return arrTemp.join("");
}

	//Initialize the additional cash to borrow option
	function initCashoutOptions() {

	    //there is no additional cash to borrow
		//the select box displays 0 and is disabled
	    noCashoutOptions[0] = new rangeEntry(0, 0, "0", "0");
		noEquityOptions[0] = new rangeEntry(0, 0, "0", "Equity Unavailable");
		//if equity available >2500 but <5000, the two options are 0 and 2500
		//the cashout dropdown does not show ranges: therefore the label for eg, is 2500 rather than 2,500-5000
	    shortCashoutOptions[0] = new rangeEntry(0, 0, "", "- Select -");
	    shortCashoutOptions[1] = new rangeEntry(2499, 0, "0", "0");
	    shortCashoutOptions[2] = new rangeEntry(4999, 2500, "2500", "2500");
		
	}
	
	//1st Mortgage Balance Initialization
	function initMB1Options() {
	    mb1Options[0] = new rangeEntry(0, 0, "", "- Select -");
	    mb1Options[1] = new rangeEntry(0, 0, "100001", "100000");
	    var lo = 100001;
	    var hi = 105000;
	    var i = 2;
		//upto 200,000 increment $5000 for next range
		//selected value is average of hi and lo - so lo+2499 gives the average for a $5000 increment
	    for (; lo<200000; i++) {
	        mb1Options[i] = new rangeEntry(hi, lo, lo+2499, hiloRangeLabel(hi, lo));
	        lo = hi + 1;
		    hi += 5000;
	    }
	    hi = 210000;
		//upto 400,000 increment $10000 for next range
		//selected value is average of hi and lo - so lo+4999 gives the average for a $5000 increment
	    for (; lo<400000; i++) {
		mb1Options[i] = new rangeEntry(hi, lo, lo+4999, hiloRangeLabel(hi, lo));
		lo = hi + 1;
		hi += 10000;
	    }
	    hi = 420000;
		//over 400,000 increment $20000 for next range
		//selected value is average of hi and lo - so lo+2499 gives the average for a $20000 increment
	    for (; hi<=1000000; i++) {
		mb1Options[i] = new rangeEntry(hi, lo, lo+9999, hiloRangeLabel(hi, lo));
		lo = hi + 1;
		hi += 20000;
	    }
		hi = 1000001;
		//over 1,000,000 increment $1,000,000 for next range
		//selected value is average of hi and lo - so lo+2499 gives the average for a $20000 increment
	    for (; hi<=2400000; i++) {
		mb1Options[i] = new rangeEntry(hi, lo, lo+99999, hiloRangeLabel(hi, lo));
		lo = hi + 1;
		hi += 100000;
	    }
	    mb1Options[mb1Options.length] = new rangeEntry(2400000, 2400000, 2400000, "Over 2,400,000");

	}
	//2nd Mortgage Balance Initialization
	function initMB2Options() {
	    mb2Options[0] = new rangeEntry(0, 0, "", "Select One");
	    mb2Options[1] = new rangeEntry(0, 0, "0", "0");
	    var lo = 1;
	    var hi = 5000;
	    var i = 2;
		//upto 200,000 increment $5000 for next range
		//selected value is average of hi and lo - so lo+2499 gives the average for a $5000 increment
	    for (; lo<200000; i++) {
	        mb2Options[i] = new rangeEntry(hi, lo, lo+2499, hiloRangeLabel(hi, lo));
	        lo = hi + 1;
		    hi += 5000;
	    }
	    hi = lo + 24999;
		//upto 400,000 increment $10000 for next range
		//selected value is average of hi and lo - so lo+4999 gives the average for a $5000 increment
	    for (; lo<1000000; i++) {
		mb2Options[i] = new rangeEntry(hi, lo, lo+12499, hiloRangeLabel(hi, lo));
		lo = hi + 1;
		hi += 25000;
	    }
	    mb2Options[mb2Options.length] = new rangeEntry(1000001, 1000001, 1000001, "Over 1,000,000");
	}	
	//Determine in the rangeOptions array of rangeEntry objects  where the value lies
	//For eg to determine the highest value for the 1st mortgage dropdown based on the chosen EHV:
	//The 'rangeoptions' array would be passed values from mb1Options and the 'value ' would be EHV * 100%
	//Another Eg: In order to find the selected value of the 1st mortgage balance: rangeoptions -> mb1Options and value ->mortgage1_balance (hidden field corresponding to 1st mortgage balance)
	function indexofValueRange(rangeOptions, value) {
		
	    if (value == null) return 0;
	    var val = value;
	    if (typeof value == "string") {
	        if (value == "") return 0;
		val = parseInt(value, 10);
	    }
	    if (isNaN(val)) return 0;
		//Determine the exact range within which the value falls in the list of range entries
	    for (i=1; i<rangeOptions.length; i++) {		
			if (val >= rangeOptions[i].lo && val <= rangeOptions[i].hi) {
			    return i;
			}
	    }
	    return rangeOptions.length-1;
	}
	
	//Create the option array for the dropdown
	function setSelectionOptions(sfield, template, topIdx, valIdx) {
	    sfield.options.length = 0;
	    sfield.options[0] = new Option(template[0].label, template[0].value, true);
	
	    var top = topIdx>=0? topIdx+1 : template.length;
	    for (i=1; i<top; i++) {
	        sfield.options[i] = new Option(template[i].label, template[i].value, false, i==valIdx?true:false);
	    }
	}
	
	
	function setOptions(sfield, equity, value, options) {
		    var equityIndex = indexofValueRange(options, equity);
		    var valueIndex = indexofValueRange(options, value);
			//sfield - >field name for the dropdown
			//options -> the arracy containing range entry objects
			//equityIndex -> the upper limit for the dropdown
			//valueIndex -> the selected value for that dropdown
		    setSelectionOptions(sfield, options, equityIndex, valueIndex);
	}
	
	//Determine the options for the ACTB field based on available equity
	//For equity < 2500 there is no cashout option
	//For equity >2500 <5000, the options are 0,2500 only
	//For equity>5000, the options are 0 to equity available
	function cashoutOptionsBy(equity) {
	    if (equity < 2500) return noCashoutOptions;
	    if (equity < 5000) return shortCashoutOptions;
		 //if available equity is greater than 5000,  dropdown selections are 0, 1-5,000, 5,001-10,000 etc upto available equity (max Over150,000)
		fullCashoutOptions = new Array();
		fullCashoutOptions[0] = new rangeEntry(0, 0, "", "- Select -");
	    fullCashoutOptions[1] = new rangeEntry(0, 0, "20001", "20000");
		var lo = 25001;
		var hi = 30000;
		
		var limit = (equity);
	   
		i=2;	
		//increment $5K upto 200,000	
	    for (; lo<=200000 && lo<=limit; i++) {
			
	        fullCashoutOptions[i] = new rangeEntry(hi, lo, lo+2499, hiloRangeLabel(hi, lo));
	        lo = hi + 1;
			hi += 5000;
	    }
		//start incrementing in 25K to limit scrolling of dropdown
		if(limit > 200000) {
		    hi = 225000;
			
			//create new option for the cashout dropdown only until available equity is lesser than a million
		    for (; lo<=limit && hi <=1000000  ; i++) {
			
				fullCashoutOptions[i] = new rangeEntry(hi, lo, lo+12499, hiloRangeLabel(hi, lo));
				lo = hi + 1;
				hi += 25000;
				
		    }
		}		
	    return fullCashoutOptions;
	}

	//Return the integer value of the selected EHV
	function ehvValue() {
	    return getInteger(document.app.home_value.value);
	}
	
	//return the integer value of the hidden field mortgage1_balance
	function mb1Value() {
	    return getInteger(document.app.mortgage1_balance.value);
	}
	
	//return if the 2nd mortgage balance option (yes or no)
	function touchedMB2() {
	    var choice = document.app.second_mortgage
	    return choice[0].checked || choice[1].checked;
	}
	
	//return the selected value for the mortgage 2 option
	function mb2Value() {
	    return getInteger(document.app.mortgage2_balance.value);
	}
	
	//return the selected value for the additional cash to borrow field
	function cashoutValue() {
	    return getInteger(document.app.cash_out.value);
	}
	
	//Reset the 1st mortgage balance selected value to Select One
	//This happens when Estimated Home Value is changed and the current 1st mortgage balance falls outside the revised upper limit, where upper limit is 100% of EHV
	//Eg: User chooses Estimated Home Value 140,001-145,000, 1st mortgage balance to 130,001-135,000
	//Then the user changes EHV to 100,001-105,000, now the new 1st mortgage balance upper limit is 100,001-105,000. However the previous selection of 130,001-135,000 falls outside the revised upper limit
	//Hence the selected value of 1st mortgage balance is now reset to "Select One" (selectedIndex of 0)
	function resetMB1() {
	    document.app.mort_bal.selectedIndex = 0;
	    document.app.mortgage1_balance.value = "";
	}
	
	//Set 2nd mortgage balance to 'Select One'
	//Will happen if EHV / 1st mortgage balance is revised and the 2nd mortgage balance falls outside the revised limit
	function resetMB2() {
	    document.app.mortgage2_balance.selectedIndex = 0;
		document.app.mortgage2_balance.value = "";
	}
	//reset cashout options if enough equity cannot be confirmed 
	function resetCashout() {
	    setOptions(document.app.cashout_dropdown, 0, null, noCashoutOptions);
	    document.app.cash_out.value = "";
	}

	function resetCashoutNoEquity() {
	    setOptions(document.app.cashout_dropdown, 0, null, noEquityOptions);
	    document.app.cash_out.value = "";
	}
	function showElement(strID) {
	try { document.getElementById(strID).style.display = ""; } catch(ex) {}
}
function hideElement(strID) {
	try { document.getElementById(strID).style.display = "none"; } catch(ex) {}
}
	//Cashout field is visible, but disabled. This happens when at any point of time the following cannot be confirmed
	//Available Equity = (EHV * 120%) - 1MB - 2MB
    //For eg, EHV = 130,001-135,000 and 1MB = 35,001-40,000, the cashout field is visible & enabled, but if the user chooses the 2nd Mortgage Balance option to yes, the cashout field is diabled (still visible) until it
	//can be confirmed that enough equity will be available after the user selects a value for the 2nd mortgage balance
	function disableCashout() {
	    if (visibleCashout) {
	        document.app.cashout_dropdown.disabled = true;
	    }
	}
	//Cashout field is made visible and enabled so that the user may choose values
	//This happens when Available Equity = (EHV * 120%) - 1MB - 2MB can be confirmed to be greater than 2500
	function enableCashout() {
	    if (!visibleCashout) {
	        showElement("ffCashOut");
	        visibleCashout = true;
	    }
	    document.app.cashout_dropdown.disabled = false;
		document.app.cashout_dropdown.selectedIndex = 0;
	}

	//If available equity cannot be determined, reset and disable cash out
	//Else cashout options are set upto available equity from 0 (exceptions no cashout for equity<2500 and only 2 options (0,2500) for equity>2500 but <5000)
	function setupCashout(equity) {
	
		var cashoutOptionsArray = new Array();
	    if (equity <= 0) {
		resetCashout();
		//disableCashout();
	    }
	    else {
			
	        setOptions(document.app.cashout_dropdown, equity, document.app.cash_out.value, cashoutOptionsBy(equity));			
	        enableCashout();			
			if(equity < 5000) cashoutOptionsArray = shortCashoutOptions;
			else cashoutOptionsArray = fullCashoutOptions;
					document.app.cashout_dropdown.value = document.app.cash_out.value;
			//reset cashout if it falls outside the equity
			if(cashoutValue() > equity || document.app.cash_out.value == "") {
				
				document.app.cashout_dropdown.selectedIndex = 0;
				if (document.app.cashout_dropdown.value == "0")
				{
					//disableCashout();
					resetCashoutNoEquity();
				}
			}
			//else find the range where the cashout lies (eg 32,500 - 30,001-35,000)
			else document.app.cashout_dropdown.selectedIndex = (indexofValueRange(cashoutOptionsArray,cashoutValue()));
			
	    }
	}

	//If there is a second mortgage, but its value is not chosen, then the available equity cannot be confirmed, so reset cashout and disable it
	//Else setup cashout following the rule - additional cash to borrow is 120% of EHV minus the mortgage balances (1&2)
	function onChangeMB2() {
		document.application.mortgage2_balance.value = document.app.mb2_dropdown.value;
		if(document.app.mortgage2_balance.value != "") 
		 setupCashout(ehvValue() * LTV2 - mb1Value() - mb2Value());
	}

	//Second Mortgage option is chosen (yes)
	//Then check for the value of second mortgage to confirm enough equity for cashout
	//If the second mortgage option is not chosen (no), then set cashout options as 120% of EHV minus the 1st mortgage balance only
	function checkM2Radio() {
		var limit2MB;
		
	    if (document.app.second_mortgage[0].checked) { //"Yes" is checked.	
			if(document.app.mb2_dropdown.value == "")
			setupCashout(-1);
		    document.app.mortgage2_balance.value = document.app.mb2_dropdown.value;
			limit2MB = ehvValue() * LTV2MB - mb1Value() - cashoutValue();
			limit2MB = parseInt(limit2MB);		
			setOptions(document.app.mb2_dropdown, limit2MB, document.app.mortgage2_balance.value, mb2Options);										
	        onChangeMB2();
	        return;
	    }
		//Later on if the user chooses no for 2MB then we need to evaluate if enough equity is available for cash out
		else {
			document.app.mb2_dropdown.selectedIndex = 0;
			document.app.mortgage2_balance.value = 0;
			document.app.mortgage2_interest_rate.selectedIndex=0
			setupCashout(ehvValue() * LTV2 - mb1Value());
		}
			
	}
	
	//If MB1 is reset to Select One or if EHV is reset, the 2nd mortgage balance and the cashout dropdowns are reset.
	//Otherwise we go on to check if a second mortgage balance is there
	function onChangeMB1() {
	
	    document.app.mortgage1_balance.value = document.app.mort_bal.value;
		setupCashout(ehvValue() * LTV2 - mb1Value());
	}

	//When an Estimated Home Value is chosen, the 1st mortgage options are set
	function onChangeEHV() {
    //debugger;
		//Upper Limit of 1st Mortgage Balance is 100% of Estimated Home Value
	    var limit = ehvValue() * LTV;		
	    setOptions(document.app.mort_bal, limit, document.app.mortgage1_balance.value, mb1Options);		
		var flag = ehvValue() * LTV2 - mb1Value();
		
		if(flag>0)
			setupCashout(ehvValue() * LTV2 - mb1Value());
	    onChangeMB1();
	}//Initialize cashout and 1st mortgage options
	function initInternals() {
		
	    if (document.app.cash_out.value != "") {
	        showElement("ffCashOut");
	        visibleCashout = true;
	    }		
	    initMB1Options();
	    initCashoutOptions();
		
	    onChangeEHV();
	}
	

