﻿var objForm = "";
var mapFrom = null;
var mapTo = null;
var MapForm = null;
var Datepicker = null;
var FormClick = null;
var IpPlace = null;
var ParamFrom = null;
var ParamTo = null;
var input_RequestFrom = null;
var input_RequestTo = null;
$(document).ready(function() {
	objForm = document.getElementById("form_GeoSearch");
	input_RequestFrom = objForm.RequestFrom;
	input_RequestTo = objForm.RequestTo;
	
	input_RequestFrom.Field = new FieldClass(input_RequestFrom);
	input_RequestTo.Field = new FieldClass(input_RequestTo);
	
	ParamFrom = document.getElementById("ParamFrom");
	ParamTo = document.getElementById("ParamTo");
	
	MapForm = new MapFormClass('CalendarForm');
	
	mapFrom = new VEMap('MapFrom');
	mapTo = new VEMap('MapTo');
	
	IpPlace = {
		Name: "Москва",
		Latitude: "55.7522222",
		Longitude: "37.6155556"
	};
	
	input_RequestFrom.suggest = new Suggest(input_RequestFrom, mapFrom);
	input_RequestTo.suggest = new Suggest(input_RequestTo, mapTo);
	
	if (ParamFrom.value != "") {
		mapFrom.initializationVEMap("From");
		input_RequestFrom.suggest.Param = ParamFrom.value;
		input_RequestFrom.suggest.makeSuggest(ParamFrom.value);
	}
	if (ParamTo.value != "") {
		mapTo.initializationVEMap("To");
		input_RequestTo.suggest.Param = ParamTo.value;
		input_RequestTo.suggest.makeSuggest(ParamTo.value);
	}
	if (ParamFrom.value == "" || ParamTo.value == "") {
		getAJAXGeoIpPlace();
	}
	
	var ExampleFrom = document.getElementById("ExampleFrom");
	var ExampleTo = document.getElementById("ExampleTo");
	
	ExampleFrom.onclick = function() {
		input_RequestFrom.focus();
		input_RequestFrom.value = ExampleFrom.firstChild.data;
		input_RequestFrom.Field.Update();
		input_RequestFrom.suggest.update();
		input_RequestFrom.suggest.makeSuggest(input_RequestFrom.value);
	};
	ExampleTo.onclick = function() {
		input_RequestTo.focus();
		input_RequestTo.value = ExampleTo.firstChild.data;
		input_RequestTo.Field.Update();
		input_RequestTo.suggest.update();
		input_RequestTo.suggest.makeSuggest(input_RequestTo.value);
	};
	
	/* Datepicker */
	Datepicker = new DatepickerObj();
	Datepicker.createStructure();
});

function MapFormClass(FormId) {
	var self = this;
	this.RequestCount = 3;
	this.Form = document.getElementById(FormId);
	self.onFormSumbitLink = function() {
		self.onFormSumbit();
		return false;
	};
	$(this.Form).bind("submit", self.onFormSumbitLink);
	
	/* Radio */
	var Passengers_col = document.getElementById("Passengers_col");
	var Passengers_col_Labels = Passengers_col.getElementsByTagName("label");
	var Passengers_col_Inputs = Passengers_col.getElementsByTagName("input");
	changeRadioLabels(Passengers_col_Labels);
	if ($.browser.msie) {
		$(Passengers_col_Inputs).click(function() {
			changeRadioLabels(Passengers_col_Labels);
		});
	} else {
		$(Passengers_col_Inputs).change(function() {
			changeRadioLabels(Passengers_col_Labels);
		});
	}
	/* /Radio */
	/* Directions */
	this.DirectionsDOM = [];
	var DirectionsTD = $("td.Direction", "#Directions");
	$(DirectionsTD).each(function(i) {
		var DirectionDOMObj = new DirectionDOMClass(self);
		DirectionDOMObj.createFromDOM(DirectionsTD[i]);
	});
	/* /Directions */
}
MapFormClass.prototype.onFormSumbit = function() {
	this.checkForm();
};
MapFormClass.prototype.checkForm = function() {
	this.Error = false;
	this.ErrorHendler = null;
	this.Alert = "";
	
	for (var i = 1; i <= 2; i++) {
		this.DirectionsDOM[i].check();
	}
	
	if (this.Error == true) {
		new AlertMessage(this.Alert);
		if (this.ErrorHendler != null) {
			this.ErrorHendler();
		}
		return false;
	} else {
		this.makeRequestIdRequest();
	}
};
MapFormClass.prototype.makeRequestIdRequest = function() {
	var self = this;
	FadeIn("blue");
	document.body.style.cursor = "wait";
	
	/*var DirectionCookie = '';
	var DatesCookie = '';
	var AdultCookie = '';
	var ChildCookie = '';
	CreateCookie('DirectionCookie',DirectionCookie);
	CreateCookie('DatesCookie',DatesCookie);
	CreateCookie('AdultCookie',AdultCount);
	CreateCookie('ChildCookie',ChildCount);*/
	$.ajax({
		cache: false,
		type: "get",
		dataType: "xml",
		url: "/avia/searching/new/",
		data: $(this.Form).serialize(),
		beforeSend: function() {
			self.RequestCount--;
		},
		success: function(xml) {
			var Request = xml.getElementsByTagName("Request")[0];
			var sStatus = Request.getAttribute("Status");
			var href = languagePath + '/avia/searching/';
			if (sStatus == "Error") {
				var sStatusInfo = Request.firstChild.data;
				switch (sStatusInfo) {
					case "NoSegmentsToSearch":
					case "ADTNeeded":
						alert(sStatus);
						break;
					case "SearchNotAvail":
						alert(MO_str_SearchUnavailable);
						document.body.removeChild(document.getElementById('FadeInDiv'));
						document.body.style.cursor = "default";
						break;
						
				}
			} else if (sStatus == 'NeedCaptcha') {
				self.Captcha(Request.getAttribute("Id"));
			} else {
				sRequestId = Request.getAttribute("Id");
				href += "?RequestId=" + sRequestId;
				top.location.href = href;
				return;
			}
		},
		error: function() {
			if (self.RequestCount <= 0) {
				alert(MO_str_SearchUnavailable);
				self.RequestCount = 3;
				document.body.removeChild(document.getElementById('FadeInDiv'));
				document.body.style.cursor = "default";
			} else {
				setTimeout(function() {
					self.makeRequestIdRequest();
				}, 2000);
			}
		}
	});
};
MapFormClass.prototype.Captcha = function(Id) {
	var self = this;
	document.body.style.cursor = "default";
	var Captcha = document.getElementById('Captcha');
	var Content = document.createElement('div');
	var TempContent = Captcha.firstChild.cloneNode(true);
	$(Content).append(TempContent);
	$('button', Content).click(function() {
		var Approval = $('input[name="Approval"]', Content)[0].value;
		$.ajax({
			type: "get",
			url: "/AviaCapture/",
			data: {
				"Number": Id,
				"Approval": Approval
			},
			dataType: "xml",
			success: function(xml) {
				document.getElementById('Approval_Number').value = Id;
				ConfirmationPopup.Hide();
				self.makeRequestIdRequest();
			}
		});
	});
	var img = document.createElement('img');
	img.src = '/AviaCapture/?Picture=' + Id;
	img.alt = '';
	$('.img_insert', Content).append(img);
	var ConfirmationPopup = new Popup(Content, "Delete");
	ConfirmationPopup.Box.style.width = "320px";
	ConfirmationPopup.Box.style.height = "200px";
	ConfirmationPopup.Box.style.minHeight = "0";
	ConfirmationPopup.Box.style.minWidth = "0";
	if ($.browser.msie) {
		ConfirmationPopup.SetStyle = function() {
			ConfirmationPopup.Box.style.marginLeft = "-110px";
			ConfirmationPopup.Box.style.top = "50%";
			ConfirmationPopup.Box.style.marginTop = "-100px";
			if (!window.XMLHttpRequest) this.Box.style.position = "absolute";
		};
	}
	ConfirmationPopup.CloseButton.style.right = "-5px";
	ConfirmationPopup.CloseButton.style.top = "-3px";
	
	ConfirmationPopup.Box.id = "ConfirmationPopup";
	ConfirmationPopup.Show();
};

function DirectionDOMClass(objForm) {
	this.objMapForm = objForm;
	this.Direction = null;
	this.DirectionNumber = null;
	
	this.entBox = null;
	this.entObj = null;
	
	this.DateInput = null;
	this.StartAirpCodeInput = null;
	this.EndAirpCodeInput = null;
}
DirectionDOMClass.prototype.createFromDOM = function(DirectionDOMObj) {
	var self = this;
	
	this.entBox = DirectionDOMObj;
	this.entObj = this.entBox.getElementsByTagName("fieldset")[0];
	this.DirectionNumber = this.entObj.id.split("Direction")[1];
	
	this.DateInput = document.getElementById("Date" + this.DirectionNumber + "_input");
	this.StartAirpCodeInput = document.getElementById("StartAirp" + this.DirectionNumber + "Code_input");
	this.EndAirpCodeInput = document.getElementById("EndAirp" + this.DirectionNumber + "Code_input");
	
	this.DateInput.onfocus = function() {
		var el_Label = $("label[for=" + self.DateInput.id + "]");
		Datepicker.show(self.DateInput, el_Label[0], self);
	};
	
	var x = (this.DirectionNumber == 1 ? 2 : 1);
	var y = (this.DirectionNumber == 1 ? 1 : 2);
	this.StartAirpCodeInput.onfocus = function() {
		var CurrentSugget = document.getElementById("DropDown" + y);
		CurrentSugget.style.visibility = "visible";
		var label = $('label[for=' + self.StartAirpCodeInput.id + ']')[0];
		var labelXY = getPosition(label);
		CurrentSugget.style.top = "";
		CurrentSugget.style.left = "";
		CurrentSugget.style.top = labelXY[0] + label.offsetHeight + "px";
		CurrentSugget.style.left = labelXY[1] + "px";
		FormClick = y;
	};
	this.EndAirpCodeInput.onfocus = function() {
		var CurrentSugget = document.getElementById("DropDown" + x);
		CurrentSugget.style.visibility = "visible";
		var label = $('label[for=' + self.EndAirpCodeInput.id + ']')[0];
		var labelXY = getPosition(label);
		CurrentSugget.style.top = "";
		CurrentSugget.style.left = "";
		CurrentSugget.style.top = labelXY[0] + label.offsetHeight + "px";
		CurrentSugget.style.left = labelXY[1] + "px";
		FormClick = y;
	};
	this.objMapForm.DirectionsDOM[this.DirectionNumber] = this;
};
DirectionDOMClass.prototype.update = function(Direction) {
	this.draw();
	
	//this.checkDefault();
	//this.updateDirection();
};
DirectionDOMClass.prototype.draw = function() {
	if (this.DateInput.value != '') this.drawDateLabel();
	
	//this.drawStartAirp();
	//this.drawEndAirp();
};
DirectionDOMClass.prototype.drawDateLabel = function() {
	var self = this;
	var tempDate = this.DateInput.value;
	var arrDate = tempDate.split('.');
	var el_Label = $("label[for=" + self.DateInput.id + "]")[0];
	var span_Text = $(el_Label).find('span[class="Text"]')[0];
	var span_Date = $(el_Label).find('span[class="Date"]')[0];
	
	span_Text.style.display = "none";
	span_Date.style.display = "inline";
	var lDate = $(span_Date).find('span[class="lDate"]')[0];
	lDate.innerHTML = parseInt(arrDate[0], 10);
	var lMonth = $(span_Date).find('span[class="lMonth"]')[0];
	lMonth.innerHTML = Datepicker.getMonthDName(arrDate[1]);
	var lYear = $(span_Date).find('span[class="lYear"]')[0];
	lYear.innerHTML = arrDate[2];
};
DirectionDOMClass.prototype.check = function() {
	var Flight2way = document.getElementById("Flight2way");
	if (!(this.DirectionNumber == 2 && Flight2way.value == "false")) {
		this.checkDate();
		this.checkAirp("Start");
		this.checkAirp("End");
	}
};
DirectionDOMClass.prototype.checkDate = function() {
	var self = this;
	if (this.DateInput.value == "") {
		if (this.objMapForm.Error == false) {
			this.objMapForm.ErrorHendler = function() {
				self.DateInput.select();
			};
			this.objMapForm.Alert = MO_str_NoDateFrom;
			this.objMapForm.Error = true;
		}
	}
};
DirectionDOMClass.prototype.checkAirp = function(Postfix) {
	var self = this;
	if (Postfix == "Start" && this.StartAirpCodeInput.value == "") {
		if (this.objMapForm.Error == false) {
			//this.objMapForm.ErrorHendler = function(){ self.StartAirpInput.focus() };
			this.objMapForm.Alert = MO_str_NoCityFrom;
			this.objMapForm.Error = true;
		}
	} else if (Postfix == "End" && this.EndAirpCodeInput.value == "") {
		if (this.objMapForm.Error == false) {
			//this.objMapForm.ErrorHendler = function(){ self.EndAirpInput.focus() };
			this.objMapForm.Alert = MO_str_NoCityTo;
			this.objMapForm.Error = true;
		}
	}
};

function getAJAXGeoIpPlace() {
	var self = this;
	$.ajax({
		cache: false,
		type: "get",
		dataType: "xml",
		url: "/_references/GeoLocation/",
		success: function(xml) {
			var response = xml;
			var Place_Name = response.getElementsByTagName("CityName")[0].firstChild.data;
			var Place_Latitude = response.getElementsByTagName("Latitude")[0].firstChild.data;
			var Place_Longitude = response.getElementsByTagName("Longitude")[0].firstChild.data;
			IpPlace = {
				Name: Place_Name,
				Latitude: Place_Latitude,
				Longitude: Place_Longitude
			};
			
			if (ParamFrom.value == "") {
				mapFrom.initializationVEMap("From");
			}
			if (ParamTo.value == "") {
				mapTo.initializationVEMap("To");
			}
		},
		error: function() {
			mapFrom.initializationVEMap("From");
			mapTo.initializationVEMap("To");
		}
	});
}

VEMap.prototype.initializationVEMap = function(Postfix) {
	var self = this;
	this.Postfix = Postfix;
	this.DirectionNumber = (Postfix == "From" ? 1 : 2);
	
	this.getGeoIpPlace();
	this.SelectedRow = null;
	
	this.LoadMapOnPoint(this.Place);
	
	this.resultDiv = document.createElement("div");
	this.resultDiv.id = "DropDown" + this.DirectionNumber;
	this.resultDiv.className = "SuggestResult";
	document.body.appendChild(this.resultDiv);
	
	if (this.DirectionNumber == 1) {
		this.SetPlacePin();
		this.gotoPlace(this.Place);
		this.makeAirportsRequest();
	}
	
	this.RouteOptions = new VERouteOptions();
	this.RouteOptions.DistanceUnit = VERouteDistanceUnit.Kilometer;
	this.RouteOptions.RouteCallback = this.onGetDirections;
};
VEMap.prototype.getGeoIpPlace = function() {
	var self = this;
	var Place_LatLong = new VELatLong(IpPlace.Latitude, IpPlace.Longitude);
	this.Place = new VEPlace(IpPlace.Name, Place_LatLong);
};
VEMap.prototype.SetPlacePin = function(event) {
	var self = this;
	var Place_Pin = new VEShape(VEShapeType.Pushpin, this.Place.LatLong);
	Place_Pin.SetCustomIcon("/images/pin-point.png");
	Place_Pin.SetTitle(this.Place.Name);
	this.AddShape(Place_Pin);
};
VEMap.prototype.gotoPlace = function(Place) {
	var self = this;
	this.InPosition = false;
	var Place_LatLong = Place.LatLong;
	
	if (this.GetZoomLevel() > 10) {
		this.SetCenterAndZoom(self.GetCenter(), 10);
	}
	setTimeout(function() {
		self.SetCenterAndZoom(Place_LatLong, 11);
		self.InPosition = true;
	}, 700);
};
VEMap.prototype.setNewPlaceFromSuggestResult = function(objResult) {
	var self = this;
	this.Clear();
	
	if (objResult != null) {
		this.Result = objResult;
		this.Place_Country = this.Result.getElementsByTagName("countryCode")[0].firstChild.data;
		var NewPlace_Name = this.Result.getElementsByTagName("name")[0].firstChild.data;
		var NewPlace_Latitude = this.Result.getElementsByTagName("lat")[0].firstChild.data;
		var NewPlace_Longitude = this.Result.getElementsByTagName("lng")[0].firstChild.data;
		var NewPlace_LatLong = new VELatLong(NewPlace_Latitude, NewPlace_Longitude);
		this.Place = new VEPlace(NewPlace_Name, NewPlace_LatLong);
		
		this.SetPlacePin();
		this.gotoPlace(this.Place);
		this.makeAirportsRequest();
		setTimeout(function() {
			self.CreatePanoramioLayer();
		}, 800);
	}
};
VEMap.prototype.makeAirportsRequest = function() {
	var self = this;
	var params = {
		Latitude: this.Place.LatLong.Latitude,
		Longitude: this.Place.LatLong.Longitude,
		Country: this.Place_Country,
		Radius: 200
	};
	$.ajax({
		type: "get",
		url: "/_references/AirportFinder/",
		dataType: "xml",
		data: params,
		success: function(xml) {
			var response = xml;
			self.setAirportsAndCities(response);
		},
		error: function() {
			alert(MO_str_SuggestNoResult);
		}
	});
};
VEMap.prototype.setAirportsAndCities = function(response) {
	var Language = document.getElementById('Language').value;
	var NameLang = ((Language != "ru") ? "NameEn" : "NameRu");
	
	var self = this;
	var responseCountries = response.getElementsByTagName("Country");
	var x = (this.DirectionNumber == 1 ? 2 : 1);
	
	var StartSelect = MapForm.DirectionsDOM[this.DirectionNumber].StartAirpCodeInput;
	StartSelect.value = "";
	var EndSelect = MapForm.DirectionsDOM[x].EndAirpCodeInput;
	EndSelect.value = "";
	
	if (this.resultDiv.firstChild != null) {
		this.resultDiv.removeChild(this.resultDiv.firstChild);
	}
	this.resultTable = document.createElement("table");
	this.resultTable.className = "SuggestResult";
	this.resultDiv.appendChild(this.resultTable);
	
	if (responseCountries.length > 0) {
		for (var i = 0, CountryLength = responseCountries.length; i < CountryLength; i++) {
			var responseCountry = responseCountries[i];
			var responseCountryName = responseCountry.getAttribute(NameLang);
			var responseCities = responseCountry.getElementsByTagName("City");
			
			for (var j = 0, CityLength = responseCities.length; j < CityLength; j++) {
				var responseCity = responseCities[j];
				var responseCityName = responseCity.getAttribute(NameLang);
				var CityCode = responseCity.getAttribute("City");
				var responseAirports = responseCity.getElementsByTagName("Airport");
				
				var responseRow = self.resultTable.insertRow(j);
				if (i == 0 && j == 0) {
					this.SelectedRow = responseRow;
				}
				responseRow.onmouseover = function() {
					$(this).addClass("hover");
					self.SelectedRow = this;
				};
				responseRow.onmouseout = function() {
					$(this).removeClass("hover");
				};
				responseRow.onclick = function() {
					self.SelectedRow = this;
					self.hideResultSuggest("One");
				};
				
				var responseName = document.createElement("span");
				responseName.appendChild(document.createTextNode(responseCity.getAttribute(NameLang) + ", " + responseCountry.getAttribute(NameLang)));
				
				var responseTextCell = responseRow.insertCell(0);
				responseTextCell.className = "SuggestResult";
				responseTextCell.appendChild(responseName);
				responseTextCell.setAttribute("City", responseCity.getAttribute(NameLang));
				responseTextCell.setAttribute("Country", responseCountry.getAttribute(NameLang));
				
				var responseCodeCell = responseRow.insertCell(1);
				responseCodeCell.className = "AirpCode";
				responseCodeCell.innerHTML = CityCode;
				
				for (var k = 0, AirpLength = responseAirports.length; k < AirpLength; k++) {
					var responseAirp = responseAirports[k];
					
					var Airp_Name = responseAirp.getElementsByTagName("Name")[0].getElementsByTagName(NameLang)[0].firstChild.data;
					var Airp_Code = responseAirp.getElementsByTagName("Code")[0].firstChild.data;
					var Airp_Latitude = responseAirp.getElementsByTagName("Latitude")[0].firstChild.data;
					var Airp_Longitude = responseAirp.getElementsByTagName("Longitude")[0].firstChild.data;
					var Airp_LatLong = new VELatLong(Airp_Latitude, Airp_Longitude);
					
					var Airp = new VEPlace(Airp_Name, Airp_LatLong);
					var AirpIcon = "/images/pin" + this.DirectionNumber + ".png";
					var AirpBaloon = Airp.Name + ", " + responseCityName + ", " + responseCountryName;
					var Params = "'" + this.DirectionNumber + "', '" + self.Place.LatLong + "', '" + Airp_LatLong + "'";
					var AirpBaloonContent = "<span onclick=\"MyGetDirections(" + Params + ")\" class=\"link_js\">" + MO_str_ShowDirection + "</span>";
					
					var Airp_Pin = new VEShape(VEShapeType.Pushpin, Airp_LatLong);
					Airp_Pin.SetCustomIcon("/images/pin" + this.DirectionNumber + ".png");
					Airp_Pin.SetTitle(Airp.Name + ", " + responseCityName + ", " + responseCountryName);
					Airp_Pin.SetDescription("<span onclick=\"MyGetDirections(" + Params + ")\" class=\"link_js\">" + MO_str_ShowDirection + "</span>");
					this.AddShape(Airp_Pin);
				}
				setTimeout(function() {
					self.SetCenterAndZoom(self.Place.LatLong, 7);
				}, 700);
			}
		}
	}
	this.hideResultSuggest();
};
VEMap.prototype.hideResultSuggest = function(One) {
	this.resultDiv.style.visibility = "hidden";
	
	var x = (this.DirectionNumber == 1 ? 2 : 1);
	var y = (this.DirectionNumber == 1 ? 1 : 2);
	
	var label1 = document.getElementById("StartAirp" + y + "Code_label");
	var label2 = document.getElementById("EndAirp" + x + "Code_label");
	var Text = this.SelectedRow.firstChild.getAttribute("City") + ", " + this.SelectedRow.firstChild.getAttribute("Country");
	var Code = this.SelectedRow.lastChild.firstChild.data;
	
	if (!(One == "One" && FormClick == x)) {
		label1.firstChild.innerHTML = Text;
		//input_RequestFrom.value = Text;
		//input_RequestFrom.Field.Update();
		var StartSelect = MapForm.DirectionsDOM[y].StartAirpCodeInput;
		StartSelect.value = Code;
	}
	if (!(One == "One" && FormClick == y)) {
		label2.firstChild.innerHTML = Text;
		var EndSelect = MapForm.DirectionsDOM[x].EndAirpCodeInput;
		EndSelect.value = Code;
	}
};
VEMap.prototype.onGetDirections = function(route) {
	route.RouteLegs = [];
	route.ShapePoints = [];
};
VEMap.prototype.myGetDirections = function(LatLongFrom, LatLongTo) {
	this.GetDirections([LatLongFrom, LatLongTo], this.RouteOptions);
};
function MyGetDirections(DirectionNumber, LatLongFrom, LatLongTo) {
	if (DirectionNumber == 1) mapFrom.myGetDirections(LatLongFrom, LatLongTo);
	else mapTo.myGetDirections(LatLongTo, LatLongFrom);
}

function Suggest(input, map) {
	var self = this;
	this.entObj = document.createElement("div");
	this.entObj.className = "SuggestResult";
	this.URL = "/_references/GeoNames/";
	this.input = input;
	this.form = this.input.form;
	this.Postfix = this.input.name.substr(7);
	this.map = map;
	
	this.inFocus = false;
	this.Complite = false;
	this.RowHover = false;
	this.mouseover = false;
	$(this.input).focus(function() {
		self.OnFocus();
	});
	$(this.input).blur(function() {
		self.OnBlur();
	});
	$(this.entObj).mouseover(function() {
		self.mouseover = true;
	}).mouseout(function() {
		self.mouseover = false;
	});
	
	this.isShow = false;
	this.TempValue = this.input.value;
	
	$(this.input).keyup(function(event) {
		self.OnKeyUp(event);
	});
}
Suggest.prototype.OnFocus = function() {
	this.inFocus = true;
};
Suggest.prototype.OnBlur = function() {
	if (this.mouseover == false) {
		this.hide();
		this.setCurrentResult();
	}
	this.inFocus = false;
	this.Complite = false;
};
Suggest.prototype.OnKeyDown = function(event) {
	var self = this.suggest;
	
	switch (event.keyCode) {
		case 27: // <Esc>
			if (self.entObj.parentNode == document.body) self.hide();
			break;
		case 38: // <Up>
			self.setPrevRowHover();
			break;
		case 40: // <Down>
			self.setNextRowHover();
			break;
		case 13: // <Enter>
			event.preventDefault();
			self.hide();
			self.setCurrentResult(true);
			self.map.setNewPlaceFromSuggestResult(self.Result);
			break;
	}
};
Suggest.prototype.OnKeyUp = function(event) {
	var self = this;
	if (this.input.value != this.TempValue) {
		this.Complite = false;
	}
	if (this.input.value != this.TempValue && this.input.value.length >= 2) {
		this.TempValue = this.input.value;
		var Temp = this.TempValue;
		setTimeout(function() {
			self.makeSuggest(Temp);
		}, 350);
	} else if (this.input.value != this.TempValue) {
		self.hide();
	}
};
Suggest.prototype.makeSuggest = function(CurrentQuery) {
	var self = this;
	if (this.TempValue == CurrentQuery || this.Param == CurrentQuery) {
		var Language = this.form.Language.value;
		var params = {
			Language: Language,
			Request: CurrentQuery
		};
		$.ajax({
			type: "post",
			dataType: "xml",
			url: self.URL,
			data: params,
			success: function(xml) {
				var response = xml;
				self.response = xml;
				self.draw(response, CurrentQuery);
			}
		});
	}
};
Suggest.prototype.draw = function(response, CurrentQuery) {
	var self = this;
	if (this.entObj.firstChild) {
		for (var ch = 0; this.entObj.childNodes.length > 0; ch++) {
			this.entObj.removeChild(this.entObj.firstChild);
		}
	}
	this.resultTable = document.createElement("table");
	this.resultTable.className = "SuggestResult";
	this.entObj.appendChild(this.resultTable);
	
	this.responseItems = response.getElementsByTagName("geoname");
	if (this.responseItems.length > 0) {
		for (var i = 0; i < this.responseItems.length; i++) {
			var responseItem = this.responseItems[i];
			var responseRow = self.resultTable.insertRow(i);
			responseRow.onmouseover = function() {
				self.RowHover = true;
				self.setRowHover(this);
			};
			responseRow.onmouseout = function() {
				self.RowHover = false;
				self.dropRowHover(this);
			};
			responseRow.onclick = function() {
				self.hide();
				self.setCurrentResult();
				self.inFocus = false;
				self.Complite = false;
				self.map.setNewPlaceFromSuggestResult(self.Result);
			};
			
			self.queryString = self.input.value;
			try {
				var re = new RegExp(self.queryString, 'ig');
			} catch (e) {}
			
			var responseName = responseItem.getElementsByTagName("name")[0].firstChild.data;
			var responseCountry = responseItem.getElementsByTagName("country")[0].getElementsByTagName("Name")[0].firstChild.data;
			var responseCountryCode = responseItem.getElementsByTagName("countryCode")[0].firstChild.data;
			var responseAdminName1 = $(responseItem.getElementsByTagName("adminName1")[0]).text();
			//var respAdminName2 = responseItems[i].getElementsByTagName("adminName2")[0].firstChild.data;
			var responseLat = responseItem.getElementsByTagName("lat")[0].firstChild.data;
			var responseLng = responseItem.getElementsByTagName("lng")[0].firstChild.data;
			
			var responseText = responseName;
			responseText += ", " + responseCountry;
			if (responseAdminName1 != responseName && responseAdminName1 != "") responseText += " (" + responseAdminName1 + ")";
			var responseTitle = responseText;
			if ($.browser.opera) {
				var matchStr = re.exec(responseText);
				responseText = responseText.replace(re, function() {
					return '<span class="match">' + matchStr + '</span>';
				});
			} else {
				responseText = responseText.replace(re, function() {
					return '<span class="match">' + re.exec(responseText) + '</span>';
				});
			}
			var suggestLink = document.createElement("a");
			
			var responseTextCell = responseRow.insertCell(0);
			responseTextCell.setAttribute("Number", i);
			responseTextCell.className = "SuggestResult";
			responseTextCell.innerHTML = responseText;
			responseTextCell.title = responseTitle;
		}
		this.resultTable.onmouseout = function() {
			self.setRowHover(self.selectedRow);
		};
		this.setFirstRowHover();
	} else {
		var Row = this.resultTable.insertRow(-1);
		var Cell = Row.insertCell(-1);
		Cell.className = "NoResults";
		Cell.appendChild(document.createTextNode(MO_str_SuggestNoResult));
	}
	if (this.inFocus == true && this.Complite != true) {
		this.show();
	} else {
		if (CurrentQuery == this.TempValue || CurrentQuery == this.Param) {
			this.setCurrentResult();
		}
	}
};
Suggest.prototype.update = function() {
	this.TempValue = this.input.value;
};
Suggest.prototype.setFirstRowHover = function() {
	this.selectedRow = this.resultTable.firstChild.firstChild;
	this.setRowHover(this.selectedRow);
};
Suggest.prototype.setLastRowHover = function() {
	if (this.selectedRow != null) {
		this.dropRowHover(this.selectedRow);
	}
	this.selectedRow = this.resultTable.firstChild.lastChild;
	this.setRowHover(this.selectedRow);
};
Suggest.prototype.setRowHover = function(Row) {
	if (this.selectedRow) {
		this.dropRowHover(this.selectedRow);
	}
	$(Row).addClass("hover");
	this.selectedRow = Row;
};
Suggest.prototype.dropRowHover = function(Row) {
	$(Row).removeClass("hover");
};
Suggest.prototype.dropTitle = function() {
	if (this.input.value != this.TempValue) {
		this.input.title = '';
	}
};
Suggest.prototype.setPrevRowHover = function() {
	if (this.selectedRow != null) {
		var PrewRow = this.selectedRow.previousSibling;
		if (PrewRow) {
			this.dropRowHover(this.selectedRow);
			this.setRowHover(PrewRow);
			this.selectedRow = PrewRow;
		}
	}
};
Suggest.prototype.setNextRowHover = function() {
	if (this.selectedRow != null) {
		var NextRow = this.selectedRow.nextSibling;
		if (NextRow) {
			this.dropRowHover(this.selectedRow);
			this.setRowHover(NextRow);
			this.selectedRow = NextRow;
		}
	}
};
Suggest.prototype.setCurrentResult = function(Focus) {
	if ((this.input.value == this.TempValue && this.TempValue == this.queryString && this.Complite != true) || this.Param != "") {
		if (this.selectedRow != null) {
			this.Complite = true;
			this.input.value = this.selectedRow.firstChild.title;
			var responseNumber = $(this.selectedRow.firstChild).attr("Number");
			this.Result = this.responseItems[responseNumber];
			this.TempValue = this.input.value;
			if (this.Param == "") {
				this.input.focus();
			} else {
				this.input.Field.Update();
			}
			this.RowHover = false;
			this.Param = "";
			if (this.inFocus == false) {
				this.map.setNewPlaceFromSuggestResult(this.Result);
			}
		}
	}
};
Suggest.prototype.show = function() {
	var self = this;
	this.isShow = true;
	
	$(this.input).unbind("keydown", self.OnKeyDown);
	$(this.input).bind("keydown", self.OnKeyDown);
	
	var inputXY = getPosition(this.input);
	var windowHeight = document.documentElement.clientHeight;
	
	document.body.appendChild(this.entObj);
	
	this.entObj.style.top = inputXY[0] + this.input.offsetHeight + "px";
	this.entObj.style.left = inputXY[1] + "px";
	
	this.entObj.style.visibility = "visible";
};
Suggest.prototype.hide = function() {
	var self = this;
	
	$(this.input).unbind("keydown", self.OnKeyDown);
	
	this.isShow = false;
	
	if (this.entObj.parentNode == document.body) {
		this.entObj.style.visibility = "hidden";
		document.body.removeChild(this.entObj);
	}
};