﻿if (!mecca)
    var mecca = {};

mecca.Search = function(options) {
    var defaults = {};
    var options = $.extend(defaults, options);
    var searchData;
    var ready = false;
    var currentText = "";
    var stopWords = [
            "about", "after", "all", "also", "an", "and",
            "another", "any", "are", "as", "at", "be",
            "because", "been", "before", "being", "between",
            "both", "but", "by", "came", "can", "come",
            "could", "did", "do", "does", "each", "else",
            "for", "from", "get", "got", "has", "had",
            "he", "have", "her", "here", "him", "himself",
            "his", "how","if", "in", "into", "is", "it",
            "its", "just", "like", "make", "many", "me",
            "might", "more", "most", "much", "must", "my",
            "never", "now", "of", "on", "only", "or",
            "other", "our", "out", "over", "re", "said",
            "same", "see", "should", "since", "so", "some",
            "still", "such", "take", "than", "that", "the",
            "their", "them", "then", "there", "these",
            "they", "this", "those", "through", "to", "too",
            "under", "up", "use", "very", "want", "was",
            "way", "we", "well", "were", "what", "when",
            "where", "which", "while", "who", "will",
            "with", "would", "you", "your", "le"
    ];

    search = function(text) {
        var results = { p: [], b: [], c: [] };
        var queryBits = [];
        var splitText = $.trim(text).split(" ");
        var tempResults = [];
        var searchPattern;

        if (splitText.length > 1) {
            for (var i = 0; i < splitText.length; i++) {
                if ($.inArray(splitText[i], stopWords) == -1)
                    queryBits.push("(" + splitText[i] + ")");
            }
            if (queryBits.length > 0)
                searchPattern = new RegExp(queryBits.join("|"), "gi");
        }
        else {
            if ($.inArray(splitText, stopWords) == -1)
                searchPattern = new RegExp(splitText, "gi");
        }

        for (var i = 0; searchPattern != undefined && i < searchData.p.length; i++) {
            if (!searchData.b[searchData.p[i].b]) {
                // omg
                //console.log(searchData.p[i]);
                //console.log(searchData.b);
                continue;
            }
            var resultKey = searchData.b[searchData.p[i].b].n + ":" + searchData.p[i].n;
            var index = $.inArray(resultKey, tempResults);
            var hits = searchData.p[i].n.match(searchPattern);
            if (hits) {
                if (index == -1) {
                    results.p.push([searchData.p[i], hits.length]);
                    tempResults.push(resultKey);
                }
                else {
                    results.p[index][1] += hits.length;
                }
            }
            else {
                hits = searchData.b[searchData.p[i].b].n.match(searchPattern);
                if (hits) {
                    if (index == -1) {
                        results.p.push([searchData.p[i], hits.length]);
                        tempResults.push(resultKey);
                    }
                    else {
                        results.p[index][1] += hits.length;
                    }
                }
                else {
                    if (searchData.p[i].s.length > 0) {
                        for (sku in searchData.p[i].s) {
                            hits = searchData.p[i].s[sku].match(searchPattern);
                            if (hits) {
                                if (index == -1) {
                                    results.p.push([searchData.p[i], hits.length]);
                                    tempResults.push(resultKey);
                                    index = $.inArray(resultKey, tempResults);
                                }
                                else {
                                    results.p[index][1] += hits.length;
                                }

                                continue;
                            }
                        }
                    }
                    if (searchData.p[i].c.length > 0) {
                        for (cat in searchData.p[i].c) {
                            hits = searchData.c[searchData.p[i].c[cat]].d.match(searchPattern);
                            if (hits) {
                                if (index == -1) {
                                    results.p.push([searchData.p[i], hits.length]);
                                    tempResults.push(resultKey);
                                    index = $.inArray(resultKey, tempResults);
                                }
                                else {
                                    results.p[index][1] += hits.length;
                                }
                                continue;
                            }
                        }
                    }
                }
            }

        }

        var tempText = $.trim($('li.search input').val());
        if (tempText != currentText) {
            return search(tempText);
        }

        results.p.sort(function(a, b) { return b[1] - a[1] });
        return results;
    }

    isReady = function() { return ready; }

    createOneResultItem = function(p) {
        var prodUrl = "/shop/" + searchData.b[p.b].t + "/" + p.h + "/";
        var imgUrl;
        if (p.i == ".")
            imgUrl = "/img/products/thumb/product-placeholder-thumb.jpg";
        else
            imgUrl = "/img/products/thumb/" + p.i + ".jpg";

        var html = "<li><a href='" + prodUrl + "' class='image'><img alt='" + p.n + "' src='" + imgUrl + "'/></a>";
        html += "<dl><dt><a href='" + prodUrl + "'>" + searchData.b[p.b].n + "</a></dt><dd>" + p.n + "</dd></dl> </li>";

        return html;
    }

    processResults = function(results) {
        var ol = $('ol.nav-search-results').html('');
        var brandsDt = $('div.box-sidebar dl dt.h-sidebar-brands');
        var catsDt = $('div.box-sidebar dl dt.h-sidebar-categories');
        var otherDt = $('div.box-sidebar dl dt.h-sidebar-other-pages');
        var foundBrands = [];
        var foundCats = [];

        for (var i in results.p.slice(0, 8)) {
            var p = results.p[i][0];
            ol.append(createOneResultItem(p));

            if ($.inArray(p.b, foundBrands) == -1)
                foundBrands.push(p.b);
            for (var cat in p.c)
                if ($.inArray(p.c[cat], foundCats) == -1)
                foundCats.push(p.c[cat]);
        }
        $('div.box-sidebar dl dd').remove();
        for (var brand in foundBrands) {
            var b = searchData.b[foundBrands[brand]];
            brandsDt.after("<dd><a href='/" + b.t + "/'>" + b.n + "</a></dd>");
        }

        for (var cat in foundCats) {
            var c = searchData.c[foundCats[cat]];
            catsDt.after("<dd><a href='/shop/" + c.n + "/'>" + c.d + "</a></dd>");
        }
    }

    doSearch = function() {
        var text = $.trim($('li.search input').val());
        if (text != currentText) {
            currentText = text;
        }

        if (text.length > 0) {
            var results = search(text);
            $('body').addClass('search-active');
            if (!$('div.nav-content-hover-overlay').length) {
                $('div.container').after('<div class="nav-content-hover-overlay"></div>');
            }

            $('div.nav-content-hover-overlay').css({ display: 'inline' });
            if (results.p && results.p.length > 0) {
                processResults(results);
                $('a.h-view-full-search-results').attr('href', '/search/default.aspx?q=' + text).css('display', 'block');
                $('div.nav-content-hover-overlay').animate({ opacity: 0.65 }, 250);
            }
            else {
                $('ol.nav-search-results').html('');
                $('a.h-view-full-search-results').attr('href', '').css('display', 'none');
                $('div.nav-content-hover-overlay').animate({ opacity: 0 }, 250, function() { $(this).css({ display: 'none' }); });
            }
            $('div.overlay-search a.h-close-search, div.nav-content-hover-overlay').unbind('click.continue').bind('click.continue', function(e) {
                $('ol.nav-search-results').html('');
                $('a.h-view-full-search-results').attr('href', '').css('display', 'none');
                $('body').removeClass('search-active');
                $('div.nav-content-hover-overlay').animate({ opacity: 0 }, 250, function() { $(this).css({ display: 'none' }); });
                $('li.search input').val('').blur();
                $('div.overlay-search a.h-continue-shopping, div.nav-content-hover-overlay').unbind('click.continue');

                if (e.preventDefault) { e.preventDefault(); }
            });
        }
        else {
            $('ol.nav-search-results').html('');
            $('a.h-view-full-search-results').attr('href', '').css('display', 'none');
            $('body').removeClass('search-active');
            $('div.nav-content-hover-overlay').animate({ opacity: 0 }, 250, function() { $(this).css({ display: 'none' }); });
        }
    }

    var searchingNow = false;
    var searchingTimer;

    init = function() {
        $.ajax({
            type: "GET",
            url: "/search/ajaxSearchData.aspx",
            dataType: 'json',
            success: function(result) {
                searchData = result;
                ready = true;
                $('li.search input').keyup(function() {
                    if (!searchingNow) {
                        clearTimeout(searchingTimer);
                        searchingTimer = setTimeout(function() {
                            searchingNow = true;
                            doSearch();
                            searchingNow = false;
                        }, 50);
                    }
                });
            },
            error: function(result) { var x = result; }
        });


    } ();

    return {};
}