///////////////////////////////////////////
///////////// initialization //////////////
///////////////////////////////////////////

var nvlSlider;
var mvlSlider;
var maxMonthlyIsZero;

function getCommonSliderConfig()
{
	return {
		'b_vertical' : false,
		'b_watch': true,
		'n_controlWidth': 292,
		'n_controlHeight': 22,
		'n_sliderWidth': 14,
		'n_sliderHeight': 22,
		'n_pathLeft' : 0,
		'n_pathTop' : 0,
		'n_pathLength' : (292 - 14),
		's_imgControl': '/static/common/images/slider_rail.gif',
		's_imgSlider': '/static/common/images/slider_handle.gif',
		'n_zIndex': 1
	}
} 

function initNowVsLaterSlider(maxVal, theVal)
{
	var A_TPL = getCommonSliderConfig();
	var A_INIT = {
		's_name': '_upfrontAmount',
		'n_minValue' : 0,
		'n_maxValue' : maxVal,	// parameter value
		'n_value' : (isNaN(theVal) ? 0 : theVal),
		'n_step' : 1000,
		'h_onMove' : updateUpfront
	}
	
	return (new slider(A_INIT, A_TPL));
}

function initMonthlyVsLocSlider(maxVal, theVal)
{
	maxMonthlyIsZero = (maxVal == 0);
	var B_TPL = getCommonSliderConfig();
	var B_INIT = {
		's_name': '_monthlyAmount',
		'n_minValue' : 0,
		'n_maxValue' : (maxVal+0.001), // 0.001 - hack to avoid DIV/0 in slider.js
		'n_value' : (isNaN(theVal) ? 0 : theVal),
		'n_step' : 10,
		'h_onMove' : updateMonthly
	}

	return (new slider(B_INIT, B_TPL));
}

///////////////////////////////////////////
///////////// event handlers //////////////
///////////////////////////////////////////
function updateUpfront(upfront)
{
	// the 'upfront' arg contains the updated value set by the slider
	var npl = Math.floor(document.getElementById('netPrincipalLimit').value);
	var up = Math.floor(upfront);

	// set the value of the visible textbox
	document.getElementById('remaining').value = formatCurrency(npl - up, false);
	document.getElementById('upfrontAmount').value = formatCurrency(up, false);
	configMonthly(up);
	
	return true;
}

function updateMonthly(monthly)
{
	if(mvlSlider.n_maxValue > 0)
	{
		document.getElementById('monthlyAmount').value = formatCurrency(monthly, false);
		return true;
	}
	else
	{
		document.getElementById('monthlyAmount').value = formatCurrency(0, false);
		return false;
	}
}

function lockMonthly(ignored)
{
	this.f_setValue(0);
	return true;
}

function configMonthly(upfront)
{
	// update the "max per month" (upper limit of the second slider):
	var npl = Math.floor(document.getElementById('netPrincipalLimit').value);
	
	var remaining = (npl - upfront);
	var maxMonthly = Math.floor(calculatePayments(remaining));
        
        if(maxMonthlyIsZero) {// avoid changing monthly max if it was zero to start with
		maxMonthly = 0;
	}
		
	if(maxMonthly == 0)
	{
		// if there is no more $ left to allocate to monthly payments, 
		mvlSlider.f_setValue(0);
		mvlSlider.h_onMove = lockMonthly;
	}
	else
	{
		mvlSlider.h_onMove = updateMonthly;
		// see http://www.softcomplex.com/support/view.php?ticketref=3568-WERV-9928
		// for an explanation of what this next fragment does
		mvlSlider.n_maxValue = maxMonthly;
		mvlSlider.s0c = mvlSlider.n_pathLength / (mvlSlider.n_maxValue - mvlSlider.n_minValue);
		mvlSlider.n_increments = mvlSlider.n_step ? mvlSlider.n_step : (mvlSlider.n_maxValue - mvlSlider.n_minValue) / 10;

		if(mvlSlider.n_value > maxMonthly)
		{
			// if the second slider's old value is greater than the new max, set the second slider's value to the new max
			mvlSlider.f_setValue(maxMonthly);
		}
		else
		{
			// otherwise set it to the original value in order to force the handle into the correct relative position
			mvlSlider.f_setValue(mvlSlider.n_value);
		}
	}

	updateMonthly(mvlSlider.n_value);

	// update the "max per month" caption
	var mmCaption = document.getElementById('maxMonthly');
	mmCaption.innerHTML = formatCurrency(maxMonthly, false, '\$');

	return true;
}

///////////////////////////////////////////
//////////// helper functions /////////////
///////////////////////////////////////////

// this function is intended to be called as an event handler on a text-entry form field
function setUpfrontPosition(ctl)
{
	// ctl is the form control that fired the event being handled by this function
	var npl = Math.floor(document.getElementById('netPrincipalLimit').value);
	var up, rem;

	// "remaining" textbox has been disabled because of the funky behavior associated with rounding off values
/*
	switch(ctl.id) {
		case 'upfrontAmount':
*/
			up = currencyToFloat(ctl.value);

			if(up <= npl) {
				rem = npl - up;
			} else {
				up = npl;
				rem = 0;
			}
/*
			break;

		case 'remaining':
			rem = currencyToFloat(ctl.value);

			if(rem <= npl) {
				up = npl - rem;
			} else {
				rem = npl;
				up = 0;
			}
			break;
	}
*/	

	if(!isNaN(up) && !isNaN(rem)) {
		// set slider position; if v is > slider.n_maxValue
		/*
		// redundant!!  see above
		if(up > nvlSlider.n_maxValue)
			nvlSlider.f_setValue(nvlSlider.n_maxValue);	// use n_maxValue instead of up
		else
		*/
			nvlSlider.f_setValue(up);
	}
	
	updateUpfront(up);

	return true;
}

// this function is intended to be called as an event handler on a text-entry form field
function setMonthlyPosition(ctl)
{
	
	if(maxMonthlyIsZero) {
            ctl.value = formatCurrency(0, false);
        }
	var monthly = currencyToFloat(ctl.value);
	// set slider position; if v is > slider.n_maxValue
	if(monthly > mvlSlider.n_maxValue) {
	   ctl.value = formatCurrency(mvlSlider.n_maxValue, false);	    
	    mvlSlider.f_setValue(mvlSlider.n_maxValue);
	    // use n_maxValue instead of monthly		
	    
	}else {
	    mvlSlider.f_setValue(monthly);
        }
	updateMonthly(monthly);
	return true;
     
}

function calculatePayments(remaining)
{
	// refresh/redeclare second slider
	var termDrop = document.getElementById("numTermPayments");
	var numTermPayments = termDrop.options[termDrop.selectedIndex].value;

	// use the HECM formula to determine the dollar amount of each monthly payment:
	//		monthlyPayment = (1 + i){Sup m} x i / [(1 + i) {Sup (m+1)} - (1 + i)]
	// where:
	//		i = monthly compounding rate ( (expectedRate + annualMIPRate) / 12 )
	//		m = total number of monthly payments over the course of the loan

	//  (note that although this formula is not identical to the one listed as Equation 6 in
	//	 Appendix 22 of HUD Handbook 4235.1, we have confirmation from HUD that THIS is the 
	//	 correct formula to use and the one published in 4235.1/A22/E6 is INCORRECT!  --ED)

	var expRate = parseFloat(document.getElementById('expectedRate').value);
	var mipRate = parseFloat(document.getElementById('annualMIPRate').value);
	var i = (expRate + mipRate) / 12;
	var m = (numTermPayments == 'TENURE') ? Number(document.getElementById('loanLifetime').value) : Number(numTermPayments);

	var pmt = remaining * Math.pow(1 + i, m) * i / (Math.pow(1 + i, m + 1) - (1 + i));

	return pmt;
}

function updateSellingCost(){  
	
	var chsp = document.getElementById('currentHomeSalePrice').value.replace(/,/g, "");
	var costPercentage = document.getElementById('sellingCostRate').value;
	var sellingCost = (chsp * costPercentage)/100;		
	var mmCaption = document.getElementById('sellingCost');
	mmCaption.innerHTML = formatCurrency(sellingCost, false, '\$');

	return true;
}
