(function($) {

    var ac = function(c, o) {
        this.cache = {};
        this.init(c, o)
    }
    ac.prototype = {

    // html elements
        ac : null, // main input
        ul : null, // autocomplete list
        img : null, // image
        container : null, // outer div

    // timeouts
        close : null, // ac hide
        timeout : null, // ac search

    // sys defs
        chars : 0, // previous search string lenght

    // user defs
        url : null, // url for ajax request
        source : null, // select (jQuery)

        minchar : 0, // minchars for search
        delay : 50, //
        fillin : false,

        width : 200, // width

    // events
        onSelect : function () {
        },
        onKeyPress : function () {
        },
        onError : function () {
        },

        init : function (ac, options) {
            $.extend(this, options)

            this.container = $("<div/>")
                .css({width:this.width})
                .addClass('ac_conteiner')
                .insertBefore(ac);

            this.ac = $(ac)
                .attr({autocomplete:"off"})
                .bind("blur", this, function(e) {
                    var d = e.data;
                    clearTimeout(d.close);
                    e.data.close = setTimeout(function() {
                        d.ul.hide();
                    }, 500);
                }) // IE bug e.data.ul[.hide()] = undefined
                .addClass('ac_input')
                .css({width:this.width - ($.browser.mozilla?20:22)}) // 18 img + 2 margin + 2 IE?
                .appendTo(this.container);
            this.img = $("<div/>")
                .bind("click", this, function(e) {
                    clearTimeout(e.data.close);
                    e.data.ul.toggle();
                    e.data.scroll();
                    e.data.ac.focus();
                })
                .addClass('ac_img')
                .appendTo(this.container);
            this.ul = $("<div/>")
                .bind("mousedown", this, function(e) {
                    var d = e.data;
                    setTimeout(function() {
                        clearTimeout(d.close);
                        d.ac.focus();
                    }, 50);
                })// IE scroll bug
                .addClass('ac_results')
                .appendTo(this.container);
            $(window).bind("resize load", this, function(e) {
                var c = e.data.container;
                e.data.ul.css({
                    width:e.data.width,
                    top:(c.offset().top + c.height() + parseInt(c.css("border-top-width"))),
                    left:(c.offset().left + parseInt(c.css("border-left-width")))
                });
            });

            if ($.browser.mozilla)
                this.ac.bind("keypress", this, this.process);
            else
                this.ac.bind("keydown", this, this.process);

            if (this.fillin)
                this.suggest("hide");
        },

        process : function (e) {
            var a = e.data;
            e.data.onKeyPress.apply(e.data,arguments);
            if ((/27$|38$|40$/.test(e.keyCode) && a.ul.is(':visible')) || (/^13$|^9$/.test(e.keyCode) && a.get())) {
                e.preventDefault();
                e.stopPropagation();
                switch (e.keyCode) {
                    case 38: // up
                        a.prev();
                        break;
                    case 40: // down
                        a.next();
                        break;
                    case 9:  // tab
                    case 13: // return
                        a.select();
                        break;
                    case 27: // escape
                        a.ul.hide();
                        break;
                }
            } else if (a.ac.val().length != a.chars || !a.ac.val().length) {
                a.chars = a.ac.val().length;

                if (a.timeout)
                    clearTimeout(a.timeout);
                a.timeout = setTimeout(function() {
                    a.suggest("show")
                }, a.delay);
            }
        },

        get : function() {
            if (!this.ul.is(':visible'))
                return false;
            var current = this.ul.children('div.ac_over');
            if (!current.length)
                return false;
            return current;
        },

        prev : function () {
            var current = this.get();
            var prev = current.prev();
            if (current) {
                current.removeClass('ac_over')
                if (prev.text())
                    prev.addClass('ac_over');
                }
            if (!current || !prev.text())
                this.ul.children('div:last-child').addClass('ac_over');
            this.scroll();
        },

        next : function () {
            var current = this.get();
            var next = current.next()
            if (current) {
                current.removeClass('ac_over')
                if (next.text())
                    next.addClass('ac_over');
            }
            if (!current || !next.text())
                this.ul.children('div:first-child').addClass('ac_over');
            this.scroll();
        },

        scroll : function(){
            if (!this.get()) return;
            var el = this.get().get(0);
            var list = this.ul.get(0);
            if(el.offsetTop + el.offsetHeight > list.scrollTop + list.clientHeight)
                list.scrollTop = el.offsetTop + el.offsetHeight - list.clientHeight;
            else if(el.offsetTop < list.scrollTop)
                list.scrollTop = el.offsetTop;
        },

        select : function () {
            var current = this.get();
            if (current) {
                this.ac.val(current.text());
                this.ul.hide();
                this.onSelect.apply(this);
            }
        },

        suggest : function (show) {
            var a = this;
            var mask = $.trim(this.ac.val());
            this.ul.empty().hide();
            if (mask.length >= this.minchar) {
                if (this.cache[mask])
                    this.display(this.cache[mask])[show]();
                else if (this.url) // use ajax
                    $.ajax({type: "GET", url:this.url+'&wojewodztwo='+$("select#wojewodztwo").val(), data:{mask:mask},
                        success:function(xml) {
                            a.prepare(xml,mask)[show]();
                        },
                        error:function(){
                            a.onError.apply(a,arguments);
                        }});
                else if (this.source) // use source
                    a.prepare(this.source,mask)[show]();
            }
        },

        prepare : function(xml,mask){
            var parse = function(text){
                if (new RegExp('^' + mask, 'ig').test(text))
                    return '<div class="ac_wyzeruj">' + text.replace(new RegExp('^' + mask, 'ig'), function(mask) {
                        return '<span class="ac_match">' + mask + '</span>';
                    }) + '</div>';
            }

            var map = xml.constructor != Array && ($.browser.opera ? $(xml).find("option").length : xml.constructor != Object) ?
                $.map($(xml).find("option"), function(n) {  // use selectbox or ajax result
                    return parse($(n).text());
                }) :
                $.map(xml, function(n) { // use array or array-like object
                    return parse(n);
                })
            this.cache[mask] = map.join("");
            return this.display(this.cache[mask]);
        },

        display : function (list) {
            if (!list) return this.ul;
            var a = this;
            return this.ul.append(list).children('div').mouseover(function() {
                a.ul.children('div').removeClass('ac_over');
                $(this).addClass('ac_over');
            }).click(function(e) {
                e.preventDefault();
                e.stopPropagation();
                a.select();
            }).end().children('div:first-child').addClass('ac_over').end();
        }
    }

    $.fn.autocomplete = function(options) {
        this.each(function() {
            new ac(this, options);
        });
        return this;
    };

})(jQuery);
