var locationPrefix = '';
var locationInput = '';

function setLocationPrefix( prefix ) {
	locationPrefix = prefix;
}

function setLocationInput( inputId ) {
	locationInput = inputId;
}

function initLocationSearch() {

	//auto suggest
	// An XHR DataSource   
	var myServer = "/xmlservice.php";
	var mySchema = ["ResultSet.Result", "display", "latitude", "longitude", "resultSize" ];
	var locationDataSource = new YAHOO.widget.DS_XHR(myServer, mySchema); 
	locationDataSource.scriptQueryAppend  = "service=locationSearch&limit=50";

	var autoCompleteLocation = new YAHOO.widget.AutoComplete( locationInput,"locationSearchSuggest", locationDataSource, { forceSelection : false, useShadow : true, allowBrowserAutocomplete : false, animHoriz : true } );
	autoCompleteLocation.maxResultsDisplayed = 50;

	autoCompleteLocation.formatResult = function(aResultItem, sQuery) {
		var name = aResultItem[0];
		var latitude = aResultItem[1];
		var longitude = aResultItem[2];
		var results = aResultItem[3];
		
		if( results ) {
			this.setHeader('Displaying: '+results+' results');
			this.setFooter('');
		}

		var aMarkup = name;
		return aMarkup;
	};
	
	autoCompleteLocation.doBeforeExpandContainer = function(oTextbox, oContainer, sQuery, aResults) {
		var pos = YAHOO.util.Dom.getXY(oTextbox);
		pos[1] += YAHOO.util.Dom.get(oTextbox).offsetHeight;
		pos[0] -= parseInt( YAHOO.util.Dom.getStyle(oTextbox, 'width') );
		pos[0] += YAHOO.util.Dom.get(oTextbox).offsetWidth;
		YAHOO.util.Dom.setXY(oContainer,pos);
		return true;
	};

	autoCompleteLocation.itemSelectEvent.subscribe( function( oSelf , elItem , aResultItem )  {
			document.getElementById( locationPrefix + '_latitude').value = elItem[2][1];
			document.getElementById( locationPrefix + '_longitude').value = elItem[2][2];
		}
		, autoCompleteLocation );

}

YAHOO.util.Event.addListener(window, "load", initLocationSearch);