YAHOO.namespace("TMM.form.mortgage");


YAHOO.TMM.form.mortgage.LoanValueCalculator = function(cfg){

	this.estimatedValueField = document.getElementById(cfg.estimatedValueField);
	this.loanValueField = document.getElementById(cfg.loanValueField);
	
	    
    // only add the listener if we have the fields we want
    if(this.estimatedValueField != null &&  this.loanValueField != null) {
    
	    YAHOO.util.Event.addListener(this.estimatedValueField, "change", this.limitLoanValue, this, true);
	    this.limitLoanValue(null);
    }
};

YAHOO.TMM.form.mortgage.LoanValueCalculator.prototype = {
	
	limitLoanValue : function(e){
		
		var selectLoanValue = getInteger(this.loanValueField.value);
		var selectVar = getInteger(this.estimatedValueField.value);
        for(var i=this.loanValueField.options.length; i>0; i--) {
			this.loanValueField.remove(i);
		}
		
		limit(selectVar*.95, this.loanValueField);
		
		this.updateLoanValue(selectVar, selectLoanValue);
	},
	
	putCommas : function(x)
	{
	x += "";
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x)) {
		x = x.replace(rgx, '$1' + ',' + '$2');
	}
	return x;
	
	},
	
	updateLoanValue : function(selectVar, selectedValue) {
		var percent = 5;
		var perc = .5;
		var bool = false;
		this.loanValueField.options.length=0;
		var i = 0;
		this.loanValueField.options.length=1;
		this.loanValueField.options[i].text = 'Select..';
		i++;
		if(selectVar >0 ){
		this.loanValueField.options.length=i;
		//Used to determine the least value which is accepted in LOAN_VAL field
		var minLoanVal = 25000;
		
		//minLoan is defined in the template which comes from the model
		if( minLoan && minLoan > 0)
		{
			minLoanVal = minLoan;
		}	
		
		for(percent = 5; percent<=95;percent=percent+5){
			
		    var lowerBound = Math.floor((percent-2.5)*selectVar/100);
			var upperBound = Math.floor((percent+2.5)*selectVar/100);
			// upperBound should be greater than min Loan Value
			if(upperBound >= minLoanVal){
			this.loanValueField.options.length=i+1;
			var temp1 = this.putCommas(lowerBound+1);
			var temp2 = this.putCommas(upperBound);
			this.loanValueField.options[i].text = temp1 +' - '+ temp2 +' ('+percent+'%) ';
			var temp3 = ((lowerBound+upperBound)/2);
			this.loanValueField.options[i].value = temp3;
			i++;
			}
		}
		}
	}
	
}