var warningList;
var result;
// var googleTrackingURL = 'http://www.googleadservices.com/pagead/conversion/1069010046/?value=1&label=SentEnquiry&script=0';
var googleTrackingURL = 'http://' + location.hostname + '/GoogleTrack.asp?label=Lead';
initWarningList();


function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

/*
//function:EmailCheck  
//Description: check the email is valied.
//parameters:emailStr(the str to be checked.)
//returns:false(if not valited);  true(if valited)
function EmailCheck(emailStr){
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var emailPat=/^(.+)@(.+)$/;
	var matchArray=emailStr.match(emailPat);
	
	if (matchArray==null){
		//alert("Email format required!");
		return false;
	}
	
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++){
		if (user.charCodeAt(i)>127){
			//alert("Email format required!");
			return false;
		}
	}
	
	for (i=0; i<domain.length; i++){
		if (domain.charCodeAt(i)>127){
			//alert("Email format required!");
			return false;
		}
	}
	
	if (user.match(userPat)==null){
		//alert("Email format required!");
		return false;
	}
	
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null){
		for (var i=1;i<=4;i++){
			if (IPArray[i]>255){
				//alert("Email format required!");
				return false;
			}
		}
		return true;
	} 
	
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++){
		if (domArr[i].search(atomPat)==-1){
			//alert("Email format required!");
			return false;
		}
	}
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1){
		//alert("Email format required!");
		return false;
	}
	if (len<2){
		//alert("Email format required!");
		return false;
	}
	
	return true;
}
*/

function initWarningList() {
  warningList = document.createElement('ul');
  warningList.className = 'warningMsgs';
}

function addWarning(msg) {
  if (msg.length > 0) {
    var li = document.createElement('li');
    var txt = document.createTextNode(msg);
    li.appendChild(txt);
    warningList.appendChild(li);
  }
}

function checkEnquiryForm(formObj,bDivShow) 
{
  var formOK = true;
  var hasValue = false;
 
	initWarningList();
	document.getElementById('warning').innerHTML = '';
	document.getElementById('warning').style.display = 'none';

  
 
   
    if (document.getElementById('FirstName').className == 'valueRequired') { document.getElementById('FirstName').className = ''; }
	if (document.getElementById('LastName').className == 'valueRequired') { document.getElementById('LastName').className = ''; }
    if (document.EnquiryForm.ContactPhone.className == 'valueRequired') { document.EnquiryForm.ContactPhone.className = ''; }
	
	if (document.getElementById('ContactMobile').className == 'valueRequired') { document.getElementById('ContactMobile').className = ''; }
	if (document.getElementById('EmailAddress').className == 'valueRequired') { document.getElementById('EmailAddress').className = ''; }
	if (document.getElementById('PostCode').className == 'valueRequired') { document.getElementById('PostCode').className = ''; }

	if (document.getElementById('validateCode').className == 'valueRequired') { document.getElementById('validateCode').className = ''; }

	if (document.EnquiryForm.owner[0].checked || document.EnquiryForm.owner[1].checked) { 	document.getElementById('checkTd').style.backgroundColor =''; }
	 
	//return false;
    if (document.getElementById('FirstName').value.length == 0) {
      formOK = false;
	    
	    addWarning('Please fill in your first name.');
	    document.getElementById('FirstName').className = 'valueRequired';
    }
	
	 
	
	if (document.getElementById('LastName').value.length == 0) {
      formOK = false;
	    addWarning('Please fill in your surname.');
	    document.getElementById('LastName').className = 'valueRequired';
    }
	
	result = getCheckedValue(document.forms['EnquiryForm'].elements['owner'])
	

	
	/*
	if (result == "") {
      formOK = false;
	    addWarning('Please specify if you own real estate property or you are paying off a mortgage.');
	    
    }
	*/
    if (document.EnquiryForm.ContactPhone.value.length == 0)  {
	
      	formOK = false;
	    addWarning('Please fill in your contact phone.');
	    document.EnquiryForm.ContactPhone.className = 'valueRequired';	
  
    }
   
	if (document.getElementById('ContactMobile').value.length == 0)  {
      	formOK = false;
	    addWarning('Please fill in your mobile phone.');
	    document.getElementById('ContactMobile').className = 'valueRequired';	
      	
    }
    
	if (document.getElementById('EmailAddress').value.length == 0)  {
      	formOK = false;
	    addWarning('Please fill in your email address.');
	    document.getElementById('EmailAddress').className = 'valueRequired';	
      	
    }
	
	if (document.getElementById('PostCode').value.length == 0)  {
	
      	formOK = false;
	    addWarning('Please fill in your post code.');
	    document.getElementById('PostCode').className = 'valueRequired';	
      	
    }
   
    if ((!document.EnquiryForm.owner[0].checked) && (!document.EnquiryForm.owner[1].checked))  {
			
			formOK = false;
      	//addWarning('Please tell us you own real estate property or are you paying off a mortgage.');
      	 addWarning('Please specify if you own real estate property or you are paying off a mortgage.');
      	document.getElementById('checkTd').style.backgroundColor ='#DD4411';
      	
    }
	
	
	if (document.getElementById('validateCode').value.length == 0)  
	{
      	formOK = false;
	    addWarning('Please fill in validation code.');
	    document.getElementById('validateCode').className = 'valueRequired';	
      	
    }
		/*
		if (document.getElementById('securitybox').checked == false) {
			loantype = document.getElementById('loanType');
			loantype = loantype[loantype.selectedIndex].text;
			if ((loantype != 'Home Loans') && (loantype != 'Motor Vehicle Finance')){
				formOK = false;
		    addWarning('Sorry, you must be able to offer security for your loan.');
			}
		}
		*/

  if (formOK == false) 
  {
	
    document.getElementById('warning').style.display = 'block';
   	document.getElementById('warning').innerHTML = 'Some required fields have not been filled in or invalid. They have been highlighted.'
    return false;
  } 
  else 
  {
    if (http) 
	{
      var qstr = getFormValues(formObj);
      qstr += '&useAJAX=y';
     
	 
	 
	 //url = 'http://' + location.hostname + '/contact.asp?';//please use this when live site
	 //url = 'http://' + location.hostname + '/alctest/contact.asp?';//the test site
	
	  //sendEnquiry(url, qstr, sendWith);
      googleTrack();
	  //formObj.reset();
	  //location.href='enquiry_complete.asp';
	  location.href="contact.asp?"+qstr;
      return false;
    }
    return true;
  }
  
  
}

var http = getHTTPObject();
var isWorking = false;
var sendWith = 'GET';

function sendEnquiry(url, qstr, sendAs) {
  if (!isWorking && http) {
    if (sendAs == 'POST') {
      http.open("POST", url, true);
      http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	    http.onreadystatechange = handleEnquiry;
	    isWorking = true;
      http.send(qstr);
    }
    if (sendAs == 'GET') {
	    http.open('GET', url + qstr, true);
	    http.onreadystatechange = handleEnquiry;
	    isWorking = true;
	    http.send(null);
    }
  }

}

function googleTrack() {
  var http2 = getHTTPObject();
  http2.open('GET', googleTrackingURL, true);
  http2.send(null);
}


function handleEnquiry() {
  if (http.readyState == 4) {
    if (http.status == 200) {
	    if (http.responseText.indexOf('error') == -1) {
	      var showtext = http.responseXML;
	      isWorking = false;
   	    //alert(http.responseText);
	    } else {
//	      alert('somefin wong');
	    }
	  } else {
//	    alert('http error');
	  }
  }
}


function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {

        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}


function getFormValues(fobj)
{
   var str = "";
   var valueArr = null;
   var val = "";
   var cmd = "";
   for(var i = 0;i < fobj.elements.length;i++)
   {
       switch(fobj.elements[i].type)
       {
           case "text":
                str += fobj.elements[i].name +
                "=" + escape(fobj.elements[i].value) + "&";
                break;
           case "select-one":
                str += fobj.elements[i].name +
                "=" + escape(fobj.elements[i].options[fobj.elements[i].selectedIndex].value) + "&";
                break;
           case "radio":
                if (fobj.elements[i].checked) {
	                str += fobj.elements[i].name +
	                "=" + escape(fobj.elements[i].value) + "&";
                }
                break;
           case "checkbox":
                if (fobj.elements[i].checked) {
	                str += fobj.elements[i].name +
	                "=" + escape(fobj.elements[i].value) + "&";
                }
                break;
           case "textarea":
                str += fobj.elements[i].name +
                "=" + escape(fobj.elements[i].value) + "&";
                break;
           case "submit":
                str += fobj.elements[i].name +
                "=" + escape(fobj.elements[i].value) + "&";
                break;
       }
   }
   str = str.substr(0,(str.length - 1));
   return str;
}

function refreshImageCode(img)
{
	try
	{
		if (img != null && img.tagName.toLowerCase() == "img")
		{
			var rnd = Math.random();
			img.src = "Lib/ValidateCode/CheckCode.asp?" + rnd;
		}
	}
	catch(e)
	{
	}
}
