/**
 * AutoComplete Field
 *
 * some of this source code is provided by http://www.fromvega.com
 *
 *
 */

// global variables
var acListTotal   =  0;
var acListCurrent = -1;
var acDelay		  = 500;
var acURL		  = null;
var acSearchId	  = null;
var acResultsId	  = null;
var acSearchField = null;
var acResultsDiv  = null;
var acIsCity	  = false;
var acResults	  = null;
var countryName	  = null;
var cityName 	  = null;
var countrySearchField = null;
var citySearchField = null;
var show_region_on_auto_complete = false;	// Change this if you want to show region on auto complete
var countryURL = 'index.php?page=ajax&action=getcountries&country=';
var cityURL = "index.php?page=ajax&action=getcities&city=";


function setAutoComplete(field_id, results_id,selected_field, get_url,is_city){

	// initialize vars
	acSearchId  = "#" + field_id;
	acResultsId = "#" + results_id;
	acSelectedId = "#" + selected_field;
	acURL 		= get_url;
	acIsCity	= is_city;
		
	


	// create the results div
	$("body").append('<div id="' + results_id + '"></div>');

	// register mostly used vars
	acSearchField	= $(acSearchId);
	acSelectedField = $(acSelectedId)
	acResultsDiv	= $(acResultsId);
	countryName 	= $("#country_name");
	cityName		 = $("#city_name");
	countrySearchField = $("#searchCountry");
	citySearchField = $("#searchCity");
	

	// reposition div
	repositionResultsDiv();
	
	// on blur listener
	acSearchField.blur(function(){ setTimeout("clearAutoComplete()", 200) });

	


	// on key up listener
	$("#loc_changer").keyup(function (e) {


		// get keyCode (window.event is for IE)
		var keyCode = e.keyCode || window.event.keyCode;
		
		//Save values
		var lastVal = acSearchField.val();
		var searchField = acSearchField;
		var url = acURL;
		var isCity = acIsCity;
		
		//First clear country and city saved names
		if (keyCode !=13)
			clearFields();
		

		// check an treat up and down arrows
		if(updownArrow(keyCode)){
			return;
		}

		// check for an ENTER, ESC or TAB
		if(keyCode == 13 || keyCode == 27 || keyCode == 9)
		{
			
			//hide options
			clearAutoComplete();
			
			//look for a matching country
			setTimeout(function () 
			{
				if ( (!isCity && countryName.val() == '') || (isCity && cityName.val() == '')) //if a country/city was already selected, dont search
					matchOne(searchField, url, isCity);
			}, acDelay + 200);
			
			return;
		}

		// if is text, call with delay
		setTimeout(function () {autoComplete(lastVal)}, acDelay);
		
	});
	
	
	//Validate submittion - only submit if both country and city have been selected
	$("#loc_changer").submit(function() {
		if (countryName.val() == '' || cityName.val() == '')
      		return false;
      	
      	return true;
    });


}

function clearFields()
{
	if (!acIsCity) 
	{
		countryName.val('');
		$("#country_code").val('');
		$("#searchCity").val('');
	}
	cityName.val('');
}

function setStatus(stat)
{
	status_line = $("#loc_search_status");
	status_line = status_line.html(stat);
}

function matchOne(searchField, url, isCity)
{
	var part = searchField.val();
	//Search for a matching country
	
	
	setStatus('Searching "' + part + '"...');
	
	if (isCity)
	{
		var full_url = url + part + '&country=' + $('#country_code').val();
	}
	else
		var full_url = url + part;
		
	var results = null;
	var result = ''; //default
	var num_results = 0;
	
	//hide options
	clearAutoComplete();
	
	$.getJSON(full_url, function(results)
	{
		for (i in results)
		{
			num_results++;
			if (isCity)
			{
				result = results[i].city_name;
				if (results[i].city_district.length && show_region_on_auto_complete)	result += ', ' + results[i].city_district;
			}
			else
			{
				result = results[i].country_name;
				if (results[i].country_region.length && show_region_on_auto_complete)	result += ', ' + results[i].country_region;
			}
			
			//only get first result
			break;
			
			
		}
		
		if (num_results > 0)
		{
			//save result
			if (!isCity)
				setCountry(results[i].country_code, results[i].country_name) //set both code and name
			else
				setCity(results[i].city_name); //its a city, only save its name
			
			//enable city search	
			disableCitySearch(false);	
				
			//show result
			searchField.val(result);
			setStatus('');
			
			//Move to the city field
			if (!isCity) citySearchField.focus();
		}
		else
		{
			clearFields();
			setStatus('No Matches for "' + part + '"')
			if (!isCity) disableCitySearch(true);
		}
		
		//hide options
		clearAutoComplete();
		
		
	});	

		
}

function setCountry(countryCode, countryName)
{
	$('#country_name').val(countryName);
	$('#country_code').val(countryCode);
	
	//enable city search	
	disableCitySearch(false);	
}

function setCity(cityName)
{
	$('#city_name').val(cityName);
}

function disableCitySearch(disable)
{
	$('#searchCity').attr("disabled", disable);
}

// treat the auto-complete action (delayed function)
function autoComplete(lastValue)
{

	// get the field value
	var part = acSearchField.val();

	// if it's empty clear the resuts box and return
	if(part == ''){
		clearAutoComplete();
		return;
	}

	// if it's equal the value from the time of the call, allow
	if(lastValue != part){
		return;
	}

	acListTotal = 0;
	
	
	if (acIsCity)
	{
		var country_code = $('#country_code').val();
		url = acURL + part + '&country=' + country_code;
	}
	else
	{
		url = acURL + part;
	}
	
	// get remote data as JSON
	$.getJSON(url, function(json){
		acResults = json;
		
		// get the total of results
		
		for (i in json)
			acListTotal++;
			
		var ansLength = acListTotal;
		
		// if there are results populate the results div
		if(ansLength){

			var newData = '';

			for (id in acResults)
			{
				if (acIsCity)
				{
					var city_name = acResults[id].city_name;
					var city_district = acResults[id].city_district;
					newData += '<div class="unselected" id="' + city_name + '">' + city_name;
					if (city_district.length && show_region_on_auto_complete)	newData += ', ' + city_district;
					newData += '</div>';	
				}
				else
				{
					var country_code = acResults[id].country_code;
					var country_name = acResults[id].country_name;
					var country_region = acResults[id].country_region;
					newData += '<div class="unselected" id="' + country_code + '">' + country_name;
					if (country_region.length && show_region_on_auto_complete)	newData += ', ' + country_region;
					newData += '</div>';
				}

			}

			newData += '<span>More...</span>';
			// update the results div
			acResultsDiv.html(newData);
			acResultsDiv.css("display","block");
			
			// for all divs in results
			var divs = $(acResultsId + " > div");
		
			// on mouse over clean previous selected and set a new one
			divs.mouseover( function() {
				divs.each(function(){ this.className = "unselected"; });
				this.className = "selected";
				
			})
		
			// on click copy the result text to the search field and hide
			divs.click( function() {
				acSearchField.val(this.childNodes[0].nodeValue);
				clearAutoComplete();
				acSelectedField.val(this.id);
				
				if (!acIsCity) //Save country name and code
				{
					setCountry(acResults[this.id].country_code, acResults[this.id].country_name);
					citySearchField.focus();
				}
			});

		} else {
			clearAutoComplete();
		}
	});
}



// clear auto complete box
function clearAutoComplete()
{
	acResultsDiv.html('');
	acResultsDiv.css("display","none");
}

// reposition the results div accordingly to the search field
function repositionResultsDiv()
{
	// get the field position
	var sf_pos    = acSearchField.offset();
	var sf_top    = sf_pos.top;
	var sf_left   = sf_pos.left;

	// get the field size
	var sf_height = acSearchField.height();
	var sf_width  = acSearchField.width();

	// apply the css styles - optimized for Firefox
	acResultsDiv.css("position","absolute");
	acResultsDiv.css("left", sf_left - 2);
	acResultsDiv.css("top", sf_top + sf_height + 5);
	acResultsDiv.css("width", sf_width - 2);
}


// treat up and down key strokes defining the next selected element
function updownArrow(keyCode) {
	if(keyCode == 40 || keyCode == 38){

		if(keyCode == 38){ // keyUp
			if(acListCurrent == 0 || acListCurrent == -1){
				acListCurrent = acListTotal-1;
			}else{
				acListCurrent--;
			}
		} else { // keyDown
			if(acListCurrent == acListTotal-1){
				acListCurrent = 0;
			}else {
				acListCurrent++;
			}
		}

		// loop through each result div applying the correct style
		acResultsDiv.children().each(function(i){
			if(i == acListCurrent){
				acSearchField.val(this.childNodes[0].nodeValue);
				this.className = "selected";
				acSelectedField.val(this.id);
				if (!acIsCity) //Save country name and code
				{
					setCountry(acResults[this.id].country_code, acResults[this.id].country_name)
				}
			} else {
				this.className = "unselected";
			}
		});

		return true;
	} else {
		// reset
		acListCurrent = -1;
		return false;
	}
}

//Setup

$(document).ready(function(){
    var change_btn = $("#change_btn");
    var location_change_div = $("#location_change");
    change_btn.click(function () 
    {
    	btn_pos = change_btn.offset();
    	location_change_div_left = btn_pos.left + 5;
    	location_change_div_top = btn_pos.top + 15;
    	
    	location_change_div.css("position","absolute");
    	location_change_div.css("top",location_change_div_top);
    	location_change_div.css("left",location_change_div_left);
    	
     	location_change_div.slideToggle("slow");
    }
    );

    $("#searchCountry").focus(function()
		{
	    setAutoComplete("searchCountry", "results","country_code", countryURL);
		}
	)
		
	$("#searchCity").focus(function()
		{
	    setAutoComplete("searchCity", "results","city_name",cityURL, true);
		}
	)
  }
  );