/* jquery.ac.js|customers */
/**
 * JSON Autocompleter which autocompletes on a single word in a input type text element.
 * the element used for this plugin MUST only match one element.
 *
 * USAGE:
 * $('#id-of-element').ac({});
 *
 * OPTIONS:
 * - url [The url that is used for autocompletion]
 * - param [The name of the parameter to send with the JSON request]
 * - classes
 *   - selected [is added to the li element when using arrow up or down]
 *   - list [is added to the generated ul list which holds the autocomplete values]
 *
 * @copyright Peytz & Co (www.peytz.dk)
 * @author Henrik Bjørnskov (hb@peytz.dk)
 * @author Troels Knak-Nielsen (tkn@peytz.dk)
 */
$.fn.ac = function(options) {
    alert("ac");
    var options = $.extend({}, $.fn.ac.defaults, options);
    var element = $(this);
    var timeout = null;
    var self = this;

  
    var ul = $('<ul />').css({ display: 'none' }).insertAfter(this).attr('id', 'ac-' + $.data(this)).addClass(options.classes.list);

    $('<li class="link"><span>Luk</span></li>').prependTo(ul).find('span').click(function(e) {
        $(this).parent().parent().hide();
        $('li:not(.link)', $(this).parent().parent()).remove();
    });

    element.attr('autocomplete', 'off');

    element.blur(function(e) {
        setTimeout(function() {
            $('li:not(.link)', ul).remove();
            ul.hide();
        }, 200);
    });

    $("#mdSearch .mdSearchButton").click(function(e) {
        var text = $('li.selected', ul).text();
        if (text) {
            element.val(text)
        }
    });

    $('li:not(.link)', ul).live('mousemove', function(e) {
        var elm = $(this);
        var li = $(elm.parent().find('li'));

        $(elm).siblings().removeClass(options.classes.selected);

        $(this).addClass(options.classes.selected);

        $.fn.ac.index = li.index(elm);
    });

    $(this).keyup(
        function(e) {
            var value = options.escape(self.val());

            switch (e.which) {
                case 13: //Enter
                case 27: //Escape
                case 37: //Left
                case 38: //Up
                case 39: //Right
                case 40: //Down
                case 46: //Delete
                    break;
                default:
                    clearTimeout(timeout);

                    $('li:not(.link)', ul).remove()
                    ul.hide();

                    timeout = setTimeout(function() {
                        $.getJSON(options.url + '?' + options.param + '=' + escape(value) + options.query(element), function(data) {
                            $.fn.ac.index = -1;

                            ul.find('li:not(.link)').remove();

                            $.each(data.reverse(), function(key, item) {
                                try {
                                    var matches = item.match(new RegExp(value, 'i'));
                                    var item = item.replace(new RegExp(value, 'i'), '<strong>' + matches[0] + '</strong>');
                                } catch (e) { }

                                var li = $('<li />').html(item).prependTo(ul).click(function(e) {
                                    $.fn.ac.select(ul, element, $(this).text());
                                    $("#mdSearch .mdSearchButton").focus().click();
                                });
                            });

                            if (ul.find('li:not(.link)').length > 0) {
                                ul.show();
                            }
                        });
                    }, 300);
            }

            e.preventDefault();
        });

    $(this).keydown(
        function(e) {
            var testIndex = $.fn.ac.index;

            switch (e.which) {
                case 13: //Enter

                    if ($.fn.ac.index != -1) {
                        $.fn.ac.select(ul, element, ul.find('li:eq(' + testIndex + ')').text(), options);
                    }

                    break;
                case 46: //Delete
                case 8: //Backspace
                case 27: //Escape
                    ul.hide();
                    $.fn.ac.index = -1;
                    break;
                case 38: //Up
                    testIndex = $.fn.ac.index - 1;
                    e.preventDefault();
                    break;
                case 40: //Down
                    testIndex = $.fn.ac.index + 1;
                    e.preventDefault();
                    break;
            }

            if (e.isDefaultPrevented()) {
                var elm = $('li:eq(' + testIndex + '):not(.link)', ul);

                if (elm.get(0)) {
                    ul.find('li:eq(' + $.fn.ac.index + ')').removeClass(options.classes.selected);
                    $.fn.ac.index = testIndex;
                    elm.addClass(options.classes.selected);
                }
                return false;
            }
            return true;
        });
};

$.fn.ac.index = -1;

$.fn.ac.select = function (ul, element, data) {    
    element.val(data);
    ul.hide();
    $.fn.ac.index = -1;
};

$.fn.ac.defaults = {
    url     : 'ac.json',
    param   : 'p_prefix',
    query   : '',
    escape : function (s) { return unescape(encodeURIComponent(s)); },
    classes : {
        list : 'ac-list',
        selected : 'ac-selected'
    }
};
