// Instantiate the API
var objLocation = new LocationAPI();

function LocationAPI()
{	
	this.strLocation	= '';
	this.strCity		= '';
	this.strState		= '';
	
	this.search = function(strSearchValue, strResultsDiv, strTextField, strHiddenField)
	{
		intResponseCounter++;
		
		var arrLocationData = new Object();
		
		if (intResponseCounter == intRequestCounter)
		{
			jQuery.get('./locationSearch', {'search':strSearchValue}, function(objResponse)
			{
				if (intResponseCounter == intRequestCounter)
				{
					if (strSearchValue!='')
					{
						jQuery(strResultsDiv).empty();
						for(i=0;i<objResponse.length;i++)
						{

							var intId		= objResponse[i].intId;
							var strSuburb	= objResponse[i].strCity;
							var strState	= objResponse[i].strState;
							
							if (i==0)
							{
								jQuery(strHiddenField).val(strSuburb+', '+strState);
							}							
							
							var objLink = jQuery('<a class="suburb" id="suburb_'+intId+'" />');
							objLink.html('<b>'+strSuburb+'</b>, '+strState);
							
							arrLocationData[intId] = objResponse[i];
							
							objLink.click(function()
							{
								var arrTokens = this.id.split('_');
								var intId = arrTokens[1];
								
								var intId		= arrLocationData[intId].intId;
								var strSuburb	= arrLocationData[intId].strCity;
								var strState	= arrLocationData[intId].strState;								
					
								jQuery(strTextField).val(strSuburb+', '+strState);								
								jQuery(strHiddenField).val(strSuburb+', '+strState);								
								
								jQuery(strResultsDiv).hide();
							});
							
							jQuery(strResultsDiv).append(objLink);
						}
						jQuery(strResultsDiv).show();
					}
					else
					{
						jQuery(strResultsDiv).html('');
						jQuery(strResultsDiv).hide();
					}	
				}
			}, 'json');
		}
	}	
	
	this.getLocation = function()
	{
		return this.strLocation;
	}
	
	this.setLocation = function(strNewLocation)
	{
		arrLocation = strNewLocation.replace(', ', ',').split(',');
		strNewCity = arrLocation[0];
		strNewState = arrLocation[1];
		jQuery.get('./setLocation', {'suburb':strNewCity, 'state':strNewState}, function(objResponse)
		{
			document.location = './';
		}, 'json');
	}
	
	this.getCity = function(callback)
	{
		jQuery.get('./getCity', {}, function(objResponse)
		{
			callback(objResponse.strCity);
		}, 'json');
	}	
	
	this.getState = function(callback)
	{
		jQuery.get('./getCity', {}, function(objResponse)
		{
			callback(objResponse.strState);
		}, 'json');
	}	
}
