/*
 *  jQuery support routines.
 * 
 *  Uses two JSON remote AJAX requests to get zip, county and lat/long info
 *  Contains callbacks to set the data in form fields
 * 
 *  Blaine Horrocks, 2008
 *  $Rev: 2 $
 *  $Id: weblead.js 2 2008-11-27 02:40:10Z bhorrock $
 * 
 */

/* ***** ENTRY POINTS **** */

function updateCounty () 
{
	if ($("#zip").val().length >= 5)
	{
		var zip5 = $("#zip").val().substring(0,5);
		var plus4 = $("#zip").val();
		$.getJSON('countyLookup.php', {zip: zip5}, postCountyData);
		$.getJSON('districtLookup.php', {zip: plus4, output: "json" }, postDistrictData);
	};
};


function updateZip () 
{
	if ($("#street").val().length >= 5 )
	{
		var streetval = $("#street").val();
		var cityval = $("#city").val();
		var stateval = $("#state").val();

		$.getJSON('zipLookup.php', {street: streetval, state: stateval, city: cityval}, postZipData);
	};
};

/* **** SUPPORT **** */

function postCountyData (response) 
{
	try 
	{
		if (response.zip != ""  && response.county != "")
		{
			$("#county").val(response.county.replace(/[\s]+/, ' '));
		}
	} 
	catch(e) { alert("Unable to resolve ZIP Code. " + e); };
};

function postZipData (response) 
{
	try 
	{
		if (response.zip != "")
		{
			$("#zip").val(response.zip);
			updateCounty();
		}
		if (response.city != "")
		{
			$("#city").val(response.city);
		}
		if (response.lat != "")
		{
			$("#00N40000001r1UK").val(response.lat);
		}
		if (response.lon != "")
		{
			$("#00N40000001r1UU").val(response.lon);
		}
	} 
	catch(e) { alert("Unable to determine ZIP Code. " + e); };
};

function postDistrictData (response) 
{
	try 
	{
		if (response.length > 0)
		{
			
			if (response[0].us_congress_seat_id != "")
			{
				var senate_seat = response[0].state_senate_seat_id; 
				var house_seat = response[0].state_house_seat_id;
				
				$("#00N40000001rnEf").val(senate_seat);
				$("#00N40000001rnEp").val(house_seat);
				$("#00N40000001rGpX").val(response[0].us_congress_seat_id);
			}			
		}

	} 
	catch(e) { alert("Unable to determine ZIP Code. " + e); };
};

/* **** jQuery extras **** */

/**
 * matches US phone number format 
 * 
 * where the area code may not start with 1 and the prefix may not start with 1 
 * allows '-' or ' ' as a separator and allows parens around area code 
 * some people may want to put a '1' in front of their number 
 * 
 * 1(212)-999-2345
 * or
 * 212 999 2344
 * or
 * 212-999-0983
 * 
 * but not
 * 111-123-5434
 * and not
 * 212 123 4567
 */
jQuery.validator.addMethod("phone", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
	return this.optional(element) || phone_number.length > 9 &&
		phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
