//Get current url
var m_currTab = 1;
var screeningResult = 1;
var count = 0;

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

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 "";
}

 
 
 function checkDate(field)
  {
    var allowBlank = true;
    var minYear = 1902;
    var maxYear = (new Date()).getFullYear();
 
    var errorMsg = "";
 
    // regular expression to match required date format
    re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
    
    if(field.value != '') {
      if(regs = field.value.match(re)) {
        if(regs[2] < 1 || regs[2] > 31) {
          errorMsg = "Please enter a correct date (invalid month): " + regs[1];
        } else if(regs[1] < 1 || regs[1] > 12) {
          errorMsg = "Please enter a correct date (invalid day): " + regs[2];
        } else if(regs[3] < minYear || regs[3] > maxYear) {
          errorMsg = "Please enter a correct date (invalid year: " + regs[3] + " - must be between " + minYear + " and " + maxYear;
        }
      } else {
        errorMsg = "Invalid date format: " + field.value;
      }
    } else if(!allowBlank) {
      errorMsg = "Empty date not allowed!";
    }
    
    if(errorMsg != "") {
      alert(errorMsg);
      field.focus();
      return false;
    }
    
    return true;
  }
 
function showTab(id)
{
	document.getElementById("tab" + m_currTab).style.display = "none";
	document.getElementById("tab" + id).style.display = "block";
	m_currTab = id;
}
 
function getQueryVariable(variable) 
{ 
	var query = window.location.search.substring(1); 
	var vars = query.split("&"); 
	for (var i=0;i<vars.length;i++) 
	{ 
		var pair = vars[i].split("="); 
		if (pair[0] == variable) 
		{ 
		return pair[1]; 
		} 
	} 
	//alert('Query Variable ' + variable + ' not found'); 
} 
 
function validateAge(field)
{
	var birthDate = field.value;
	var maxYear = (new Date()).getFullYear();	
 
	// regular expression to match required date format
    re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;	
	
    if(field.value != '') 
	{
      if(regs = field.value.match(re)) 
	  {	
		if ((parseInt(maxYear) - parseInt(regs[3])) < 18)
		{
			alert("You must be over 18 to order.");
			setCookie("pony_bd","1",1);
			return false;
		}
	  }
	}
	
	return true;
}
 

 
function sendOrder()
{
	registerQuery();
 
	var isOK = true;
 
	//Validate all required fields
	if (!validateFields()) isOK = false;
 
	//Validate dates
	if (!checkDate(document.getElementById("bdate"))) isOK = false;
	
	if ((document.getElementById("pbdate").value == "") && (isOK))
	{
		alert("Please enter your birthdate");
		document.getElementById("pbdate").focus();
		isOK = false;
	}
	
	if (!checkDate(document.getElementById("pbdate"))) isOK = false;
 
	//Validate that it is the guardian
	if ((!document.getElementById("parentAge").checked) && (isOK))
	{
		alert("Please confirm that you are the parent/guardian.");
		isOK = false;
	}
	
	//Validate parents age	
	if (!validateAge(document.getElementById("pbdate"))) isOK = false;
	
	//Agreed to terms?
	if ((!document.getElementById("validation").checked) && (isOK))
	{
		alert("You have to accept the membership terms.");
		isOK = false;
	}
 
	//var email = document.getElementById("acceptEmail").checked;
	//if (email) document.getElementById("ouse").value = "Y";
 
	//Send order
	if (isOK) 
	{
		if(!getCookie("pony_bd") && screeningResult < 17)
		{
			document.Form2.submit();
		}
		else
		{
			document.location = "/activate-your-account";
		}
	}
 
	//alert("commit");
}
 
function registerQuery()
{
	var query = getQueryVariable("c");
	if (query != "")
	{
			//document.getElementById("concept").value = query.substring(0,3);
	}
	
}

function validateFields(){
  		
	if (document.Form2.pgiven.value == "" || document.Form2.pgiven.value == "First Name")
	{
		alert("Please enter Your First Name ");
	
		document.Form2.pgiven.focus();
		return false;
	}
	
	if (document.Form2.pfamily.value == "" || document.Form2.pfamily.value == "Last Name")
	{
		alert("Please enter Your Last Name ");
	
		document.Form2.pfamily.focus();
		return false;
	}
	
	if (document.Form2.street.value == "" || document.Form2.street.value == "Street Address")
	{
		alert("Please enter a Street Address");
	
		document.Form2.street.focus();
		return false;
	}
	
	if (document.Form2.city.value == "" || document.Form2.city.value == "Street Address")
	{
		alert("Please enter a City");
	
		document.Form2.city.focus();
		return false;
	}
	
	if (document.Form2.zip.value == "" || document.Form2.zip.value == "Zip Code")
	{
		alert("Please enter a Zip Code");
	
		document.Form2.zip.focus();
		return false;
	}
	
	
	if (document.Form2.email.value != "" && document.Form2.email.value != "Email Address") { 
	 
	
		var emailFilter=/^.+@.+\..{2,3}$|^$/;
		if (!(emailFilter.test(document.Form2.email.value)))
		{
			alert("There seems to be something wrong with the email address");
			document.Form2.email.focus();
			return false;
		}
		var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/;
		if (document.Form2.email.value.match(illegalChars)) {
			alert("There seems to be something wrong with the email address");
			document.Form2.email.focus();
			return false;
		}
	}
	
	if (!(document.Form2.zip.value.length > 4 && document.Form2.zip.value.length < 6))
	{
	
		alert("Please enter a correct Zip Code. Do note that it should be only numeric and just 5 digits.");
		document.Form2.zip.focus();
		return false;
	}
	
	if (document.Form2.zip.value.length > 4 && document.Form2.zip.value.length < 6  )
	{
		var yrFilter= /^\d*$/ ;
		if (!(yrFilter.test(document.Form2.zip.value)))
		{
			alert("Please enter a correct Zip Code. Do note that it should be only numeric and just 5 digits.");
			document.Form2.zip.focus();
		return false;
		}
	}
	
	if(CheckAddress(document.Form2.pgiven.value,document.Form2.pfamily.value,document.Form2.street.value,document.Form2.city.value,document.Form2.state.value,document.Form2.zip.value))
	{
		return true;	
	}
	else
	{
		return false;
	}
} 



		
	function CheckAddress(f,l,a,c,s,z)
	{
		if(document.Form2.pfamily.value != "" && document.Form2.zip.value != "")
		{ 
			data = GetAlliantData(f,l,a,c,s,z);
			if(data)
			{		
				responseCode = data.getElementsByTagName("ResponseCode")[0].childNodes[0].nodeValue;
				_gaq.push(['_trackEvent', 'Alliant_Response_Code', responseCode]);
				
				screeningResult = data.getElementsByTagName("VALUE")[0].childNodes[0].nodeValue;
				_gaq.push(['_trackEvent', 'Alliant_Screening_Score', screeningResult]);
				document.Form2.ppscore.value = screeningResult;
				
				if(responseCode != "0")
				{
					
					switch (responseCode){
						case "0": 
							return true;
						case "1": 
							alert("The city does not seem to be correct. Are you sure you have entered it correctly?");
							document.Form2.city.focus();
							return false;
						case "2": 
							alert("The Street Name does not seem to be entered correctly. Are you sure its correct?");
							document.Form2.street.focus();
							return false;
						case "3": 
							alert("The House Number does not seem to exist on that street. Are you sure you entered it correctly?");
							document.Form2.street.focus();
							return false;
						case "4":
							alert("The apartment or suite number does not seem to exist in that building. Are you sure you entered it correctly?");
							document.Form2.street.focus();
							return false;
						case "5":
							alert("The address information you've entered matches more than one household, and we're not sure we got it right. Can you specify it further by for instance add apartment or suite number?");
							document.Form2.street.focus();
							return false;
						case "9":
							FixAddress(data);
							
							return true;
						default : 
							return true;
						}
				}
				else
				{
					return true;
				}
			}
			return false;
		}
		else
		{
			return false;
		}
	}
	
	function GetAlliantData(fn,ln,al,ci,st,zc)
	{
		var outputData = jQuery.ajax({
			type: "GET",
			url: "http://www.pony.us/wrapper.php",
			data: { f: fn, l: ln, a: al, c: ci, s: st, z: zc },
			async: false,
			success: function(data){
			},
			error: function(data){
				return false;
			}
		}).responseText;
		
		try //Internet Explorer
		{
		  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		  xmlDoc.async="false";
		  xmlDoc.loadXML(outputData);
		  return xmlDoc;
		}
		catch(e)
		{
		  parser=new DOMParser();
		  xmlDoc=parser.parseFromString(outputData,"text/xml");
		  return xmlDoc;
		}
	}
	
	function FixAddress(data)
	{
		document.Form2.street.value = data.getElementsByTagName("AddressLine")[0].childNodes[0].nodeValue;
		document.Form2.city.value = data.getElementsByTagName("City")[0].childNodes[0].nodeValue;
		document.Form2.state.value = data.getElementsByTagName("State")[0].childNodes[0].nodeValue.substring(0,2);
		document.Form2.zip.value = data.getElementsByTagName("ZipCode")[0].childNodes[0].nodeValue.substring(0,5);
	}


