intValRE = new RegExp(/[^0-9]/g);
var o;
var clickCounter = 0;
var hrefStr = "";
var button1;
var button2;
function CompareRates() {
	if (o && o.length > 0) {
		var loans = new Array();
		for (var i=0; i<o.length; i++) {
			if (o[i].checked) {
				loans.push(o[i].value);
				if (loans.length == 2) break;
			}
		}
		if (loans.length == 2) {
			window.location.href = "/comparator/"+loans[0]+"/"+loans[1];
		}
	}
}
function MortgageRates() {
	if (t = $("table1")) {
		if (t.tBodies && t.tBodies.length > 0) {
			button1 = $("img1");
			button2 = $("img2");

			var onSrc = "/images/RatesCompareOn.gif";
			var offSrc = "/images/RatesCompareOff.gif";
			var on2Src = "/images/RatesCompareOn2.gif";
			var off2Src = "/images/RatesCompareOff2.gif";
			var tmp1 = new Image();
			tmp1.src = onSrc;
			var tmp2 = new Image();
			tmp2.src = on2Src;
			clickCounter=0;
			o = t.getElementsByTagName("INPUT");
			if (o.length > 0) {
				for (var i=0; i<o.length; i++) {
					o[i].onclick = function() {
						clickCounter = 0;
						tempBoxes = $ES('input');
						tempBoxes.each(function(box){
							if(box.checked && box.type == 'checkbox' && box.name=='ListingId'){
								clickCounter++;
							}
							}
						);
						if (clickCounter == 2) {
							for(var j=0;j<o.length;j++){
								if (!o[j].checked) {
									o[j].disabled = true;
								}
							}
							button1.src = onSrc, button2.src = on2Src;
						} else {
							for(var j=0;j<o.length;j++){
								o[j].disabled = false;
							}
							button1.src = offSrc, button2.src = off2Src;
						}
					}
				}
			}
		}
	}
}
function showError (b, msg, field) {
	b.setHTML(msg);
	b.setStyles({"display": "block"});
	field.focus();
	return false;
}
function submitRateOptionsForm(FHALoanLimit, VALoanLimit){
	var mBox = $("RatesStatus");
	var fel = document.getElementById("RateOptions").elements;
	var loanAmt = parseInt(fel["USER_LOAN_AMOUNT"].value.replace(intValRE, ""));

	if(fel['USER_STATE'].selectedIndex == 0){
		return showError(mBox, "Please select a state.", fel["USER_STATE"]);
	}
	if(fel['USER_LOAN_PROGRAM'].selectedIndex == 0){
		return showError(mBox, "Please select a loan type.", fel["USER_LOAN_PROGRAM"]);
	}
	if(isNaN(loanAmt) || loanAmt <= 0){
		return showError(mBox, "Please enter a valid loan amount.", fel["USER_LOAN_AMOUNT"]);
	}

	var href = fel['USER_STATE'].value+"/"+fel['USER_LOAN_PROGRAM'].value+"/"+fel['USER_POINTS'].value+"/"+loanAmt;

	if (fel["USER_LOAN_PROGRAM"].value.indexOf("HE") >= 0) {
		if(loanAmt < 10000){
			return showError(mBox, "Home Equity loan amount must be at least $10,000.", fel["USER_LOAN_AMOUNT"]);
		}
	} else {
		if (loanAmt < 10000) {
			return showError(mBox, "Mortgage loan amount must be at least $10,000.", fel["USER_LOAN_AMOUNT"]);
		}
	}
	if (fel["USER_LOAN_PROGRAM"].options[fel["USER_LOAN_PROGRAM"].selectedIndex].text.indexOf("FHA") >= 0) {
		if (loanAmt > FHALoanLimit) {
			return showError(mBox, "Maximum FHA Loan Amount is $"+FHALoanLimit, fel["USER_LOAN_AMOUNT"]);
		}
	} else if (fel["USER_LOAN_PROGRAM"].options[fel["USER_LOAN_PROGRAM"].selectedIndex].text.indexOf("VA") >= 0) {
		if (loanAmt > VALoanLimit) {
			return showError(mBox, "Maximum VA Loan Amount is $"+VALoanLimit, fel["USER_LOAN_AMOUNT"]);
		}
	}

	//validation complete, hide error box.
	mBox.setStyles({"display": "none"});
	href = window.location.protocol +"//"+ window.location.host +"/mortgage-rates/"+href;
	window.location.href = href;
}
function sortCompleteCallback(tableId) {
	var SortCols = Array(0,0,1,2,3,4,5,6,7); //maps "Ethical" to "More Lenders" columns
	if (tableId == "table1" && $("table2")) {
		var t1 = $("table1");
		var t2 = $("table2");
		var tHead = t1.tHead.rows[0].cells;

		for (var i=0; i < tHead.length; i++) {
			if (tHead[i].className && tHead[i].className.match(/forwardSort|reverseSort/g)) {
				fdTableSort.jsWrapper("table2", SortCols[i]);
				break;
			}
		}
	}
}
function callLender (/*HTMLTableCellObj*/ el) {
	var obj = arguments[arguments.length-1];
	var content = "<strong>" + obj.lenderName + "</strong> can be reached at: ";
	content += "<h1>" + obj.phoneNumber + "</h1>";
	content += "<p>Tell them you found it on RealEstateABC.com!</p>";
	if (obj.phoneUrl) {
		content += "<img src='" + obj.phoneUrl + "' height='1' width='1' alt=''/>";
	}

	el = $(el);
	var co = el.getPosition();
	if (arguments.length == 4) {
		var offsetTop = arguments[1];
		var offsetLeft = arguments[2];
	} else {
		var offsetTop = 6;
		var offsetLeft = 40;
	}
	offsetTop = (co.y + offsetTop)+'px';
	offsetLeft = (co.x + offsetLeft)+'px';

	var fp = $("CallLender");
	var fpContent = fp.getElementsByTagName("div").item(1);
	$(fpContent).setHTML(content);
	fp.setStyles({ 'display': 'block', 'left': offsetLeft, 'top': offsetTop });
}
function sendLenderFeedback (/*DOM node*/ a, /*int*/ rateId) {
	var url = "/lender-feedback/"+rateId;
	a = $(a);
	var co = a.getPosition();
	var props = {width: 500, height: 412, left: co.x-500, top: co.y+50};
	openGenericWindow(url, props);
}

function setupTooltips() {
	if ($("table1")) {
		var LenderName = $("LenderName").getElementsByTagName("a").item(0);
		LenderName.setAttribute("title", "The name of the mortgage company offering this rate. The mortgage company could be a bank, an S&amp;L, a mortgage banker, a mortgage broker, or a consumer finance company.");
		var Rate = $("Rate").getElementsByTagName("img").item(0);
		Rate.setAttribute("title", "The note rate. This is what the monthly payments are based on.  Loan.com rates are valid for purchase and rate &amp; term refinance transactions. Rates may differ for cash-out refinance transactions.");
		var Points = $("Points").getElementsByTagName("img").item(0);
		Points.setAttribute("title", "Points are up-front interest paid to reduce the interest rate. 1 point is 1% of the loan amount. On a $100,000 loan, 1 point is $1,000. Loan.com points quoted include both discount and origination points.");
		var Fees = $("Fees").getElementsByTagName("img").item(0);
		Fees.setAttribute("title", "Loan.com Fees quoted include all broker and/or lender fees as well as appraisal and credit report fees. Fees quoted do not include fees charged by the third parties.");
		var Update = $("UpdateDate").getElementsByTagName("img").item(0);
		Update.setAttribute("title", "The last time the Loan.com rate was updated for a particular lender or broker.");
//		var Rating = $("Rating").getElementsByTagName("img").item(0);
//		Rating.setAttribute("title", "The Loan.com rating system is designed to assist you in learning more about the lenders listed.  Stars may be awarded on the basis of the following:<br/><br/> One star will be awarded if the lender has affirmed that their borrowing practices are consistent with the Borrower's Bill of Rights.<br/><br/> One star will also be awarded if the lender is a member in good standing of the Better Business Bureau.<br/><br/> A third star may also be awarded at Loan.com's discretion if the lender receives positive feedback from its customers.");

		//HE
		if ($("Term")) {
			var LockTerm = $("Term").getElementsByTagName("img").item(0);
			LockTerm.setAttribute("title", "The length of time of the loan. The terms of \"second mortgages\" is usually shorter than that of first mortgages, usually 15 years or less.");
		} else {
			var LockTerm = $("Lock").getElementsByTagName("img").item(0);
			LockTerm.setAttribute("title", "The number of days for which the specified rate can be locked.  The Loan.com minimum lock period allowed is 30 days.");
		}

		var MonthlyPmt = $("MonthlyPmt").getElementsByTagName("img").item(0);
		MonthlyPmt.setAttribute("title", "The estimated monthly payment on principle and interest based on loan amount entered and the listed Rate.  Please note that actual monthly payment may be higher due to escrows for tax and insurance.");
		var APR = $("APR").getElementsByTagName("img").item(0);
		APR.setAttribute("title", "APR is an acronym for annual percentage rate. The APR is designed to measure the effective or actual cost of a loan over its life. Different lenders and brokers include different fees and use different formulas when computing APRs, so do not compare loans solely on the basis of APRs.");
		var AllTips = Array(LenderName, Rate, Points, Fees, Update, LockTerm, MonthlyPmt, APR);
		var ret = new Tips(AllTips, {offsets: {x:0, y:30}});
	}
	if ($("MoreLenders")) {
		var MoreLenders = $("MoreLenders");
		MoreLenders.setAttribute("title", "We are providing rates from additional lenders to help in your decision making process. Be aware that these lenders may not have attested to the Borrower's Bill of Rights like the Ethical Lenders above.");
		var ret2 = new Tips(Array(MoreLenders), {offsets: {x:0, y:30}});
	}
}
function sortDateReverse(a,b) {
	var aa = a[fdTableSort.pos];
	var bb = b[fdTableSort.pos];
	if(aa == bb) return 0;
	if(aa < bb)  return 1;
	return -1;
}
function sortDateReversePrepareData(tdNode, tdText) {
	var d = tdText.split("/");
	d[0] = (d[0].length == 1) ? "0"+d[0] : d[0];
	d[1] = (d[1].length == 1) ? "0"+d[1] : d[1];
	return d[2]+d[0]+d[1];
}
function sortLenderRating(a, b) { //Sort Lender Rating Stars. First sort is reverse.
	var aa = a[fdTableSort.pos];
	var bb = b[fdTableSort.pos];
	// Sort the data 
	if(aa == bb) return 0;
	if(aa < bb)  return 1;
	return -1;
}
function sortLenderRatingPrepareData(tdNode, tdText) {
	return (tdNode.getElementsByTagName("img").length > 0) ? tdNode.getElementsByTagName("img").length : tdNode.getElementsByTagName("span").length;
}
function setupLenderRating() {
	if ($("table1")) {
		var rows = $("table1").tBodies[0].rows;
		var LenderRatingTips = Array();
		for(var i = 0, row; row = rows[i]; i++) {
			var img = row.cells[9].getElementsByTagName("img");
			if (img.length > 0) {
				var img = row.cells[9].getElementsByTagName("img");
				var TipStr = "";
				for (var j=0; j<img.length; j++) {
					TipStr += "<h2>"+img[j].getAttribute("alt")+"</h2>\n";
				}
				row.cells[9].title = TipStr;
				LenderRatingTips.push(row.cells[9]);
			}
		}
		var ret = new Tips(LenderRatingTips, {offsets: {x:0, y:30}, className: "LenderRating"});
	}
}
function RSSUrl () {
	this.printUrl = function() {
		var url = "/rss/rates/?";
		var tmp = Array();
		for (i in this) {
			if (i != "printUrl") {
				tmp[tmp.length] = i+"="+escape(this[i]);
			}
		}
		url += tmp.join("&");
		return url;
		//console.debug(url);
	}
}
function LaunchRSS() {
	if ($("table1")) {
		//get loan params
		var Url = new RSSUrl();
		if ($("USER_STATE").value) {
			Url.State = $("USER_STATE").value;
		}
		if ($("USER_LOAN_PROGRAM").value) {
			Url.LoanProgram = $("USER_LOAN_PROGRAM").value;
			if (Url.LoanProgram.match(/HE/g)) {
				Url.PropertyValue = $("USER_PROPERTY_VALUE").value.replace(intValRE, "");
				Url.MortgageBalance = $("USER_MORTGAGE_BALANCE").value.replace(intValRE, "");
			}
		}
		if ($("USER_POINTS").value) {
			Url.Points = $("USER_POINTS").value;
		}
		if ($("USER_LOAN_AMOUNT").value) {
			Url.LoanAmount = $("USER_LOAN_AMOUNT").value.replace(intValRE, "");
		}

		//get current sort. If not found, use default table sort.
		var headers = $("table1").tHead.rows[0].cells;
		for (var i=0; i<headers.length; i++) {
			if (headers[i].className.match(/forwardSort/g)) {
				Url.Sort = headers[i].id + "_forward";
				break;
			} else if (headers[i].className.match(/reverseSort/g)) {
				Url.Sort = headers[i].id + "_reverse";
				break;
			} 
		}
		if (!Url.Sort) {
			Url.Sort = "default";
		}
		window.location.href = Url.printUrl();
	}
}
window.addEvent("domready", function(){
	//because of callLender() this script is called in 2 more pages.
	//if (window.location.href.indexOf("mortgage-rates") != -1) {
		fdTableSort.init();
		MortgageRates();
		setupTooltips();
//		setupLenderRating();
	//}
});


