if(!a10) {var a10 = {};} //if a10 not defined yet

a10.ss = {};    

//-------------------------------------//


/* Search Suggestion */

/*
Optimization Note:

These rules are currently implemented to minimize the number of suggestion requests:

    * No request is made for events that doesn't change the query (e.g. enter, arrow keys, etc.)
    * No request is made if the new characters added to the query wouldn't change the suggestion results.  That is,
      if the new query still forms a valid prefix of all the current suggestion results.
    * No request is made when the query is less than two characters.
    * If a query returns no result, additional characters appended to that query will not generate a request.
    * A request is made only after user pauses typing for some number of milliseconds.

*/

/* Search Suggestions Global Variables and Constants */

/* Query matching the current results.  Value will be null before the first request and when the query is less than two
   characters long. */
a10.ss.lastSuccessfulQuery = null;

/* A copy of the query string currently in query box.  This value is used to determine whether a key event
   has actually changed the query.  It is set initially on page load, and is updated on each key event. */
a10.ss.currentQuery = null;

/* Array contaning the current list of suggestions.  Elements in the array are references to the actual search suggestion
   anchor elements within the DOM.  */
a10.ss.currentResults = new Array();

/* Supports the implementation of PAUSE_PERIOD.*/
a10.ss.pauseTimeoutID = null;

/* Index of the currently selected suggestion. */
a10.ss.selectedIndex = -1;

/* Boolean value indicating whether this result page has made any search suggestion request. */
a10.ss.pageHasMadeRequest = false;

/* Boolean value indicating whether this result page has made any search suggestion request. */
a10.ss.formSubmitted = false;

/* Boolean value indicating whether the search suggestions pane is hidden */
a10.ss.hidden = true;

/* Number of milliseconds after user stops typing that a suggestion request will be sent.
   The setting here is only the default value, it will be overridden with the value on the
   static server.  See init() for detail. */
a10.ss.PAUSE_PERIOD = 201;

/* Duration (in seconds) of the search suggestion fade in/out effect. */
a10.ss.FADE_SPEED = 0.07;

/* Workaround for Safari's bug where arrow key events are fired twice.  This flag enables us to only handle every other one. */
a10.ss.skipNextArrowKeyEvent = false;


//id of query box input
a10.ss.inputId = "";

//id of search suggestion ui
a10.ss.uiId = "";
a10.ss.uiBodyId = "";

//positional offset
a10.ss.offsetLeft = 10;

// Default SS QSRC value for clicks and return : TRES-5237
a10.ss.ssQsrcDefault = "2352";

// SS QSRC for homepage only : TRES-5237
a10.ss.ssQsrcHP = "178";

// Initialized qsrc
a10.ss.qsrc = a10.ss.ssQsrcDefault;

// IE6 popup cover
a10.ss.popupIE6Cover = "";
a10.ss.popupIE6CoverTarget = "";

a10.ss.uiSuggestlistId = "suggestlist";

/**
 * Initialized the search suggestion module by binding a event handler to querybox with specified id
 *
 * @param id id of the input box to bind search suggestion to
 * @param uiId html id of the search suggestion div
 * @param uiBodyId html id of the search suggestion content div
 * @param pausePeriod pause in seconds milliseconds between search suggestion requests
 * @addon
 */
a10.ss.init = function(id, uiId, uiBodyId, pausePeriod) {
    a10.ss.inputId = id;
    a10.ss.uiId = uiId;
    a10.ss.uiBodyId = uiBodyId;
    if ('event' in a10) {
        a10.event.addListener(document.getElementById(id), "keyup", a10.ss.searchSuggestion);
        a10.event.addListener(document.documentElement, "click", a10.ss.closePopup);
    }

    if(pausePeriod) {
        a10.ss.PAUSE_PERIOD = pausePeriod; //allow override from constructor
    }
    // Request for search suggestion config on static server.  processSuggestConfig() will be called when
    // response is received.
    //using default pause period for now.
    //var jrObj = new JSONscriptRequest('http://sp.ask.com/config/a10/search_suggest_config.json');
    //jrObj.makeRequest();
};

/**
 * Closes the search suggestion popup
 */
a10.ss.closePopup = function() {
    var popup = $(a10.ss.uiId);
    if(popup) {
        popup.style.display = 'none';
    }
    if (a10.browser.isIE6() && a10.ss.popupIE6Cover) {
        a10.ss.popupIE6Cover.hide();
    }
}

/**
 * This is the keyup event handler for the search box.  It manages the timeout for the PAUSE_PERIOD, and
 * delegates all tasks to the searchSuggestHandler, which is invoked when the timeout expires.
 */
a10.ss.searchSuggestion = function(event) {
    var cookie = Cookie.getCookie("gset");

    if (a10.ss.hp == "true") {
        a10.ss.qsrc = a10.ss.ssQsrcHP;
    }

    // Apply the save settings cookie
    if ((!cookie) || (cookie.indexOf("ss=0") == -1))
    {
        if (!event) event = window.event

        // Trap special key event
        switch (event.keyCode ) {
            case 38: // Up Key
            // Handle double firing of arrow event for Safari versions older than 3
                if ((navigator.userAgent.indexOf('AppleWebKit') != -1) && (navigator.appVersion.indexOf("Version/") == -1)) {
                    if (a10.ss.skipNextArrowKeyEvent) {
                        a10.ss.skipNextArrowKeyEvent = false;
                        return;
                    } else {
                        a10.ss.skipNextArrowKeyEvent = true;
                    }
                }

                a10.ss.handleKey(38);
                return;
            case 40: // Down key
            // Handle double firing of arrow event for Safari versions older than 3
                if ((navigator.userAgent.indexOf('AppleWebKit') != -1) && (navigator.appVersion.indexOf("Version/") == -1)) {
                    if (a10.ss.skipNextArrowKeyEvent) {
                        a10.ss.skipNextArrowKeyEvent = false;
                        return;
                    } else {
                        a10.ss.skipNextArrowKeyEvent = true;
                    }
                }

                a10.ss.handleKey(40);
                return;
            case 13: // Enter key
            // Ignore it.  If don't ignore, will trigger search suggestion on the next result page.

                a10.ss.formSubmitted = true;
                a10.ss.closePopup();

                return;
            case 9: //Tab key
            case 18: //Alt Key
            //ignore
                return;
        }

        // Do nothing if key event didn't change the query string.
        if (a10.ss.currentQuery == $(a10.ss.inputId).value)  {
            return;
        }

        a10.ss.currentQuery = $(a10.ss.inputId).value;

        // Clear previously scheduled timeout (if any)
        if (a10.ss.pauseTimeoutID) {
            clearTimeout(a10.ss.pauseTimeoutID);
            a10.ss.pauseTimeoutID = null;
        }

        // Schedule new timeout
        a10.ss.pauseTimeoutID = setTimeout(function(){a10.ss.pauseTimeoutID = null; a10.ss.searchSuggestHandler();}, a10.ss.PAUSE_PERIOD);
    }
};

// TRES-9219
a10.ss.updateQsrc = function() {
    if (a10.ss.selectedIndex != -1) {
        var qsrcInput = document.getElementById("qsrc");
        if (qsrcInput) {
            qsrcInput.value = a10.ss.qsrc;
        }
    }
};


/**
 * Highlight a suggestion
 */
a10.ss.select = function(index) {

    var len = a10.ss.currentResults.length;

    function deselect(idx) {
        if (idx >= 0 && idx < len) {
            el = a10.ss.currentResults[idx];
            el.className = "";
        }
    };
    deselect(a10.ss.selectedIndex);

    var originalQuery = a10.ss.lastSuccessfulQuery;

    if (index >= 0 && index < len) {
        el = a10.ss.currentResults[index];

        /* Set the query to the currently selected option */
        links = el.getElementsByTagName('a');

        if (links.length == 0)  {
            return 0;
        }

        el.className = "selected";
    }
    else {
        a10.ss.setValue($(a10.ss.inputId), originalQuery);
    }

    /* Only deselect when we know we can successfully select something else */
    a10.ss.selectedIndex = index;
    return 1;
};

/**
 * Handles the up and down keys so that search suggestion results can be navigate using the keyboard.
 */
a10.ss.handleKey = function(direction) {
    var UP = 38;
    var DOWN = 40;

    var len = a10.ss.currentResults.length;

    /* Key handler helpers for moving selection and wrapping */

    function wrap(index) {
        if (index < -1) {
            return len-1;
        }
        else if (index >= len) {
            return -1;
        } 
        else {
            return index;
        }
    };


    if($(a10.ss.uiId).style.display != 'none' && len > 0) { 
        var current = a10.ss.selectedIndex;

        if (direction == UP) {
            delta = -1;
        } else if (direction == DOWN) {
            delta = +1
        }

        current += delta;
        current = wrap(current);

        /* There should only ever be one separator. If you encounter it while wrapping, move the cursor
         * again and select the new query.
         */
        if (!a10.ss.select(current)) {
            current += delta;
            current = wrap(current);
            a10.ss.select(current);
        }

        a10.ss.copyToInput(current);

    }
};

/**
 * Copy the contents of the specified selection to the input box
 */
a10.ss.copyToInput = function(index) {
    if (index < 0) {
        return;
    }
    el = a10.ss.currentResults[index];
    link = el.getElementsByTagName('a')[0];
    query = link.innerText || link.textContent;
    a10.ss.setValue($(a10.ss.inputId), query);
    a10.ss.currentQuery = query;
};


/**
 * Makes AJAX request to retrieve search suggestions for the query in the search box.  This is the timeout handler
 * that gets called with the user's typing has paused for PAUSE_PERIOD.
 */
a10.ss.searchSuggestHandler = function() {
    /*  Helper function. returns true if the given query (q) is a prefix of all the search suggestions in
        the anchors array.   */
    function isPrefixOf(q, anchors) {
        for (var i = 0; i < anchors.length; i++) {
            if (anchors[i].innerHTML.toLowerCase().indexOf(q.toLowerCase()) != 0) return false;
        }
        return true;
    }

    var v = $(a10.ss.inputId).value; // current query

    var jrObj; // JSON request object


    // Skip this event permanently if the the new query wouldn't yield new results.
    if (a10.ss.currentResults.length > 0 &&  // if there exists some results and...
        ((v == a10.ss.lastSuccessfulQuery) || // the query hasn't changed, or ...
         (v.length > a10.ss.lastSuccessfulQuery.length && // new chars have been added to the query
          isPrefixOf(v, a10.ss.currentResults)))) { // and the new query is still a prefix of all current results
        return;
    }

    // Skip this event permanently if the last successful query yielded no result and the new
    // query is identical or simply appends additional characters to the last query.
    var lowerCasedLastSuccessfulQuery = a10.ss.lastSuccessfulQuery? a10.ss.lastSuccessfulQuery.toLowerCase() : null;
    if (a10.ss.currentResults.length == 0 && v.toLowerCase().indexOf(lowerCasedLastSuccessfulQuery) == 0) {
        return;
    }

    if(v.length > 1) { // only request if there are more than one characters
        // Need to convert query to lower case as is required by the suggestion server API.
        a10.ss.pageHasMadeRequest = true;
        a10.ss2.execute(v, _country, _language);
    } else {
        a10.ss.lastSuccessfulQuery = null;

        // Clear currentResults
        a10.ss.currentResults = new Array();

        // Hide suggestions pane if it's shown
        if($(a10.ss.uiId).style.display != 'none') a10.ss.transitionSuggestion(true);
    }

};

/**
 * Callback method for when a response is received from the server. jsonData contains the payload.
 *
 * @param jsonData JSON data to process and display search suggestion to the user
 */
function suggestCallBack(jsonData) {
    //in refresh version, once form is submitted, no need to should search suggest
    if(a10.ss.formSubmitted) return;

    // Ignore any response for request made while on the previous result page.
    if (!a10.ss.pageHasMadeRequest) return;

    // Ignore response if the original request's query (jsonData["Query"]) differs from the current query
    var query = a10.ss2.getQuery(jsonData);
    if (query != $(a10.ss.inputId).value.toLowerCase()) return;

    a10.ss.selectedIndex = -1;
    a10.ss.lastSuccessfulQuery = query;
    var suggestions = a10.ss2.getSuggestions(jsonData);  // Array of suggestions

    if (suggestions.length > 0) {
        var suggestionsHTML = '';

         _origin = $F('o');

         if( _origin == ""){
            // Use origin = 0 as default
            _origin = 0;
         }

        _partnerID = $F('l');

         if( _partnerID == ""){
            // Use partnerID = dir as default
            _partnerID = 'dir';
         }

        _siteID = $F('siteid');
        
         if( _siteID == ""){
            // Use '' as default
            _siteID = '';
         } else {
             // TODO nelson - For UK locale, if siteID has the same value as origin, then we might only use origin and partner ID
            _siteID = '&siteid=' + $F('siteid');
         }
      
        // Loop through suggestion results and build HTML fragment for the suggestions. escape suggestions text to prevent truncation on mouse click e.g. single quote
        suggestionsHTML += a10.ss2.createSuggestions(suggestions, a10.ss.qsrc, _origin, _partnerID, _siteID, a10.ss.getCountry());

        //Ask kids does not show the disable link.
        if (typeof _disableSSApplicable == "undefined") {
            _disableSSApplicable = true;
        }
        //var _disableSSApplicable = true;
        if (_disableSSApplicable) {
            // Add the turn-off search suggestions link
            if (GlobalNav.Variables._isEraser || GlobalNav.Variables._isEraserOptOutEligible) {
                suggestionsHTML += "<div id='disablediv'><a id='ssdisable' href='#' onclick='askerasersuppressDialog.show();return false;'" +
                                   " class='L3'>"+ _disableSSMsg + "</a></div>"
            }
            else {
                var cookie = Cookie.getCookie("gset");
                if ((!cookie) || (cookie.indexOf("ss=0") == -1)) {
                suggestionsHTML += "<div id='disablediv'><a id='ssdisable' href='#' " +
                                   " onclick='a10.ss.turnOffSS()'" +
                                   " class='L3'>"+ _disableSSMsg + "</a></div>"
                }
            }
        }
        // Insert suggestion HTML into the document's DOM
        $(a10.ss.uiBodyId).innerHTML = suggestionsHTML;

        // Update currentResults with the new suggestions.
        a10.ss.currentResults = $(a10.ss.uiSuggestlistId).getElementsByTagName('li');

        // Show suggest pane if not visible
        if($(a10.ss.uiId).style.display == 'none') a10.ss.transitionSuggestion(false);

    }
    else {
        a10.ss.clearSuggestions();
    }

    a10.ss2.postRender();
};

a10.ss.getCountry = function() {
    var all = $('alltop') || $('all');
    var ctry = $('ctrytop') || $('ctry');
    var lang = $('langtop') || $('lang');

    if (!all || !ctry || !lang) return '';
    var _dm = 'all';
    if (all.checked) {
        _dm = 'all';
    }
    else if (ctry.checked) {
        _dm = 'ctry';
    }
    else if(lang.checked) {
        _dm = 'lang';
    }
    return _dm;
}

// Remove all suggestions and update the UI accordingly
a10.ss.clearSuggestions = function() {
    // Clear currentResults
    a10.ss.currentResults = new Array();

    // Show nothing
    $(a10.ss.uiBodyId).innerHTML = '<div class="lh18">'
            + '<span style="color:gray;padding-left:6px;">' + _noSSFoundMsg + '</span>'+ '</div>';
};

/**
 * Clears state information for search suggestion
 */
a10.ss.reset = function() {
    // Prevent suggestion results from appearing when user presses up/down key in the new result page.
    a10.ss.currentResults = new Array();

    // So will not trigger a request from an event left over from the previous page
    if (a10.ss.pauseTimeoutID) {
        clearTimeout(a10.ss.pauseTimeoutID);
        a10.ss.pauseTimeoutID = null;
    }

    // So will ignore response to suggestion request made on the previous page
    a10.ss.pageHasMadeRequest = false;

    a10.ss.lastSuccessfulQuery = null;
    a10.ss.hidden = true;
};

/**
 * Handles transition complete event
 *
 * @param hidden show/hide search suggestion
 */
a10.ss.transitionSuggestion = function(hidden) {
    a10.ss.hidden = hidden;

    if(hidden) {
        a10.ss.closePopup();
        a10.ss.transitionSuggestionDone();
    } else {
        a10.ss.transitionSuggestionDone();
    }
};

/*
 * Updates value of textfield and move the cursor to the end of the textfield
 *
 * @param input html input element
 * @param value value to set input element with
 */
a10.ss.setValue = function(input, value) {
    input.value = value;
    if(navigator.userAgent.indexOf('AppleWebKit') && input.setSelectionRange) {
        input.setSelectionRange(input.value.length, input.value.length);
    }
};

/**
 * Finish search suggestions transition.  Fade in whatever that needs to be shown, according to a10.ss.hidden.
 */
a10.ss.transitionSuggestionDone = function() {
    if (!a10.ss.hidden ) {
        $(a10.ss.uiId).style.display = '';
    }
}

/**
 * Turn off search suggestions
 */
a10.ss.turnOffSS = function() {
    var cookie = Cookie.getCookie("gset");

    var nextYr = new Date();
    nextYr.setFullYear(nextYr.getFullYear() + 2);

    // Apply the save settings cookie
    var newCookieVal = "ss=0";
    if ((cookie)) {
        if (cookie.indexOf("&ss=1") != -1) {
            // Split out the ss piece only
            var piecesArray = cookie.split("&ss=1");

            newCookieVal = piecesArray.join("");
        } else if (cookie.indexOf("&ss=0") != -1) {
            // Split out the ss piece only
            var piecesArray = cookie.split("&ss=0");

            newCookieVal = piecesArray.join("");
        }

        newCookieVal += "&ss=0";
    }
    Cookie.deleteCookie("gset", "/");

    document.cookie = 'gset=' + newCookieVal +'; expires=' + nextYr.toGMTString() + '; path=/; domain=.ask.com';
    var queryBox = $('q');
    if(queryBox) {
        queryBox.focus();
    }
};

//call back function to hook up additional functionality once the search suggestion module has been loaded
if(typeof ssloaded != 'undefined') {
    ssloaded();
}


