var appEntryFormAlreadySubmitted = false;
var appEntryDoNotSubmitOnEnter = false;

Array.prototype.removeByValue = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) {
            this.splice(i, 1);
            break;
        }
    }
}

/* generic functions */
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

function applyUnselectableTo(jquerySelector)
{
	jquerySelector.mouseup(function() {
			this.__chk = this.checked;
		}).click(function() {
			if (this.__chk) this.checked = false;
		});
}

jQuery(document).ajaxComplete(function (event, xhr, settings) {
	var header = xhr.getResponseHeader("X-AjaxRedirect");
	if (header) {
		window.location = header;
	}
});

jQuery('button.buttonlink, input.buttonlink').live('click', function (e) {
	var href = jQuery(this).attr('data-href');
	if (jQuery(this).is('.ajaxpanel')) {
		var containerId = jQuery(this).attr('data-containerid');
		jQuery('#' + containerId).load(href);
	}
	else {
		window.location.href = href;
	}

	return false;
});

jQuery('form.ajaxpanel').live('submit', function (e) {
	var containerId = jQuery(this).attr('data-containerid');
	var container = jQuery('#' + containerId);
	jQuery(this).ajaxSubmit({
		cache:false,
		success: function (content) {
			container.html(content);
		}
	});
	return false;
});

// Idealview

jQuery(document).ready(function(documentEvent) {

	var divs = jQuery('div#collateral1_content, div#collateral2_content');
	var links = jQuery('a#collateral1, a#collateral2');

	jQuery('a#collateral1, a#collateral2').click(function() {  
			divs.hide();  
			jQuery('a#collateral1').removeClass('tab_on');  
			jQuery('a#collateral1').addClass('tab');
			jQuery('a#collateral2').removeClass('tab_on');  
			jQuery('a#collateral2').addClass('tab');
			jQuery('div#' + this.id + '_content').show(); 
			jQuery(this).removeClass('tab'); 
			jQuery(this).addClass('tab_on');   
			  return false;
		});

	var divs2 = jQuery('div#credit1_content, div#credit2_content, div#credit3_content, div#credit4_content, div#credit5_content' );
	var links2 = jQuery('a#credit1, a#credit2, a#credit3, a#credit4, a#credit5');

	// App Entry specific
	jQuery(".appEntrySaveAndGoto").click(function() {
			appEntryFormAlreadySubmitted = true;
			var gotoLocation = jQuery(this).attr("goto");
			var ajaxOptions = { type: "POST", async: false, success: function(r) { location.href = gotoLocation; } };
			jQuery("#appEntrySave").ajaxSubmit(ajaxOptions);
		});

	// App Entry specific
	if (typeof(jQuery("#appEntrySave")[0]) != "undefined") {
		jQuery("#appEntrySave").bind("keypress", function(keypressEvent) {
				if (!appEntryDoNotSubmitOnEnter && getKeyCode(keypressEvent) == 13) {
					appEntryFormAlreadySubmitted = true;
					jQuery(":input:disabled").each(function() {
						jQuery(this).removeAttr("disabled");
					});
					jQuery("#appEntrySave").submit();
				}
			});
		document.onkeyup = function(documentKeyUpEvent) {
			if (!appEntryDoNotSubmitOnEnter && getKeyCode(documentKeyUpEvent) == 13) {
				appEntryFormAlreadySubmitted = true;
				jQuery(":input:disabled").each(function() {
					jQuery(this).removeAttr("disabled");
				});
				jQuery("#appEntrySave").submit();
			}
		}
		window.onbeforeunload = function(beforeunloadEvent) {
			if (!appEntryFormAlreadySubmitted) {
				jQuery(":input:disabled").each(function() {
					jQuery(this).removeAttr("disabled");
				});
				submitAppEntryFormAndWait(1000);
			}
		}
	}
});

var wordCounterCursorPos = 0;

function wordCounter(valueFieldId, htmlFieldId, charLimit, e) {
	if (charLimit == null || charLimit == 0) {
		alert("charLimit is a required parameter");
		return;
	}

	var valueField = jQuery(valueFieldId);
	var valueFieldLength = valueField.val().length;
	var currentPos = valueField.scrollTop();
	var htmlField = jQuery(htmlFieldId);
	htmlField.removeClass("word_count_alert");
	htmlField.html((charLimit - valueFieldLength) + " remaining");

	if (charLimit != null && charLimit >= 0 && valueFieldLength > charLimit) {
		htmlField.addClass("word_count_alert");
		htmlField.html("Maximum character length exceeded by " + Math.abs(charLimit - valueFieldLength));
	}

	if ($.browser.msie) {
		valueField.blur(function() {
			valueField[0].scrollTop = valueField[0].scrollHeight;
		});

		if (e != null) {
			var keyCode = (window.event) ? e.which : e.keyCode;
			if (typeof(keyCode) != "undefined")
				if (keyCode == 0 || keyCode == 17 || keyCode == 86) {
					setTimeout(function() {
						if (currentPos > wordCounterCursorPos) wordCounterCursorPos = currentPos;
						valueField.scrollTop(wordCounterCursorPos);
					}, 1);
					return;
				}
		}

		setTimeout(function() { valueField.scrollTop(currentPos); }, 1);
	}
}

function submitAppEntryFormAndWait(delay) {
	var count = 0;
    var start = new Date().getTime();
    var ajaxOptions = { type: "POST", async: false };
	jQuery("#appEntrySave").ajaxSubmit(ajaxOptions);
// If timeout (sleep) functionality is needed, this is how you do it. I removed it since async: false is set.
//    while (new Date().getTime() < start + delay) {
//		count++; // for logging
//    }
}

var tipShown = 0;

function showTip( tip, e ) {   // Tool tip function 
	if (tipShown != 1){
		var x = 0;
		var y = 0;
		if (e.pageX || e.pageY) 	{
			x = e.pageX;
			y = e.pageY;
		}
		else if (e.clientX || e.clientY) 	{
			x = e.clientX + document.body.scrollLeft
				+ document.documentElement.scrollLeft;
			y = e.clientY + document.body.scrollTop
				+ document.documentElement.scrollTop;
		}
	
	var element = document.getElementById( 'tips' );
	element.style.display = "block";
	element.style.left = x + 'px';
	element.style.top = y + 13 + 'px';
	element.style.zIndex= 999;
	element.innerHTML = tip; 
	tipShown = 1;
	} }

function hideTip() {                                                                
	 tipShown = 0;  
	 setTimeout("document.getElementById( 'tips' ).style.display = 'none';tipShown = 0;",25);    
	 
	}
	
	
	var errorShown = 0;

	function showError( error, e ) {   // Tool error function 
		if (errorShown != 1){
			var x = 0;
			var y = 0;
			if (e.pageX || e.pageY) 	{
				x = e.pageX;
				y = e.pageY;
			}
			else if (e.clientX || e.clientY) 	{
				x = e.clientX + document.body.scrollLeft
					+ document.documentElement.scrollLeft;
				y = e.clientY + document.body.scrollTop
					+ document.documentElement.scrollTop;
			}

		var element = document.getElementById( 'errors' );
		element.style.display = "block";
		element.style.left = x + 'px';
		element.style.top = y + 13 + 'px';
		element.style.zIndex= 999;
		element.innerHTML = error; 
		errorShown = 1;
		} }

	function hideError() {
		 setTimeout("document.getElementById( 'errors' ).style.display = 'none';errorShown = 0;",500);    

		}   
	

//  App Entry Functions
 function showApplicant(x){
		var active = x;
		var i=0;
	    for (i=0;i<=3;i++){
			if (document.getElementById("applicant" + i))
				document.getElementById("applicant" + i).style.display = 'none';

			if (document.getElementById("applicant" + i + "_tab"))
				document.getElementById("applicant" + i + "_tab").className = 'applicant';
	   	}
	   	var applicantIndex = parseFloat(active.replace(/[^\d\.]/g, '') * 1);
	   	document.getElementById("currentApplicantIndex").value = applicantIndex;
		document.getElementById(active + "_tab").className = 'applicant_on';
	    document.getElementById(active).style.display = '';
	}
 function showApplicantPreFill(x){
		var active = x;     
		var i=0;			    
	    for (i=0;i<=3;i++){
			if (document.getElementById("applicantPreFill" + i))
				document.getElementById("applicantPreFill" + i).style.display = 'none';

			if (document.getElementById("applicantPreFill" + i + "_tab"))
				document.getElementById("applicantPreFill" + i + "_tab").className = 'applicant';   
	   	}
		document.getElementById(active + "_tab").className = 'applicant_on';
	    document.getElementById(active).style.display = '';
	    document.getElementById("currentApplicantIndex").value = parseFloat(active.replace(/[^\d\.]/g, '') * 1);
	}
	function showPrevious(table, type, fields, box){    
		var active = table;
		var i = 1;   
		if  (box.checked == true) {  
		  for (i=1;i<=fields;i++){        
		   
				document.getElementById(type + active + "_" + i).style.display = '';
		   	}  }
		else {
			  for (i=1;i<=fields;i++){         
					document.getElementById(type + active + "_" + i).style.display = 'none';
			   	}  }
	}	
		
		// This shows/hides the sub menus for the ideal dashbaord menu
		function showSubMenu(x) {  
			var activeMenu = "workflow_menu" + x + "_sub";
			var activeTab =  "workflow_tab" + x;
			for (i=1;i<=6;i++){        
				if (document.getElementById("workflow_menu" + i + "_sub")){
				document.getElementById("workflow_menu" + i + "_sub").style.display = "none";      //Hides the sub items   
				}
				if (document.getElementById("workflow_tab" + i)){
				document.getElementById("workflow_tab" + i).className = '';}         //turns tabs off
			}
			document.getElementById(activeTab).className = "workflow_menu_on";
			document.getElementById(activeMenu).style.display = "";  
		}
            
		//This function is for the note interface that displays which post you are repyling to     
		
		function showReply(x) {  
			if (x == '(Click reply on a note above to reply to that note)'){ 
			  document.getElementById("note_id").innerHTML = x;}
		   else {
			  document.getElementById("notes_form").note_type[1].checked = true;  
			  document.getElementById("note_id").innerHTML = x;
			}  
		}              
		
		// This shows extra fields in the doc layer popup
		
		function docFunction(x) {
		var field = x.value;
		document.getElementById("doc_fax_number").style.display = "none";
		document.getElementById("doc_app_id").style.display = "none";
		document.getElementById("doc_name").style.display = "none";        
		document.getElementById("doc_hide").style.display = "none";        
		   switch (field) {
		   case "move":        
			    document.getElementById("doc_app_id").style.display = "";   
			  break; 
		 	case "copy":        
				    document.getElementById("doc_app_id").style.display = "";   
				  break;
			case "refax":        
				    document.getElementById("doc_fax_number").style.display = "";   
				  break; 
		   		case "rename":        
					    document.getElementById("doc_name").style.display = "";   
					  break;   
	 				  case "hide":        
							    document.getElementById("doc_hide").style.display = "";   
							  break;   			  
		   }
		}
		
		// This does the calculations on the loan app pages
		function doCalc(whichOne){
			if (whichOne == 1){   //decides which form we are calculating between purchase or lease
				//this is purchase
				var form = new Array()  
				form[0] = document.getElementById("save").price;
				form[1] = document.getElementById("save").tax;
				form[2] = document.getElementById("save").license; 
				form[3] = document.getElementById("save").fees; 
				form[4] = document.getElementById("save").products;
				form[5] = document.getElementById("save").trade;
				form[6] = document.getElementById("save").rebate;
				form[7] = document.getElementById("save").down;
				
				for (i=0;i<form.length;i++) {    
				   if (form[i].value == ''){
					  form[i] = parseFloat(0);
					}
					else {
				   		form[i] = parseFloat(((Math.round(form[i].value*100))/100).toFixed(2)); 
					}
				}
				 document.getElementById("save").total.value = parseFloat(((Math.round((eval(form[0] + form[1] + form[2] + form[3] + form[4] + form[5] - form[6] - form[7]))*100))/100).toFixed(2));
			}
			else if (whichOne == 2){   //decides which form we are calculating between purchase or lease
				//this is lease
				var form = new Array();
				form[0] = parseFloat(document.getElementById("collateralForm_lease_cashSellingPrice").value.replace(/[^\d\.]/g, '') * 1);
				form[1] = parseFloat(document.getElementById("collateralForm_downPayment").value.replace(/[^\d\.]/g, '') * 1);
				form[2] = parseFloat(document.getElementById("collateralForm_rebate").value.replace(/[^\d\.]/g, '') * 1);
				form[3] = stringToNumber(document.getElementById("collateralForm_netTrade").value);
				
				for (i=0;i<form.length;i++) {    
				   if (isNaN(form[i])) {
					  form[i] = parseFloat(0);
					}
					else {
				   		form[i] = parseFloat(((Math.round(form[i]*100))/100).toFixed(2)); 
					}
				}
				
				document.getElementById("collateralForm_lease_adjustedCapCost").value = formatCurrencyIfHasValueAndAllowNegative(parseFloat(((Math.round((eval((form[0] - form[1] - form[2]) - form[3]))*100))/100).toFixed(2)));
			}           
		}
		
function tb_resize(width, height)
{
	TB_WIDTH = width;
	TB_HEIGHT = height;
	var contentWidth = TB_WIDTH - 30;
	var contentHeight = TB_HEIGHT - 45;
	var tbcontent = jQuery('#TB_window').children();
	tbcontent.width(contentWidth);
	tbcontent.height(contentHeight);
	tb_position();
}

function tb_show_loadbox() {
	tb_showOverlay();
	tb_showLoader();
}

function tb_show_inline(id, width, height, options)
{
	if (!options)
		options = { modal: true };
		
	var url = '#TB_inline?height=' + height + '&width=' + width + '&inlineId=' + id + '&modal=' + options.modal;
	tb_show(null, url, null);
}

function validSsn(ssn) {
	return /^\d{3}-?\d{2}-?\d{4}$/.test(ssn);
}

function formatSsn(ssn) {
	if (!validSsn(ssn))
		return ssn;

	var result = new String(ssn).replace(/[^0-9]/g, "");
	var cleanSsn = result;
	if (cleanSsn.length == 0) return "";
	if (cleanSsn.length == 9) {
		result = cleanSsn.substring(0, 3);
		result += "-" + cleanSsn.substring(3, 5);
		result += "-" + cleanSsn.substring(5, 9);
	}
	return result;
}

function formatPhone(phone) {
	var result = new String(phone).replace(/[^0-9]/g, "");
	var cleanPhone = result;
	if (cleanPhone.length == 0) return "";
	if (cleanPhone.length == 10) {
		result = "(" + cleanPhone.substring(0, 3) + ") ";
		result += cleanPhone.substring(3, 6);
		result += "-" + cleanPhone.substring(6, 10);
	}
	return result;
}

function formatNumericIfHasValue(number) {
	if (number.toString().length > 0) {
		return formatNumeric(number);
	}
	return "";
}

function formatNumeric(number) {
	var result = new String(number).replace(/[^0-9]/g, "");
	return stringToNumber(result);
}

function stringToNumber(value) {
	if (value == null)
		return NaN;
	value = formatCurrencyNegatives(value);
	value = value + '';
	value = value.replace(/^\$/, "").replace(/,/g, "");
	value = value.replace(/%$/, "");
	return parseFloat(value);
}

function isValidCurrency(rawValue)
{
	if (typeof(rawValue) == 'number')
		return true;
	
	if (rawValue == null)
		return false;
	
	var isValidString = /^-?\$?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d{2})?$/.test(rawValue);
	return isValidString;
}

function formatCurrencyNegatives(value) {
	if (value.toString().startsWith("-")) {
		value = "-" + value.replace("-", "").replace("$", "");
	}
	return value;
}

function isValidPercentage(rawValue)
{
	if (typeof(rawValue) == Number)
		return true;
	
	if (rawValue == null)
		return false;

	var isValidString = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?%?$/.test(rawValue);
	return isValidString;
}

function formatPercentage(thePercent, numberOfDecimalPoints) {
	if (thePercent != null && thePercent[0] == ".")
		thePercent = 0 + thePercent;

	if (thePercent != null && thePercent.length > 1 && thePercent[0] == "-" && thePercent[1] == ".")
		thePercent = thePercent.replace("-.", "-0.");
	
	if (!isValidPercentage(thePercent))
		return thePercent;
	
	if (numberOfDecimalPoints == null)
		numberOfDecimalPoints = 2;
	
	var theAmountNum = parseAllFloatFormats(thePercent);
	theAmountNum = theAmountNum.toFixed(numberOfDecimalPoints);
	if (theAmountNum && !isNaN(theAmountNum))
		return theAmountNum + '%';
		
	return thePercent;
}

/* allows a percentage sign at the end of the string and a dollar sign at the beginning*/
function parseAllFloatFormats(theAmount)
{
	if (typeof(theAmount) == 'string')
		theAmount = theAmount.trim();
	if (typeof(theAmount) == 'number')
		return theAmount;
	if (!theAmount)
		return NaN;
	theAmount = theAmount + '';
	theAmount = theAmount.replace(/^\$/, "").replace(/,/g, "");
	theAmount = theAmount.replace(/^-\$/, "-").replace(/,/g, "");
	theAmount = theAmount.replace(/%$/, "");
	theAmount = parseFloat(theAmount);
	return theAmount;
}

function parseAllIntFormats(theAmount)
{
	if (theAmount == 0)
		return 0;
	if (!theAmount)
		return NaN;
	if (typeof(theAmount) == 'number')
		return parseInt(theAmount);
	
	theAmount = theAmount + '';
	theAmount = theAmount.replace(/^\$/, "").replace(/,/g, "");
	theAmount = theAmount.replace(/%$/, "");
	theAmount = parseInt(theAmount);
	return theAmount;
}

function formatCurrencyIfHasValueAndAllowNegative(num) {
	if (isValidCurrency(num)) {
		return formatCurrency(num);
	}
	return num;
}

function formatCurrencyIfHasValueAndAllowZero(num) {
	if (isValidCurrency(num)) {
		return formatCurrency(num);
	}
	return num;
}

function formatCurrencyIfHasValue(num) {
	
	if (isValidCurrency(num)) {
		return formatCurrency(num);
	}
	return num;
}

function formatCurrencyAbsolute(num) {
	if (num == null || isNaN(num))
		return num;
	return formatCurrency(num).replace("-", "");
}

function formatCurrency(rawNum) {
	if (!isValidCurrency(rawNum))
		return rawNum;

	num = parseAllFloatFormats(rawNum);
	if(isNaN(num))
		return rawNum;
	
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents < 10)
		cents = "0" + cents;
	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 (((sign)?'':'-') + '$' + num + '.' + cents);
}

// Works for both IE and Firefox. Event is the captured from the key event: $("#id").keyup(function(event){ console.log(getKeyCode(event)); });
function getKeyCode(localEvent) {
	var foundEvent = (localEvent) ? localEvent : ((event) ? event : null);
	if (foundEvent)
		return (foundEvent.charCode) ? foundEvent.charCode : foundEvent.keyCode;
	return null;
}

var tb_show_safe_disabled_element_array = new Array();

function tb_show_safe(caption, url, imageGroup, doNotDisableTheseElementsIdArray) {
	jQuery(":input:disabled").each(function() {
			tb_show_safe_disabled_element_array.push(get_id_safe(jQuery(this)));
		});
	jQuery(":input:visible:enabled").each(function() {
			if (!doNotDisableTheseElementsIdArray || !doNotDisableTheseElementsIdArray.contains(get_id_safe(jQuery(this))))
				jQuery(this).attr("disabled", "disabled");
		});
	tb_show(caption, url, imageGroup);
}

function tb_remove_safe() {
	jQuery(":input:disabled").each(function() {
			if (!tb_show_safe_disabled_element_array.contains(get_id_safe(jQuery(this))))
				jQuery(this).attr("disabled", "");
		});
	tb_remove();
	focusOnFirstVisibleEnabledField();
}

function get_id_safe(obj) {
	var id = obj.attr("id");
	if (typeof(id) == "undefined")
		id = obj.attr("name")
	return id;
}

function focusOnFirstVisibleEnabledField() {
	// Note: http://bytes.com/groups/javascript/157703-set-cursor-position-end-text-field
	setTimeout(function() {
			var fieldObj = jQuery(":input:visible:enabled:first");
			if (fieldObj.attr("id") == "initialForm_applicants_0_ssn" || fieldObj.attr("id") == "flipForm_applicants_0_ssn") {
				jQuery(".ssn").each(function() {
						if (jQuery(this).val().trim().length == 0) {
							jQuery(this).focus();
							jQuery(this).val(jQuery(this).val());
							return false;
						}
					});
				return;
			}
			fieldObj.focus();
			fieldObj.val(fieldObj.val());
		}, 20);
}

function userProfileTogglePasswordResetCheckboxes() {
	var resetPasswordObj = $('#resetPassword');
	var sendWelcomeMessageObj = $('#sendWelcomeMessage');

	if (sendWelcomeMessageObj.is(":checked"))
		resetPasswordObj.attr("disabled", "disabled")
	else
		resetPasswordObj.removeAttr("disabled");

	if (resetPasswordObj.is(":checked"))
		sendWelcomeMessageObj.attr("disabled", "disabled")
	else
		sendWelcomeMessageObj.removeAttr("disabled");
}

Array.prototype.contains = function(element) 
{
      for (var i = 0; i < this.length; i++) 
   {
          if (this[i] == element) 
      {
                  return true;
          }
      }
      return false;
};

/* All properties are nullable if calculations could not be made */
var ApprovalAmounts = Class.extend(
{
	/* args: {decimal estimatedPayment, decimal projectedDti, decimal projectedLtv, decimal loanAmount, decimal rate, int term} */
	init: function(args)
	{
		this.loanAmount = args.loanAmount;
		this.rate = args.rate;
		this.term = args.term;
		this.estimatedPayment = args.estimatedPayment;
		this.projectedDti = args.projectedDti;
		this.projectedLtv = args.projectedLtv;
	}
});

var Calculations = Class.extend(
{

	/* return: ApprovalAmounts 
	 *
	 * args = {decimal amount, decimal rate, decimal term, decimal currentDebt, decimal currentIncome, decimal bookValue}
	 */
	
	calcApprovalAmounts: function(args)
	{
		var amount = parseAllFloatFormats(args.amount);
		var rate = parseAllFloatFormats(args.rate);
		var term = parseAllIntFormats(args.term);
		var currentDebt = parseAllFloatFormats(args.currentDebt);
		var currentIncome = parseAllFloatFormats(args.currentIncome);
		var bookValue = parseAllFloatFormats(args.bookValue);
		
		var pmt = this.estimatePayment(amount, rate, term);
		var dti = this.projectedDti(currentDebt, currentIncome, pmt);
		var ltv = this.ltv(amount, bookValue);

		var amounts = new ApprovalAmounts({ loanAmount:amount, rate: rate, term: term, estimatedPayment: pmt, projectedDti: dti, projectedLtv: ltv });
		
		return amounts;
	},
	
	projectedDti: function(currentDebt, currentIncome, estimatedPayment)
	{
		if (currentIncome == 0)
			return null;
		currentDebt = parseAllFloatFormats(currentDebt);
		currentIncome = parseAllFloatFormats(currentIncome);
		estimatedPayment = parseAllFloatFormats(estimatedPayment);
		var dti = 100 * ((currentDebt + estimatedPayment) / currentIncome);
		return dti;
	},
	
	estimatePayment: function(loanAmount, rate, term)
	{
		loanAmount = parseAllFloatFormats(loanAmount);
		rate = parseAllFloatFormats(rate);
		term = parseInt(term);
		if (!loanAmount || !rate || !term)
			return null;
		
		var negTerm = term * -1;
		
		var rateAsDec = rate/100;
		
		var top = loanAmount * (rateAsDec / 12);
		var bottom = 1 - Math.pow((1 + rateAsDec / 12), negTerm);
		var pmt = top/bottom;
		
		return pmt;
	},
	
	ltv: function(loanAmount, bookValue)
	{
		loanAmount = parseAllFloatFormats(loanAmount);
		bookValue = parseAllFloatFormats(bookValue);
		
		var ltv = (loanAmount / bookValue) * 100;
		return ltv;
	}
});

Array.prototype.unique =
  function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };

String.prototype.startsWith = function(str) 
{return (this.match("^"+str)==str)}

String.prototype.endsWith = function(str) 
{return (this.match(str+"$")==str)}

function cancelEvent(evt) // used to cancel the expansion of a row when a user clicks on a link within that row.
{
	if(!evt) 
		evt=window.event;
	evt.cancelBubble=true;
	evt.stopPropagation();
}

Array.max = function(array) { return Math.max.apply(Math, array); };
Array.min = function(array) { return Math.min.apply(Math, array); };
function is_array(input) { return typeof (input) == "object" && (input instanceof Array); }

/* have to use jQuery instead of $ here because some legacy pages still use prototype */
jQuery(function () {
	if (jQuery('#rate-calculator-container').length == 0) {
		var containerHtml = '<div id="rate-calculator-container"></div>';
		jQuery('body').append(containerHtml);
	}

	jQuery('#rate-calculator-container .x_button').live('click', function () {
		jQuery('#rate-calculator-container').hide();
		return false;
	});

	if (jQuery.livequery) {
		jQuery('#rate-calculator select[name="RateCalculatorForm.LenderId"]').live('change', function () {
			var url = jQuery(this).attr('href');
			jQuery.ajax({
				type: "POST",
				url: url,
				data: jQuery('#rate-calculator-form').serialize(),
				beforeSend: function () {
					jQuery('#rate-calculator-loading').show();
					jQuery('#rate-calculator-form-container').hide();
				},
				success: function (msg) {
					jQuery('#rate-calculator-container').html(msg);
					jQuery('#rate-calculator-container').show();
				}
			});
		});

		jQuery('#rate-calculator').livequery(function () {
			jQuery("#rate-calculator-container").draggable({ handle: 'th.drag_handle' });

			//resize the container to encompass the calculator
			var width = jQuery('#rate-calculator .table_container').width();
			var height = jQuery('#rate-calculator').height();
			jQuery("#rate-calculator-container").width(width + 20);
			jQuery("#rate-calculator-container").height(height + 20);
		});
	}

	jQuery('.rate-calculator-button').live('click', function () {
		var url = jQuery(this).attr('href');
		jQuery.ajax({
			type: "POST",
			url: url,
			beforeSubmit: function () {
				jQuery('#rate-calculator-loading').show();
				jQuery('#rate-calculator-form-container').hide();
			},
			success: function (msg) {
				jQuery('#rate-calculator-container').html(msg);
				jQuery('#rate-calculator-container').show();
			}
		});

		return false;
	});

	jQuery('#rate-calculator-form-container input[name="RateCalculatorForm.Source"]').live('click', function () {
		var url = jQuery(this).attr('href');
		jQuery.ajax({
			type: "POST",
			url: url,
			beforeSend: function () {
				jQuery('#rate-calculator-loading').show();
				jQuery('#rate-calculator-form-container').hide();
			},
			success: function (msg) {
				jQuery('#rate-calculator-container').html(msg);
				jQuery('#rate-calculator-container').show();
			}
		});
	});

	//progress log in ideal
	jQuery('#progress_log_choices').live('change', function () {
		var pLogs = jQuery(this);
		var url = pLogs.attr('href');
		var valResultId = pLogs.val();

		jQuery.ajax({
			url: url,
			data: 'valResultId=' + valResultId,
			success: function (data) {
				jQuery('#contract_details_content, #compliance_content').html(data);
			},
			beforeSend: function () {
				jQuery('#contract_details_content, #compliance_content').html("Loading...");
			}
		});
	});

	jQuery('input.currency').live('blur', function () {
		var rawVal = jQuery(this).val();
		var formatted = formatCurrency(rawVal);
		jQuery(this).val(formatted);
	});
	jQuery('input.rate').live('blur', function () {
		var rawVal = jQuery(this).val();
		var formatted = formatPercentage(rawVal);
		jQuery(this).val(formatted);
	});

	if (jQuery.livequery) {
		jQuery('.autofocus').livequery(function () { jQuery(this).focus(); });

		jQuery('input.phone').live('blur', function () {
			var currentVal = jQuery(this).val();
			jQuery(this).val(formatPhone(currentVal));
		});

	}


});


function analyzePasswordStrength(pwd) {
	var strength = "Weak";
	var score = 0;

	var length = pwd.length;
	var countOfUpperCase = 0;
	var countOfLowerCase = 0;
	var countOfDigits = 0;
	var countOfSymbols = 0;
	var countOfConsecutiveUpperCase = 0;
	var countOfConsecutiveLowerCase = 0;
	var countOfConsecutiveDigits = 0;
	var score = 0; //the basis for the score
	var pwdArray = pwd.replace(/\s+/g, "").split(/\s*/);
	var pwdArrayLen = pwdArray.length;

	for (var i = 0; i < pwdArrayLen; i++) {
		var c = pwdArray[i];
		var previousC = '';
		if (i > 0)
			previousC = pwdArray[i - 1];

		if (c.match(/[A-Z]/g)) {
			++countOfUpperCase;
			if (previousC.match(/[A-Z]/g)) { ++countOfConsecutiveUpperCase; }
		}
		else if (c.match(/[a-z]/g)) {
			++countOfLowerCase;
			if (previousC.match(/[a-z]/g)) { ++countOfConsecutiveLowerCase; }
		}
		else if (c.match(/[0-9]/g)) {
			++countOfDigits;
			if (previousC.match(/[0-9]/g)) { ++countOfConsecutiveDigits; }
		}
		else if (c.match(/[^a-zA-Z0-9_]/g)) {
			++countOfSymbols;
		}
	}

	var requirementsMet = true;
	if (length < 8 || countOfUpperCase < 1 || countOfLowerCase < 1 || (countOfSymbols + countOfDigits) < 1)
		requirementsMet = false;

	if (requirementsMet)
		score += 30;

	score += length * 4;
	score += (length - countOfUpperCase) * 2;
	score += (length - countOfLowerCase) * 2;
	score += countOfDigits * 4;
	score += countOfSymbols * 6;
	score -= countOfConsecutiveLowerCase * 2;
	score -= countOfConsecutiveUpperCase * 2;
	score -= countOfConsecutiveDigits * 2;

	if (score < 0)
		score = 0;
	if (score > 100)
		score = 100;

	if (!requirementsMet && score > 49)
		score = 49;

	if (score <= 40)
		strength = 'Weak';
	else if (score > 40 && score <= 70)
		strength = 'Moderate';
	else if (score > 70)
		strength = 'Strong';

	return { strength: strength, score: score, requirementsMet: requirementsMet };
}

(function ($) {
	$.fn.passwordMeter = function (options) {
		//need passwordInputId.
		var settings = {
			afterAnalyze: function(results){}
			};
		// If options exist, lets merge them
		// with our default settings
		if ( options ) { 
			$.extend( settings, options );
		}
		var passwordInput = $('#' + options.passwordInputId);
		return this.each(function () {
			var $this = $(this);

			var showMeter = function(dontRunAfterAnalyze){
				var pwd = passwordInput.val();
				var result = analyzePasswordStrength(pwd);
				var score = result.score;

				var html = '';
				for (var i = 1; i < 13; ++i){
					var minScoreForSlice = (100 / 12 * i);
					//console.log('score= ' + score);
					//console.log('minScoreForSlice= ' + minScoreForSlice);
					var shouldShowColor = score >= minScoreForSlice;
					var colorClass = i <= 4 ? "weak" : i <= 8 ? "moderate" : "strong";
					var meterSlice = $('<div class="password-meter-slice"></div>');
					if (shouldShowColor)
						meterSlice.addClass(colorClass);

					html += meterSlice.wrap('<div></div>').parent().html();
				}

				$this.html(html);

				if (!dontRunAfterAnalyze)
					settings.afterAnalyze(result);
				
			};

			passwordInput.keyup(function(){ showMeter(false); });

			showMeter(true);
		});
	};
})(jQuery);
