
function findValue(li) {
	
	if( li == null ) return alert("No match!");
 
	// if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) var sValue = li.extra[0];
 
	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;
 
	//alert("The value you selected was: " + sValue);
}
 
function selectItem(li) {
	findValue(li);
}
 
function formatItem(row) {
	return row[0];// + " (id: " + row[1] + ")";
}
 
function lookupAjax(){
	var oSuggest = $("#CityAjax")[0].autocompleter;
 
	oSuggest.findValue();
 
	return false;
}
 
function lookupLocal(){
	var oSuggest = $("#CityLocal")[0].autocompleter;
 
	oSuggest.findValue();
 
	return false;
}
 
$(document).ready(function() {
	
	$("#CityAjax").autocomplete(
		"/backend/streets",
		{
			delay:400,
			minChars:15,
			matchSubset:0,
			matchContains:0,
			cacheLength:10,
			onItemSelect:selectItem,
			onFindValue:findValue,
			formatItem:formatItem,
			autoFill:true
		}
	);
	
	setevents();
	
	
	if( $('#autoload[code="sections"]') ){
		section_id = $('#autoload[code="sections"]').attr('section_id');
		area_id = $('#autoload[code="sections"]').attr('area_id');
		$.get( '/personal/getsections?area_id=' + area_id + '&section_id=' + section_id, function(data){
			setSectionsTo(data);
		});
	}
	
	if( $('#autoload[code="streets"]') ){
		section_id = $('#autoload[code="streets"]').attr('section_id');
		street_id = $('#autoload[code="streets"]').attr('street_id');
		$.get( '/personal/getstreets?street_id=' + street_id + '&section_id=' + section_id, function(data){
			setStreetsTo(data);
		});
	}


});


	
function setevents(){
	
	$('#fAreas select').unbind('change');
	$('#fAreas select').bind('change', function(){
		$.get( '/personal/getsections?area_id=' + $(this).val(), function(data){
			setSectionsTo(data);
		});
	});
	
	$('#fSections select').unbind('change');
	$('#fSections select').bind('change', function(){
		$.get( '/personal/getstreets?section_id=' + $(this).val(), function(data){
			setStreetsTo(data);
		});
	});
	
	
}

function setSectionsTo(data){
	if( data > '' ){
		$('#fSections').fadeIn();
		$('#fSections div').html(data);
	}else{
		$('#fSections').fadeOut();
		$('#fSections div').html('');
	}
	setStreetsTo('');
	setevents();
}

function setStreetsTo(data){
	if( data > '' ){
		$('#fStreets').fadeIn();
		$('#fStreets div').html(data);
		$('#othform').fadeIn();
	}else{
		$('#fStreets').fadeOut();
		$('#fStreets div').html('');
		$('#othform').fadeOut();
	}
}
