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);
  
  // Overseas Territories
  pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);

  // Load up the string to check
  var postCode = toCheck;

  // Assume we're not going to find a valid postcode
  var valid = 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
      valid = 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 (valid) {return postCode;} else return false;
}

$(document).ready(function() {						   

$(".help-popup a").hover(function() {
$(this).next("em").stop(true, true).animate({opacity: "show", top: "-40"}, "slow");
}, function() {
$(this).next("em").animate({opacity: "hide", top: "-60"}, "fast");
});

	$('#req_form').validate({		
		rules: {
			first_name: "required",
			street: "required",
			city: "required",
			'00N200000015enZ': "required",
			'00N200000015ene': "required",
			phone: "required"
		},
		messages: {
			first_name: "Please enter your full name",
			street: "Please select your address",
			city: "Please enter your town / city",
			phone: "Please enter your phone number"
		},
		errorClass: "req_error",
		errorElement: "p",
		errorPlacement: function(error, element) {
			var myError = error.insertBefore(element.parent('div'));
			$(myError).hide().slideDown('slow');
		}

	});

$('#req_form input[type=text]').toggleVal();

});

var app_type_flag = false;
var postcode_flag = false;

$('#submit').click(function(){
var comment = $("#00N200000015eoI").val();
	if (comment == 'e.g. Fault Description / Model Number') {		
		$("#00N200000015eoI").val('');	
	}	
});

$('#00N200000015eoI').click(function(){
var comment = $("#00N200000015eoI").val();
	if (comment == 'e.g. Fault Description / Model Number') {			
		$("#00N200000015eoI").val('');	
	}	
});

$('#nextButton').click(function(){
	
	var postcode_array = new Array();
	var app_type = $("select#00N200000015enj").val();

	var postcode = $("input#postcode_anywhere").val().toUpperCase(); 
	var postcode_match = false;

	//Check Application Type Dropdown for value
	if (app_type == null || app_type == '') {
		if (app_type_flag == false) {	
			$('p#application_error').addClass('req_error');
			$('p#application_error').hide().slideDown('slow', function() { app_type_flag = true; });
			$('select#00N200000015enj').addClass('req_error');		
		}
	} else {		
		$('p#application_error').hide();
	}
	
	//Check Postcode Input for value
	if (postcode == null || postcode == '') {			
		if (postcode_flag == false) {	
			$('p#postcode_anywhere_error').addClass('req_error');		
			$('p#postcode_anywhere_error').hide().slideDown('slow', function() { postcode_flag = true; });		
			$('input#postcode_anywhere').addClass('req_error');	
		}	
	} else {	
		$('p#postcode_anywhere_error').hide();
	}
	
	if (app_type == 'Cookers Gas' || app_type == 'Gas Range Cooker' || app_type == 'Hob Gas' || app_type == 'Conventional Boiler' || app_type == 'Combination Boiler' || app_type == 'Combination Storage Boilers' || app_type == 'System Boilers' || app_type == 'Back Boilers' || app_type == 'Condensing Boilers') {
	  postcode_array = ["AL", "EN", "IG", "LU", "MK", "RM", "SG", "SS", "WD", "PE27", "PE28", "PE29", "HP1", "HP2", "HP3", "HP4", "HP20", "HP21", "HP22", "CM5", "CM6", "CM11", "CM12", "CM13", "CM16", "CM17", "CM18", "CM19", "CM20", "CM21", "CM22", "CM23", "CM24", "CB1", "CB2", "CB3", "CB4", "CB5", "CB8", "CB9","CB10", "CB11", "CB21", "CB22", "CB23", "CB24", "CB25"];
	} else {
	  postcode_array = ["AL", "EN", "IG", "LU", "MK", "RM", "SG", "SS", "WD", "PE27", "PE28", "PE29", "HP1", "HP2", "HP3", "HP4", "HP20", "HP21", "HP22", "CM5", "CM6", "CM11", "CM12", "CM13", "CM16", "CM17", "CM18", "CM19", "CM20", "CM21", "CM22", "CM23", "CM24", "CB1", "CB2", "CB3", "CB4", "CB5", "CB8", "CB9","CB10", "CB11", "CB21", "CB22", "CB23", "CB24", "CB25"];
	}

	var x;
	for (x in postcode_array) { 
	  var len = postcode_array[x].length;  
	  var postcode_check = postcode.substring(0, len);  
	  if (postcode_check == postcode_array[x]) { 
	    postcode_match = true;	
	  }
	}
	
	if (checkPostCode(postcode)) {
		if (postcode_match == true && app_type != '') {	
	  		pcaByPostcodeBegin();
		} else if(app_type != '' && postcode != '') {
	  		$('#xigen_header').addClass('xigen_outofservice');	
	  		$('#xigen_step1').hide();
	  		$('#xigen_step3').hide().slideDown('slow');
		}
	} else {		
		if (postcode != '') {		
			$('p#postcode_anywhere_valid').addClass('req_error');		
			$('p#postcode_anywhere_valid').hide().slideDown('slow', function() { postcode_flag = true; });		
			$('input#postcode_anywhere').addClass('req_error');		
		}
	}

});

	$('#backButton').click(function(){
		$('#xigen_step2').hide();
		$('#postcode_anywhere_valid').hide();
		$('#xigen_step1').hide().slideDown('slow');								
	});

		var account_code='BEDFO11130';
		var license_code='KW57-TB64-BF15-ZH48';
		var machine_id='';
		
		function pcaByPostcodeBegin()
		   {
			  var postcode = document.forms[0]["postcode_anywhere"].value;
		      var scriptTag = document.getElementById("pcaScriptTag");
		      var headTag = document.getElementsByTagName("head").item(0);
		      var strUrl = "";
		      
		      //document.getElementById("divLoading").style.display = '';
		      
		      //Build the url
		      strUrl = "http://services.postcodeanywhere.co.uk/inline.aspx?";
		      strUrl += "&action=lookup";
		      strUrl += "&type=by_postcode";
		      strUrl += "&postcode=" + escape(postcode);
		      strUrl += "&account_code=" + escape(account_code);
		      strUrl += "&license_code=" + escape(license_code);
		      strUrl += "&machine_id=" + escape(machine_id);
		      strUrl += "&callback=pcaByPostcodeEnd";
		      
		      //Make the request
		      if (scriptTag)
		         {
		            //The following 2 lines perform the same function and should be interchangeable
		            headTag.removeChild(scriptTag);
		            //scriptTag.parentNode.removeChild(scriptTag);
		         }
		      scriptTag = document.createElement("script");
		      scriptTag.src = strUrl
		      scriptTag.type = "text/javascript";
		      scriptTag.id = "pcaScriptTag";
		      headTag.appendChild(scriptTag);  
		      
		   }

		function pcaByPostcodeEnd()
		   {
			  //document.getElementById("divLoading").style.display = 'none';
			  
		      //Test for an error
			  if (pcaIsError)
		         {
		            //Show the error message
		            document.getElementById("selectaddress").style.display = 'none';
		            //document.getElementById("btnFetch").style.display = 'none';				
					//alert(pcaErrorMessage);
					
		         }
		      else
		         {

					$('#xigen_step1').hide();
	  	  			$('#xigen_step2').hide().slideDown('slow');
					
					//Check if there were any items found					
					if (pcaRecordCount==0)
		               {
		                  document.getElementById("selectaddress").style.display = 'none';
						  //document.getElementById("btnFetch").style.display = 'none';
		                  //alert("Sorry, no matching items found. Please try another postcode.");
		               	  
						  var postcode_sent = document.getElementById("postcode_anywhere").value;
						  var split_post = postcode_sent.split(" ");
						  if (!split_post[1]) {
							split_post = postcode_sent.substr(4, 7); 
							document.forms[0]["00N200000015enZ"].value = postcode_sent.substr(0, (postcode_sent.length - 3)).toUpperCase();						
						    document.forms[0]["00N200000015ene"].value = postcode_sent.substr((postcode_sent.length - 3), (postcode_sent.length)).toUpperCase();
						  } else {
							document.forms[0]["00N200000015enZ"].value = split_post[0].toUpperCase();						  	   					    document.forms[0]["00N200000015ene"].value = split_post[1].toUpperCase();
						  }
						  
						  document.getElementById("street").style.display = 'inline';
						  document.getElementById("xigen_address_more").style.display = 'inline';
					   }
		            else
		               {
						  document.forms[0]["selectaddress"].style.display = '';
						  //document.forms[0]["btnFetch"].style.display = '';
						  
						  for (i=document.forms[0]["selectaddress"].options.length-1; i>=0; i--){
							  document.forms[0]["selectaddress"].options[i] = null;
							}
						  
						  document.forms[0]["selectaddress"].options[document.forms[0]["selectaddress"].length] = new Option('Please Select:', '');
						  
						  for (i=0; i<pca_id.length; i++){
		                    document.forms[0]["selectaddress"].options[document.forms[0]["selectaddress"].length] = new Option(pca_description[i], pca_id[i]);
		                  }
		               }
		         }
		   }
		
		function pcaFetchBegin()
		   {
			  var address_id = document.forms[0]["selectaddress"].value;
		      var scriptTag = document.getElementById("pcaScriptTag");
		      var headTag = document.getElementsByTagName("head").item(0);
		      var strUrl = "";

		      //Build the url
		      strUrl = "http://services.postcodeanywhere.co.uk/inline.aspx?";
		      strUrl += "&action=fetch";
		      strUrl += "&id=" + escape(address_id);
		      strUrl += "&account_code=" + escape(account_code);
		      strUrl += "&license_code=" + escape(license_code);
		      strUrl += "&machine_id=" + escape(machine_id);
		      strUrl += "&callback=pcaFetchEnd";

		      //Make the request
		      if (scriptTag)
		         {
		            //The following 2 lines perform the same function and should be interchangeable
		            headTag.removeChild(scriptTag);
		            //scriptTag.parentNode.removeChild(scriptTag);
		         }
		      scriptTag = document.createElement("script");
		      scriptTag.src = strUrl
		      scriptTag.type = "text/javascript";
		      scriptTag.id = "pcaScriptTag";
		      headTag.appendChild(scriptTag);
		      
		      //document.forms[0]["selectaddress"].style.display = 'none';
		      //document.forms[0]["btnFetch"].style.display = 'none';
		   }

		function pcaFetchEnd()
		   {
		      //Test for an error
		      if (pcaIsError)
		         {
		            //Show the error message
		            alert(pcaErrorMessage);
		         }
		      else
		         {
		            //Check if there were any items found
		            if (pcaRecordCount==0)
		               {
		                  alert("Sorry, no matching items found");
						  	  
						  
		               }
		            else
		               {
						  //document.forms[0]["company"].value = '' + pca_organisation_name[0];
						  document.forms[0]["street"].value = '' + pca_line1[0];
						  //document.forms[0]["line2"].value = '' + pca_line2[0];
						  //document.forms[0]["line3"].value = '' + pca_line3[0];
						  //document.forms[0]["line4"].value = '' + pca_line4[0];
						  //document.forms[0]["line5"].value = '' + pca_line5[0];
						  document.forms[0]["city"].value = '' + pca_post_town[0];
						  document.forms[0]["state"].value = '' + pca_county[0];	  
						  var split_post = pca_postcode[0].split(" ");
						  document.forms[0]["00N200000015enZ"].value = '' + split_post[0];						  
						  document.forms[0]["00N200000015ene"].value = '' + split_post[1];
		               }
		         }
		   }
