Search.Popup = function()
{
	this.is_item_select = false; // флаг обозначающий что значение было выбранно из списка вручную
	this.city_name;
	this.city_code;
	this.city_from_last_value = "";
	this.city_to_last_value = "";
}
Search.Popup.prototype = {
	init: function()
	{
		var self = this;
		// удалить все направления
		$("div.dest-reset").click(function()
		{
			Search.Params.city_from = null; // очищаем выбранный перелет туда
			Search.Params.city_to = null	  // очищаем выбранный перелет обратно
			self.city_code = null;
			self.city_name = null;
			self.checkDirection(); // проверяем необходимость добавить направление	
			self.checkInput($("div.dest-city01").find(".dest-city-inp-act").val("")); // очищаем элемент управления
			self.checkInput($("div.dest-city02").find(".dest-city-inp-act").val("")); // очищаем элемент управления
		});
		// удалить второе направление
		$("div.dest-reset2").click(function()
		{
			removeDirectionTo();
			Search.Params.is_flight_back = false;
			SearchDatepicker.removeSelectDateTo();	
		});
		// добавить перелет обратно
		$("div.dest-return-btn").click(function()
		{
			addDirectionTo();
			Search.Params.is_flight_back = true;	
		});
		
		this.elementAutocomplete($("input#city_from"), $("div.dest-city01"));
		this.elementAutocomplete($("input#city_to"), $("div.dest-city02"));
		
		// инпут получил фокус очищаем его если он содержит значение по умолчанию
		$("input.dest-city-inp").focusin(function() {
			if ($(this).val() == "откуда" || $(this).val() == "куда") {
				$(this).val("");
			} else {
				if ($(this).attr("id") == "city_from") {
					self.city_from_last_value = $(this).val();
				} else {
					self.city_to_last_value = $(this).val();
				}	
			}
		});
		// инпут потерял фокус, заполняем его выбранным значением или очищаем если ничего не выбранно
		$("input.dest-city-inp").focusout(function() {
			var element = $(this);
			var last_value;
			if ($(this).attr("id") == "city_from") {
				last_value = self.city_from_last_value;
			} else {
				last_value = self.city_to_last_value;
			}
			if (last_value != $(this).val() || $(this).val() == "") {
				window.setTimeout(function() { self.changeInput(element) }, 150);
			}
		});
	},
	checkInput: function(element)
	{
		if (typeof element == "undefined") return;
		if (element.val() == "") {
			//
			if (element.attr("id") == "city_from") {
				element.val('откуда');
				element.parent().find(".dest-city-port").text("");
			}
			else {
				element.val('куда');
				element.parent().find(".dest-city-port").text("");
			}
			//
			element.removeClass("dest-city-inp-act");
			element.addClass("dest-city-inp");
		} else {
			element.removeClass("dest-city-inp");
			element.addClass("dest-city-inp-act");
		}	
	},
	changeInput: function(element)
	{
		var self = SearchPopup;
		var element2;
		if (!self.is_item_select) {
			element.search(function (result) {
				if (typeof result != "undefined") {
					self.city_name = result.data.name;
					self.city_code = result.data.code;
				}
			});
		}
		if (element.attr("id") == "city_from") {
			element2 = $("div.dest-city04");
			if (typeof self.city_code == "undefined") {
				Search.Params.city_from = null;
			} else {
				Search.Params.city_from = self.city_code;
			}
		} else if (element.attr("id") == "city_to") {
			element2 = $("div.dest-city03");
			if (typeof self.city_code == "undefined") {
				Search.Params.city_to = null;
			} else {
				Search.Params.city_to = self.city_code;
			}
		}
		
		element.val(self.city_name).parent().find(".dest-city-port").text(self.city_code);
		element2.find(".dest-city-inp-act").val(self.city_name).parent().find(".dest-city-port").text(self.city_code);
		
		self.checkDirection();
		self.checkInput(element);
	},
	// проверяем необходимость добавить классы с направлениями 
	checkDirection: function()
	{
		if (Search.Params.city_from != null && Search.Params.city_to != null) {
			addDirectionFrom();
			if (Search.Params.is_flight_back) addDirectionTo();
		} else {
			removeDirectionFrom();
			if (Search.Params.is_flight_back) removeDirectionTo();
		}
		SearchDatepicker.redrawCalendar(); // перерисовать календарь, необходимо для того чтобы в выбранных датах менялись направления
	},
	// автозаполнение
	elementAutocomplete: function(element, parentEelement)
	{
		// автозаполнение города
		var self = this; 
		element.autocomplete("/ajax/cities/", {
	            max: 6,
	            parentElement: parentEelement,
				minChars: 2,
				dataType: "json",
	            autoFill:true,
	            deferRequestBy: 10,
		        formatItem: function(row) {
		        	return '<div class="dest-item"><div class="dest-city-pop">' + row.name + ', ' + row.country_name + '<label class="dest-city-port-pop">' + row.code + '</label></div></div>';
		        },
				formatResult: function(row) {
					return row.name;
				},
		        parse: function(data) {
		        		SearchPopup.is_item_select = false;
		                var array = new Array();
		                for(var i=0;i<data.length;i++) {   
		                	array.push({ data: data[i], value: data[i].name, result: data[i].name});
		                }
		                return array;
		        }
		}).result(function(e, data) {
			self.city_name = data.name;
			self.city_code = data.code;
			self.is_item_select = true;
		});
	}
}
