﻿
//////////////////////////////////////////////////////////////////////

function AddressFinderAjax_Initialise(obj)
{
    // trap the keypress event so that we can prevent the enter button from submitting the form
	jQuery('#' + obj.txtHouseID).unbind('keypress').bind('keypress', { o: obj }, AddressFinderAjax_KeyPress);
	jQuery('#' + obj.txtPostcodeID).unbind('keypress').bind('keypress', { o: obj }, AddressFinderAjax_KeyPress);

    // unbind any existing click events on the "find" button, and then re-bind to our own click listener
	jQuery('#' + obj.btnFindID).unbind('click').bind('click', { o: obj }, AddressFinderAjax_FindClick);
}

// Event Listeners ///////////////////////////////////////////////////

function AddressFinderAjax_KeyPress(evt)
{
	var obj = evt.data.o;

    // if the user hits enter in the textbox then we'll find the address rather than submitting the form
    if (evt.keyCode == 13)
    {
        AddressFinderAjax_FindAddress(obj);

	    // cancel form submit
	    evt.preventDefault();
    }
}

function AddressFinderAjax_FindClick(evt)
{
	var obj = evt.data.o;

	AddressFinderAjax_FindAddress(obj);

	// cancel form submit
	evt.preventDefault();
}

// Helpers ///////////////////////////////////////////////////////////

function AddressFinderAjax_FindAddress(obj)
{
	var house = jQuery('#' + obj.txtHouseID).val();
	var postcode = jQuery('#' + obj.txtPostcodeID).val();
	var rx = /^[A-Za-z]{1,2}\d/;

	if ((postcode != '') && rx.test(postcode))
	{
		jQuery('#' + obj.errorDivID).css('display', 'none').html('');

		jQuery.ajax(
		{
			url: obj.webServiceUrl,
			type: 'POST',
			contentType: 'application/json; charset=utf-8',
			dataType: 'json',
			data: '{house:\'' + house.replace(/'/g, '\\\'') + '\',postcode:\'' + postcode.replace(/'/g, '\\\'') + '\'}',
			success: function(msg, status)
			{
				if (msg.d == undefined)
					jQuery('#' + obj.errorDivID).html('Unable to recognise postcode ' + AddressFinderAjax_HtmlEncode(postcode)).slideDown('fast');
				else
				    obj.callBackFunction(msg.d);
			}
		});
	}
	else
	{
		jQuery('#' + obj.errorDivID).html('Please enter a valid UK postcode').slideDown('fast');
	}
}

//////////////////////////////////////////////////////////////////////

function AddressFinderAjax_HtmlEncode(str)
{
	var div = document.createElement('div');
	var txt = document.createTextNode(str);
	div.appendChild(txt);
	return div.innerHTML;
}

//////////////////////////////////////////////////////////////////////
