// JavaScript Variables
var xmlHttp;
var version = "v2";
var base_url = "http://ratewindow.com/services/"+version;
var domain = "http://ratewindow.com";
var widget_id;
var remote_host;
var querystring;
var style='tabbed_default_ie';
var splash='normal';
var agent='yes';
var init_state_id='';
var init_county_id='';
var ref='';

//-------------------------------
// Main traffic control for requests/response/display
//-------------------------------

// Everything happens inside this div

function rw_init(widget_id)
{
//TODO: add check for qs that is too long
//TODO: add check to make sure the width of the div is wide enough
// displays the first loan request form to the user.
// required:
// 1. widget_id
this.widget_id = widget_id;
this.style=style;
this.agent=agent;
this.init_state_id=init_state_id; 
this.init_county_id=init_county_id;
querystring = String(document.location).split('?');
this.remote_host = querystring[0]; //domain name
this.querystring = querystring[1]; //all the variables
if(style==''){style='default';}
loader();
document.write("<link rel='stylesheet' type='text/css' href='"+domain+"/services/v2/css/"+style+"/style.css'><div id='ratewindow_container'></div>");

//start the magic
//send_request(querystring);

}

function loader()
{
	//alert('STARTING');
   var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   if(navigator.appName!='Netscape')
   script.onreadystatechange= function () { if(this.readyState=='loaded' || this.readyState=='complete')load_jquery("http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js")}
   else
   script.onload= function () {load_jquery("http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js")}
   script.src= base_url+"/css/"+style+"/js/functions.js";
   head.appendChild(script);
	//json(base_url+"/css/"+style+"/js/functions.js");
}

function load_jquery(url)
{
	var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   if(navigator.appName!='Netscape')
   script.onreadystatechange= function () { if(this.readyState=='loaded' || this.readyState=='complete')load_ui("http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js")}
   else
   script.onload= function () {load_ui("http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js")}
   script.src = url;
   head.appendChild(script);
}

function load_ui(url)
{
   var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   if(navigator.appName!='Netscape')
   script.onreadystatechange= function () { if(this.readyState=='loaded' || this.readyState=='complete')send_request(querystring);}
   else
   script.onload= function () {send_request(querystring);}
   script.src = url;
   head.appendChild(script);
}

// Used to send requests to ratewindow
function send_request(post_data)
{	
  var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   if(navigator.appName!='Netscape')
   script.onreadystatechange= function () { if(this.readyState=='loaded')load_data()}
   else
   script.onload= function () {load_data()}
   script.src = base_url+'/traffic.php?'+post_data+"&style="+this.style+"&agent="+this.agent+"&widget_id="+this.widget_id;
   head.appendChild(script);
	//var url = base_url+'/traffic.php?'+post_data+"&style="+this.style+"&agent="+this.agent+"&widget_id="+this.widget_id; 
	//json(url);
}


//callback function used to display the proper forms and pages
function rw_display(obj)
{
	document.getElementById('ratewindow_container').innerHTML = obj; 
}



//---------------------------------------------------------------------------------
// Below are worker functions that are used for formatting, file
// communication, and form validation
//---------------------------------------------------------------------------------
function form_submit(type, stage, post_data)
{
	pass = true;
	//TODO add all inputs from both the quick form and the advanced form
	var form_str = '';
	var adv_form_str = '';
	price = post_data._PropertyValue.value;
	if(price==''){alert('Missing Property Value');pass=false;}
	if(!price.match(/^[0-9]+$/)){alert("Price must be numeric");pass=false;}
	state_id = post_data._StateID.options[post_data._StateID.selectedIndex].value;
	if(state_id==0){alert('Please Select A State');pass=false;}else{
	county_id = post_data._CountyID.options[post_data._CountyID.selectedIndex].value;
	if(county_id==''){alert('Missing County');pass=false;}}
	property_type = post_data._PropertyType.options[post_data._PropertyType.selectedIndex].value;
	credit_score = post_data._CreditScore.options[post_data._CreditScore.selectedIndex].value;
	if(type=='advanced'){
	loan_purpose = post_data._LoanPurpose.options[post_data._LoanPurpose.selectedIndex].value;
	pricing_type = post_data._PricingTypeID.options[post_data._PricingTypeID.selectedIndex].value;
	occupancy = post_data._Occupancy.options[post_data._Occupancy.selectedIndex].value;
	doc_type = post_data._DocumentType.options[post_data._DocumentType.selectedIndex].value;
	loan_amount = post_data._FirstLeinAmt.value;
	if(loan_amount==''){alert('Missing Loan Amount Value');pass=false;}
	if(!loan_amount.match(/^[0-9]+$/)){alert("Loan amount must be numeric");pass=false;}
	if(loan_amount>price){alert("Loan amount must be less then price");pass=false;}
	adv_form_str="&_LoanPurpose="+loan_purpose+"&_PricingTypeID="+pricing_type+"&_Occupancy="+occupancy+"&_DocumentType="+doc_type+"&_FirstLeinAmt="+loan_amount;
	}
	
	if(pass)
	{
	form_str = "?remote_host="+remote_host+"&widget_id="+widget_id+"&rw_stage=form_submit&_PropertyValue="+price+"&_StateID="+state_id+"&_CountyID="+county_id+"&_PropertyType="+property_type+"&_CreditScore="+credit_score+adv_form_str;
	display_working();
	get_loan_results(form_str);
	}
	
}



function get_loan_results(inputs) 	
{
	var req  = base_url+"/inc/get_loan_results.php"+inputs;
	bObj = new JSONscriptRequest(req); 
	bObj.buildScriptTag(); 
	bObj.addScriptTag();
}

function return_loan_id(obj)
{
	//redirect page with loan_id in querystring
	if(querystring!=null)
	{
		remove_qs_vars();
		
		if(querystring.match(/rw_loan_id=/)!=null)
		querystring=querystring.replace(/rw_loan_id=[0-9]+/,"rw_loan_id="+obj)
		else
		querystring=querystring+"&rw_loan_id="+obj;
		
		if(querystring.match(/rw_stage=/)!=null)
		querystring=querystring.replace(/rw_stage=[a-z_]+/,"rw_stage=loan_results")
		else
		querystring=querystring+"&rw_stage=loan_results";
	}
	else
	{
	querystring="?rw_stage=loan_results&rw_loan_id="+obj;	
	}
	
	querystring=querystring.replace(/rw_product_id=[0-9]+/,'');
	
	querystring=querystring.replace(/^[?]/,'');
	
	window.location.href=remote_host+"?"+querystring;
}

function get_loan_details(product_id)
{
	remove_qs_vars();
	querystring=querystring.replace(/rw_stage=[a-z_]+/,"rw_stage=loan_details")
	if(querystring.match(/rw_product_id=[0-9]+/)!=null)
	querystring=querystring.replace(/rw_product_id=[0-9]+/,'rw_product_id='+product_id);
	else
	querystring = querystring+"&rw_product_id="+product_id;
	window.location.href=remote_host+"?"+querystring;
}

function apply_now(product_id)
{
	remove_qs_vars();
	querystring=querystring.replace(/rw_stage=[a-z_]+/,"rw_stage=loan_apply");
	if(querystring.match(/rw_product_id=[0-9]+/)!=null)
	querystring=querystring.replace(/rw_product_id=[0-9]+/,'rw_product_id='+product_id);
	else
	querystring = querystring+"&rw_product_id="+product_id;
	window.location.href=remote_host+"?"+querystring;
}

function apply_submit(post_data)
{
	var pass=true;
	rw_first_name = post_data.first_name.value;
	if(rw_first_name==''){pass=false;alert('First Name Required')}
	rw_last_name = post_data.last_name.value;
	if(rw_last_name==''){pass=false;alert('Last Name Required')}
	rw_email = post_data.email.value;
	if(rw_email==''){pass=false;alert('Email Required')}
	rw_phone = post_data.phone.value;
	if(rw_phone==''){pass=false;alert('Phone Required')}
	form_str = "&wid="+widget_id+"&rw_first_name="+rw_first_name+"&rw_last_name="+rw_last_name+"&rw_email="+rw_email+"&rw_phone="+rw_phone;
	
	querystring=querystring.replace(/rw_stage=[a-z_]+/,"rw_stage=apply_submit")
	//post_data.action=form_str;
	if(pass)
	window.location.href=remote_host+"?"+querystring+form_str;
	//send_request(form_str);
}

function new_search()
{
	remove_qs_vars();
	querystring=querystring.replace(/rw_stage=[a-z_]+/,"");
	if(querystring.match(/rw_product_id=[0-9]+/)!=null)
	querystring=querystring.replace(/rw_product_id=[0-9]+/,'');
	if(querystring.match(/rw_loan_id=/)!=null)
	querystring=querystring.replace(/rw_loan_id=[0-9]+/,"");
	
	window.location.href=remote_host+"?"+querystring;
}

//-------------------------------
// New Counties from state change
// Used to change counties when the state is changed
//-------------------------------
function get_county_in_state(state_id) 	
{
	var req  = base_url+"/inc/rw_get_counties.php?state_id="+state_id; 
	bObj = new JSONscriptRequest(req); 
	bObj.buildScriptTag(); 
	bObj.addScriptTag();
}

function rw_results_counties(obj)
{
	container = document.getElementById('countyrow');
	if(container!=null){
	container.style.display="";
	document.getElementById('county_div').innerHTML = obj;
	}
	
}

function display_working()
{
if(splash=='narrow')
document.getElementById('ratewindow_container').innerHTML = '<div style="width:100%; margin:0 auto; position:relative; text-align:center; height:267px; width:400px; padding-top:20px; background-repeat:no-repeat; background-image:url('+base_url+'/images/splash_small.jpg)"><div style="position:absolute; margin:0 auto; bottom:25px; left:50px;"><img style="margin:0 auto;" src="'+base_url+'/images/ajax-loader.gif" /></div>';
else
document.getElementById('ratewindow_container').innerHTML = '<div style="width:100%; margin:0 auto; position:relative; text-align:center; height:400px; width:600px; padding-top:20px; background-repeat:no-repeat; background-image:url('+base_url+'/images/splash.jpg)"><div style="position:absolute; margin:0 auto; bottom:30px; left:200px;"><img style="margin:0 auto;" src="'+base_url+'/images/ajax-loader.gif" /></div>';
}

function popup(filename) {
    var width = 600;
    var height = 600;
    var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
    var windowFeatures = "width=" + width + ",height=" + height + ",resizable,left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top;
    myWindow = window.open(domain+"/global/"+filename, "subWind", windowFeatures);
}


// json core functions
//DO NOT EDIT
function JSONscriptRequest(fullUrl)
{
	this.fullUrl = fullUrl;
	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.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 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 remove_qs_vars()
{
	querystring=querystring.replace(/rw_first_name=[0-9a-z'-_ ]+/,"");
	querystring=querystring.replace(/rw_last_name=[0-9a-z'-_ ]+/,"");
	querystring=querystring.replace(/rw_email=[0-9a-z'-_ ]+/,"");
	querystring=querystring.replace(/rw_phone=[0-9a-z'-_ ]+/,"");
	return querystring;
}

function ge(name)
{
return document.getElementById(name);	
}

function remove_tabs(tab)
{
if(tab!=null)
document.getElementById(tab).className = document.getElementById(tab).className.replace(/\bcurrent\b/,'')
}
function update_tabs(tab)
{
this.tab = tab;
document.getElementById(tab).setAttribute("class", "current");
}


