var analysis_window = '';
var details_window = '';
var update_ids = Array();
var theCountyTop = 0;
var thePresentTop = 0;
var purposeOtherDisc = '';

function emptyValue(obj) {
	if ( (obj.value == 'Enter Email Address') || (obj.value == 'Enter Phone Number') )
	obj.value = '';
}

function changeChecks(ckname, obj) {	
	var valuesArray = document.getElementsByName(obj.name);
	for (j=0; j<valuesArray.length; j++) {	
		if ( (obj.value != valuesArray[j].value) || (obj.id != valuesArray[j].id) ) {
			valuesArray[j].checked = false;
			if ((obj.name == 'purpose') && (obj.value != '2')) {
				document.getElementById('table_1').className = 'show';
				document.getElementById('table_2').className = 'hide';
				document.getElementById('refi_purpose').className = 'hide';
			}
		} else {
			valuesArray[j].checked = true;
			if ((obj.name == 'purpose') && (obj.value == '2')) {
				document.getElementById('table_1').className = 'hide';
				document.getElementById('table_2').className = 'show';
				document.getElementById('refi_purpose').className = 'show';
			}
		}
	}
}
function openIncome() {
	incomeWin = createWin.setup();
	var winWidth = 290;
	var winHeight = 278;
	incomeWin.setWidth(winWidth);
	incomeWin.setHeight(winHeight);
	var leftPos = (document.documentElement.clientWidth-winWidth)/2;
	var topPos = (document.documentElement.clientHeight-winHeight)/2;
	incomeWin.setPosition(leftPos,topPos);
	incomeWin.setTitle('Income');
	incomeWin.setContentUrl('/lvl1/support/income.php');
	incomeWin.show();
}

function openHousing() {
	housingWin = createWin.setup();
	var winWidth = 390;
	var winHeight = 284;
	housingWin.setWidth(winWidth);
	housingWin.setHeight(winHeight);
	var leftPos = (document.documentElement.clientWidth-winWidth)/2;
	var topPos = (document.documentElement.clientHeight-winHeight)/2;
	housingWin.setPosition(leftPos,topPos);
	housingWin.setTitle('Housing Expense and Obligations');
	housingWin.setContentUrl('/lvl1/support/housing.php');
	housingWin.show();
}

function verifyValues() {
	if (document.getElementById('bfico').value == '') {alert ("Please enter the Borrower's Credit Score."); return false;}
	
	if ( (document.getElementById('totalincome').value == '<- Click Here') || (document.getElementById('totalincome').value == '') ) {alert ("Please enter your gross monthly income by clicking on the 'Income' button."); return false;}	
	if ( (document.getElementById('housingpmt').value == '<- Click Here') || (document.getElementById('housingpmt').value == '') ) {alert ("Please enter your monthly housing costs by clicking on the 'Obligations' button."); return false;}	
	if (document.getElementById('otherpmt').value == '') {alert ("Please enter your monthly debt payments by clicking on the 'Obligations' button."); return false;}

	//if (document.getElementById('saddress').value == '') {alert ("Please enter the Subject Property street address. If this is a purchase transaction, and you don't know the street address yet, put 'TBD' in the address field."); return false;}
	if (document.getElementById('scity').value == '') {alert ("Please enter the Subject Property city."); return false;}
	if (document.getElementById('sstate').value == '') {alert ("Please enter the Subject Property state."); return false;}
	if (document.getElementById('szip').value == '') {alert ("Please enter the Subject Property postal code."); return false;}
	if (document.getElementById('scounty').value == '') {alert ("Please enter the Subject Property county."); return false;}
	
	if (document.getElementById("purpose_1").checked) { //Purchase
		if (document.getElementById('saleval').value == '') {alert ("Please enter the Sale Price of the property."); return false;}
		if (document.getElementById('loanval_p').value == '') {alert ("Please enter the Loan Amount."); return false;}

	} else {
		if (document.getElementById('appval').value == '') {alert ("Please enter the Appraised Value of the property."); return false;}
		if (document.getElementById('loanval_r').value == '') {alert ("Please enter the Loan Amount."); return false;}
	}
	
	return true;
}

function checkLength(obj, len) {
	number = numericInt(obj.value)+'';
	if (number != '') {	
		if (number.length != len) return false;
	}
	return true;
}

function emailCheck (emailStr) {
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) return false;
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) return false;
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) return false;
	}
	if (user.match(userPat)==null) return false;
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) return false;
		}
		return true;
	}
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) return false;
	}
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) return false;
	if (len<2) return false;
	
	return true;
}
/*
function calcDown1(salePrice, loanAmt) {
	var downPmt1 = (numericReal(salePrice) - numericReal(loanAmt));
	return formatCurrency(downPmt1);
}
*/




//Update functions-----------------------------------------------------------------
function checkCalcFields() {
	if (document.getElementById("purpose_1").checked) { //Purchase
	
		if(document.getElementById('saleval').value == '' || document.getElementById('saleval').value == 0) return false;
		if(document.getElementById('loanval_p').value == '' || document.getElementById('loanval_p').value == 0) return false;
	
	} else if (document.getElementById("purpose_2").checked) {
			
		if(document.getElementById('appval').value == '' || document.getElementById('appval').value == 0) return false;
		if(document.getElementById('loanval_r').value == '' || document.getElementById('loanval_r').value == 0) return false;

	}

	return true;
}

function loanAmtChange() {
	
	if (checkCalcFields()) {
		var oldmtgins = numericReal(document.getElementById('mtgins').value);
		var mtgInsRate = 0.5;
		var oldTotal = numericReal(document.getElementById('housingpmt').value)*1;

		var result = getLTV();


		if (result[0] > 0.8) { //calculate mortgage insurance...
			
			var mtgInsPmt = (mtgInsRate/1200)*result[1];
			document.getElementById('mtgins').value = mtgInsPmt;
			
		} else { 
		
			var mtgInsPmt = 0;
			document.getElementById('mtgins').value = '0';
			
		}

		var difference = oldmtgins - mtgInsPmt;
		var newTotal = (oldTotal - difference);		
		document.getElementById('housingpmt').value = formatCurrency2(newTotal);
		
	}
}

function getLTV() {
	var result = Array();
	
	if (document.getElementById("purpose_1").checked) { //Purchase
		
		result[0] = numericReal(document.getElementById("loanval_p").value)/numericReal(parent.document.getElementById("saleval").value);
		result[1] = numericReal(document.getElementById("loanval_p").value);
		return result;	
	
	} else if (document.getElementById("purpose_2").checked) { //Refi
		
		result[0] = numericReal(document.getElementById("loanval_r").value)/numericReal(parent.document.getElementById("appval").value);
		result[1] = numericReal(document.getElementById("loanval_r").value);
		return result;
		
	}
}

function salePriceChange(saleObj) {
	//update downPmt fields
	if (saleObj.value != '' && saleObj.value != 0 && saleObj.value != '$0') {	
		var salePrice = numericReal(saleObj.value);
		var downPmt = numericReal(document.getElementById('downpmt').value);
		var dnPerc = downPerc(downPmt,salePrice);

		document.getElementById('downpct').value = dnPerc;
		document.getElementById('loanval_p').value = formatCurrency(salePrice-downPmt);
		loanAmtChange();
	}
}
function downPerc(downPmt, salePrice) {
	if ((numericReal(downPmt) > 0) && (numericReal(salePrice) > 0)) {
		var perc = (numericReal(downPmt)/numericReal(salePrice))*100;
		return perc.toFixed(2);
	} else {
		return 0;
	}
}

function downPctChange(downPctObj) {
	var downPct = downPctObj.value;
	var salePrice = document.getElementById('saleval').value;
	
	document.getElementById('downpmt').value = calcDown2(salePrice, downPct);
	document.getElementById('loanval_p').value = calcLoanAmt(salePrice, downPct);
	
	loanAmtChange();
}

function calcDown2(salePrice, downPerc) {
	var downPmt2 = numericReal(salePrice) * (numericReal(downPerc)/100);
	return formatCurrency(downPmt2);
}

function calcLoanAmt(salePrice, downPerc) {
	var loanAmt = numericReal(salePrice) * ((100-numericReal(downPerc))/100);
	return formatCurrency(loanAmt);
}

function downPmtChange(downPmtObj) {
	downPt = downPmtObj.value;
	salePrice = document.getElementById('saleval').value;
	downPct = downPerc(downPt, salePrice);
	loanAmt = numericReal(salePrice) - numericReal(downPt);
	
	document.getElementById('downpct').value = downPct;
	document.getElementById('loanval_p').value = formatCurrency(loanAmt);
	loanAmtChange();
	setCurrency(downPmtObj);
}

//Copy functions--------------------------------------

function copyProp() {
	if (
				(document.getElementById("haddress").value != '') ||
				(document.getElementById("hcity").value != '') ||
				(document.getElementById("hstate").value != '') ||
				(document.getElementById("hzip").value != '')
			) {
		t = confirm("There is already data in the Present Address fields that will be overwritten and lost.\nAre you sure you want to proceed?");
	} else {
		t = true;
	}
	if (t) {
		document.getElementById("haddress").value = document.getElementById("saddress").value;
		document.getElementById("hcity").value = document.getElementById("scity").value;
		document.getElementById("hstate").value = document.getElementById("sstate").value;
		document.getElementById("hzip").value = document.getElementById("szip").value;
	}
}
/*
function findCounty(zipObj) {
	theZip = zipObj.value;
	if (theZip.length == 5) {
		document.getElementById('cnty').src = '/loan_app/support/getcounty.php?code='+theZip+'&data='+zipObj.id;
	}
}*//*
function getCountyInfo(oArgs) {
	return {
    source: '/db/getCounty.php?q=' + escape(oArgs.keyword),
    sourceType: 'json/url'
  };	
};
function displayCountyInfo(oTip) {
	if (theCountyTop == 0) {
		theElement = document.getElementById("contact_address-addresstype='Subject':zip").previousSibling;
		savedTop = numericInt(theElement.style.top);
		thePageTop = numericInt(document.getElementById("bodydiv_1").style.top);
		newTop = savedTop-thePageTop+"px";
		theElement.style.top = newTop;
		theCountyTop = newTop;
	}
	return oTip.city + ', ' + oTip.state + ' ' + oTip.zip_code;
};
function displayPresentInfo(oTip) {
	if (thePresentTop == 0) {
		theElement = document.getElementById("contact_address-addresstype='Home'*former=false:zip").previousSibling;
		savedTop = numericInt(theElement.style.top);
		thePageTop = numericInt(document.getElementById("bodydiv_1").style.top);
		newTop = savedTop-thePageTop+"px";
		theElement.style.top = newTop;
		thePresentTop = newTop;
	}
	return oTip.city + ', ' + oTip.state + ' ' + oTip.zip_code;
};
function setCountyData(oContainer) {
	document.getElementById("contact_address-addresstype='Subject':city").value = oContainer.city;
	document.getElementById("contact_address-addresstype='Subject':city").onchange();
	document.getElementById("contact_address-addresstype='Subject':state").value = oContainer.state;
	document.getElementById("contact_address-addresstype='Subject':state").onchange();
	document.getElementById("contact_address-addresstype='Subject':zip").value = oContainer.zip_code;
	document.getElementById("contact_address-addresstype='Subject':zip").onchange();
	document.getElementById("contact_address-addresstype='Subject':county").value = oContainer.county;
	document.getElementById("contact_address-addresstype='Subject':county").onchange();
}
function setPresentData(oContainer) {
	document.getElementById("contact_address-addresstype='Home'*former=false:city").value = oContainer.city;
	document.getElementById("contact_address-addresstype='Home'*former=false:city").onchange();
	document.getElementById("contact_address-addresstype='Home'*former=false:state").value = oContainer.state;
	document.getElementById("contact_address-addresstype='Home'*former=false:state").onchange();
	document.getElementById("contact_address-addresstype='Home'*former=false:zip").value = oContainer.zip_code;
	document.getElementById("contact_address-addresstype='Home'*former=false:zip").onchange();	
}
*/
//Open Screens---------------------------------------------------

function popWin() {
	this.setup = function() { 
		return Zapatec.Window.setup({
			initialState: "hidden",
			left:50, 
			top:130,
			iframeContent: true,
			urlContent: "/images/mconnects.gif",
			raiseOnlyOnTitle:false, 
			theme: "osx",
			showMinButton: true,
			showCloseButton: true,
			showStatus: false,
			canResize: false,
			canDrag: true,
			hideOnClose: true,
			dragMethod: "cut",
			modal: true
		});
	}
}
function popWin2() {
	this.setup = function() { 
		return Zapatec.Window.setup({
			initialState: "hidden",
			left:70, 
			top:150,
			iframeContent: true,
			urlContent: "/images/mconnects.gif",
			raiseOnlyOnTitle:false, 
			theme: "osx",
			showMinButton: true,
			showCloseButton: true,
			showStatus: false,
			canResize: false,
			canDrag: true,
			hideOnClose: true,
			dragMethod: "cut",
			modal: true
		});
	}
}
var createWin = new popWin();
var createWin2 = new popWin2();
var housingWin, incomeWin, baseWin;

function sendData() {
	//validate the email address
	if (!emailCheck(document.getElementById('contact_email').value)) {
		alert("Please verify your email address.");
		return;
	}
	
	var loan = getLoanData();
		var vals = document.getElementsByName('occupancy');
		for (i=0; i<vals.length; i++) {
			if (vals[i].checked) {
				var occval = vals[i].value;
				break;
			}
		}
		if (occval == '1') occval = 'Primary';
		if (occval == '2') occval = 'Secondary';
		if (occval == '3') occval = 'Investment';
		vals = document.getElementsByName('purpose');
		for (i=0; i<vals.length; i++) {
			if (vals[i].checked) {
				var purpval = vals[i].value;
				break;
			}
		}
		if (purpval == '1') purpval = 'Purchase';
		if (purpval == '2') purpval = 'Refinance';
		
		var params = "";
		
		params += "&a1="+document.getElementById('bfirstname').value;
		params += "&a2="+document.getElementById('blastname').value;
		params += "&a3="+document.getElementById('bfico').value;
		params += "&a4="+document.getElementById('cfirstname').value;
		params += "&a5="+document.getElementById('clastname').value;
		params += "&a6="+document.getElementById('cbfico').value;
		params += "&a7="+purpval;
		params += "&a8="+occval;
		if (purpval == 'Purchase') {
			params += "&a9="+document.getElementById('saleval').value;
			params += "&a10="+document.getElementById('downpmt').value;
			params += "&a11="+document.getElementById('loanval_p').value;
		} else {
			params += "&a9="+document.getElementById('appval').value;
			params += "&a11="+document.getElementById('loanval_r').value;
		}
		params += "&a12="+document.getElementById('totalincome').value;
		params += "&a13="+document.getElementById('otherpmt').value;
		params += "&a14="+document.getElementById('saddress').value;
		params += "&a15="+document.getElementById('scity').value;
		params += "&a16="+document.getElementById('sstate').value;
		params += "&a17="+document.getElementById('szip').value;
		params += "&a18="+document.getElementById('scounty').value;
		params += "&a19="+document.getElementById('haddress').value;
		params += "&a20="+document.getElementById('hcity').value;
		params += "&a21="+document.getElementById('hstate').value;
		params += "&a22="+document.getElementById('hzip').value;
		params += "&a23="+document.getElementById('contact_email').value;
		params += "&a24="+document.getElementById('contact_phone').value;
		
		
	
		var xmlHttp=GetXmlHttpObject();
		if (xmlHttp==null) {
		 alert ("You need to be using a Mozilla Firefox browser or at least IE 7.0");
		 return;
		}
		xmlHttp.open("POST",'/db/signup_email.php',true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", params.length);
		xmlHttp.setRequestHeader("Connection", "close");
		xmlHttp.onreadystatechange = function() { stateChanged(xmlHttp); };	
		xmlHttp.send(params);
		
		alert("Thank you. Your request has been sent.");
		//Disable the button so it can't be pressed twice.
		document.getElementById('contactme').disabled = true;
}