/**
*  jQuery JSON ccLiveSearch version 0.1
*  (c) 2010 Christian Schweinhardt
*
*  Creative Cubes - Schmidt & Schweinhardt GbR
*  http://www.creativecubes.de
*
*/
(function($){

    function ccLiveSearch(el, options){
        this.el = $(el);
        this.curValue = this.el.val();
        
        this.url = this.el.attr('url');
        this.queryvar = this.el.attr('query');
        this.targeturl = this.el.attr('targeturl');
        this.targetp = this.el.attr('targetp');
        this.art = this.el.attr('art');
        this.lang = this.el.attr('lang');
        
        this.onChangeInterval = null;
        this.intervalId = 0;
        this.options = {
            zindex : 99999,
            deferRequestBy : 0,
        }
        this.init();
        this.setOpts(options);
    }
    
    $.fn.cclivesearch = function(options) {
        return new ccLiveSearch(this.get(0)||$('<input />'), options);
    };
    
    ccLiveSearch.prototype = {
        kill: null,
        init : function(){
            var me, unique, liveSearchContainerId, liveSearchId;
            me = this;
            unique = Math.floor(Math.random()*0x100000).toString(16);
            liveSearchId = 'cc-livesearch-' + unique;
            this.liveSearchContainerId = 'cc-livesearch-container-' + unique;
            this.kill = function(e) {
                if ($(e.target).parents('.cclivesearch').size() === 0) {
                    me.killResults();
                    me.disableKill();
                }
            };
            
            $('<div>', {
                id : this.liveSearchContainerId,
                css : {
                    'position' : 'absolute',
                    'z-index' : this.options.zindex
                },
                html : '<div class="cclivesearch" id="' + liveSearchId + '" style="display: none;"></div>'
            }).appendTo('body');
            this.liveSearch = $('#' + liveSearchId);
            this.fixContainer();
            if (window.opera) {
                this.el.keypress(function(e) { me.onKeyPress(e); });
            } else {
                this.el.keydown(function(e) { me.onKeyPress(e); });
            }
            this.el.keyup(function(e) { me.onKeyUp(e); });
            this.el.blur(function() { me.enableKill(); });
            this.el.focus(function() { me.fixContainer(); });
        },
        
        setOpts : function(options){
            var o = this.options;
            $.extend(o, options);
        },
        
        enableKill: function() {
            var me = this;
            $(document).bind('click', me.kill);
        },
        
        disableKill: function() {
            var me = this;
            $(document).unbind('click', me.kill);
        },
        
        killResults: function() {
            var me = this;
            this.stopKillResults();
            this.intervalId = window.setInterval(function() {
                me.hide();
                me.stopKillResults();
            }, 300);
        },
        
        stopKillResults: function() {
            window.clearInterval(this.intervalId);
        },
        
        enabled : function() {
            this.disabled = false;
        },
        
        disable : function() {
            this.disabled = true;
        },
        
        onKeyPress: function(e) {
            if (this.disabled || !this.enabled) { return; }
            switch (e.keyCode) {
                case 27: //KEY_ESC:
                    this.el.val(this.curValue);
                    this.hide();
                    break;
                default:
                    return;
            }
            e.stopImmediatePropagation();
            e.preventDefault();
        },
        
        onKeyUp : function(e){
            if (this.disabled){ return; }
            
            switch (e.keyCode) {
                case 38:
                case 40:
                    return;
            }
            
            clearInterval(this.onChangeInterval);
            if (this.currentValue !== this.el.val()) {
                if (this.options.deferRequestBy > 0) {
                    var me = this;
                    this.onChangeInterval = setInterval(function() {
                        me.onChangeValue();
                    }, this.options.deferRequestBy);
                } else {
                    this.onChangeValue();
                }
            }
        },
        
        fixContainer : function() {
            var offset = this.el.offset();
            $('#' + this.liveSearchContainerId).css({
                top : (offset.top + this.el.innerHeight()) + 'px', 
                left : offset.left + 'px'
            });
        },
        
        onChangeValue : function() {
            this.curValue = this.el.val();
            var query = this.curValue;
            
            if (query == '') { this.hide(); } 
            if (query != '' && query.length > 1) { this.getResults(query) }
        },
        
        getResults : function(query) {
            var q, me;
            me = this;
            q = query;
            $.getJSON(this.url + '?' + this.queryvar + '=' + q, function (results) {
                me.renderResults(results);
            });
        },
        
        renderResults : function(results) {
            var r;
            r = results;
            r.sort();
            
            if (r.length === 0) {
                this.hide();
                return;
            }
            
            this.liveSearch.hide().empty();
            
            switch (this.art) {
                case 'product':
                    for (var i = 0; i < r.length; i++) {
                        var input, stronginput, name, resultname, catentry, urlparam;
                            input = this.el.val();
                            input = input.toLowerCase()
                            stronginput = '<strong>' + input + '</strong>';
                            // Nur den Namen der aktuellen Sprache Liefern
                            if (this.lang == 'en') { name = r[i].name_en; }
                            else if (this.lang == 'fr') { name = r[i].name_fr; }
                            else if (this.lang == 'es') { name = r[i].name_es; }
                            else { name = r[i].name; }
                            catentry = r[i].catalogue_entry;
                            name = name.toLowerCase();
                            resultname = name.replace(input, stronginput);
                            urlparam = '?' + this.targetp + '=' + r[i].id;
                        
                        if (r[i].parent) {
                            urlparam = urlparam = '?' + this.targetp + '=' + r[i].parent.id + '&first_parent_id=' + r[i].id;
                            if (r[i].parent.parent) {
                                urlparam = urlparam = '?' + this.targetp + '=' + r[i].parent.parent.id + '&first_parent_id=' + r[i].parent.id + '&second_parent_id=' + r[i].id;
                            }
                        }
                        
                        if (i <= 25) {
                            $('<div>', {
                                html : '<a href="' + this.targeturl + urlparam + '">' + resultname + '</a>'
                            }).appendTo(this.liveSearch);
                        }
                    }
                    break;
                    
                case 'company':
                    for (var i = 0; i < r.length; i++) {
                        var input, stronginput, name, resultname, catentry, targeturl, letter;
                            input = this.el.val();
                            input = input.toLowerCase()
                            stronginput = '<strong>' + input + '</strong>';
                            name = r[i].name;
                            catentry = r[i].catalogue_entry;
                            name = name.toLowerCase();
                            resultname = name.replace(input, stronginput);
                            letter = r[i].order.substring(0,1);
                            letter = letter.toUpperCase();
                            if (catentry == false) {
                                targeturl = '/company-index/#' + letter;
                            } else {
                                targeturl = this.targeturl + '?' + this.targetp + '=' + r[i].id;
                            }
                            
                        if (i <= 25) {
                            $('<div>', {
                                html : '<a href="' + targeturl + '">' + resultname + '</a>'
                            }).appendTo(this.liveSearch);
                        }
                    }
                    break;
            }
            
            this.enabled = true;
            this.liveSearch.show();
        },
        
        hide : function() {
            this.enabled = false;
            this.liveSearch.hide();
        },
    }
}(jQuery));
