// JavaScript Document

function toggleContent(srcObj,targData,contentID) {
	//alert(srcObj.options[srcObj.options.selectedIndex].value);
	//alert(targData);
	if (!srcObj) return;
	targObj = document.getElementById(contentID);
	if (!targObj) return;
	
	// Note: The below is unnecessarily complicated to read, but 
	// puzzles are fun aren't they?
	if (srcObj.type == 'select-one' || srcObj.type == 'select') {
		targObj.style.display = (srcObj.options[srcObj.options.selectedIndex].value == targData) ? "block" : "none";
	} else if (srcObj.type == 'radio') {
		targObj.style.display = (srcObj.value == targData) ? "block" : "none";
	} else {
		alert('Unknown type received by handler: '+srcObj.type);
	}
	return false;
}

function preValidate(srcObj,dataType) {
	// This function prevalidates and changes user input to match
	// what we require.
	if (!srcObj || !dataType) return;
	
	switch(dataType) {
		case "currency":
			srcObj.value = srcObj.value.replace(/[^\d\.]+/g,'');
			break;
		case "numeric":
			// Remove any non-numeric character (0-9) in the field
			srcObj.value = srcObj.value.replace(/[^0-9\ ]/g,'');
			break;
		case "ucase":
			srcObj.value = srcObj.value.replace(/[a-z]/g,'$&').toUpperCase();
			break;
	}
}

function removeDupeHiddenFFs() {
	// 
	// **OBSOLETED**
	//
	// This function removes duplicate "hidden" form fields created by PHP
	// insertFormFields() function.  Whilst haven't duplicates doesn't really affect
	// data transfer, it does make referencing specific DOM elements annoying.
	var cElm, cElmAry;
	var myForm = document.loanForm;
	if (!myForm) return;
	
	for (i=0;i<myForm.elements.length;i++) {
		cElm = myForm.elements[i];
		cElmAry = document.getElementsByName(cElm.name);
		if (cElmAry.length > 1) {
			// Remove the hidden elements (as applicable)
			for (j=0;j<cElmAry.length;j++) {
				if (cElmAry[j].type == "hidden") {
					//alert("Would remove hidden element ["+j+"] "+cElmAry[j].name);
					myForm.removeChild(cElmAry[j]);
				}
			}
		}
	}
}

// This array defines which variables depend on others for their "requiredness".
// Some fields on the form only need to be filled in as the result of selections 
// made on other options, and we only need this information IF the user has selected
// pre-defined options
var prqAry = new Array();
var prqAry2 = new Array();
prqAry["secondApplName"] 		= "jointApp,yes";
prqAry["secondApplEmail"] 		= "jointApp,yes";
prqAry["secondApplAnnualIncome"] 		= "jointApp,yes";



function checkPreReqs(chkFld) {
	// Some required fields are only required if they have been "activated" (unhidden)
	// by a previous selection (which may itself be required).  If this is the case
	// we need to make sure that the required field we're checking is actually required
	// at this stage.
	var myForm = document.appForm;
	if (!myForm) return;
	
	if (!prqAry[chkFld]) {
		// No pre-reqs defined
		return true;
	} else {
		var iPrq = prqAry[chkFld].split(",");
		var prFld = document.getElementsByName(iPrq[0]);
		for (j=0;j<prFld.length;j++) {
			if (prFld[j].type == 'radio') {
				if (prFld[j].value == iPrq[1] && prFld[j].checked) {
					// Pre-requisites matched - source field is expected value
					//alert(j+": pre-req match: "+iPrq[0]+", val: "+prFld[j].value+" and is checked");
					return true;
				}
			} else if (prFld[j].type == 'select-one' || prFld[j].type == 'select') {
				if (prFld[j].options[prFld[j].options.selectedIndex].value == iPrq[1]) {
					// Pre-requisites matched - source field is expected value
					//alert(j+": pre-req match: "+iPrq[0]+", val: "+prFld[j].options[prFld[j].options.selectedIndex].value);
					return true;
				}
			}
		}
	
	if (iPrq[0]=="residential")
			{ 
			if(chkFld=="propertyvalue")
			{
			var iPrq = prqAry2[chkFld].split(",");
			var prFld = document.getElementsByName(iPrq[0]);
			//alert(iPrq[1]);
			for (j=0;j<prFld.length;j++) {
				if (prFld[j].type == 'radio') {
					if (prFld[j].value == iPrq[1] && prFld[j].checked) {
						// Pre-requisites matched - source field is expected value
						//alert(j+": pre-req match: "+iPrq[0]+", val: "+prFld[j].value+" and is checked");
						return true;
					}
				} else if (prFld[j].type == 'select-one' || prFld[j].type == 'select') {
					if (prFld[j].options[prFld[j].options.selectedIndex].value == iPrq[1]) {
						// Pre-requisites matched - source field is expected value
						//alert(j+": pre-req match: "+iPrq[0]+", val: "+prFld[j].options[prFld[j].options.selectedIndex].value);
						return true;
					}
				}
			}
		}
			}
	}
	return false;
}

function showMissingFields(ivFlds) {
	// This function basically just removes duplicate entries in the array and formats
	// it for display in an alert box.
	if (!ivFlds) return "";
	
	var tmpFlds = new Array();
	ivFlds.sort();
	for (i=0;i<ivFlds.length;i++) {
		if (ivFlds[i] == ivFlds[i+1])
			continue;
		tmpFlds[tmpFlds.length] = "- "+ivFlds[i];
	}
				
	ivFlds = tmpFlds.join("\n");
	return ivFlds;
}	
	
function validateForm(myForm) {
	
	var elm, fldName;
	var isValid = true, fldValid, optValid;
	var ivFlds = new Array();
	var igFlds = new Array();
	
	if (!myForm) return;
	
	// We check for required fields through a bastardisation of the "Title" attribute of
	// HTML tags.  Each form field has a title tag, and part of this title may specify
	// the string "(REQUIRED)".  We look for this string and if found check to see whether
	// the user has supplied data for it.  If not, we prompt them.
	for (i=0;i<myForm.elements.length;i++) {
		elm = myForm.elements[i];
		
		
		
		/// Checking valid mobile no ends here
		if (elm.title.indexOf("(REQUIRED)") > 0) {
			
			// This field is required, find out what it is
			fldName = elm.title.replace(/ \(REQUIRED\)/,"");
			fldValid = true;
			
			if (elm.type == 'select-one' || elm.type == 'select') {
				if (elm.options.selectedIndex == 0 && checkPreReqs(elm.name)) {
					isValid = false;
					fldValid = false;
					ivFlds.push(fldName);
				}
			} else if (elm.type == 'text') {
				if (elm.value.length < 1 && checkPreReqs(elm.name)) {
					isValid = false;
					fldValid = false;
					ivFlds.push(fldName);
				}
			} else if (elm.type == 'checkbox') {
				// Assume it has to be checked if its a required field
				if (!elm.checked) {
					isValid = false;
					fldValid = false;
					ivFlds.push(fldName);
				}
			} else if (elm.type == 'radio') {
				// Radio buttons are a bit more complicated as there can be several of them with
				// the same name on the form, and we only need to check that one of them (from a 
				// group) has been selected.
				if (checkPreReqs(elm.name)) {
					// Loop through all named elements of the same type and only invalidate if 
					// none of them are set
					optValid = false;
					optFlds = document.getElementsByName(elm.name);
					for (j=0;j<optFlds.length;j++) {
						if (optFlds[j].checked) {
							optValid = true;
							break;
						}
					}
					if (!optValid) {
						isValid = false;
						fldValid = false;
						ivFlds.push(fldName);
					}
				}
			} 
			
			// Toggle CSS class (redness) based on field required status
			if (!fldValid) {
				elm.className = ((elm.className.indexOf("Req") > 0) ? elm.className : elm.className+"Req");
			} else {
				elm.className = ((elm.className.indexOf("Req") > 0) ? elm.className.substr(0,elm.className.length-3) : elm.className);
			}
		}
		
	}
	
	
		
	
	// Show error message if one or more fields are invalid
	if (!isValid) {
		alert("One or more required fields have not been completed.\nPlease go back and enter details for all highlighted fields:\n\n"+showMissingFields(ivFlds)+finalCheck());
		return false;
	}
	
	if (isValid) {
		var finalMessage=finalCheck();
		
		if(finalMessage == "")
			myForm.submit();
		else
			{
					alert(finalMessage);
					return false;
			}
	}
}




//Gets parameters from querystring
function getParam(url, param)
 {
  var i;
  var val;
  if ((i = url.indexOf("?" + param + "=")) > -1 ||(i = url.indexOf("?" + param.toUpperCase() + "=")) > -1 ||(i = url.indexOf("&" + param +"=")) > -1 ||(i = url.indexOf("&" + param.toUpperCase() + "=")) > -1) 
  {
    val = url.substring(i + param.length + 2, url.length);
    if ((i = val.indexOf("&")) > -1) {  val = val.substring(0, i);  }
  }
    if(val)
	{
	return val;
	}
	else
	return "";
}


// Capturing campaign data

if(document.cookie.indexOf("se") <0)
document.cookie="se="+getParam(window.location.href,"se");
if(document.cookie.indexOf("cat") <0)
document.cookie="cat="+getParam(window.location.href,"cat");
if(document.cookie.indexOf("kw") <0)
document.cookie="kw="+getParam(window.location.href,"kw");
							se=getCookie('se');
							 cat=getCookie('cat');
							 kw=getCookie('kw');

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
return ""
}

// Validates email id.
function emailcheck(txtfld, mes)
{
var str;
var string1=txtfld.value;
 str = "";
if (string1.indexOf("@")==-1){
	str = "NO";}
else if (string1.indexOf("@")==0){
	str = "NO";}
else if (string1.indexOf(".")==-1){
	str = "NO";}
else if (string1.indexOf(".")==0){
	str = "NO";}
else if (string1.indexOf("@") + 1 == string1.indexOf(".")){
	str = "NO";}
else if (string1.indexOf("@") + 1== string1.length){
	str = "NO";}
else if(string1.lastIndexOf(".") + 1== string1.length){
	str = "NO";}
else if(string1.indexOf("@") != string1.lastIndexOf("@")){
	str = "NO";}

else{
	str = "YES";}

if (str=="NO"){	
	//alert(mes);
	//txtfld.select();
	txtfld.focus();
	finalchk=0;
	return true;
	}
	else{
		finalchk=1;}
		return false;
	}
	
// Function to validate Phone field

function chkTel(txtfld, mes)
{
 //alert(txtfld);
 var txtString= fnTrim(txtfld.value);
 telPhNo=txtString.length;
 startwith=txtString.substr(0,2);
 

 
 if((telPhNo<7)||(telPhNo>11) )
 {
 //alert(mes)
 txtfld.focus();
 txtfld.select();
 //alert(mes);
 return true;
 }
 
 return false;
  
}

// Trims the input string of leading and trailing spaces and returns the new string
function fnTrim(string)
{
	var cnt;	
	len = string.length;
	str = string;
	begin = -1;
	for(cnt=0;cnt<len;cnt++)
	{
		if (str.charAt(cnt) == " ")
		{	
			begin = cnt;
		}	
		else
		break;
		
	}
	str = str.slice(begin+1,len);
	len = str.length;
	end = len;
	for(cnt=len-1;cnt>=0;cnt--)
	{
		if (str.charAt(cnt) == " ")
		{	
			end = cnt;
		}	
		else
		break;
	}
	str = str.slice(0,end);
	return str;
}

function finalCheck()
	{
		myForm=document.appForm;
		var finalMessage="";
		if(chkTel(myForm.telePhone, "Please enter a valid telephone nuber") && fnTrim(myForm.telePhone.value) != "")
			{
			finalMessage+="\n - Please enter a valid telephone number (It should be 7 - 11 digits)";
			}
		if(chkTel(myForm.mobiPhone, "Please enter a valid mobile number") && fnTrim(myForm.mobiPhone.value) != "")
			{
			finalMessage+="\n - Please enter a valid mobile number (It should be 7 - 11 digits)";
			}
		if(emailcheck(myForm.email, "Please enter a valid email id") && fnTrim(myForm.email.value) != "")
			{
			finalMessage+="\n - Please enter a valid email id";
			}
		return finalMessage;
		}