REQUEST_INTERVAL = 200;
/* Autosuggest Textbox written by Nicholas C. Zakas
   Taked from http://www.webreference.com/programming/javascript/ncz/ */
/*   Функциональность несколько расширена: добавлена фильтрация нажимаемых
   клавиш, Ajax-обмен с сервером предлагаемых значений, Ajax-проверка не
   является ли слово заблокированным в базе*/
/**
 * An autosuggest textbox control.
 * @class
 * @scope public
 */
function AutoSuggestControl(oTextbox /*:HTMLInputElement*/, 
                            oProvider /*:SuggestionProvider*/) {
    
    /**
     * The currently selected suggestions. //выбранное предложение
     * @scope private
     */   
    this.cur /*:int*/ = -1;

    /**
     * The dropdown list layer. //выпадающий список слоёв(уровней)
     * @scope private
     */
    this.layer = null;
    
    /**
     * Suggestion provider for the autosuggest feature./// поставшик предложений для автоматически предлагаемых  свойств(особенностей)
     * @scope private.
     */
    this.provider /*:SuggestionProvider*/ = oProvider;
    
    /**
     * The textbox to capture. //Текстбокс для ввода
     * @scope private
     */
    this.textbox /*:HTMLInputElement*/ = oTextbox;
    this.currentNodes = [];
    this.selectedNode = null;
    this.pressTimer = null;
    //initialize the control //устанавливать контроль(управление)
    this.init();
}

/**
 * Autosuggests one or more suggestions for what the user has typed.(писать, определять)
 * If no suggestions are passed in(проходить, передавать), then no autosuggest occurs.(происходить)
 * @scope private
 * @param aSuggestions An array of suggestion strings.
 * @param bTypeAhead If the control should provide a type ahead suggestion.
 */
AutoSuggestControl.prototype.autosuggest = function (aSuggestions /*:Array*/,bTypeAhead /*:boolean*/) 
{
//make sure there's at least one suggestion //удостоверится что есть хотя бы одно предложение

	if (aSuggestions.length > 0)
	{
	//alert(aSuggestions.length);
	
        	if (bTypeAhead)
		{
			this.typeAhead(aSuggestions[0]);
		}

		this.showSuggestions(aSuggestions);
	}
	else if(aSuggestions.name)
	{
		this.showSuggestions(aSuggestions.name);
		this.selectedNode = sSuggestion;
		this.showInputs();
	//this.comm[p].innerHTML = c.selectedNode.name
	//alert("funkcija 2");
	//this.typeAhead(aSuggestions.name[0]);
	}
/*	else if(aSuggestions.length = 0)
	{
		this.selectedNode = sSuggestion;
	}*/
	else
	{
		this.hideSuggestions();
	}

	this.currentNodes = aSuggestions;
};

/**
 * Creates the dropdown layer to display multiple suggestions. создается падающий слой(уровень) для показа большого количества предложений
 * @scope private
 */
AutoSuggestControl.prototype.createDropDown = function () {

    var oThis = this;

    //create the layer and assign styles // создание уровней и определение стилей
    this.layer = document.createElement("div");
    this.layer.className = "suggestions";
    this.layer.style.visibility = "hidden";
    this.layer.style.width = this.textbox.offsetWidth;
    
    //when the user clicks on the a suggestion,get the text(innerHTML)/когда клиент нажимает на предложение, получает текст
    //and place it into a textbox       // и помещается в текстбокс
    this.layer.onmousedown = 
    this.layer.onmouseup = 
    this.layer.onmouseover = function (oEvent)
    {
        oEvent = oEvent || window.event;
        oTarget = oEvent.target || oEvent.srcElement;

        if (oEvent.type == "mousedown")
	{
	oThis.textbox.value = oTarget.firstChild.nodeValue;
	var cSuggestionNodes = oThis.layer.childNodes;
	for (var i=0;i<cSuggestionNodes.length;i++)
		if (cSuggestionNodes[i] == oTarget) break;
		if (i==cSuggestionNodes.length) oThis.selectedNode = null;
		else oThis.selectedNode = oThis.currentNodes[i];

	oThis.updateInputs();
	//oThis.selectedNode = oThis.currentNodes[this.cur];
	//document.getElementById("kladr_regionType").innerHTML = oThis.selectedNode.id;
	oThis.hideSuggestions();
	
	if(oThis.selectedNode.level==5)
		{
		oThis.group.IndexFilling(oThis);
		return;
		}
        }
	else if (oEvent.type == "mouseover") 
	{
		oThis.highlightSuggestion(oTarget);
	}
	else
	{
            oThis.textbox.focus();
        }
    };

    document.body.appendChild(this.layer);
};

/**
 * Gets the left coordinate of the textbox.   //получение левой координаты текстбокса
 * @scope private
 * @return The left coordinate of the textbox in pixels. // возвращает левую координату текстбокса в пикселях
 */
AutoSuggestControl.prototype.getLeft = function () /*:int*/ {

    var oNode = this.textbox;
    var iLeft = 0;

    while(oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;
    }

    return iLeft;
};

/**
 * Gets the top coordinate of the textbox.     получение верхней координаты текстбокса
 * @scope private
 * @return The top coordinate of the textbox in pixels. // возвращает верхнюю координату текстбокса в пикселях
 */
AutoSuggestControl.prototype.getTop = function () /*:int*/ {

    var oNode = this.textbox;
    var iTop = 0;

    while(oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }

    return iTop;
};

AutoSuggestControl.prototype.getValue = function() {
    return this.textbox.value;
}

/**
 * Handles three keydown events. управление тремя событиями
 * @scope private
 * @param oEvent The event object for the keydown event. // объект "событие"...
 */
AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) {
    switch(oEvent.keyCode) {
        case 38: //up arrow  //стрелка вверх
            this.previousSuggestion();
            break;
        case 40: //down arrow //стрелка вниз
            this.nextSuggestion();
            break;
        case 13: //enter
		if(this.selectedNode.level==5)
		{
		this.group.IndexFilling(this);
		}
            this.group.focusNext(this);
        case 9:  //tab
        case 27: //esc
            this.hideSuggestions();
            break;
    }

};

/**
 * Handles keyup events. //управление кейап событиями
 * @scope private
 * @param oEvent The event object for the keyup event.
 */
AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {
    var oThis = this;
    function onTimer() {
        oThis.provider.requestSuggestions(oThis, true);
    }
    var iKeyCode = oEvent.keyCode
    //for backspace (8) and delete (46), shows suggestions without typeahead  
    if (iKeyCode == 8 || iKeyCode == 46) {
        this.selectedNode = null;
        clearTimeout(this.requestTimer);
        this.cur = -1;
        this.requestTimer = setTimeout(onTimer, REQUEST_INTERVAL);
    //make sure not to interfere with non-character keys  делать уверенным не мешать не буквенным клавишам
    } else if (iKeyCode>0 && iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
        //ignore
//	alert(iKeyCode)
    } else {
        clearTimeout(this.requestTimer);
        this.cur = -1;
        this.requestTimer = setTimeout(onTimer, REQUEST_INTERVAL);
 //request suggestions from the suggestion provider with typeahead /// запрашиваемые предложения от поставщика предложений
        this.selectedNode = null;
        this.updateInputs();
    }
};

/**
 * Hides the suggestion dropdown. скрывать падающие предложения
 * @scope private
 */
AutoSuggestControl.prototype.hideSuggestions = function () {
    this.layer.style.visibility = "hidden";
};

/**
 * Highlights the given node in the suggestions dropdown. ///  выделять заданный узел в списке предложений
 * @scope private
 * @param oSuggestionNode The node representing a suggestion in the dropdown.// узел представляющий предложение в выпадающем списке
 */
AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) {
    
    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i];
        if (oNode == oSuggestionNode) {
            oNode.className = "current"
        } else if (oNode.className == "current") {
            oNode.className = "";
        }
    }
};

/**
 * Initializes the textbox with event handlers for      //инициализировать текстбокс с событием обработчика для авто 
 * auto suggest functionality.   //предлагающего функцианальное назначение(выполняемые функции)..
 * @scope private
 */
AutoSuggestControl.prototype.init = function () {

    //save a reference to this object
    var oThis = this;       //сохранение ссылки на этот объект
    
    //assign the onkeyup event handler        устанавливать(назначать) обработчик события нажатия кнопки вверх
//    this.textbox.setAttribute("autocomplete", "off");
    this.textbox.onkeyup = function (oEvent) {
    
        //check for the proper location of the event object  //проверка правильного положения объкта события
        if (!oEvent) {
            oEvent = window.event;
        }    
        
        //call the handleKeyUp() method with the event object  // вызов функции нажатия клавиши вверх с помощью объекта событие
        oThis.handleKeyUp(oEvent);
    };
    
    // filtering
    this.textbox.onkeypress = function (oEvent) {
    	if (!oEvent) oEvent = window.event;
    	var keyCode = 0;
    	if (oEvent.which) keyCode = oEvent.which;
    	else if (oEvent.keyCode) keyCode = oEvent.keyCode;
    	if (keyCode!=0) {
    	    if (oThis.group.filter)
    		if (!oThis.group.filter(keyCode, oEvent.charCode)) {
    		    if (oEvent.preventDefault) oEvent.preventDefault();
    		    else oEvent.returnValue = false;
    		}
    	}
    }
    //assign onkeydown event handler            //установка обработчика собития кнопка вниз
    this.textbox.onkeydown = function (oEvent) {
        //check for the proper location of the event object     //проверка правильного положения объкта события
        if (!oEvent) {
            oEvent = window.event;
        }    
        
        //call the handleKeyDown() method with the event object
        oThis.handleKeyDown(oEvent);     // вызов функции нажатия клавиши вниз с помощью объекта событие
    };
    
    //create the suggestions dropdown    создание падающего списка предложений
    this.createDropDown();
};

/**
 * Highlights the next suggestion in the dropdown and    //выделение следующего предложения в списке
 * places the suggestion into the textbox.               //и размещение предложения в тектбоксе
 * @scope private
 */
AutoSuggestControl.prototype.nextSuggestion = function () {
    var cSuggestionNodes = this.layer.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) {
        var oNode = cSuggestionNodes[++this.cur];
        this.highlightSuggestion(oNode);
        this.textbox.value = oNode.firstChild.nodeValue;
        this.selectedNode = this.currentNodes[this.cur];
        this.updateInputs();
    }
};

/**
 * Highlights the previous suggestion in the dropdown and  //выделение предыдущего предложения в списке
 * places the suggestion into the textbox.                 //и размещение предложения в тектбоксе
 * @scope private
 */
AutoSuggestControl.prototype.previousSuggestion = function () {
    var cSuggestionNodes = this.layer.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur > 0) {
        var oNode = cSuggestionNodes[--this.cur];
        this.highlightSuggestion(oNode);
        this.textbox.value = oNode.firstChild.nodeValue;
        this.selectedNode = this.currentNodes[this.cur];
        this.updateInputs();
    }
};

AutoSuggestControl.prototype.updateInputs = function() {
    if (!this.group) return;
    if (this.selectedNode) this.group.showNextInput(this);
    else this.group.hideNextInputs(this);
}
AutoSuggestControl.prototype.showInputs = function() {
//	alert("showInputs");
    if (!this.group) {/*alert("!this.group");*/ return;}
    this.group.showNextInput(this);
// 	alert("this.group.showNextInput(this)");
if(this.selectedNode.level==5)
{
	this.group.IndexFilling(this);
}
}
AutoSuggestControl.prototype.needAutocomplete = function() {
    if (!this.group) return false;
    return this.group.needAutoComplete(this);
}

/**
 * Selects a range of text in the textbox.          // выбор области текста в текстбоксе
 * @scope public
 * @param iStart The start index (base 0) of the selection.
 * @param iLength The number of characters to select.
 */
AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iLength /*:int*/) {

    //use text ranges for Internet Explorer
    if (this.textbox.createTextRange) {
        var oRange = this.textbox.createTextRange(); 
        oRange.moveStart("character", iStart); 
        oRange.moveEnd("character", iLength - this.textbox.value.length);      
        oRange.select();
        
    //use setSelectionRange() for Mozilla
    } else if (this.textbox.setSelectionRange) {
        this.textbox.setSelectionRange(iStart, iLength);
    }     

    //set focus back to the textbox
    this.textbox.focus();      
}; 

/**
 * Builds the suggestion layer contents, moves it into position,  // создание содержимого слоя предложений, перемещение в
 * and displays the layer.                           // позиции, и вывод на экран слоя
 * @scope private
 * @param aSuggestions An array of suggestions for the control.
 */

AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/)
{
	var oDiv = null;
	this.layer.innerHTML = "";  //clear contents of the layer //отчистить содержимое слоя
	//alert(aSuggestions);

	for (var i=0; i < aSuggestions.length; i++)
	{
		oDiv = document.createElement("div");
		if (typeof aSuggestions[i] == "string")
			oDiv.appendChild(document.createTextNode(aSuggestions[i]));
		else
		{
			var s = aSuggestions[i];
			var text = this.provider.fieldToString(aSuggestions[i]);
			oDiv.appendChild(document.createTextNode(text));
		}
        this.layer.appendChild(oDiv);
	}

	this.layer.style.left = this.getLeft() + "px";
	this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px";
	this.layer.style.visibility = "visible";
};

/**
 * Inserts a suggestion into the textbox, highlighting the   // вставить предложение в текстбокс, выделить
 * suggested part of the text.                        	предложенную часть текста
 * @scope private
 * @param sSuggestion The suggestion for the textbox.
 */
AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) {

    //check for support of typeahead functionality    //проверка поддержки typeahead функциональности
    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
		
        var iLen = this.textbox.value.length;
        var text = this.provider.fieldToString(sSuggestion);
	//alert(sSuggestion);
        this.textbox.value = text;
	//alert(text.length);
        this.selectRange(iLen, text.length);
        this.selectedNode = sSuggestion;
        this.showInputs();
    }
};

