/**
 * @author Nguyen Duc Thuan <me@ndthuan.com>
 */


function WordSuggestion(url, oForm, oText, oDiv, wordSeperator){
    this.oForm = oForm;
    this.oText = oText;
    this.oDiv = oDiv;
    this.url = url;
    this.currentIndex = -1;
    this.maxIndex = -1;
    this.wordSeperator = wordSeperator;
    this.formSubmit = this.oForm.getAttribute('onsubmit');
    this.init();
}

WordSuggestion.prototype = {
    init: function(){
        var obj = this.oText;
        var top = left = 0;
        
        if (obj.offsetParent) {
            do {
                top += obj.offsetTop;
                left += obj.offsetLeft;
            }
            while (obj = obj.offsetParent);
        }
        
        this.oDiv.style.left = left + 'px';
        this.oDiv.style.top = Number(top + this.oText.offsetHeight) + 'px';
        this.oDiv.style.width = this.oText.offsetWidth - 2 + 'px';
        this.oDiv.style.background = '#fff';
        
        var p = this;
        this.oText.onblur = function(){
            if (p.currentIndex < 0) {
                p.hideSuggestions();
            }
        }
        
        this.oText.onkeyup = function(event){
            p.checkKey(event);
        };
    },
    
    enableForm: function(){
        var p = this;
        this.oForm.onsubmit = function(){
            return eval(p.formSubmit.replace(/return\s+/g, ''));
        };
    },
    
    checkKey: function(e){
        e = e ? e : window.event;
        var keyCode = e.keyCode ? e.keyCode : e.which;
        var word = this.oText.value.trim();//.replace(/^\W+/, '').replace(/\W+$/, '');
        if (this.currentIndex > -1) {
            this.oForm.onsubmit = function(){
                return false;
            };
        }
        if (27 === keyCode || 13 === keyCode) {
            this.hideSuggestions();
            this.enableForm();
        }
        else 
            if (keyCode !== 37 && keyCode !== 38 && keyCode !== 39 && keyCode !== 40) {
                if (word.length < 1) {
                    this.hideSuggestions();
                }
                else {
                    this.request(word);
                }
            }
            else 
                if ('visible' === this.oDiv.style.visibility && (38 === keyCode || 40 === keyCode)) {
                    if (-1 !== this.currentIndex) {
                        this.setNonSelected($('suggest_' + this.currentIndex));
                    }
                    if (38 === keyCode) {
                        if (this.currentIndex <= 0) {
                            this.currentIndex = this.maxIndex;
                        }
                        else {
                            this.currentIndex--;
                        }
                    }
                    else 
                        if (40 === keyCode) {
                            if (this.currentIndex >= this.maxIndex) {
                                this.currentIndex = 0;
                            }
                            else {
                                this.currentIndex++;
                            }
                        }
                    this.setSelected($('suggest_' + this.currentIndex));
                }
    },
    
    request: function(word){
        Ducthuans.Ajax.initHandlers();
        Ducthuans.Ajax.setConfig({
            'url': this.url + '?k=' + encodeURIComponent(word),
            'method': 'GET',
            'isAsync': true
        });
        var obj = this;
        Ducthuans.Ajax.addHandler('onSucceed', function(){
            obj.show();
        });
        Ducthuans.Ajax.send();
    },
    
    show: function(){
        this.oDiv.innerHTML = '';
        this.enableForm();
        var string = Ducthuans.Ajax.responseText.trim();
        var stringArray = string.split(this.wordSeperator);
        if (string != '' && stringArray.length > 0) {
            this.maxIndex = stringArray.length - 1;
            for (var key = 0, word; word = stringArray[key]; key++) {
                var div = document.createElement('div');
                var obj = this;
                div.onmouseover = function(){
                    obj.setSelected(this, true);
                    obj.enableForm();
                };
                div.onmouseout = function(){
                    obj.setNonSelected(this);
                    obj.currentIndex = -1;
                    obj.enableForm();
                };
                div.onclick = function(){
                    obj.oText.value = this.innerHTML;
                    obj.hideSuggestions();
                    obj.enableForm();
                };
                div.style.padding = '2px';
                div.style.textAlign = 'left';
                div.id = 'suggest_' + key;
                div.style.cursor = 'default';
                div.appendChild(document.createTextNode(stringArray[key]));
                this.oDiv.appendChild(div);
            }
            this.oDiv.style.visibility = 'visible';
        }
    },
    
    hideSuggestions: function(){
        this.oDiv.style.visibility = 'hidden';
        this.currentIndex = -1;
    },
    
    setSelected: function(div, dontSetValue){
        if (this.currentIndex > -1) {
            this.setNonSelected($('suggest_' + this.currentIndex));
        }
        this.currentIndex = div.id.replace(/^suggest_/, '');
        div.style.color = '#fff';
        div.style.background = '#4369c4';
        if (!dontSetValue) {
            this.oText.value = div.innerHTML;
        }
    },
    
    setNonSelected: function(div){
        div.style.color = '#000';
        div.style.background = '#fff';
    }
};
