﻿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 splitText = $.trim(text).split(" ");
        var tempResults = [];
        var searchPatternArray = [];
        var tempStr = "";

        for (var i = 0; i < splitText.length; i++) {
            if ($.inArray(splitText[i], stopWords) == -1)
            {
                searchPatternArray.push(new RegExp(splitText[i], "gi"));
            }
        }

        for (var i = 0; searchPatternArray.length > 0 && 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 = "";
            
            var skuString = "";
            for (sku in searchData.p[i].s)
            {
                skuString += searchData.p[i].s[sku] + " ";
            }

            var catString = "";
            for (cat in searchData.p[i].c)
            {
                catString += searchData.c[searchData.p[i].c[cat]].d + " ";
            }

            var hits = andRegexMatching(searchData.p[i].n + " " + searchData.b[searchData.p[i].b].n + " " + skuString + catString, searchPatternArray);
            if (hits) {
                if (index == -1) {
                    results.p.push([searchData.p[i], hits.length]);
                    tempResults.push(resultKey);
                }
                else {
                    results.p[index][1] += hits.length;
                }
            }
        }

        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;
    }

    andRegexMatching = function(input, searchPatternArray)
    {
        //Lets loop through the array of regexes in order to do an AND regex match. If any of the regexes don't match, then there is no hit.
        //They all have to match.
        var hits = "";
        var tempStr = "";
        for (var j = 0; j < searchPatternArray.length; j++)
        {
            tempStr = input.match(searchPatternArray[j]);
            if (tempStr)
            {
                hits += tempStr;
            }
            else
            {
                hits = "";
                break;
            }
        }
        
        return hits;
    }

    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();
        $('div.box-sidebar dl dt').css('opacity', 1);
        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;
        }
        $('ol.nav-search-results').removeClass('no-results');

        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("<em>We couldn't find anything to match your quick search<br/>- would you like to perform a full search?</em>")
                    .addClass('no-results');
                $('div.box-sidebar dl dd').remove();
                $('div.box-sidebar dl dt').css('opacity', 0.3);
                $('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);
                    }
                });
            }
        });


    } ();

    return {};
}
