/* Suggest */
    function Suggest(input,ParObj){
        var self = this;
        this.entObj = document.createElement("div");
        this.entObj.className = "SuggestResult";
        this.URL = citySearchURL;

        this.ParObj = ParObj || null;
        this.input = input;
        this.Try = 0;
        
        this.inFocus = false;
        this.Complite = false;
        this.RowHover = false;
	this.Success = true; 
        $(this.input).focus(function(){ self.OnFocus() });
        $(this.input).blur(function(){ self.OnBlur() });
        
        this.isShow = false;
        this.InputName = this.input.name;
        this.CodeInput = document.getElementById( this.InputName + 'Code_input');
        this.TempValue = this.input.value;
        
        $(this.input).keyup(function(event){ self.OnKeyUp(event) });
    }
    Suggest.prototype.OnFocus = function(){
        this.inFocus = true;
    }
    Suggest.prototype.OnBlur = function(){
        var self = this;
        //this.hide();
        this.dropCodeValue();
        this.setCurrentResult();
        this.inFocus = 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);
                break;
            case 9: // <Tab>
            	self.hide();
            	break;
        }
    }
    Suggest.prototype.OnKeyUp = function(event){
        var self = this;
        if(this.input.value != this.TempValue){
            this.dropCodeValue();
        }
        if(this.input.value != this.TempValue && this.input.value.length > 2){
            this.TempValue = this.input.value;
            var Temp = this.TempValue;
            this.Try = 0;
            setTimeout( function(){self.makeSuggest(Temp)} , 350);
        } else if(this.input.value != this.TempValue) {
            self.hide();
        }
//        if(this.input.value =='') this.ParObj.update();
    }
    Suggest.prototype.makeSuggest = function(CurrentQuery) {
        var self = this;

        if (citySearchURL == '/calendar/bus_cities/' && !this.Success)
		return false;

        if (this.TempValue == CurrentQuery) {
            
            var code = '';
            if (this.CodeInput.id.substr(0, 9) == 'StartAirp'){
                code = $("#"+this.CodeInput.id.replace(/StartAirp/i, "EndAirp")).val();
                dir = 'departure';
            } else {
                code = $("#"+this.CodeInput.id.replace(/EndAirp/i, "StartAirp")).val();
                dir = 'arrival';
            }
            

            var lang = language;
            var params = {
                filter: CurrentQuery,
                lang: lang,
                code: code,
                dir: dir
            };

	    if (CurrentQuery == '') {
            	var response = [];
            	self.draw(response, CurrentQuery, "ascending");
            	self.draw(response, CurrentQuery, "descending");

	    } else {
            	$.ajax({
            	    type: "post",
            	    url: this.URL,
            	    dataType: "json",
            	    data: params,
            	    beforeSend: function() {
			self.Success = false;
            	        $(self.CodeInput).addClass("wait").removeClass('hide');
            	    },
            	    success: function(data) {
            	        $(self.CodeInput).removeClass("wait");
            	        self.Success = true; 
            	        var response = data;
            	        self.draw(response, CurrentQuery, "ascending");
            	        self.draw(response, CurrentQuery, "descending");
            	    },
            	    error: function() {
            	        if (self.Try < 3) {
            	            self.Try += 1;
            	            setTimeout(function() { self.makeSuggest(CurrentQuery) }, 350);
            	            return;
            	        }
            	        $(self.CodeInput).removeClass("wait");
            	        alert(MO_str_SuggestUnavailable);
            	    }
            	});
	    }
        }
    }
    


    Suggest.prototype.draw = function(response, CurrentQuery, Sort) {
        var self = this;
        if (this.entObj.firstChild) {
            for (var ch = 0; this.entObj.childNodes.length > 0; ch++) {
                this.entObj.removeChild(this.entObj.firstChild);
            }
        }
        var resultTable = document.createElement("table");
        	resultTable.className = "SuggestResult";

        //var responseItems = response.firstChild.childNodes;
        var responseItems = response;
        if (responseItems.length > 0) {
            
            if (responseItems.length < 10) {
                $(this.entObj).height(25*responseItems.length);
				$(this.entObj).css("padding","0");
               resultTable.style.marginRight = 0;
            } else {
                $(this.entObj).height(250);
				$(this.entObj).css("padding","7px 7px 7px 0");
            }
            for (var i = 0; i < responseItems.length; i++) {
                if (Sort == "ascending")
                    var responseItem = responseItems[i];
                else
                    var responseItem = responseItems[responseItems.length - i - 1];
                    
                var responseRow = 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(); }
                
                if (typeof(response[0].service) != 'undefined') {
                	$(responseRow).data(response[0]);
                }
                                
                self.queryString = self.input.value;                
                self.queryString = self.queryString.replace(/\[/, "х")
                self.queryString = self.queryString.replace(/\]/, "ъ")                

                self.input.value = self.queryString; 
                
                var re = new RegExp(self.queryString, 'ig');

                var responseText = responseItem.name + responseItem.info;
                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 responseCode = responseItem.code;

                var responseTextCell = responseRow.insertCell(0);
                responseTextCell.className = "SuggestResult";
                responseTextCell.innerHTML = responseText;

                if (responseItem.airport) {
                    responseTextCell.className = 'airport';
                }
                
                responseTextCell.setAttribute("City", responseItem.name);

                var responseCodeCell = responseRow.insertCell(1);
                responseCodeCell.className = "AirpCode";
                if (responseCode.match(re)) {
                    $(responseCodeCell).addClass("match");
                }
                
                responseCodeCell.innerHTML = responseCode;
                
            }
            resultTable.onmouseout = function() { self.setRowHover(self.selectedRow) }

            if (Sort == "ascending") {
                this.resultTable = resultTable;
                this.setFirstRowHover();
                this.setRowHover(this.selectedRow);
            } else {
                this.resultTableDesc = resultTable;
            }

            if (responseItems.length == 1) { //if only 1 suggest result - select by default
                self.dropCodeValue();
                self.setCurrentResult();
                self.hide();
            }
        } else {
            $(this.entObj).height(25);
            var Row = resultTable.insertRow(-1);
            var Cell = Row.insertCell(-1);
            Cell.className = "NoResults";
            resultTable.style.marginRight = 0;
			$(this.entObj).css("padding","0");
            Cell.appendChild(document.createTextNode(MO_str_SuggestNoResult + " "));
            if (this.input.id.indexOf("Start") >= 0) {
                var From = this.input.value;
                var NameRe = /Start/gi;
                var ToId = this.input.id.replace(NameRe, "End");
                var To = document.getElementById(ToId).value;
            } else {
                var To = this.input.value;
                var NameRe = /End/gi;
                var FromId = this.input.id.replace(NameRe, "Start");
                var From = document.getElementById(FromId).value;
            }
            
            if (Sort == "ascending") {
                this.resultTable = resultTable;
            } else {
                this.resultTableDesc = resultTable;
            }
        }

        this.resultDiv = document.createElement("div");
        this.resultDiv.className = "SuggestResult_ins";

        this.resultDiv.appendChild(this.resultTable);
        this.entObj.appendChild(this.resultDiv);
        
        if (this.inFocus == true && this.Complite != true) {
            if (Sort == "descending")
                this.show();
        } else {
            if (CurrentQuery == this.TempValue) {
                this.setCurrentResult();
            }
        }
             
        if(typeof(this.ParObj.EndAirpInput) != 'undefined' && response.lenght > 0){
            this.ParObj.EndAirpInput.focus();
        }
    }
    
    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.dropCodeValue = function(){
        if(this.input.value != this.TempValue){
            this.Complite = false;
            this.CodeInput.value = '';
            this.dropTitle();
        }
    }
    Suggest.prototype.dropTitle = function(){
        if(this.input.value != this.TempValue){
            this.input.title = '';
            this.CodeInput.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){
            if(this.selectedRow != null){
                this.Complite = true;
                if(this.selectedRow.firstChild.className == 'airport') {
                    this.input.setAttribute('airport', 1);
                } else {
                    this.input.setAttribute('airport', 0);
                }
               
                this.input.value = this.selectedRow.firstChild.getAttribute("City");
                this.input.title = $(this.selectedRow.firstChild).text();
                this.CodeInput.value = this.selectedRow.lastChild.firstChild.data; 
                this.CodeInput.title = $(this.selectedRow.firstChild).text(); 
                               
                if (cur_domain != 'avia') {
                	$(this.CodeInput).addClass('hide');
                } 
                
                if (cur_domain == 'bus') {
                	$(this.input).data($(this.selectedRow).data());
                }
                
                this.TempValue = this.input.value;
                this.RowHover = false;
                this.ParObj.update();
            }
        }
    }
    Suggest.prototype.setEndInputFocus = function(){
        var re = /StartAirp/g;
        var EndAirpInputId = this.input.id.replace( re, 'EndAirp' );
        var EndAirpInput = document.getElementById(EndAirpInputId);
        EndAirpInput.focus();
        CurrentFocus = EndAirpInput;
    }
    Suggest.prototype.show = function(){
        var self = this;        
        this.isShow = true;
        
        $(".page").bind("click", function(){
            self.hide();
        });
        
        $(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 );
        
        if( (inputXY[0] + this.input.offsetHeight + this.entObj.offsetHeight - $(window).scrollTop() ) > windowHeight ){
            this.entObj.style.top = inputXY[0] - this.entObj.offsetHeight +"px";
            this.entObj.style.left = inputXY[1]+"px";
        } else {
            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 );
        }
    }
/* /Suggest */

