(function($) {
    $.fn.extend({
        _keyBinds: {
            38: 'up',
            40: 'down',
            27: 'esc',
            13: 'enter'
        },
        livesearch: function() {
            if (this.is("input[type=text]")) {
                var searchField = this;
                searchField.attr('autocomplete', 'off');
                var result = $("<div class=\"pg-livesearch\"><div class=\"pg-livesearch-results\"></div><div class=\"pg-livesearch-top\"></div><div clasS=\"pg-livesearch-bottom\"></div></div>").hide();
                var showButton = $("<a class=\"pg-livesearch-show\" href=\"#\" title=\"Vis hurtigs&oslash;k\">Vis hurtigs&oslash;k</a>")
                                    .click(function(e) {
                                        e.preventDefault();
                                        $.cookie('hideLiveSearch', null);
                                        if (result.hasClass("pg-disabled"))
                                            result.show().removeClass("pg-disabled");
                                        $(this).hide();
                                    }).hide();
                
                searchField.after(result);
                searchField.after(showButton);
                result.css({
                    zIndex: 20,
                    left: this.position().left,
                    marginLeft: "6px"
                });
                this.focus(function(e) {
                    if (!$.cookie('hideLiveSearch')) {
                        if (this.value.length > 0)
                            result.show();
                        $(this).addClass("pg-search-focused");
                    }
                })
                .blur(function(e) {
                    if (!$.cookie('hideLiveSearch')) {
                        $(this).removeClass("pg-search-focused");
                        result.hide();
                    }
                })
                .keyup(function(e) {
                    if ($.cookie('hideLiveSearch')) {
                        showButton.show();
                    }
                    else {
                        var that = $(this),
                        val = this.value;
                        if (val.length > 0) {
                            if ($.fn._keyBinds[e.keyCode] == undefined) {
                                var drawResults = function(data) {
                                    $.fn._step = null;
                                    result.find(".pg-livesearch-results").empty();
                                    if (data['total-results'] > 8) {
                                        $("<a href=\"#\"><strong>+ Vis flere treff (" + data['total-results'] + ")</strong></a>")
                                              .css({
                                                  position: "absolute",
                                                  bottom: "-20px",
                                                  left: "30px",
                                                  zIndex: "1",
                                                  color: "#fff"
                                              })
                                              .mousedown(function(e) {
                                                    e.preventDefault();
                                                    $(this).parents("form").get(0).submit();
                                              }).click(function() {return false;}).appendTo(result.find("div.pg-livesearch-results"));
                                    }

                                    $("<a href=\"#\"><strong>Sl&aring; av hurtigs&oslash;k</strong></a>")
                                          .css({
                                              position: "absolute",
                                              bottom: "-20px",
                                              right: "30px",
                                              zIndex: "1",
                                              color: "#fff"
                                          }).click(function() {return false;})
                                          .mousedown(function() {
                                              searchField.removeClass("pg-search-focused");
                                              showButton.show();
                                              $.cookie('hideLiveSearch', true);
                                              result.hide().addClass("pg-disabled");
                                          }).appendTo(result.find("div.pg-livesearch-results"));
                                    result.show();
                                    var list = function(item) {
                                            if (item.imageURL != "") {
                                                $.imageParseImageUrl(item.imageURL[0]);
                                                var image = $("<span class=\"pg-livesearch-image\"><img src=\"" + $.imageGetSizeUrl(60, 40, false) + "\" alt=\"" + item.fullName + "\" /></span>");
                                            }
					    var anchor =  $("<a href=\"/produkt/" + item.productId + "\" class=\"pg-livesearch-item pg-clearfix\"></a>");
					    anchor.append(image);
                                            anchor.append("<strong class=\"pg-livesearch-item-name\">" 
                                                + item.fullName + 
                                                "</strong>" +
						"<span class=\"pg-livesearch-details pg-block\">" + item.techInfoString + "</span>")
                                                .hover(
                                                    function(e) {
                                                        result.find(".pg-selected").removeClass("pg-selected");
                                                        $(this).addClass("pg-selected");
                                                    },
                                                    function(e) {
                                                        $(this).removeClass("pg-selected");
                                                    }
                                                )
                                                .mousedown(function(e) {
                                                    e.preventDefault();
                                                    window.location.href = $(this).attr("href");
                                                })
                                                .appendTo(result.find("div.pg-livesearch-results"));
                                    }
                                    if ($.isArray(data.document)) {
                                        $.each(data.document, function() {
                                            list(this);
                                        });
                                    }
                                }
                                if (!$._isCached(val)) {
                                    if (val.indexOf("OR") > -1 || val.indexOf("ELLER") > -1) {
                                        var queries = val.replace("ELLER", "OR").split("OR"),
                                            queryString = "?quick_title=" + queries[0];
                                        if (queries.length > 1) {
                                            queryString = queryString + "&quick_title_or=" +  queries[1];
                                        }
                                    }
                                    else {
                                        var queryString = "?quick_title=" + val;
                                    }

                                    var query = "http://webs1.edda.no.webdealhosting.com:8080/eddamedia/hn/search/product.json" + queryString + "&sortby=popularity&pageSize=8&jsonP=?";
                                    $.getJSON(query,
                                            function(resp) {
                                                var data = resp.hnSearch[0].products[0];
                                                if (data['total-results'] == 0)
                                                    result
                                                        .hide()
                                                        .find("div.pg-livesearch-results")
                                                            .empty();
                                                if (data.document != undefined) {
                                                    $._cache(val, data);
                                                    drawResults(data);
                                                }
                                            });
                                }
                                else {
                                    drawResults($._cache(val));
                                }
                            }
                            else {
                                switch ($.fn._keyBinds[e.keyCode]) {
                                    case 'up':
                                        $.fn._stepItem(-1, result);
                                        break;
                                    case 'down':
                                        $.fn._stepItem(1, result);
                                        break;
                                    case 'enter':
                                        $.fn._selectItem(result, this);
                                        break;
                                    case 'esc':
                                        result.hide();
                                        break;
                                }
                            }
                        }
                        else {
                            result.hide();
                        }
                    }
                });
            }
        },
        _selectItem: function(result, field) {
            var link = result.find("a.pg-selected").attr("href");
            if (link == undefined)
                field.form.submit();
            else
                window.location.href = link;
        },
        _stepItem: function(step, result) {
            result.show();
            var list = result.find("a.pg-livesearch-item");
            if (this._step == null) {
                if (step > 0)
                    this._step = list.length - 1;
                else
                    this._step = 0;
            }
            else {
                list.eq(this._step).removeClass("pg-selected");
            }

            this._step = this._step + step;

            if (this._step == list.length)
                this._step = 0;
            else if (this._step < 0)
                this._step = list.length - 1;

            list.eq(this._step).addClass("pg-selected");
        }
    });
})(jQuery);
