//if(!initial_load) {
	document.write("<div id='rw_container'></div>");
	document.write("<div id='divBBDebug'></div>");
//}
//var show_header;
//var show_owner_bottom_form;
var tb_pathToImage = "http://ratewindow.com/services/js/loadingAnimation.gif";
var style = "\n<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"http://ratewindow.com/services/js/style.css\" />\n";
var ltv;
document.write(style);
function JSONscriptRequest(fullUrl){this.fullUrl = fullUrl;this.noCacheIE='&noCacheIE='+(new Date()).getTime();this.headLoc = document.getElementsByTagName("head").item(0);this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;}
JSONscriptRequest.scriptCounter=1;
JSONscriptRequest.prototype.buildScriptTag=function(){this.scriptObj = document.createElement("script");this.scriptObj.setAttribute("type", "text/javascript");this.scriptObj.setAttribute("charset", "utf-8");this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);this.scriptObj.setAttribute("id", this.scriptId);}
JSONscriptRequest.prototype.removeScriptTag=function(){this.headLoc.removeChild(this.scriptObj);  }
JSONscriptRequest.prototype.addScriptTag=function(){this.headLoc.appendChild(this.scriptObj);}
function json(url){bObj = new JSONscriptRequest(url); bObj.buildScriptTag(); bObj.addScriptTag();}

function get_county_in_state(){document.getElementById('county_holder').innerHTML = "<img border='0' src='http://ratewindow.com/images/ani.gif' />";var id = document.getElementById('states').options[document.getElementById('states').selectedIndex].value;json('http://ratewindow.com/services/ratewindow_form_counties.php?callback=rw_results_counties&id='+id);}
function rw_results_counties(obj){document.getElementById('county_holder').innerHTML = obj;}

//workers
function getURLVar(urlVarName) {var urlHalves = String(document.location).split('?');var urlVarValue = '';if(urlHalves[1]){var urlVars = urlHalves[1].split('&');for(i=0; i<=(urlVars.length); i++){if(urlVars[i]){var urlVarPair = urlVars[i].split('=');if (urlVarPair[0] && urlVarPair[0] == urlVarName) {urlVarValue = urlVarPair[1];}}}}return urlVarValue;}
function display_working(stage)
{
	
	var message = "RateWindow is Working";
	if(stage=="rw_results")
		message = "RateWindow is gathering your loan results, <br>could take up to 1 minute";
	else
		message = "RateWindow is working";
	
	//if(false)
	//{
	document.getElementById('rw_container').innerHTML = "<div><div style=\"padding-top:60px;font-size:1.2em; color:#6C88BA; font-family:arial;\"><div style='width:93%;padding:5px; font-size:1.2em; text-align:center; border-top:1px solid #00CC33; border-bottom:1px solid #00CC33; background-color:#E1EBD6'>"+message+"<br /><br /><img src='http://ratewindow.com/services/js/loadingAnimation.gif' /></div>";
	//}
	//else
	//{
	//document.getElementById('rw_container').innerHTML = "<div><div style=\"padding-top:60px;font-size:1.2em; color:#6C88BA; font-family:arial;\"><div style='width:93%;padding:5px; font-size:1.2em; text-align:center;'><br /><br /><img src='http://ratewindow.com/services/js/loadingAnimation.gif' /></div>";
	//}
}

var emailerror = false;
function form_submit(f,type){
	emailerror=false;
	if(check_form(type)){
			if(type==1 || type==3) {
						
						var formElements = "";var pt = "";
						for (var n=0; n < f.elements.length; n++) {
							if(f.elements[n].name != '_ProductType[]'){
									formElements += "&" + f.elements[n].name + "=" + f.elements[n].value;
							}else{
								if(f.elements[n].checked){
									pt += f.elements[n].value + ",";
								}
							}
						}
							pt = rtrim(pt, ",");
							var redirect = location.href;
							var str = formElements + "&product_type=" + pt + "&redirect=" + redirect+"&type="+type;
							//alert(str);
							send_request('rw_results', str);
					
			} else {
				//alert("next");
				toggle_forms_1(type);
				bb_save_state();
			}
	} else {
				if(type!=2 && emailerror==false) {
					toggle_forms_1(type);
					bb_save_state();
				}
	}
}

function get_ltv(){var loan = document.getElementById('loanamount').value;var price = document.getElementById('propertyprice').value;loan = loan.replace(/,/g, "");price = price.replace(/,/g, "");if(loan != '' && price != ''){ltv = (loan/price)*100;if(ltv>100){document.getElementById('ltv_holder').innerHTML = "<font color='red'>"+ltv.toFixed(2)+"%</font>";}else{document.getElementById('ltv_holder').innerHTML = ltv.toFixed(2)+"%";}}}
function update_loan_purpose(){var sel = document.getElementById("loan_purpose");var id = sel.options[sel.selectedIndex].value;if(id != 1){document.getElementById('pricetitle').innerHTML = "<font color='red'>Estimated Property Value:</font>";}else{document.getElementById('pricetitle').innerHTML = "Purchase Price:";}}
function fill_loan_payment(){var amount = document.getElementById('loanamount').value;amount = amount.replace(/,/g, "");amount = amount*.0085;document.getElementById('emp').value = amount.toFixed(0);total_debt();if(document.getElementById('emp').value!=0 && document.getElementById('gs').value!=0){total_income();}}
function total_debt(){var emp = document.getElementById('emp').value;var credit_cards = document.getElementById('credit_cards').value;var car_loan = document.getElementById('car_loan').value;var student_loan = document.getElementById('student_loan').value;var alimony = document.getElementById('alimony').value;var other_loan = document.getElementById('other_loan').value;document.getElementById('debt_total').innerHTML = parseFloat(emp)+parseFloat(credit_cards)+parseFloat(car_loan)+parseFloat(student_loan)+parseFloat(alimony)+parseFloat(other_loan);if(document.getElementById('debt_total').innerHTML!='' && document.getElementById('income_total').innerHTML!=''){get_dti_total();}}
function total_income(){var gs = document.getElementById('gs').value;var mo = document.getElementById('mo').value;var cs = document.getElementById('cs').value;var omi = document.getElementById('omi').value;document.getElementById('income_total').innerHTML = parseFloat(gs)+parseFloat(mo)+parseFloat(cs)+parseFloat(omi);if(document.getElementById('debt_total').innerHTML!='' && document.getElementById('income_total').innerHTML!=''){get_dti_total();}}
function get_dti_total(){var dtit = 100*parseFloat(document.getElementById('debt_total').innerHTML) / parseFloat(document.getElementById('income_total').innerHTML);document.getElementById('dti_total').innerHTML = dtit.toFixed(2)+"%";}
function submit_dti(){
	document.getElementById('rw_dti').value = document.getElementById('dti_total').innerHTML;
	var amount = parseFloat(document.getElementById('emp').value)/.0085;
	amount = Math.round(amount);
	var old_amount = document.getElementById('loanamount').value
	old_amount = old_amount.replace(/,/g, "")
	if(document.getElementById('loanamount').value=='' || amount != old_amount)
	{
		document.getElementById('loanamount').value = amount;
		add_commas('loanamount');
		document.getElementById('dti_message').innerHTML = '<br>This Value Changed From DTI Calc';
	}
	else
	{
		document.getElementById('dti_message').innerHTML = '';
	}
	tb_remove();
	}

function cancel_dti(){document.getElementById('main_rw_broker_form').style.display = 'block';document.getElementById('dti_calc').style.display = 'none';}
function IsNumeric(strString){var strValidChars = "0123456789.-";var strChar;var blnResult = true;if (strString.length == 0) return false;for (i = 0; i < strString.length && blnResult == true; i++){strChar = strString.charAt(i);if (strValidChars.indexOf(strChar) == -1){ blnResult = false;}}return blnResult;}
function convert(nStr){nStr += '';x = nStr.split('.');x1 = x[0];x2 = x.length > 1 ? '.' + x[1] : '';var rgx = /(\d+)(\d{3})/;while (rgx.test(x1)) {x1 = x1.replace(rgx, '$1' + ',' + '$2');}return x1 + x2;}
function add_commas(input){var val = document.getElementById(input).value;val = val.replace(/,/g, "");document.getElementById(input).value = convert(val);get_ltv();if(input == 'loanamount')document.getElementById('dti_message').innerHTML = '';}
function clear_input(element){if(element.value == 0)element.select();}

function check_form(type)
{
	var prop_val = document.getElementById('propertyprice').value;
	prop_val = prop_val.replace(/,/g, "");
	var loan_val = document.getElementById('loanamount').value;
	loan_val = loan_val.replace(/,/g, "");
	
	if(document.getElementById('states').options[document.getElementById('states').selectedIndex].value == 0)
	{
		alert ("Please select a State");
		document.getElementById('statetitle').style.color = '#cc0000'
		return false;
	}
	
	if(document.getElementById('county_holder').innerHTML == '')
	{
		alert ("Please select a State, then select a county");
		document.getElementById('countytitle').style.color = '#cc0000'
		return false
	}
	
	if(document.getElementById('propertyprice').value == '')
	{
		alert ("Missing Property Price");
		document.getElementById('pricetitle').style.color = '#cc0000'
		return false
	}
	
	if(IsNumeric(prop_val)==false)
	{
		alert ("Property Price is not a numeric value");
		document.getElementById('pricetitle').style.color = '#cc0000'
		return false
	}
	
	if(document.getElementById('loanamount').value == '')
	{
		alert ("Missing Loan Amount");
		document.getElementById('loantitle').style.color = '#cc0000'
		return false
	}
	
	if(IsNumeric(loan_val)==false)
	{
		alert ("Loan Amount is not a numeric value");
		document.getElementById('loantitle').style.color = '#cc0000'
		return false
	}
	
	if(type!=2) {
		if(document.getElementById('customer_email').value == '')
		{
			alert ("Email required for validation");
			document.getElementById('emailtitle').style.color = '#cc0000'
			emailerror = true;
			return false
		}
	}
	if(document.getElementById('creditscore').value == '')
	{
		alert ("Missing credit score");
		document.getElementById('credittitle').style.color = '#cc0000'
		return false
	}
	
	if(document.getElementById('creditscore').value > 840 || document.getElementById('creditscore').value < 500)
	{
		alert ("Credit Score is out of range (500-840)");
		document.getElementById('credittitle').style.color = '#cc0000'
		return false
	}
	
	if(IsNumeric(document.getElementById('creditscore').value)==false)
	{
		alert ("Credit score is not a numeric value");
		document.getElementById('credittitle').style.color = '#cc0000'
		return false
	}
	
	if(document.getElementById('rw_dti').value == '')
	{
		alert ("Missing debt to income");
		document.getElementById('dtititle').style.color = '#cc0000'
		return false
	}
	
	if(IsNumeric(rtrim(document.getElementById('rw_dti').value, "%"))==false)
	{
		alert ("Debt to income is not a numeric value");
		document.getElementById('dtititle').style.color = '#cc0000'
		return false
	}
	if(document.getElementById('drdBorrowerType').options[document.getElementById('drdBorrowerType').selectedIndex].value == 0)
	{
		alert ("Please select borrower type");
		document.getElementById('bttitle').style.color = '#cc0000'
		return false;
	}
	
	if(ltv>100)
	{
		alert ("your loan amount is higher then your purchase price. You will not get any results");
		return false;
	}
	
	return true;
}

function rtrim(str, chars){chars = chars || "\\s";return str.replace(new RegExp("[" + chars + "]+$", "g"), "");}
function open_window(url, name, height, width){var iMyWidth;var iMyHeight;iMyWidth = (window.screen.width/2) - (width/2 + 10);iMyHeight = (window.screen.height/2) - (height/2 + 50);var newwindow = window.open("http://ratewindow.com/definitions/index.php#"+url, name, 'location=0,status=0,scrollbars=1,width='+width+',height='+height+', resizable=no,left=' + iMyWidth + ',top=' + iMyHeight + ',screenX=' + iMyWidth + ',screenY=' + iMyHeight + ',toolbar=no,menubar=no,directories=no');if(window.focus) newwindow.focus();}

function open_pop_window(url, name, height, width){var iMyWidth;var iMyHeight;iMyWidth = (window.screen.width/2) - (width/2 + 10);iMyHeight = (window.screen.height/2) - (height/2 + 50);var newwindow = window.open(url, name, 'location=0,status=0,scrollbars=1,width='+width+',height='+height+', resizable=no,left=' + iMyWidth + ',top=' + iMyHeight + ',screenX=' + iMyWidth + ',screenY=' + iMyHeight + ',toolbar=no,menubar=no,directories=no');if(window.focus) newwindow.focus();}

function open_window_email(url, name, height, width){var iMyWidth;var iMyHeight;iMyWidth = (window.screen.width/2) - (width/2 + 10);iMyHeight = (window.screen.height/2) - (height/2 + 50);var newwindow = window.open(url, name, 'location=0,status=0,scrollbars=1,width='+width+',height='+height+', resizable=no,left=' + iMyWidth + ',top=' + iMyHeight + ',screenX=' + iMyWidth + ',screenY=' + iMyHeight + ',toolbar=no,menubar=no,directories=no');if(window.focus) newwindow.focus();}
function tb_remove()
{return true}



function toggle_forms(){if(document.getElementById('dti_calc').style.display == 'none'){document.getElementById('main_rw_broker_form').style.display = 'none';document.getElementById('dti_calc').style.display = 'block';}else{document.getElementById('main_rw_broker_form').style.display = 'block';document.getElementById('dti_calc').style.display = 'none';}}

function toggle_forms_1(type){
	if(type==2) {
		document.getElementById('rw_first_form').style.display = 'none';
		document.getElementById('cust_details').style.display = 'block';
	} else {
		document.getElementById('rw_first_form').style.display = 'block';
		document.getElementById('cust_details').style.display = 'none';
	}
}


//	var OKtoLeave = false;
//
//	window.onbeforeunload = function (evt,message) {
//		evt = (evt) ? evt : window.event;
//		if(document.getElementById('dti_calc').style.display=='block') {
//			toggle_forms();
//			window.location = window.location+"#top";	
//			
//			
//		} else {
//	return "Are you sure that you want to navigate away from the Ratewindow calculator";
//		}
//	}

function send_request(stage, post_data)
{
//alert(stage);
//post_data is a string that has to start with &
//post_data must send account_key

display_working(stage);
json('http://ratewindow.com/services/ratewindow_request.php?callback=rw_display&show_header='+show_header+'&show_mb='+show_owner_bottom_form+'&rw_stage='+stage+post_data);
}
//function rw_form(obj){document.getElementById('rw_container').innerHTML = "<div style='background-color:#F7C7BB; border:1px solid #FF0000; padding:5px; margin:5px 0px 5px 0px;'><b>This is the demo version of Ratewindow&trade;</b></div>"+obj;}

var inited = false;
function rw_display(obj){document.getElementById('rw_container').innerHTML = obj;
//if(inited==false) {
//	inited=true;
//	bb_init('rw_container',true);
//	} else {
bb_save_state();
//	}
}

function rw_init(){send_request('', '&widget_key='+key+'&activation_key='+getURLVar('key')+'&show_header='+show_header+'&show_mb='+show_owner_bottom_form);}
var query = location.search;
var url = query.replace("?", "&");
switch(getURLVar('rw_pull'))
{
	case "rw_custom_pull":
		send_request('rw_results', url);
	break;
	
	case "repeat_pull":
		send_request('rw_results', url);
	break;
	
	case "download_widget":
		send_request('rw_download_widget', '&key='+key);
	break;
	
	default:
		//if(!initial_load)
		rw_init();
	break;
}

// bb fix
var bb_count =0;
var bb_curr_idx ="";
var bb_cache = new Array;
var bb_debug = false;
var bb_iframe_script = "/wp-content/plugins/ratewindow_brokers/updateFrame.php?count=";
var bb_iframe_loaded = false;
var bb_target_div = " ";
bb_init('rw_container',false);
//If debug is enabled via bb_int(),then
//we append some data to the divTrail
//element.

function bb_debug_update (str) {
	if (bb_debug){
	    var divBBDebug = document.getElementById ("divBBDebug");
	    divBBDebug.innerHTML = divBBDebug.innerHTML + "<br>" + str;
	}
}

//Run from the interval timer (once a second)
//this function reads a cache index value
//stored in the DIVelement of the child IFRAME.
//
//If this extrated cache index, then the bac buttom was
//pressed . In this case, we pull the corresponding 
//data from the cache and update the page.

function bb_check_state () {

	if (bb_iframe_loaded == false) {
	   return;
	}
var doc = window.frames['bbFrame1'].document;
if(doc.getElementById('divFrameCount')) {
var new_idx = doc.getElementById('divFrameCount').innerHTML;


if (new_idx != bb_curr_idx) {

var debug_msg ="IFRAME changed . Was "
	              + bb_curr_idx
	              + " , now "
	              + new_idx;

//Pull aprevious state from the cache ( if it exists).

if (bb_cache[new_idx]) {
    var divBody = document.getElementById("rw_container");
    divBody.innerHTML = bb_cache [new_idx];



	debug_msg += " pulled "
		      + new_idx
		      + " from cache ]";
	}

	bb_curr_idx =new_idx;
	
	bb_debug_update(debug_msg);
         } }
}

function bb_done_loading() {
	
	bb_iframe_loaded = true;

}

function bb_loadframe() {
	var bbFrame1 = document.getElementById("bbFrame1");
	bb_iframe_loaded =false;
	bbFrame1.src = bb_iframe_script + bb_count;
}


function bb_save_state() {

var div_to_cache = document.getElementById(bb_target_div);
	bb_count++;
	bb_cache[bb_count] = div_to_cache.innerHTML;
	bb_debug_update ( "Added  " + bb_count + " to cache");

	bb_loadframe();
	bb_curr_idx = bb_count;
}

function bb_init(div_name,debug_val)
{
	bb_target_div = div_name;
	bb_debug = debug_val;
	bb_loadframe();
	window.setInterval('bb_check_state()',1000);
	//bb_save_state();
}
function get_js_code()
{
document.getElementById("js_code_holder").style.display = "block";
}
function close_js_code()
{
document.getElementById("js_code_holder").style.display = "none";
}
function get_ifjs_code()
{
document.getElementById("ifjs_code_holder").style.display = "block";
}
function close_ifjs_code()
{
document.getElementById("ifjs_code_holder").style.display = "none";
}