﻿// Selectors and Strings 
strSearchPhrasePrevious = "";
strSearchResultSelector = "#QuickSearchContainer"
strSearchResultSelectorLiItems = "ul.ProductList li"
strSearchFieldSelector = "body div.TopLinks div.QuickSearch input[type=text]"


// Timers 
timSearchPhrasePreviousIsSetting = null;
timSearchInProgress = null;
timSearchHideInProgress = null;

// Other 
booSearchNewCharacterTyped = false;


// Do stuff when document is finished loading 
jQuery(document).ready(function() {

    // Add events
    jQuery(strSearchFieldSelector).keydown(function() {
        booSearchNewCharacterTyped = true;
    });
    jQuery(strSearchFieldSelector).keyup(function(event) {
        OnSearchTyping(event);
    });
    jQuery(document).click(function(event) {
        HideSearchHandler(event);
    });

});

function urlescape(strQuery) {
    stripRegex = new RegExp("[^ a-zæøåA-ZÆØÅ0-9\-\/]", "g");
    strQuery = strQuery.replace(stripRegex, "");
    strQuery = strQuery.replace("/", " ");
    strQuery = encodeURI(strQuery);
    return strQuery;
}

// Execute the Ajax search
function DoSearch(strQuery) {
    // Get current ResultSetIdentifier
    var strCurrentResultSetID = GetResultSetIdentifier(jQuery(strSearchResultSelector).find(strSearchResultSelectorLiItems));
    
    // Do ajax call to search server
    jQuery.ajax({
        type: "GET",
        url: mStrRoot + "Ajax/GetQuickSearchResult.aspx",
        cache: false,
        data: "&query=" + urlescape(strQuery),
        dataType: "html",
        success: function(data) { // If the request went ok, pass the return data to the DoSearchPost function.

            // Only show result if the resultset has changed
            if (strCurrentResultSetID != GetResultSetIdentifier(jQuery(data).find(strSearchResultSelectorLiItems))) {

                // Add resultset HTML to the quicksearch container
                jQuery(strSearchResultSelector).html(data);

                // Get the last image in the result and wait for it to complete loading the blank.gif, before we show the content. 
                var objLastImage = jQuery(strSearchResultSelector).find(strSearchResultSelectorLiItems).find("img:last");
                if (objLastImage.length > 0) {
                    objLastImage.load(function() {
                        booSearchNewCharacterTyped = false;
                        DoSearchPost(objLastImage);
                    })
                } else {
                    booSearchNewCharacterTyped = false;
                    DoSearchPost(objLastImage);
                }
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            // An ajax error occured 
        }
    });
}
// Callback function for the ajax search
function DoSearchPost(objImageToUnload) {
    if (!booSearchNewCharacterTyped) {
        // Unbind load event from last image before we set it again
        objImageToUnload.unbind();

        // Fix DOM errors before we show the result 
        FixDOMRenderErrors();

        // Show the resultset
        ShowSearch();
    }
}

// Some browsers have problems rendering the content correctly after the DOM has changed. These errors are fixed here.
function FixDOMRenderErrors() {}

// Get a string representing the result (All productID's) 
function GetResultSetIdentifier(objLiItems) {
    var strIdentifier = new String("");
    for (i = 0; i < objLiItems.length; i++) {
        strIdentifier += jQuery(objLiItems[i]).attr("class").split()[0];
    }
    return strIdentifier;
}

// Show the search result
function ShowSearch() {
    jQuery(strSearchResultSelector + " .ProductBlock").parent().hover(
        function() { jQuery(this).addClass("Hover"); },
        function() { jQuery(this).removeClass("Hover"); }
    );
    jQuery(strSearchResultSelector).show();
}

// When the user clicks somewhere on the page that is not the search result. Hide the search. 
function HideSearchHandler(e) {
    var targ;
    if (!e) e = window.event;

    if (e.target) {
        targ = e.target;
    } else if (e.srcElement) {
        targ = e.srcElement;
    }

    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    var objParents = jQuery(targ).parents();
    if (objParents.filter(strSearchResultSelector).length == 0 && objParents.filter("#Search").length == 0) {
        HideSearch();
    }
}

// Hide the search result 
function HideSearch() {
    var objSearchResult = jQuery(strSearchResultSelector);
    if (!jQuery.browser.msie) {
        objSearchResult.fadeOut("normal", function() {
            objSearchResult.html("");
        });
    } else {
        // IE can't fade png images correctly
        objSearchResult.hide();
        objSearchResult.html("");
    }
}


// Handles keypresses in search field
// arrow left / right are ignored (37, 39)
function OnSearchTyping(e) {
    //SetHideSearchTimer();
    var txtSearchField = jQuery(strSearchFieldSelector);
    var intKeyCode = (e) ? e.keyCode : window.event.keyCode;
    if (intKeyCode != 40 && intKeyCode != 38 && intKeyCode != 39 && intKeyCode != 37) {
        if (txtSearchField.val() && txtSearchField.val().length > 0) {
            if (timSearchPhrasePreviousIsSetting) clearTimeout(timSearchPhrasePreviousIsSetting);
            if (timSearchHideInProgress) clearTimeout(timSearchHideInProgress);
            if (timSearchInProgress) clearTimeout(timSearchInProgress);
            if (jQuery.trim(txtSearchField.val()) != jQuery.trim(strSearchPhrasePrevious)) {
                timSearchInProgress = setTimeout("DoSearch('" + txtSearchField.val() + "')", 450);
                timSearchPhrasePreviousIsSetting = setTimeout("strSearchPhrasePrevious = '" + txtSearchField.val() + "';", 450);
            }
        }
        else if (txtSearchField.val().length == 0) {
            if (timSearchPhrasePreviousIsSetting) clearTimeout(timSearchPhrasePreviousIsSetting);
            if (timSearchHideInProgress) clearTimeout(timSearchHideInProgress);
            if (timSearchInProgress) clearTimeout(timSearchInProgress);
            strSearchPhrasePrevious = "";
            HideSearch();
        }
    }
}
