﻿jQuery.noConflict()(function () {
    var jq = jQuery,
		searchBox = jq('#TextBox_SearchBox').attr('autocomplete', 'off'),
		resultContainer = jq('<div id="search-results" />').hide(),
		searchMessage = jq('<div class="message searching">Söker...</div>'),
		isSearching = false,
		errorMessage = jq('<div class="message error"><strong>Oops, förhandsgranskning av söken fungerar ej. Tryck Enter för att söka.</strong></div>'),
        closeLink = jq('<a href="#" class="close" title="Dölj sökresultatet">Stäng</a>'),
		userHasSearched = false, // Show the big search gfx only on first search
		startSearchAt = 3, // Start searching at 3 characters
		searchDelay = 150, // Delay ajax request (ms)
		dataString = '',
		queryString = '',
		productSearch = '',
		keyPressed = '',
        requestId = 0, // Send this to the server
        responseId = 0,
        showingResponse = 0;

    resultContainer.appendTo('#mastBlueGrad .whiteheadersmaller');

    // Check whether the search sholud be anabled or not
    jq.ajax({
        type: "POST",
        url: "/AJAX/AjaxSearch.aspx",
        data: dataString,
        cache: false,
        success: function (data) {
            resultContainer.html(data);
            if (resultContainer.find('div:first-child').hasClass('SearchEnabled')) {
                searchBox.bind('keyup', searchBoxKeyUp);
            }
        }
    });

    // Check for valid keyCodes
    function isValidKeyCode(keyCode) {
        switch (keyCode) {
            case 37: // left arrow
            case 39: // right arrow
            case 38: // up arrow
            case 13: //enter
            case 10: //enter
            case 32: //Space
                return false;
                break;
        }
        return true;
    }

    // Search products and categories
    function searchBoxKeyUp(e) {
        keyPressed = e != null ? e.keyCode : 0;
        if (searchBox.val().length >= startSearchAt && isValidKeyCode(keyPressed)) {
            if (keyPressed === 27) { // Hide on Esc-click
                resultContainer.fadeOut('fast');
            }
            if (keyPressed === 40) { // Move focus to the product list
                jq('.product-listing li:first-child a').focus();
                jq('.product-listing li:first-child').addClass('hover');
            } else {
                if (isSearching && (productSearch !== '')) { // Prevent unnecessary requests
                    clearTimeout(productSearch);
                }
                resultContainer.show();
                if (!userHasSearched) { // Show the loading message only the first time
                    resultContainer.show().html(searchMessage);
                }
                dataString = searchBox.val();
                isSearching = true;
                productSearch = setTimeout(function () { // Make a product search                    
                    requestId++;
                    queryString = "?searchText=" + escape(dataString) + "&requestId=" + requestId;
                    jq('.result-header h2').addClass('searching');
                    jq.ajax({
                        type: "POST",
                        url: "/AJAX/AjaxSearch.aspx" + queryString,
                        data: dataString,
                        cache: false,
                        success: function (data) {
                            jq('.result-header h2').removeClass('searching');
                            responseId = jq(data).find('.search-result').attr('id').slice(9); // Strip away "response-" from the id attribute
                            if (parseInt(responseId) > showingResponse) { // Only show responses that are newer than the one currently showing
                                resultContainer.html(data);
                                resultContainer.prepend(closeLink);
                                closeLink.bind('click', function (e) {
                                    e.preventDefault();
                                    closeSearchResults();
                                });
                                showingResponse = responseId;
                            }
                            highlightText('.search-result li a', dataString);
                            userHasSearched = true;
                            isSearching = false;
                            jq('.result-header a').bind('click', showAllSearchResults);
                        },
                        error: function () {
                            resultContainer.html(errorMessage);
                            userHasSearched = true;
                            isSearching = false;
                        }
                    });
                }, searchDelay);
            }
        } else if (searchBox.val().length < startSearchAt) {
            resultContainer.hide(); // Hide the container if less than 3 characters
        };
    };

    /* Show all search results (post the search form)
    -------------------------------------------------- */
    function showAllSearchResults(e) {
        e.preventDefault();
        Search_Search();
    }

    /* Show/hide the search result
    ---------------------------------------------- */
    function showSearchResults() {
        resultContainer.fadeIn('fast');
    }

    function closeSearchResults() {
        nd(); //Make sure to hide Product Mouse Over Div
        resultContainer.fadeOut('fast');
    }

    searchBox.focus(function () {
        if (userHasSearched) {
            showSearchResults();
        }
        else
            searchBoxKeyUp(null);
    });

    jq(document).click(function (e) {
        if (jq(e.target).closest('#search-results').get(0) == null) { // click outside
            closeSearchResults();
        }
    });

    jq('#TextBox_SearchBox').click(function (e) {
        e.stopPropagation(); // Don't hide if clicked inside the resultContainer
    });


    /* Handle clicks on category links
    ---------------------------------------------- */
    jq('.category-listing li a').live('click', function (e) {
        var src = jq(this).attr('href').split('SL_SectionId=');
        var srcId = src[src.length - 1];
        if (m2c(parseInt(srcId), 0)) {
            setTimeout(function () {
                closeSearchResults();
            }, 200);
        }
        e.preventDefault();
    });

    /* Make the search results keyboard navigable
    ---------------------------------------------- */
    jq('.search-result a').live('keydown', function (e) { // Keyboard navigation
        var el = jq(this),
		    parent = el.parent();
        if (e.keyCode === 40) { // ↓ Move down ↓
            parent.removeClass('hover');
            if (isLastListItem(parent)) { // Move focus to the first list item
                el.parents('ul').find('li:first-child').addClass('hover').find('a').focus();
            }
            parent.next().addClass('hover').find('a').focus();
        } else if (e.keyCode === 38) { // ↑ Move up ↑
            parent.removeClass('hover');
            if (isFirstListItem(parent)) { // Move focus to the last list item
                el.parents('ul').find('li:last-child').addClass('hover').find('a').focus();
            }
            parent.prev().addClass('hover').find('a').focus();
        } else if (e.keyCode === 37 || e.keyCode === 39) { // ⇆ Move sideways ⇆
            if (el.parents('div').hasClass('.product-listing')) {
                parent.removeClass('hover');
                jq('.category-listing li:first-child').addClass('hover');
                jq('.category-listing li:first-child a').focus(); // If in products, focus on categories
            } else {
                parent.removeClass('hover');
                jq('.product-listing li:first-child').addClass('hover');
                jq('.product-listing li:first-child a').focus(); // If in categories, focus on products
            }
        }
    });

    function isFirstListItem(el) {
        return el.parent().children('li').index(el) === 0;
    }

    function isLastListItem(el) {
        return el.parent().children('li').index(el) === el.parent().children('li').length - 1;
    }

    /* Highlight text found in element (el) that contains the text (str)
    --------------------------------------------------------------------- */
    function highlightText(el, str) {
        var el = jq(el),
			searchWords = '',
		searchWords = str.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1").split(' ').join('|');
        el.each(function () {
            jq(this).html(jq(this).text().replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + searchWords + ")(?![^<>]*>)(?![^&;]+;)", "gi"), '<span class="highlight">$1</span>'));
        });
    };
});
