/*
 * jQuery ScrutariSuggestion plugin
 *
 * Copyright (c) 2010 Vincent Calame - Exemole
 *
 * Derivated from jQuery Autocomplete plugin 1.1
 *
 * Copyright (c) 2009 Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
 */

;(function($) {
        
$.fn.extend({
        scrutarisuggestion: function(url, options) {
                options = $.extend({}, $.ScrutariSuggereur.defaults, {url: url}, options);
                SCTJS_BaseData.initBaseDataMap(url, options.langUi);
                return this.each(function() {
                        new $.ScrutariSuggereur(this, options);
                });
        },
        setOptions: function(options){
                return this.trigger("setOptions", [options]);
        }
});

$.ScrutariSuggereur = function(input, options) {

        var KEY = {
                UP: 38,
                DOWN: 40,
                DEL: 46,
                TAB: 9,
                RETURN: 13,
                ESC: 27,
                COMMA: 188,
                PAGEUP: 33,
                PAGEDOWN: 34,
                BACKSPACE: 8
        };

        // Create $ object for input element
        var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

        var timeout;
        var previousValue = "";
        var hasFocus = 0;
        var lastKeyPressCode;
        var config = {
                mouseDownOnSelect: false
        };
        var select = $.ScrutariSuggereur.Select(options, input, selectCurrent, config);
        
        var blockSubmit;
        
        // prevent form submit in opera when selecting with return key
        $.browser.opera && $(input.form).bind("submit.autocomplete", function() {
                if (blockSubmit) {
                        blockSubmit = false;
                        return false;
                }
        });
        
        // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
        $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
                // a keypress means the input has focus
                // avoids issue where input had focus before the autocomplete was applied
                hasFocus = 1;
                // track last key pressed
                lastKeyPressCode = event.keyCode;
                switch(event.keyCode) {
                
                        case KEY.UP:
                                event.preventDefault();
                                if ( select.visible() ) {
                                        select.prev();
                                } else {
                                        onChange(0, true);
                                }
                                break;
                                
                        case KEY.DOWN:
                                event.preventDefault();
                                if ( select.visible() ) {
                                        select.next();
                                } else {
                                        onChange(0, true);
                                }
                                break;
                                
                        case KEY.PAGEUP:
                                event.preventDefault();
                                if ( select.visible() ) {
                                        select.pageUp();
                                } else {
                                        onChange(0, true);
                                }
                                break;
                                
                        case KEY.PAGEDOWN:
                                event.preventDefault();
                                if ( select.visible() ) {
                                        select.pageDown();
                                } else {
                                        onChange(0, true);
                                }
                                break;
                        
                        case KEY.TAB:
                        case KEY.RETURN:
                                if( selectCurrent() ) {
                                        // stop default to prevent a form submit, Opera needs special handling
                                        event.preventDefault();
                                        blockSubmit = true;
                                        return false;
                                }
                                break;
                                
                        case KEY.ESC:
                                select.hide();
                                break;
                                
                        default:
                                clearTimeout(timeout);
                                timeout = setTimeout(onChange, options.delay);
                                break;
                }
        }).focus(function(){
                // track whether the field has focus, we shouldn't process any
                // results if the field no longer has focus
                hasFocus++;
        }).blur(function() {
                hasFocus = 0;
                if (!config.mouseDownOnSelect) {
                        hideResults();
                }
        }).click(function() {
                // show select when clicking in a focused field
                if ( hasFocus++ > 1 && !select.visible() ) {
                        onChange(0, true);
                }
        }).bind("setOptions", function() {
                $.extend(options, arguments[1]);
                SCTJS_BaseData.initBaseDataMap(options.url, options.langUi);
        });
        
        
        function selectCurrent() {
                var selectedInfo = select.getSelectedInfo();
                if( !selectedInfo) return false;
                var quotedSelectedLib = "\"" + selectedInfo.lib + "\"";
                previousValue = quotedSelectedLib;
                $input.val(quotedSelectedLib);
                hideResultsNow();
                if (options.submitOnSelect.length && options.submitOnSelect.length > 0) {
                    if (options.supermotcleInput.length && options.supermotcleInput.length > 0) {
                        $(options.supermotcleInput).val(options.langUi + "/" + selectedInfo.cdsmc);
                    }
                    $(options.submitOnSelect).submit();
                }
                return true;
        }
        
        function onChange(crap, skipPrevCheck) {
                if( lastKeyPressCode == KEY.DEL ) {
                        select.hide();
                        return;
                }
                
                var currentValue = $input.val();
                
                if ( !skipPrevCheck && currentValue == previousValue )
                        return;
                
                previousValue = currentValue;

                if ( currentValue.length >= options.minChars) {
                        $input.addClass(options.loadingClass);
                        request(currentValue, receiveObjetResultat, hideResultsNow);
                } else {
                        stopLoading();
                        select.hide();
                }
        };
        
        function hideResults() {
                clearTimeout(timeout);
                timeout = setTimeout(hideResultsNow, 200);
        };

        function hideResultsNow() {
                var wasVisible = select.visible();
                select.hide();
                clearTimeout(timeout);
                stopLoading();
        };

        function receiveObjetResultat(chaineRecherche, objetResultat) {
                var done = false;
                if (objetResultat && hasFocus) {
                    var supermotcleSearchResult = null;
                    if (objetResultat.supermotcleSearchResult) {
                        supermotcleSearchResult = objetResultat.supermotcleSearchResult;
                    } else if (objetResultat.motcleSearchResult) {
                        supermotcleSearchResult = objetResultat.motcleSearchResult;
                    }
                    if (supermotcleSearchResult) {
                        stopLoading();
                        select.display(objetResultat.supermotcleSearchResult, chaineRecherche);
                        select.show();
                        done = true;
                    }
                }
                if (!done) {
                    hideResultsNow();
                }
        };

        function request(chaineRecherche, fonctionSucces, fonctionEchec) {
                       
                        var extraParams = {
                                timestamp: +new Date()
                        };
                        $.each(options.extraParams, function(key, param) {
                                extraParams[key] = typeof param == "function" ? param() : param;
                        });
                         $.ajax({
                                // try to leverage ajaxQueue plugin to abort previous requests
                                mode: "abort",
                                // limit abortion to this input
                                port: "autocomplete" + input.name,
                                dataType: "jsonp",
                                url: options.url,
                                data: $.extend({
                                        type: "q-supermotcle",
                                        langui: options.langUi,
                                        q: chaineRecherche,
                                        limit: options.limit
                                }, extraParams),
                                success: function(objetResultat) {
                                        fonctionSucces(chaineRecherche, objetResultat);
                                }
                        });
            };
        

        function stopLoading() {
                $input.removeClass(options.loadingClass);
        };

};

$.ScrutariSuggereur.defaults = {
        langUi: "fr",
        withBaseIcon: true,
        inputClass: "sctsugg_input",
        resultsClass: "sctsugg_results",
        loadingClass: "sctsugg_loading",
        minChars: 3,
        delay: 400,
        limit: 50,
        extraParams: {},
        selectFirst: true,
        width: 0,
        scroll: true,
        scrollHeight: 180,
        submitOnSelect: "",
        supermotcleInput: ""
};

$.ScrutariSuggereur.Select = function (options, input, select, config) {
        var CLASSES = {
                ACTIVE: "sctsugg_over"
        };
        
        var listItems,
                active = -1,
                data,
                term = "",
                needsInit = true,
                element,
                list,
                keyScrollEvent=0;
        
        // Create results
        function init() {
                if (!needsInit)
                        return;
                element = $("<div/>")
                .hide()
                .addClass(options.resultsClass)
                .css("position", "absolute")
                .appendTo(document.body);
        
                list = $("<ul/>").appendTo(element).mouseover( function(event) {
                
                        if (keyScrollEvent > 0) {
                            keyScrollEvent++;
                            if (keyScrollEvent > 1) keyScrollEvent = 0;
                            return;
                        }
                        if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
                    active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
                            $(target(event)).addClass(CLASSES.ACTIVE);            
                }
                }).click(function(event) {
                        $(target(event)).addClass(CLASSES.ACTIVE);
                        select();
                        // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
                        input.focus();
                        return false;
                }).mousedown(function() {
                        config.mouseDownOnSelect = true;
                }).mouseup(function() {
                        config.mouseDownOnSelect = false;
                });
                
                if( options.width > 0 )
                        element.css("width", options.width);
                        
                needsInit = false;
        } 
        
        function target(event) {
                var element = event.target;
                while(element && element.tagName != "LI")
                        element = element.parentNode;
                // more fun with IE, sometimes event.target is empty, just ignore it then
                if(!element)
                        return [];
                return element;
        }

        function moveSelect(step) {
                listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
                movePosition(step);
        var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
        if(options.scroll) {
            var offset = 0;
            listItems.slice(0, active).each(function() {
                                offset += this.offsetHeight;
                        });
                        keyScrollEvent=1;
            if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
            } else if(offset < list.scrollTop()) {
                list.scrollTop(offset);
            }
        }
        };
        
        function movePosition(step) {
                active += step;
                if (active < 0) {
                        active = listItems.size() - 1;
                } else if (active >= listItems.size()) {
                        active = 0;
                }
        }
        
        function fillList() {
                list.empty();
                //Traitement de l'objet supermotcleSearchResult (voir http://www.scrutari.net/dokuwiki/serveurscrutari:json:type_supermotcle)
                var count = supermotcleSearchResult.supermotcleCount;
                if (count == 0) return;
                var supermotcleArray = supermotcleSearchResult.supermotcleArray;
                var baseMap = SCTJS_BaseData.getBaseDataMap(options.url);
                for (var i=0; i < supermotcleArray.length; i++) {
                    var supermotcle = supermotcleArray[i];
                    var mlib = SCTJS_BaseData.replaceM(supermotcle.mlib, "<strong>", "</strong>");
                    var htmlText = mlib + " <em>(" + supermotcle.indexationCount + ")</em>";
                    if (options.withBaseIcon) {
                        var baseArray = supermotcle.baseArray;
                        var baseArrayLength = baseArray.length;
                        for(var j = 0; j < baseArrayLength; j++) {
                            var baseIcon = SCTJS_BaseData.getBaseIcon(baseMap, baseArray[j].codebase);
                            if (baseIcon.length > 0) htmlText = htmlText + " " + "<img width=\"16\" height=\"16\" src=\"" + baseIcon + "\">";
                            if (baseArrayLength > 1) {
                                htmlText = htmlText + "<small><em>" + baseArray[j].indexationCount + "</em></small>&nbsp;";
                            }
                        }
                    }
                    var li = $("<li/>").html(htmlText).addClass(i%2 == 0 ? "sctsugg_even" : "sctsugg_odd").appendTo(list)[0];
                    $(li).data("sctsugg_supermotcle", supermotcle);
                }
                listItems = list.find("li");
                if ( options.selectFirst ) {
                        listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
                        active = 0;
                }
                // apply bgiframe if available
                if ( $.fn.bgiframe )
                        list.bgiframe();
        }
        
        return {
                display: function(sr, q) {
                        init();
                        supermotcleSearchResult = sr;
                        term = q;
                        fillList();
                },
                next: function() {
                        moveSelect(1);
                },
                prev: function() {
                        moveSelect(-1);
                },
                pageUp: function() {
                        if (active != 0 && active - 8 < 0) {
                                moveSelect( -active );
                        } else {
                                moveSelect(-8);
                        }
                },
                pageDown: function() {
                        if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
                                moveSelect( listItems.size() - 1 - active );
                        } else {
                                moveSelect(8);
                        }
                },
                hide: function() {
                        element && element.hide();
                        listItems && listItems.removeClass(CLASSES.ACTIVE);
                        active = -1;
                },
                visible : function() {
                        return element && element.is(":visible");
                },
                current: function() {
                        return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
                },
                show: function() {
                        var offset = $(input).offset();
                        element.css({
                                width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
                                top: offset.top + input.offsetHeight,
                                left: offset.left
                        }).show();
            if(options.scroll) {
                list.scrollTop(0);
                list.css({
                                        maxHeight: options.scrollHeight,
                                        overflow: 'auto'
                                });
                                
                if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
                                        var listHeight = 0;
                                        listItems.each(function() {
                                                listHeight += this.offsetHeight;
                                        });
                                        var scrollbarsVisible = listHeight > options.scrollHeight;
                    list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
                                        if (!scrollbarsVisible) {
                                                // IE doesn't recalculate width when scrollbar disappears
                                                listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
                                        }
                }
                
            }
                },
                getSelectedInfo: function() {
                        if (!listItems) return false;
                        var jqSelectedLi = listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
                        if (jqSelectedLi.length != 1) return false;
                        return jqSelectedLi.data("sctsugg_supermotcle");
                },
                emptyList: function (){
                        list && list.empty();
                },
                unbind: function() {
                        element && element.remove();
                }
        };
};

$.fn.selection = function(start, end) {
        if (start !== undefined) {
                return this.each(function() {
                        if( this.createTextRange ){
                                var selRange = this.createTextRange();
                                if (end === undefined || start == end) {
                                        selRange.move("character", start);
                                        selRange.select();
                                } else {
                                        selRange.collapse(true);
                                        selRange.moveStart("character", start);
                                        selRange.moveEnd("character", end);
                                        selRange.select();
                                }
                        } else if( this.setSelectionRange ){
                                this.setSelectionRange(start, end);
                        } else if( this.selectionStart ){
                                this.selectionStart = start;
                                this.selectionEnd = end;
                        }
                });
        }
        var field = this[0];
        if ( field.createTextRange ) {
                var range = document.selection.createRange(),
                        orig = field.value,
                        teststring = "<->",
                        textLength = range.text.length;
                range.text = teststring;
                var caretAt = field.value.indexOf(teststring);
                field.value = orig;
                this.selection(caretAt, caretAt + textLength);
                return {
                        start: caretAt,
                        end: caretAt + textLength
                }
        } else if( field.selectionStart !== undefined ){
                return {
                        start: field.selectionStart,
                        end: field.selectionEnd
                }
        }
};

})(jQuery);


