// JavaScript Document
var theForm=document.getElementById('form2');var err_state=false;
function Calling_DIV(dispid,hide1,hide2,hide3,hide4,hide5,hide6) {
	document.getElementById(dispid).style.display='';
	document.getElementById(hide1).style.display='none';
	document.getElementById(hide2).style.display='none';
	document.getElementById(hide3).style.display='none';
	document.getElementById(hide4).style.display='none';
	document.getElementById(hide5).style.display='none';
	document.getElementById(hide6).style.display='none';
}
function panel_call(dispid,hide1){
	document.getElementById(dispid).style.display='block';
	document.getElementById(hide1).style.display='none';
}

function Calc_Loan() {
	var theForm=document.getElementById('form2');
	var error_msg="";err_state=false;
	var Eq_Val=(el_fi('lead_property_value')-el_fi('lead_mortgage_value'))*((el_fi('app_age')-35)/100);
	Eq_Val=Eq_Val.toFixed(0);
	el_get('potcash').value=Eq_Val;
	eq_diff=el_fi('lead_property_value')-el_fi('lead_mortgage_value');
	
if(checkNumber("app_age") || document.getElementById('app_age').value < 55 || document.getElementById('app_age').value > 95){
	error_msg+="You must be aged between 55 and 95 years<br>";
	err_state=true;
	field = theForm.app_age;
	highlite(theForm.app_age);
}
if(!radio_sel('whowns')){
	error_msg+="Please indicate who owns the property<br>";
	err_state=true;
	//highlite(theForm.whowns);
	}
if(el_get('whownsN').checked && checkNumber("part_age")){
	error_msg+="Please indicate your partners age<br>";
	err_state=true;
	highlite(theForm.part_age);
	}
if(el_get('whownsN').checked && !checkNumber("part_age") && (el_fi("part_age")<55 ||  el_fi("part_age")>95)){
	error_msg+="Your partner must be 55-95 years of age<br>";
	err_state=true;
	highlite(theForm.part_age);
	}	
/*if(checkNumber("lead_property_value")){
	err_state=true;
	error_msg+="Property Value must be a valid amount<br>";
	field = theForm.lead_property_value;
	highlite(field);
}
if(checkNumber("lead_mortgage_value")){
	err_state=true;
	error_msg+="Outstanding Mortgage must be a valid amount";
	field = theForm.lead_mortgage_value;
	highlite(field);
}*/
var Prop_val=el_fi("lead_property_value");var Mort_val=el_fi("lead_mortgage_value");
if(checkNumberVal(Prop_val)){
	err_state=true;
	error_msg+="Property Value must be a valid amount<br>";
	field = theForm.lead_property_value;
	highlite(field);
}else{lowlite(theForm.lead_property_value);}
if(checkNumberVal(Mort_val)){
	err_state=true;
	error_msg+="Outstanding Mortgage must be a valid amount<br>(Please enter 0 if no Mortgage balance remains)";
	field = theForm.lead_mortgage_value;
	highlite(field);
}else{lowlite(theForm.lead_mortgage_value);}
if(eq_diff<70000){
	err_state=true;
	error_msg+="Equity should at least £70,000 <br>(Property value minus mortgage/loans)<br>";
	field = theForm.lead_mortgage_value;
	highlite(field);
}
	if(Eq_Val<0){
	err_state=true;
	error_msg+="Property Value must be greater than the Outstanding Mortgage ";
		}
	//var elem = document.getElementById(field);
	//document.getElementById('Calc_Err').style.display='block';
if(err_state){
	error_msg="<b>Cannot perform your calculation<br /><br />Please correct the items indicated below </b><br /><br /> "+error_msg;
		document.getElementById("Calc_Err").innerHTML=error_msg;
		document.getElementById('Calc_Err').style.display='block';
}else{
		//document.getElementById("Eq_Loan_Val").firstChild.nodeValue="You may be eligable for a loan of up to £"+Eq_Val+"";
		//document.getElementById("Eq_Loan_Val").innerHTML="Congratulations! You <u>are</u> be eligible for a loan of up to £"+Eq_Val+", <u>depending</u> on the provider you use";
		//document.getElementById("Eq_Loan_Val").innerHTML="Congratulations! You qualify to release cash from your property";
		document.getElementById("calc_loan").value=Eq_Val;
		document.getElementById('Calculator_form').style.display='none';
		document.getElementById('Contact_form').style.display='block';
		document.getElementById('Calc_Err').style.display='none';	
	}
}


function form_submit(){
var theForm=document.getElementById('form2');
var con_err_state=false;var con_error_msg="";
var app_name=trimInput(document.getElementById("fname").value) 
var app_add=trimInput(document.getElementById("Add1").value)
var app_email=trimInput(document.getElementById("Email").value)

if(app_name.length<2){
		field = theForm.fname;
		highlite(field);
		con_err_state=true;
		con_error_msg+="Please enter your name<br>";;
		}
if(app_add.length<3){
		field = theForm.Add1;
		highlite(field);
		con_err_state=true;
		con_error_msg+="Please enter 1st line of your address (house no. and street)<br>";;
		}
if (checkPostCode(theForm.Pcode.value)){
		theForm.Pcode.value=checkPostCode(theForm.Pcode.value);	
	}else{
		field = theForm.Pcode;
		highlite(field);
		con_err_state=true;
		con_error_msg+="Postcode must have valid UK format (please do not use - , etc)<br>";
	}
var UkPhoneNumberErrorMessages = ["Please enter Telephone No. without country code or +", "Telephone No. should be 10 or 11 digits", "Telephone No. should start with a zero", "06 / 070 Telephone Nos. not accepted", "Please enter home, work or mobile Telephone No.","Telephone No. should contain numbers only"];
	errorcode=UkPhoneNumber(document.getElementById("Telephone").value);
if(errorcode!=-1){
		field = theForm.Telephone;
		highlite(field);
		con_err_state=true;
		con_error_msg+=UkPhoneNumberErrorMessages[errorcode]+"<br>";
	}else{}	
//if(app_email.length!=0){
		if(!isValidEmail(app_email)){
		field = theForm.Email;
		highlite(field);
		con_err_state=true;
		con_error_msg+="Please correct email format (eg you@email.com)<br>";;
			}
	//	}




//document.getElementById("Email").value=trimInput(app_email);
	
	
	
	
	if(con_err_state){
	con_error_msg="<b>Please correct the highlighted boxes as advised below</b><br /><br />"+con_error_msg;
		document.getElementById("Contact_Err").innerHTML=con_error_msg;
	}else{
		//theForm.submit();
		//makeVCALLRequest('Call');
		call_init();
		}
}
function whownschecked(){
if(el_get('whownsY').checked){hide_all('part_age_row');}
if(el_get('whownsN').checked){show_all('part_age_row');}
if(radio_sel('whowns') && err_state	){
	curr_message=el_get("Calc_Err").innerHTML;
	new_message=curr_message.replace(/Please indicate who owns the property/g, "");
	el_get("Calc_Err").innerHTML=new_message;}

	}
function el_get(el){
	el=document.getElementById(el);
	return el;
}
function el_val(el){
	el=document.getElementById(el).value;
	return el;
}
function el_i(el){
	el=parseInt(document.getElementById(el).value);
	return el;
}
function el_fi(ID)
{   tVal=el_get(ID).value;
	return parseInt( tVal.replace(/[^0-9]*/g, ""), 10 );
}
function addCommas( numberString )
{
	numberString += '';
	numberString=numberString.replace(/-/g, "");
	x = numberString.replace(/[^0-9.\-]*/g, "").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 addCommasToNumberTextbox(id)
{
	id.value = addCommas( id.value );
	id.style.background="fffff";
}
function addCommasToCurrencyTextbox(id)
{
	id.value = "£" + addCommas( id.value );
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	var ck = name+"="+value+expires+"; path=/";
	// if (days != -1) alert('Cookie\n' + ck + '\ncreated');
	document.cookie = ck;
}


function start_form(){
var field=document.getElementById('app_age');
field.focus();
field.style.background="#CCFF00";	
}

function highlite(field){
field.style.background="#FFB3B3";
}
function lowlite(field){
field.style.background="#FFFFFF";
}
function checkNumber(field){
var elem = document.getElementById(field);
var alpha = /\w/;
if ((isNaN(elem.value)) || (!alpha.test(elem.value))){
	return true;
		}else{
	return false;
		}
}

function checkNumberVal(s__Val){
var alpha = /\w/;
if ((isNaN(s__Val)) || (!alpha.test(s__Val))){
	return true;
		}else{
	return false;
		}
}
function show_step(){
	if(arguments[0]!="none"){el_get(arguments[0]).style.display="block";}
	for(var i=1; i<arguments.length; i++) 
		{el_get(arguments[i]).style.display="none";}
}

function show_all(){
	for(var i=0; i<arguments.length; i++) 
		{el_get(arguments[i]).style.display="block";}
}
function hide_all(){
	for(var i=0; i<arguments.length; i++) 
		{el_get(arguments[i]).style.display="none";}
}
function disable_control(){
		for(var i=0; i<arguments.length; i++) 
		{el_get(arguments[i]).disabled=true;}
}
function enable_control(){
		for(var i=0; i<arguments.length; i++) 
		{el_get(arguments[i]).disabled=false;}
}
function read_xml(text){

try //Internet Explorer
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async="false";
  xmlDoc.loadXML(text);
  }
catch(e)
  {
  try //Firefox, Mozilla, Opera, etc.
    {
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(text,"text/xml");
    }
  catch(e) {alert(e.message)}
  }

return xmlDoc;
}
function get_str_data(str_body,str_start,str_end){
	var str_lenth=str_start.length;
	st_index=str_body.lastIndexOf(str_start);en_index=str_body.lastIndexOf(str_end);
	var ret_str=str_body.substring(st_index+str_lenth,en_index);
return ret_str;
}
function get_tab_data(str_body,str_id){
	var str_start="<"+str_id+">";
	var str_end="</"+str_id+">";
	var str_lenth=str_start.length;
	st_index=str_body.lastIndexOf(str_start);en_index=str_body.lastIndexOf(str_end);
	var ret_str=str_body.substring(st_index+str_lenth,en_index);
return ret_str;
}
function isRadioChk(name)
{
	var controls = document.getElementsByName(name);
	
	for( var i = 0 ; i < controls.length ; i++ )
	{
		if( controls[i].checked )
		{
			return true;
		}
	}
	
	return false;
}

function radio_val(name){
	var controls = document.getElementsByName(name);
	
	for( var i = 0 ; i < controls.length ; i++ )
	{
		if( controls[i].checked )
		{
			return controls[i].value;
		}
	}
	
	return "na";
}
function radio_sel(id){
//var controls = [{id:'lumpSum', label:'lumpSum_lbl'}]; 
var m = document.getElementsByName(id);
   //alert(m.length);
	for (var i = 0; i < m.length; i++) { 
		//var c = el_get(controls[i].id); 
		//alert(m[i].value);
		if(m[i].checked){return true;}
		//if (c.checked){return true;}
	}
return false;
}

function UkPhoneNumber(field_val)
{
	// Get the phone number as a string from the text box
	var telephoneNumber = field_val;
	
	// Don't allow country codes to be included (assumes a leading "+")
	if ( telephoneNumber.match(/^\+.+$/) )
	{
		return 0;
	}

	if (telephoneNumber.match(/^\+?[0-9 ()-]+[0-9]$/) == null )
	{
		return 5;
	}

	// Remove everything but numeric digits from the telephone number to help validation
	telephoneNumber = telephoneNumber.replace(/[^0-9]*([0-9]*)/g, "$1");

	// Now check that it is 10 or 11 digits long
	if( telephoneNumber.match(/^[0-9]{10,11}$/) == null )
	{
		return 1;
	}

	// Now check that the first digit is 0
	if ( telephoneNumber.match(/^0[0-9]{9,10}$/) == null )
	{
		return 2;
	}

	// Finally check that the telephone number is appropriate.
	if ( telephoneNumber.match(/^(06|070)[0-9]+$/) )
	{
		return 3;
	}

	// Check that the telephone number is appropriate.
	if (telephoneNumber.match(/^(01|02|03|05|07|08)[0-9]+$/) == null )
	{
		return 4;
	}

	// Check for too many repeating digits
	if (telephoneNumber.match(/^\d*(\d)\1{7}\d*$/) )
	{
		return 4;
	}
	if (telephoneNumber.match(/^\+?[0-9 ()-]+[0-9]$/) == null )
	{
		return 4;
	}
	if (telephoneNumber== '01234567890' || telephoneNumber== '0123456789')
	{
		return 4;
	}	
	return -1;
}


function checkPostCode (toCheck) {

  // Permitted letters depend upon their position in the postcode.
  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
  var alpha3 = "[abcdefghjkstuw]";                                // Character 3
  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5
  

  // Array holds the regular expressions for the valid postcodes
  var pcexp = new Array ();

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Expression for postcodes: ANA NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

  // Expression for postcodes: AANA  NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  
  // Standard BFPO numbers
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  
  // c/o BFPO numbers
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);

  // Load up the string to check
  var postCode = toCheck;

  // Assume we're not going to find a valid postcode
  var validPC = false;
  
  // Check the string against the types of post codes
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
    
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      
      // Copy it back into the original string, converting it to uppercase and
      // inserting a space between the inward and outward codes
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      
      // If it is a BFPO c/o type postcode, tidy up the "c/o" part
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      
      // Load new postcode back into the form element
      validPC = true;
      
      // Remember that we have found that the code is valid and break from loop
      break;
    }
  }
  
  // Return with either the reformatted valid postcode or the original invalid 
  // postcode
  if (validPC) {return postCode;} else return false;
}
function trimInput(sStr)
{
//return str.replace(/^\s*|\s*$/,"");

while (sStr.substring(0,1) == ' ')
{
sStr = sStr.substring(1, sStr.length);
}
while (sStr.substring(sStr.length-1, sStr.length) == ' ')
{
sStr = sStr.substring(0,sStr.length-1);
}
return sStr;
}
function isValidEmail(strEmail) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
	if (strEmail.length < 5) { return false; }
	if (!strEmail.match(re)) { return false; }
	return true;
}