var group_element ="";
var path = "";
function get_postcode_data()
{
	//$( '#divLoading'  ).show('slow'); 

	var postcode = $('#postcode_search').val() 
	url = path+"aj/aj_getpostcode.php?postcode=" + postcode ;
	//alert(url);
    $.getJSON( url, handlePostcodeAjaxReply );
    // if the call does not return a valid JSON string then this calls an error Handling function
    $('body').ajaxError( handleError );
}

function handlePostcodeAjaxReply( data , textStatus)
{
	//$( '#divLoading'  ).hide('fast'); 
	$('#selectaddress').children().remove().end()
	var array_length = data.select_options.length;
	if(array_length != 1)
	{
		$('#selectaddress').get(0).add(new Option('Please Select Your Address',''),document.all ? 0 : null);	
		for (i=0; i<array_length; i++)
		{
	        $('#selectaddress').get(0).add(new Option(data.select_options[i].description,data.select_options[i].id),document.all ? 0 : null);
		}
		$( '#addressp'  ).text("");
		$( '#addressdiv'  ).show('slow'); 
		$( '#selectaddress'  ).show('slow'); 
	}
	else
	{	
		$( '#selectaddress'  ).hide(); 
		$( '#addressp'  ).text("This is not a valid postcode. Please re-enter your postcode.");
		$( '#addressdiv'  ).show('slow'); 
	}
}

function get_postcode_address(group_element_id)
{
	group_element = group_element_id;

	var address_id = $('#selectaddress').val();
	url = path+"aj/aj_getpostcode.php?address_id=" + address_id ;

    $.getJSON( url, handleAddressAjaxReply );
    
    // if the call does not return a valid JSON string then this calls an error Handling function
    $('body').ajaxError( handleError );
}

function handleAddressAjaxReply( data , textStatus)
{

	var address = data.address[0];
	$("#"+ group_element +"company").val(address['company']);
	$("#"+ group_element +"line1").val(address['line1']);
	$("#"+ group_element +"line2").val(address['line2']);
	$("#"+ group_element +"line3").val(address['line3']);
	$("#"+ group_element +"town").val(address['post_town']);
	$("#"+ group_element +"county").val(address['county']);
	$("#"+ group_element +"postcode").val(address['postcode']);
	
//	$("#"+ group_element +"input").val(address['mailsort']);
//	$("#"+ group_element +"input").val(address['barcode']);
//	$("#"+ group_element +"input").val(address['is_residential']);
//	$("#"+ group_element +"input").val(address['is_small_organisation']);
//	$("#"+ group_element +"input").val(address['is_large_organisation']);
}

function handleError(){
	$( '#selectaddress'  ).hide(); 
	$( '#addressp'  ).text("This is not a valid postcode. Please re-enter your postcode.");
	$( '#addressdiv'  ).show('slow'); 
}


