﻿jQuery(document).ready(function() {

	// Make GetCities web service call only if search box exists
	if (jQuery("#keyword input").length > 0) {
		initCitySearch();
	}
});

function initCitySearch() {
	jQuery.ajax({
		type: "POST",
		url: "/_vti_bin/Services/Cities.svc/GetCities",
		data: "{}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: initAutoSuggest
	});

	jQuery("#keyword input").data("originalValue", jQuery("#keyword input").val());
	jQuery("#keyword input").focus(function() {
		var input = jQuery(this);
		if (input.val() == input.data("originalValue")) {
			input.val("");
		}
		input.removeClass("inactive");
	});
	jQuery("#keyword input").blur(function() {
		var input = jQuery(this);
		if (input.val() == "") {
			input.val(input.data("originalValue"));
			input.addClass("inactive");
		}
	});
}

function initAutoSuggest(json) {
	json = eval("(" + json + ")");
	jQuery("#keyword input").autocompleteArray(
		json.cities,
		json.settings
	);
}

function findValue(li) {
	if (li == null) return;
	// 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;
}

function selectItem(li) {
	findValue(li);
}

