function Suggest(id)
{
    this._id = id; // Session id
    this._timeout = 2000;
    this._activeElement = null; // Focused input field
    this._initialText = '';
    this._elements = [];
    this._list = null; // Dropdown list
    this._listHolder = null;
    this._aDelimChars = [" ", ","]; // Address separators
    this._extractedText = '';
    this._extractedStart = 0;
    this._extractedEnd = 0;
    this._listPosition = 0;
    this._xml = {};
    this._enterPressed = false;

    var _me = this;

    this.init = function()
    {
        if(document.addEventListener) {
            document.addEventListener('click', this.processClick, false);
        } else {
            document.attachEvent('onclick', this.processClick);
        }
    }

    this.processClick = function(e)
    {
        _me.hideList();
    }

    this.bindElement = function(el)
    {
        this._elements.push(el);

        // Enter key processing for form submit
        // preventing
        if(navigator.userAgent.indexOf("Opera") != -1) {
            el.onkeypress = this.processEnterKey;
        } else {
            el.onkeydown = this.processEnterKey;
        }

        // Suggest process
        el.onkeyup = this.processKeyEvent;

        el.onblurs = function(e) {

            if (!e) e = window.event;

            alert(e.currentTarget);
            var oInp = e.target ? e.target : e.srcElement;
            oInp = oInp.nodeType == 3 ? oInp.parentNode : oInp;

            _me.hideList();
            _me._initialText = '';
        }

        el.onfocus = function(e)
        {
            if (!e) e = window.event;

            var oInp = e.target ? e.target : e.srcElement;
            oInp = oInp.nodeType == 3 ? oInp.parentNode : oInp;

            _me._initialText = oInp.value;
            _me.rewindListPosition();
        }
    }

    this.processEnterKey = function(e)
    {
        if (!e) e = window.event;        

        if(e.keyCode == 13) {
            Event.stop(e);
            _me._enterPressed = true;
            _me.appendAddressByEnter();
            _me.hideList();
            return false;
        }
    }

    this.processKeyEvent = function(e)
    {
        if ( _me._enterPressed ) {
            _me._enterPressed = false;
            return;
        }
        if (!e) e = window.event;

        var oInp = e.target ? e.target : e.srcElement;
        oInp = oInp.nodeType == 3 ? oInp.parentNode : oInp;

        if(_me.trim(oInp.value) == '') {
            _me.hideList();
            return;
        }

        _me._initialText = oInp.value;

        // Escapable keys. We should skip them
        var nKeyCode = e.keyCode;

        if ((nKeyCode == 9)  || // tab
        (nKeyCode == 16) || (nKeyCode == 17) || // shift, ctl
        (nKeyCode >= 18 && nKeyCode <= 20) || // alt,pause/break,caps lock
        (nKeyCode == 27) || // esc
        (nKeyCode >= 33 && nKeyCode <= 35) || // page up,page down,end
        (nKeyCode >= 36 && nKeyCode <= 37 ) || // home,left,right
        (nKeyCode == 39) ||
        (nKeyCode >= 44 && nKeyCode <= 45)) { // print screen,insert
            return true;
        }

        // List scrolling
        if(nKeyCode == 38 || nKeyCode == 40) {
            _me.scrollList(nKeyCode == 40);
        }

        // Suggesting
        else {
            var nCaretPosition = _me.getCaretPosition(oInp);
            var sUserText = _me.extractText(oInp.value, nCaretPosition);

            if(sUserText != '') {
                _me._extractedText = sUserText;
                _me._activeElement = oInp;
                _me.suggestTry(sUserText);
                _me.rewindListPosition();
            } else {
                _me.hideList();
            }
        }
    }

    this.scrollList = function(bDown)
    {
        var oList = this.getList();
        var nTotalItems = oList.childNodes[0].childNodes.length;

        var nNewPosition = this._listPosition + (bDown ? 1 : -1);
        if(nNewPosition <= 0 || nNewPosition > nTotalItems) {
            return false;
        }

        for(var i=0; i<nTotalItems; i++) {
            if(i+1 == nNewPosition) {
                oList.childNodes[0].childNodes[i].className = 'active';
            } else {
                oList.childNodes[0].childNodes[i].className = '';
            }
        }

        this._listPosition = nNewPosition;
    }

    this.appendAddressByEnter = function()
    {
        if(this._listPosition) {

            var aLis = this.getList().childNodes[0].childNodes;
            if(aLis.item(this._listPosition-1)) {
                var sValue = aLis.item(this._listPosition-1).childNodes[0].innerHTML;
                this.appendAddress(sValue);
            }
        }

        return false;
    }

    this.appendAddressByClick = function()
    {
        if(this.tagName && this.tagName == 'A') {
            _me.appendAddress(unescape(this.innerHTML));
        }

        return false;
    }

    this.getCaretPosition = function(oObj)
    {
        if(oObj.selectionStart) {
             return oObj.selectionStart;
        } else if(!document.selection) {
            return 0;
        }

        // Set focus on the element
        oObj.focus ();

        // To get cursor position, get empty selection range
        var oSel = document.selection.createRange();

        // Move selection start to 0 position
        oSel.moveStart ('character', -oObj.value.length);

        // The caret position is selection length
        nCaretPos = oSel.text.length;

        return nCaretPos;
    }

    this.suggestTry = function(sPart)
    {
        sPart = sPart.replace(/[<>]+/m,'').toLowerCase();
        if(sPart == '') return;
        
        var chr = sPart.charAt(0);
        
        // Under request
        if ( this._xml[chr] === 1 ) return;

        // exists
        if ( typeof this._xml[chr] == 'object' ) return this._draw(sPart);
        
        // do request
        this._xml[chr] = 1;
        new Ajax.Request('/adb/suggest/', {
            method: 'post',
            parameters: {part: encodeURIComponent(chr)},
            onSuccess: function(tr) {
                _me._xml[chr] = tr.responseXML;
                if (typeof(_me._xml[chr].setProperty) != 'undefined') {
                    _me._xml[chr].setProperty('SelectionLanguage', 'XPath');
                   }
                _me._draw(sPart);
            }
        });
    }

    this._translit = function(str)
    {
        var ruChars = ["ц", "ч", "ш", "щ", "ъ", "ы", "ь", "э", "ю", "я", "а", "б", 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х'];
        var enChars = ['ts', 'ch', 'sh', 'shh', "'", 'y', "'", 'e', 'yu', 'ya', 'a', 'b', 'v', 'g', 'd', 'e', 'jo', 'zh', 'z', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h'];
        for(var i=0; i<ruChars.length; i++) {
            str = str.replace( new RegExp(ruChars[i]), enChars[i] );
        }
        return str;
    };

    this._draw = function(s)
    {
        s = s.toLowerCase();
        if (!s) return;
        var chr = s.charAt(0);
        var xml = this._xml[chr];
        if ( typeof xml != 'object' ) return;
        var ts = this._translit(s);
        var nodes = xml.selectNodes('/contacts/contact['+
            'starts-with(@emailLower,"'+s+'") or starts-with(@emailLower,"'+ts+'") or '+
            'starts-with(@nameLower,"'+s+'") or starts-with(@nameLower,"'+ts+'") or '+
            'starts-with(@name2Lower,"'+s+'") or starts-with(@name2Lower,"'+ts+'") or '+
            'starts-with(@nickLower,"'+s+'") or starts-with(@nickLower,"'+ts+'")'+
            ']');
        
        this.clearList();
        var oList = this.getList().childNodes[0];
        var count = Math.min(nodes.length, 10);
        for(var i=0; i<count; i++) {
            var oLi = document.createElement('li');
            var oA = document.createElement('a');
            var nick = nodes[i].getAttribute('nick');
            var email = nodes[i].getAttribute('email'); 
            oA.innerHTML = nick ? nick+' &lt;'+email+'&gt;': email;
            oA.setAttribute('href', '#');
            oA.onclick = _me.appendAddressByClick;

            oLi.appendChild(oA);
            oList.appendChild(oLi);
        }

        nodes.length ? _me.showList() : _me.hideList();
    };

    // Extracts user input from whole string.
    // Separators used.
    this.extractText = function(sUserText, nCursorPos)
    {
        //var aDelimChars = this._aDelimChars;
        var posStart = nCursorPos-1;

        if(this.isDelim(sUserText.charAt(posStart))) return '';

        var ch = sUserText.charAt(posStart);
        while(posStart > 0)
        {
            if(this.isDelim(sUserText.charAt(posStart-1))) break;
            posStart--;
        }

        var len = sUserText.length;
        var posEnd = posStart + 1;
        while(posEnd < len) {
            if(this.isDelim(sUserText.charAt(posEnd))) break;
            posEnd++;
        }

        this._extractedStart = posStart;
        this._extractedEnd = posEnd;

        var extracted = sUserText.substr(posStart, posEnd - posStart);
        extracted = (extracted.length == 1 && this.isDelim(extracted)) ? '' : extracted;

        return this.trim(extracted);
    }

    this.isDelim = function(cChr)
    {
        var aDelimChars = this._aDelimChars;
        for(var i=0, len=aDelimChars.length; i<len; i++) {
            if(aDelimChars[i] == cChr) {
                return true;
            }
        }

        return false;
    }

    this.getList = function()
    {
        if( ! this._list ) {
            this._list = document.createElement('div');
            this._list.className = 'suggestwrap';
            var oUl = document.createElement('ul');
            oUl.className = 'suggest';
            this._list.appendChild(oUl);
        }

        return this._list;
    }

    this.clearList = function()
    {
        var oList = this.getList().childNodes[0];

        while(oList.childNodes.length) {
            oList.removeChild(oList.childNodes[0]);
        }
    }

    this.showList = function()
    {
        this._activeElement.parentNode.parentNode.insertBefore(this.getList(), this._activeElement.nextSibling);
        this.getList().style.display = 'block';
    }

    this.hideList = function()
    {
        this.getList().style.display = 'none';
    }

    this._nullFunc = function()
    {
        return false;
    }

    this.trim = function(sStr)
       {
         s = sStr.replace(/^(\s)*/, '');
         s = s.replace(/(\s)*$/, '');
         return s;
       }

       this.rewindListPosition = function()
       {
           this._listPosition = 0;
       }

    this.appendAddress = function(sValueToAppend)
    {
        _me.hideList();

        var oEl = this._activeElement;

        sValueToAppend = sValueToAppend.replace('&gt;', '>');
        sValueToAppend = sValueToAppend.replace('&lt;', '<');
        sValueToAppend = sValueToAppend.replace('&quot;', '"');

        var nStartPos = this._extractedStart;
        var nEndPos = this._extractedEnd;

        var sExtracted = this._extractedText;
        var sValue = oEl.value;

        var sStrBefore = sValue.substr(0, nStartPos);
        var sStrAfter = sValue.substr(nEndPos);

        // Should we place a comma before
        var bNeedCommaBefore = false;
        for(var i=nStartPos-1; i>0; i--) {
            if(sValue.charAt(i) != " ") {
                if(sValue.charAt(i) != ",") {
                    bNeedCommaBefore = true;
                }

                break;
            }
        }

        if(bNeedCommaBefore) {
            sValueToAppend = ', ' + sValueToAppend;
        } else {
            sValueToAppend = ' ' + sValueToAppend;
        }

        // Should we place a comma after
        var bNeedCommaAfter = false;
        for(var i=nEndPos+1, len=sValue.length; i<len; i++) {
            if(sValue.charAt(i) != " ") {
                if(sValue.charAt(i) != ",") {
                    bNeedCommaAfter = true;
                }

                break;
            }
        }

        if(bNeedCommaAfter) {
            sValueToAppend += ', ';
        } else {
            sValueToAppend += ' ';
        }

        oEl.value = _me.trim(sStrBefore + sValueToAppend + sStrAfter);
    }
};
