$.questionSearch = {
    _lastQuery: 'this is last query',
    _stopTimer: null,
    _questionList: null,
    _active: -1,
    _questionArray: Array(),
    _jsonQuestions: null,
    getLastQuery: function () {
        return this._lastQuery;
    },
    setLastQuery: function (q) {
        return this._lastQuery = q;
    },
    removeList: function () {
        if (this._questionList) {
            this._questionList.remove();
            this._questionList = null;
        }
    },
    createList: function (holder) {
        if (!this._questionList) {
            this._questionList = $('<div class="firmSearchList"></div>');
            this._questionList.css({
                margin: '0',
                padding: '0',
                position: 'absolute',
                zIndex: '10000'
            });
            //position and width
            if (holder) {
                var holderPos = holder.offset({
                    margin: true,
                    padding: false,
                    border: false
                });
                this._questionList.css({
                    width: (holder.outerWidth()) + 'px',
                    top: (holderPos.top + holder.outerHeight()) + 'px',
                    left: holderPos.left + 'px'
                });
            }
            $(document.body).append(this._questionList);
            //odstranit list ked sa klikne mimo
            this._questionList.mouseup(function () {
                return false;
            });
            $(document).one('mouseup',function () {
                $.questionSearch.removeList();
            });
        }
    },
    createList2: function () {
        if (!this._questionList) {
            this._questionList = $('#similarQuestion');
        }
    },
    _showError: function (msg) {
        this._createListObject('error').text(msg);
    },
    _createListObject: function (clsnm) {
        if (typeof(clsnm) == 'undefined') {
            clsnm = 'firmListEntry';
        }
        var listObject = $('<div class="' + clsnm + '"></div>');
        listObject.hover(function () {
            $(this).addClass(clsnm + 'Hover');
        },function () {
            $(this).removeClass(clsnm + 'Hover');
        });
        
        this._questionArray.push(listObject);
        return listObject.appendTo(this._questionList);
        
    },
    getQuestions: function (q,params) {
        var self = this;
        if (!this.isTimerRunnig()) {
            this.startTimer();
            $.getJSON(Router('joblife/advice/search-json'),{
                q: q,
                limit: params.limit
            },function (jsonList) {
                self._questionList.empty();
                if (jsonList.error) {
                    self._showError(jsonList.error);
                } else {
                    self._jsonQuestions = jsonList.questions;
                    self._showQuestions(jsonList.questions,params);
                    self._showCategory(jsonList.category);
                }
            });
        }
    },
    _showCategory:function (categories) {
        
        $('#zoznamnavrhov').empty();
        
        var category;
        var categoryObj = [];
        var i;
        var self = this;
        
        if (categories.length) {
            $.each(categories,function (idx,categoryObj) {
                category = "<input type='radio' name='advice_category_navrh' value='"+categoryObj.id+"' />"+categoryObj.name+"<br />";
                $('#zoznamnavrhov').append(category);
            });
        }
    },
    _showQuestions: function (questions,params) {
        var question;
        var questionObj = [];
        var i;
        var self = this;
        if (questions.length) {
            this._questionList.show();
            $.each(questions,function (idx,questionObj) {
                question = self._createListObject();
                question.text(questionObj.name);
                question.attr('rel',questionObj.id);
                question.click(function () {
                    $.questionSearch.removeList();
                    if (typeof(params.onSelect) == 'function') {
                        params.onSelect(params._holder,questionObj);
                    }
                });
            });
        } else {
            this._questionList.hide();
        }
    },
    resetTimer: function () {
        this._stopTimer = null;
    },
    isTimerRunnig: function () {
        return this._stopTimer;
    },
    startTimer: function () {
        var self = this;
        this._stopTimer = window.setTimeout(function () {
            self.resetTimer();
        },250);
    },
    moveSelect: function (step) {
        clsnm = 'firmListEntry';
		this._active += step;
        
		if (this._active < 0) {
			this._active = 0;
		} else if (this._active >= this._questionArray.length) {
			this._active = this._questionArray.length - 1;
		}
        
		$('.firmListEntryHover').removeClass(clsnm + 'Hover');
        
		$(this._questionArray[this._active]).addClass(clsnm + 'Hover');
    },
    selectCurrent: function (params) {
        $.questionSearch.removeList();
        var self = this;
        
        if (typeof(params.onSelect) == 'function') {
            setTimeout(function() { 
                params.onSelect(params._holder,self._jsonQuestions[self._active]);
            }, 1);
        }
    }
};
$.fn.questionSearch = function (params) {
    params = $.extend({
        _holder: this,
        // onselect = fumkcia ktora sa zavola, ked sa klikne na questionu function (holder,questiona)
        onSelect: null,
        limit: 5
    },params);
    //this - jquery objekt na ktore sa to vztahuje
    var self = this;
    
    self.attr("autocomplete", "off");
    
    //pridame udalosti
    this.keyup(function(e) {
		switch(e.keyCode) {
			case 38: // up
				e.preventDefault();
				$.questionSearch.moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				$.questionSearch.moveSelect(1);
				break;
			case 13: // return
                e.preventDefault();
                $.questionSearch.selectCurrent(params);
				break;
			default:
				q = self.val();
                if (q.length >= 3 && $.questionSearch.getLastQuery() != q) {
                    $.questionSearch._jsonQuestions = null;
                    $.questionSearch._questionArray.length = null;
                    $.questionSearch._questionArray = Array();
                    $.questionSearch._active = -1;
                    $.questionSearch.createList(self);
                    $.questionSearch.getQuestions(q,params);
                    $.questionSearch.setLastQuery(q);
                }
				break;
		}
	});
    // this.keyup(function () {
    //     q = self.val();
    //     if (q.length >= 3 && $.questionSearch.getLastQuery() != q) {
    //         $.questionSearch.createList(self);
    //         $.questionSearch.getQuestions(q,params);
    //         $.questionSearch.setLastQuery(q);
    //     }
    // });
    return this;
}
$.fn.similarQuestionSearch = function (params) {
    params = $.extend({
        _holder: null,
        // onselect = fumkcia ktora sa zavola, ked sa klikne na questionu function (holder,questiona)
        onSelect: null,
        limit: 5
    },params);
    //this - jquery objekt na ktore sa to vztahuje
    var self = this;
    
    self.attr("autocomplete", "off");
    
    //pridame udalosti
    this.keyup(function () {
        q = self.val();
        if (q.length >= 3 && $.questionSearch.getLastQuery() != q) {
            $.questionSearch.createList2();
            $.questionSearch.getQuestions(q,params);
            $.questionSearch.setLastQuery(q);
        }
    });
    return this;
}
$.fn.similarQuestionSearch2 = function (params) {
    params = $.extend({
        _holder: null,
        // onselect = fumkcia ktora sa zavola, ked sa klikne na questionu function (holder,questiona)
        onSelect: null,
        limit: 5
    },params);
    //this - jquery objekt na ktore sa to vztahuje
    var self = this;
    
    self.attr("autocomplete", "off");
    
    //pridame udalosti
        q = self.val();
        if (q.length >= 3 && $.questionSearch.getLastQuery() != q) {
            $.questionSearch.createList2();
            $.questionSearch.getQuestions(q,params);
            $.questionSearch.setLastQuery(q);
        }
    return this;
}
