function getHost() {
	var url = window.location.href;
	var nohttp = url.split('//')[1];
	var hostPort = nohttp.split('/')[1];
	return hostPort;
}

jQuery.fn.inputHints = function(idleclass,focusclass) {
    // hides the input display text stored in the title on focus
    // and sets it on blur if the user hasn't changed it.

    // show the display text
		$(this).each(function(i) {
			$(this).val($(this).attr('title'));
		});
	
		// hook up the blur & focus
		$(this).focus(function() {
			$(this).removeClass(idleclass).addClass(focusclass);
			if ($(this).val() == $(this).attr('title'))
				$(this).val('');
		}).blur(function() {
			$(this).removeClass(focusclass).addClass(idleclass);
			if ($(this).val() == '')
				$(this).val($(this).attr('title'));
		});
};

function createA(){
    var xmlhttp = false;
    try{
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E){
            if (!xmlhttp && typeof XMLHttpRequest!='undefined') xmlhttp=new XMLHttpRequest();
        }
    }
    return xmlhttp;
}
// /^\s*(\$|\+|-)?((\d+(\.\d\d)?)|(\.\d\d))\s*$/; con símbolo de dollar
// /^\s*(\$|\+|-)?((\d+(\,\.\d\d)?)|(\,\.\d\d))\s*$/; con símbolo de dollar y coma
// /^\s*(\+|-)?((\d+(\.\d\d)?)|(\.\d\d))\s*$/ normal
var isCurrency_re    = /^\s*(\$|\+|-)?((\d+(\.\d\d)?)|(\.\d\d))\s*$/;;
function isCurrency (s) {
   return String(s).search (isCurrency_re) != -1
}


function run(){
	
	/*
default_sale_price = "Sales Price"
default_annual_interest_percent = "Annual Interest Rate %"
default_year_term = "Mortgage in Years"
default_down_percent = "Percentage Down %"
	*/

	if ($("#sale_price").val() == "" || $("#sale_price").val() == "Sales Price"){
		alert("Please enter the Sale Price");
		return false;
	}
	if($("#down_percent").val() == "" || $("#down_percent").val() == "Percentage Down"){
		alert("Plese enter the Percentage Down");
		return false;
	}
	if($("#year_term").val() == "" || $("#year_term").val() == "Mortgage in Years"){
		alert("Plese enter the Mortgage Years");
		return false;
	}
	if($("#annual_interest_percent").val() == "" || $("#annual_interest_percent").val() == "Annual Interest Rate"){
		alert("Plese enter the Annual Interest Rate");
		return false;
	}
	
	var a = createA();
	var bfn = "";
	var bt  = "";
	burl = "";
	try{
		a.open("POST","../calculator/calculateprocess.asp");
		if ($("#bannerfilename").length != 0){bfn = "&b="+$("#bannerfilename").val();}
		else{bfn = "";}
		if ($("#bannertype").length != 0){bt="&t="+$("#bannertype").val();}
		else{bt="";}
		if($("#bannerurl").length != 0){ burl = "&u="+escape($("#bannerurl").val());}
		else{burl = "";}
	}catch(ex){}
	
		
		var par = "sale_price="+ $("#sale_price").val() +"&down_percent=" + $("#down_percent").val() + "&year_term=" + $("#year_term").val() + "&annual_interest_percent= "+$("#annual_interest_percent").val()+"&form_complete=1&process=0" + bfn + bt + burl;
		var res = document.getElementById("results");
		a.onreadystatechange = function(){
			if (a.readyState == 4 ){
				if(a.status == 200){
					res.innerHTML = a.responseText;
					$.openDOMWindow({ 
						width:800,
						loader:1, 
						loaderImagePath:'animationProcessing.gif', 
						loaderHeight:16, 
						loaderWidth:17, 
						windowSourceID:'#results' 
					}); 
				}
				
			}else if(a.readyState == 1){
				//window.alert("hello");
				res.innerHTML = "Loading data ...";
			}
		};
		a.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		a.setRequestHeader("Content-length", par.length);
		a.setRequestHeader("Connection", "close");
		a.send(par);
		
}

$(document).ready(function(){
						   
	$('#sale_price').inputHints("idleField","focusField");
	$('#down_percent').inputHints("idleField","focusField");
	$('#year_term').inputHints("idleField","focusField");
	$('#annual_interest_percent').inputHints("idleField","focusField");
	
	$('#send').click(function(){
		run();
    	return false; 
	}); 
});





function showform(){
	thecookie = null;
	thecookie = Get_Cookie("calc");
	//alert(thecookie);
	if(thecookie == null){
		var info = document.getElementById("putinfo");
		info.innerHTML="<div style='padding-top:5px;'>Please enter your NAME and E-MAIL to proceed with the Calculations and Amortization</div>Name : <input type='text'  id='oname' style='margin:3px'  /> <br />E-mail : <input  type='text'  id='oemail' style='margin:3px'  /> <br /> Phone : <input type='text' id='ophone' style='margin:3px;'/> <br /> <input type='button' onclick='sendInfo()' value='Submit'/><div id='listresult'></div>";
	}else{
		getProcess(thecookie);
	}
}

function sendInfo(){
	
	var j = createA();
	
	var name = document.getElementById("oname").value;
	var email = document.getElementById("oemail").value;
	var ophone = document.getElementById("ophone").value;
	//alert(name+email+ophone);
	if(name == ""){
		alert("Name can not be empty");
		return
	}
	
	var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	if(email != ""){
		if (!filter.test(email)) {
			alert('Please provide a valid email address');
			return
		}
	}else{
		alert("Email can  not be empty");
		return
	}
	
	var sale_price = $("#sale_price").val();
	var down_percent = $("#down_percent").val();
	var year_term = $("#year_term").val();
	var annual_interest_percent = $("#annual_interest_percent").val();
	
	var state = getHost();
	
	//var par = "name="+ name +"&email=" + email;
	var par = "&sp="+sale_price+"&pd="+down_percent+"&my="+year_term+"&ai="+annual_interest_percent+"&state="+state;
	j.open("get","../calculator/insertCalculatorUser.asp?name="+name+"&email="+email+"&phone="+ophone+par+"&ran="+Math.random());
	//alert("../calculator/insertCalculatorUser.asp?name="+name+"&email="+email+"&phone="+ophone+par+"&ran="+Math.random());
	var res = document.getElementById("putinfo");
	j.onreadystatechange = function(){
		if (j.readyState == 4){
			if(j.status == 200){
				res.innerHTML = "";
				var val = j.responseText;
				Set_Cookie("calc",val,"","/","","");
				getProcess("");
				
			}
		}else if(j.readyState == 1){
			res.innerHTML = "sending data ...";
		}
	};
	j.send(null);
	
}

function getProcess(tc){
	
	$("#btn_process").hide();
	
	var x = createA();
	
	var sale_price = document.getElementById("sale_price").value;
	var down_percent = document.getElementById("down_percent").value;
	var year_term = document.getElementById("year_term").value;
	var annual_interest_percent = document.getElementById("annual_interest_percent").value;
	
	var state = getHost();
	
	var url = "../calculator/calcAllResults.asp?tc="+tc+"&sale_price="+sale_price+"&down_percent="+down_percent+"&year_term="+year_term+"&annual_interest_percent="+annual_interest_percent+"&form_complete=1&ran="+Math.random();
	
	//alert(url);
	
	x.open("get",url);
	
	var res = document.getElementById("process");
	
	x.onreadystatechange = function(){
		if (x.readyState == 4){
			if(x.status == 200){
				res.innerHTML = x.responseText;
				$.openDOMWindow({
					width:800,
					loader:1, 
					loaderImagePath:'animationProcessing.gif', 
					loaderHeight:16, 
					loaderWidth:17, 
					windowSourceID:'#process' 
				});
				
			}
		}else if(x.readyState == 1){
			res.innerHTML = "getting data ...";
		}
	};
	
	x.send(null);
	/*var inres = "<form action='calcAllResults.asp' method='post' id='sendProcess' >";
	inres += "<input type='hidden' name='sale_price' value='"+sale_price+"'>";
	inres +="<input type='hidden' name='down_percent' value='"+down_percent+"'/>";
	inres +="<input type='hidden' name='year_term' value='"+year_term+"'>";
	inres +="<input type='hidden' name='annual_interest_percent' value='"+annual_interest_percent+"'>";
	inres +="<input type='hidden' name='form_complete' value='1'>";
	inres +="</form>";
	res.innerHTML=inres;
	document.getElementById("sendProcess").submit();*/
}

function Set_Cookie( name, value, expires, path, domain, secure ){
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires ){
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
