$(document).ready(function() {
    $(".twotabsearchtextbox").bind("keydown", function(event) { searchBoxHandler(event); });
});

/* functions for showing the details of a book in the userbookstore */
function showUserBookstoreBook(itemid){
	var item = "item_"+itemid;
	document.getElementById(item).style.display = 'block';
}
function hideUserBookstoreBook(itemid){
	var item = "item_"+itemid;
	document.getElementById(item).style.display = 'none';
}
/* END functions for showing the details of a book in the userbookstore */


function popup(url) {
    document.getElementById('overlay').style.display = 'block';
    document.getElementById('checkout').style.display = 'block';
    document.getElementById('checkout').innerHTML = '<iframe id="amazonIframe" src="' + url + '"></iframe><input id="amazonClose" type="button" value="Close" onclick="popclose();" />';
}
function popclose() {
    document.getElementById('overlay').style.display = 'none';
    document.getElementById('checkout').style.display = 'none';
}
function writeOrderCookie(CookieName, UniqueId, BookId, Price, Name, Image, Isbn) {
    //0 CookieName    Name of the  cookie
    //1 UniqueId      UniqueId. can be different for amazon and zwux
    //2 BookId        ID of the book
    //3 Price         Price of this book
    //4 Name          Name of the book
    //5 Image         Path to the image
    //6 Isbn          isbnnr user to link back to the Detail page
    //alert(CookieName + '  ' + UniqueId + '  ' + BookId + '  ' + Price + '  ' + Name + '  ' + Image + '  ' + Isbn);
    if (getCookieValue(CookieName)) {
        //Get the old cookie and check if the article is already in the cookie
        var Order_arr = GetOrderAsArray(CookieName);
        var CookieString = '';
        //loop through the old cookie values
        for (i = 0; i < Order_arr.length; i++) {
            //put a ~ if this is not the first article
            if (Order_arr[i][0] != UniqueId) {
                if (CookieString != '') {
                    CookieString += '~';
                }
                //add the old items from the cookie
                CookieString += Order_arr[i][0] + '|' + Order_arr[i][1] + '|' + Order_arr[i][2] + '|' + Order_arr[i][3] + '|' + Order_arr[i][4]+ '|' + Order_arr[i][5];
            }
        }
        //now add the new item
        CookieString += '~' + UniqueId + '|' + BookId + '|' + Price + '|' + Name + '|' + Image  + '|' + Isbn;
    } else {
        //add the first item in the shoppingcart
        CookieString = UniqueId + '|' + BookId + '|' + Price + '|' + Name + '|' + Image  + '|' + Isbn;
    }
    //delete the old cookie values and add the new values
    deleteCookie(CookieName);
    writeSessionCookie(CookieName, CookieString);
    //document.getElementById('shoppingcart').innerHTML = PrintShoppingCart(CookieName);
    //alert(CookieString);
}
function GetOrderAsArray(CookieName) {
    if (getCookieValue(CookieName)) {
        var Result_arr = [];
        var Order = getCookieValue(CookieName);
        var Products_arr = Order.split('~');
        for (i = 0; i < Products_arr.length; i++) {
            var Product_arr = Products_arr[i].split('|');
            Result_arr[i] = Product_arr;
        }
        return Result_arr;
    }
    else return false;
}
function DeleteItemInCart(CookieName, UniqueId) {
    if (GetOrderAsArray(CookieName)) {
        var Order_arr = GetOrderAsArray(CookieName);
        var Order_arr_length = Order_arr.length;
        deleteCookie(CookieName); //del old cookie
        for (var i = 0; i < Order_arr_length; i++) {
            if (Order_arr[i][0] != UniqueId) { // if this is not an article to be deleted..
                writeOrderCookie(CookieName, Order_arr[i][0], Order_arr[i][1], Order_arr[i][2], Order_arr[i][3], Order_arr[i][4], Order_arr[i][5]); //write the new cookie
            }
        }
        document.location.reload(true);
    }
}
function ShowShoppingCartCookie(CookieName) {
    // CookieName = name of the cookie
    var Result = '';
    if (GetOrderAsArray(CookieName)) {
        var Order_arr = GetOrderAsArray(CookieName);
        for (i = 0; i < Order_arr.length; i++) {
            if (!Order_arr[i][0] == "0" || !Order_arr[i][0] == "") { //0 and empty values are ignored
                var UniqueId = Order_arr[i][0];
                var BookId = Order_arr[i][1];
                var Price = Order_arr[i][2];
                var Name = Order_arr[i][3];
                var Image = Order_arr[i][4];
                var Isbn = Order_arr[i][5];
                Result += UniqueId + '|' + BookId + '|' + Price + '|' + Name + '|' + Image + '|' + Isbn +'\n';
            }
        }
    }
    alert(Result);
    //return Result;
}
function CountShoppingCart(CookieName) {
    // CookieName = name of the cookie
    var $Total = 0;
    if (GetOrderAsArray(CookieName)) {
        var Order_arr = GetOrderAsArray(CookieName);
        for (i = 0; i < Order_arr.length; i++) {
            if (!Order_arr[i][1] == "0" || !Order_arr[i][1] == "") { //0 and empty values are ignored
                $Total++;
            }
        }
    }
    return $Total;
}
function PrintShoppingCart(CookieName) {
    //Get the text we need from cookievalues...
    var Language = getLanguageFromUrl();
    var TextCookieName = 'Zwux' + Language;
    var DeleteText = 'Verwijder';  //GetTextFromCookie(TextCookieName, 'Delete');
    
    var Result = '';
    if (GetOrderAsArray(CookieName)) {
        var Total = 0;
        var Order_arr = GetOrderAsArray(CookieName);
        for (i = 0; i < Order_arr.length; i++) {
            if (!Order_arr[i][1] == "0" || !Order_arr[i][1] == "") { //0 and empty values are ignored
                var UniqueId = Order_arr[i][0];
                var BookId = Order_arr[i][1];
                var Amount = 1;
                var Price = Order_arr[i][2];
                var Name = Order_arr[i][3];
                var Image = Order_arr[i][4];
                var Isbn = Order_arr[i][5];
                Result += '<tr>';
                Result += '   <td class="description_row"><div class="shopimg"><a href="/bookmarket/' + getLocale() + '/books/detail/' + Isbn + '/' + encodeURIComponent(Name) + '"><img src="' + Image + '" /></a></div><a href="/bookmarket/' + getLocale() + '/books/detail/' + Isbn + '/' + encodeURIComponent(Name) + '">' + Name + '</a></td>';
                Result += '   <td class="deliver_row"></td>';
                Result += '   <td class="amount_row">' + Amount + '</td>';
                Result += '   <td class="price_row">' + Price + '</td>';
                Result += '   <td class="total_row">' + Price + '</td>';
                Result += '   <td class="save_row"><a href="#" onclick="DeleteItemInCart(\'' + CookieName + '\',\'' + UniqueId + '\')"><img src="/application/20_img/buttons/btn_delete.png" /></a></td>';
                Result += '</tr>';
            }
        }
    }
    return Result;
}
function WriteTextCookie(CookieName, Text) {
    var lv_periodType = 'years'; //"years","months","days","hours", "minutes"
    var lv_offset = '10';    //Number of units specified in periodType
    writePersistentCookie(CookieName, Text, lv_periodType, lv_offset);
}
function GetTextFromCookie(CookieName, TextToGet) {
    // expects cookie to look something like this: 'Delete|del~Close|close~Update|upd'
    if (getCookieValue(CookieName)) {
        var Result_arr = [];
        var Text = getCookieValue(CookieName);
        var Text_arr = Text.split('~');
        for (i = 0; i < Text_arr.length; i++) {
            var Word_arr = Text_arr[i].split('|');
            if (TextToGet == Word_arr[0]) {
                return (Word_arr[1]);
            }
        }
    }
    else return false;
}
//************************************
//Start function show sellers
//************************************
function showSellers(divString, totalRows) {
    //Show all sellers
    for (var i = 1; i <= totalRows; i++) {
        var objFilter = document.getElementById("div_" + divString + "_" + i);
        if (objFilter) {
            if (isMsie) {
                objFilter.setAttribute("className", "showseller");
            } else {
                objFilter.setAttribute('class', 'showseller')
            }
        }
    }
    return false;
}
//************************************
//Show hide main menu
//************************************
function toggleMenu(menuid, totalRows) {
    //hide all menu's
    for (var i = 1; i <= totalRows; i++) {
        var Level = document.getElementById("mt_" + i);
        var thisLevel = document.getElementById("m_" + i);
        if (thisLevel) {
            Level.setAttribute("className", "");
            Level.setAttribute("class", "");
            thisLevel.style.display = 'none';
        }
    }
    // now open the active one.
    var Level = document.getElementById("mt_" + menuid);
    var thisLevel = document.getElementById("m_" + menuid);
    if (thisLevel.style.display == "none") {
        thisLevel.style.display = "block";
        Level.setAttribute("className", "navActive");
        Level.setAttribute("class", "navActive");
        return false;
    } else {
        thisLevel.style.display = "none";
        thisLevel.style.Visibility = "hidden";
        return false;
    }
}
//************************************
//Set the values in a session var php
//************************************
function setValues(mId, sId) {
    writeSessionCookie('mId', mId);
    writeSessionCookie('sId', sId);
}
function readCookie(name) {
    var ca = document.cookie.split(';');
    var nameEQ = name + "=";
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length); //delete spaces
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}
//************************************
//Open main menu on the right node
//************************************
function openMenu() {
    // now open the active one.
    var mId = readCookie("mId");
    var sId = readCookie("sId");
    var thisLevelText = document.getElementById("mt_" + mId);
    var thisLevel = document.getElementById("m_" + mId);
    var thisSubLevel = document.getElementById("s_" + sId);
    if (mId != null) {
        if (thisLevel.style.display == "none") {
            thisLevel.style.display = "block";
            thisLevelText.setAttribute("className", "navActive");
            thisSubLevel.setAttribute("className", "subnavActive");
            thisLevelText.setAttribute("class", "navActive");
            thisSubLevel.setAttribute("class", "subnavActive");
            return false;
        } else {
            var thisLevel = document.getElementById("m_" + mId);
            thisLevel.style.display = "none";
            return false;
        }
    }
}
//************************************
//Show hide tabs start
//************************************
function toggleTab(tabId) {
    //hide all menu's
    for (var i = 1; i <= 6; i++) {
        var t = document.getElementById("t" + i);
        var s = document.getElementById("s" + i);
        if (t) {
            t.style.backgroundPosition = '0% -42px';
        }
        if (s) {
            s.style.backgroundPosition = '0% -42px';
        }
        var objFilter = document.getElementById("d" + i);
        if (objFilter) {
            objFilter.style.display = 'none';
        }
    }
    // now open the active one.
    var thisLevel = document.getElementById("d" + tabId);
    if (thisLevel.style.display == "none") {
        thisLevel.style.display = "block";
        document.getElementById("t" + tabId).style.backgroundPosition='0% 1px';
        document.getElementById("s" + tabId).style.backgroundPosition='100% 0px';
        return false;
    } else {
        thisLevel.style.display = "none";
        return false;
    }
}
//************************************
//Show hide tabs End
//************************************
// Get the language parameter from the url
function getLanguageFromUrl() {
    pathArray = window.location.pathname.split('/');
    var locale   = pathArray[2];
    var language = locale.substr(locale.length-2);
    //alert(language);
    return language;
}
// Get the language parameter from the url
function getLocale() {
    pathArray = window.location.pathname.split('/');
    var locale = pathArray[2];
    return locale;
}
/**
* AJAX
*/
function filterBooks(string1) {
    http.open("GET", string1, true);
    document.getElementById('main_content').innerHTML = ('<span><img id="ajaxloaderImg" src="/application/20_img/ajax-loader.gif" /></span>');
    http.onreadystatechange = handleHttpResponse;
    http.send(null);
}
function handleHttpResponse() {
    if (http.readyState == 4) {
        if (http.status == 200) {
            var results = http.responseText;
            //document.getElementById('results').innerHTML = results;
            document.getElementById('main_content').innerHTML = results;
        }
    }
}
function getHTTPObject() {
    var xmlhttp;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        if (!xmlhttp) {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
    }
    return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
function GetXmlHttpObject() {
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        return new XMLHttpRequest();
    }
    if (window.ActiveXObject) {
        // code for IE6, IE5
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return null;
}
var xhttp;
function showResult(str) {
    if (str.length == 0) {
        document.getElementById("livesearch").innerHTML = "";
        document.getElementById("livesearch").style.border = "0px";
        return;
    }
    xhttp = GetXmlHttpObject()

    if (xhttp == null) {
        alert("Your browser does not support XML HTTP Request");
        return;
    }
    var url = "/application/40_ajax_php/livesearch.php";
    url = url + "?q=" + str;
    url = url + "&sid=" + Math.random();
    xhttp.onreadystatechange = stateChanged;
    xhttp.open("GET", url, true);
    xhttp.send(null);
}
function stateChanged() {
    if (xhttp.readyState == 4) {
        document.getElementById("livesearch").innerHTML = xhttp.responseText;
        document.getElementById("livesearch").style.border = "1px solid #A5ACB2";
    }
}
/**
* Filter
*/
//Below all filter functions
var cintTotal = 10;
var checkboxesDisabled = false;
function openFilter(cbox) {
    var select;
    objLink = document.getElementById("f" + cbox);
    if (objLink.className.length > 0 && objLink.className + "" == 'selected') {
        select = '';
    } else {
        select = 'selected';
    }
    //now hide the open filter
    hideFilter();
    document.getElementById("f" + cbox).className = select;
}
function initCheckbox(intNum) {
    var strChecked = '';
    var arrInputs = document.getElementsByTagName("input");
    for (var i = 0; i < arrInputs.length; i++) {
        // All the inputboxes you can find below now ON!!
        if (arrInputs[i].id.indexOf("o") > -1 && (arrInputs[i].checked == true)) {
            strChecked += arrInputs[i].id + ",";
        }
    }
    //alert(strChecked);
    document.getElementById('filterSelection').value = strChecked;

}
function hideFilter() {
    arrLinks = document.getElementsByTagName('a');
    for (var i = 0; i < arrLinks.length; i++) {
        objLink = arrLinks[i];
        if (objLink.getAttribute('id')) {
            linkId = objLink.getAttribute('id');
            //Look for all href's in the document with the name 'f....' end remove the last char.
            if (linkId.substring(0, 1) == "f") {
                document.getElementById(linkId).className = '';
            }
        }
    }
}
function updateVars(intNum) {
    var objFilterOpties = document.getElementById("f_" + intNum);
    var blnAlGetoond = (objFilterOpties && objFilterOpties.style.display == 'block');
    geenFilter();
    if (blnAlGetoond || !objFilterOpties) {
        return false;
    }
    objFilterOpties.style.display = 'block';
    var objGefilterdOp = document.getElementById("f_on");
    var objGefilterdOpFilter = document.getElementById("fon_" + intNum);
    if (objGefilterdOp && objGefilterdOpFilter) {
        objGefilterdOpFilter.innerHTML = objGefilterdOp.innerHTML;
    }
    return false;
}
function geenFilter() {
    for (var i = 1; i <= cintTotal; i++) {
        var objFilter = document.getElementById("f_" + i);
        if (objFilter) {
            objFilter.style.display = 'none';
        }
    }
}
function fillArray(intNum) {
    var strSelected = '';
    var strSelection = '';
    var strFiltername = '';
    var arrInputs = document.getElementsByTagName("input");
    for (var i = 0; i < arrInputs.length; i++) {
        if (arrInputs[i].id.indexOf("o" + intNum + "_") > -1 && arrInputs[i].checked) {
            strSelected = arrInputs[i].value;
            strSelection += strSelected + ",";
            strFiltername = arrInputs[i].name;
        }
    }
    //alert(strSelection);
    var strLen = strSelection.length;
    strSelection = strSelection.slice(0, strLen - 1);
    if (strFiltername == 'cat') {
        document.getElementById('categoryid').value = strSelection;
        //alert(document.getElementById('categoryid').value);
    } else if (strFiltername == 'author') {
        document.getElementById('authorid').value = strSelection;
        //alert(document.getElementById('authorid').value);
    } else if (strFiltername == 'publisher') {
        document.getElementById('publisherid').value = strSelection;
        //alert(document.getElementById('publisherid').value);
    }
}
function show(step, intNum, page) {
    initCheckbox(intNum);
    var url = "/application/40_ajax_php/booksresult.php?categoryid=" + document.getElementById('categoryid').value + "&pcategoryid=" + document.getElementById('pcategoryid').value + "&displayname=" + document.getElementById('displayname').value + "&tagid=" + document.getElementById('tagid').value + "&resultpage=" + page + "&filterselection=" + document.getElementById('filterSelection').value + "&p_rows=" + document.getElementById('p_rows').value + "&offset=" + document.getElementById('offset').value + "&authorid=" + document.getElementById('authorid').value + "&region=" + document.getElementById('region').value + "&language=" + document.getElementById('language').value + "&publisherid=" + document.getElementById('publisherid').value + "&step=" + step + "";
    //alert(url);
    filterBooks(url);
    return false;
}
// End filter functions


// start autocomplete functions
var curSelection = -1;
var curSuggestions = [];
var curSize = 0;
var curText = "";
var curTextSel = "";
var hideDelayTimerId = null;
var searchSuggestionTimerId = null;
var maxSuggestions = 10;
var prevWndResizeEventHandler = null;
var prevWndOnLoadEventHandler = null;
var isMsie = false;
var suggestRequest = null;
var defaultAction = "";
var clientId = "amazon-search-ui";
var suggestionsLoaded = false;
var suggestDiv = null;

function attachEventListener(elemObj, eventType, eventHandler) {
    var eventName = "on" + eventType; if (elemObj.addEventListener)
    { elemObj.addEventListener(eventType, eventHandler, false); }
    else
        if (elemObj.attachEvent)
    { elemObj.attachEvent(eventName, eventHandler); }
    else {
        var f = elemObj[eventName]; elemObj[eventName] = function() {
            var res1 = f.apply(this, arguments); var res2 = eventHandler.apply(this, arguments); if (res1 == undefined)
            { return res2; }
            else {
                if (res2 == undefined)
                { return res1; }
                else
                { return res2 && res1; }
            }
        };
    }
}
function initSearchSuggest() {
    if (suggestionsLoaded) return; isMsie = navigator.userAgent.toLowerCase().indexOf("msie") != -1; var searchBox = getSearchBox(); if (searchBox) {
    curText = searchBox.value; searchBox.setAttribute("autocomplete", "off"); attachEventListener(searchBox, "keydown", onKeyDownEvent); attachEventListener(searchBox, "keyup", onKeyUpEvent); attachEventListener(searchBox, "keypress", onKeyPressedEvent); attachEventListener(searchBox, "blur", onFocusLost); prevWndResizeEventHandler = window.onresize; attachEventListener(window, "resize", onWindowResized); var searchForm = getSearchForm();
        if (searchForm){ defaultAction = searchForm.action; }
        suggestionsLoaded = true;
        if (window.issMktid == 6) {
            window.setInterval(function() {var val = searchBox.value; if (val != curText && val != curTextSel){ curText = val; setSearchSuggestionTimeout(); }}, 20);
        }
    }
}
function supportedSearchAlias(alias) {
    var found = 0; if (window.issSearchAliases) {
        for (i = 0; i < window.issSearchAliases.length; i++) {
            if (alias == window.issSearchAliases[i])
            { found = 1; break; }
        }
    }
    return found;
}
function searchBoxHandler(e) {
    if (e.which == 13) {
        setKeyword();
    }
}
function onKeyDownEvent(event) {
    var key = event.keyCode; switch (key)
    { case 40: moveDown(); stopEvent(event); break; case 38: moveUp(); stopEvent(event); break; }
}
function onKeyUpEvent(event) {
    var key = event.keyCode; switch (key) {
        case 13: if (window.issMktid != 6) HideSuggestionsDiv(); break; case 40: break; case 38: break; case 37: break; case 39: break;default:
            {
                var val = getSearchBox().value;
                if (val != curText) { curText = val; setSearchSuggestionTimeout(); }
            }
            break;
    }
}
function onKeyPressedEvent(event) {
    if (event.keyCode == 27 && getSearchSuggest().style.display != "none")
    { setSuggestionHideTimeout(); getSearchBox().value = curText; return false; }
}
function onFocusLost(event) {
$('#main_content').css({ 'z-index': '0' })
setSuggestionHideTimeout(); }
function onWindowResized(event) {
    getSearchSuggest().style.width = getSearchBox().offsetWidth; if (prevWndResizeEventHandler)
    { prevWndResizeEventHandler(event); }
}
function displaySuggestions(curSuggestions, curPrefix) {
    $('#main_content').css({ 'z-index': '-1' })
    try
{ curSize = Math.min(maxSuggestions, curSuggestions.length); }
    catch (e)
{ curSize = 0; }
    var ss = getSearchSuggest(); ss.innerHTML = ''; if (curSize > 0)
    { ss.style.display = ""; ss.innerHTML += '<div id="sugdivhdr" align="right"> ' + getSuggestionsDivTitle() + '</div>'; }
    else
    { HideSuggestionsDiv(); }
    for (i = 0; i < curSize; ++i)
    { var suggest = '<div id="sugdiv' + i + '" onmouseover="javascript:suggestOver(this);" '; suggest += 'onmouseout="javascript:suggestOut(this);" '; suggest += 'onclick="javascript:setSearchByIndex(' + i + ');" '; suggest += 'class="suggest_link">' + getFormatedSuggestionLine(curSuggestions[i], curPrefix) + '</div>'; ss.innerHTML += suggest; }
    if (curSize > 0)
    { ss.innerHTML += '<div id="sugdivhdr" align="right">&nbsp;</div>'; }
}
function suggestOver(div_value)
{ div_value.style.cursor = "default"; unhighlightCurrentSuggestion(); divId = div_value.id; curSelection = divId.substr(6); highlightCurrentSuggestion(false); }
function suggestOut(div_value)
{ unhighlightSuggestion(div_value); }
function setSearch(value, indexInList) {
    curTextSel = value; getSearchBox().value = value; var actionForm = getSearchForm(); var actionVal = defaultAction;
    if (indexInList >= 0) {
        //actionVal += '_' + indexInList + '_' + curText.length; var prefixElems = document.getElementsByName('sprefix'); var inputPrefix = null; if (prefixElems.length > 0)
        actionVal += value + '/1'; var prefixElems = document.getElementsByName('sprefix'); var inputPrefix = null;
        if (prefixElems.length > 0) {
            inputPrefix = prefixElems[0]; inputPrefix.setAttribute("value", curText);
        } //else {
           // inputPrefix = document.createElement("input"); inputPrefix.setAttribute("type", "hidden"); inputPrefix.setAttribute("name", "sprefix"); inputPrefix.setAttribute("value", curText); getSearchForm().appendChild(inputPrefix);
        //}
    } else {
        var prefixElems = document.getElementsByName('sprefix'); for (var i = prefixElems.length - 1; i >= 0; --i)
        { getSearchForm().removeChild(prefixElems[i]); }
    }
    actionForm.action = actionVal;
}
function setKeyword() {
    var curText = getSearchBox().value;
    var actionForm = getSearchForm();
    var actionVal = defaultAction;
    actionVal += curText + '/1';
    actionForm.action = actionVal;
}
function setSearchByIndex(index)
{ setSearch(curSuggestions[index], index); getSearchSuggest().innerHTML = ''; var navBarForm = getSearchForm(); navBarForm.submit(); }
function highlightSuggestion(div_value)
{ div_value.className = 'suggest_link_over'; }
function unhighlightSuggestion(div_value)
{ div_value.className = 'suggest_link'; }
function highlightCurrentSuggestion(updateSearchBox) {
    if (updateSearchBox) {
        if (curSelection == -1)
        { setSearch(curText, -1); }
        else
        { setSearch(curSuggestions[curSelection], curSelection); }
    }
    var selection = document.getElementById('sugdiv' + curSelection); highlightSuggestion(selection);
}
function unhighlightCurrentSuggestion() {
    var selection = null; try
{ selection = document.getElementById('sugdiv' + curSelection); }
    catch (e) { }
    if (selection)
    { unhighlightSuggestion(selection); }
}
function moveDown() {
    if (curSize <= 0) return; try {
        unhighlightCurrentSuggestion(); if (curSelection >= curSize - 1)
        { curSelection = -1; }
        else
        { ++curSelection; }
        highlightCurrentSuggestion(true);
    }
    catch (ex)
{ }
}
function moveUp() {
    if (curSize <= 0) return; try {
        unhighlightCurrentSuggestion(); if (curSelection < 0)
        { curSelection = curSize - 1; }
        else
        { --curSelection; }
        highlightCurrentSuggestion(true);
    }
    catch (ex)
{ }
}
function stopEvent(event) {
    if (isMsie)
    { event.cancelBubble = true; }
    else
    { event.preventDefault(); }
}
function getFormatedSuggestionLine(curSuggestion, curPrefix) {
    var lowercaseCurrentText = curPrefix.toLowerCase(); var lowercaseCurrentSuggestion = curSuggestion.toLowerCase(); var len = curPrefix.length; var start = lowercaseCurrentSuggestion.indexOf(lowercaseCurrentText); if (start == -1)
    { return curSuggestion; }
    return curSuggestion.substr(0, start) + "<b>" + curSuggestion.substr(start, len) + "</b>" + curSuggestion.substr(start + len);
}
function getSearchBox() {
    return document.getElementById('twotabsearchtextbox');
}
function getSearchSuggest() {
    if (!suggestDiv)
    { suggestDiv = createSuggestionDiv(getSearchBox()); }
    return suggestDiv;
}
function getSearchForm()
{ return document.getElementsByName('sitesearch')[0]; }
function getSearchAlias() {
    var searchInCtrl = document.getElementsByName('url')[0]; var aliasName = searchInCtrl.value.match(/search-alias\s*=\s*([\w-]+)/); if (aliasName)
    { return aliasName[1]; }
    else
    { return null; }
}
function findPos(obj) {
    var curleft = curtop = 0; if (obj.offsetParent) {
        do
        { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent);
    }
    return [curleft, curtop];
}

function createSuggestionDiv(parent) {
    var suggestionDiv = document.createElement("div"); suggestionDiv.style.border = "1px solid black"; suggestionDiv.style.position = "absolute"; suggestionDiv.style.backgroundColor = "white"; suggestionDiv.style.color = "black"; var parentPos = findPos(parent); suggestionDiv.style.left = parentPos[0]; if (isMsie)
    { suggestionDiv.style.top = "50px"; suggestionDiv.style.left = "190px"; suggestionDiv.style.width = "540px"; suggestionDiv.style.backgroundColor = "white"; }
    suggestionDiv.style.width = parent.offsetWidth; suggestionDiv.style.zIndex = "130"; suggestionDiv.style.display = "none"; suggestionDiv.id = "search_suggest"; parent.parentNode.appendChild(suggestionDiv); return suggestionDiv;
}
function setSuggestionHideTimeout() {
    hideDelayTimerId = setTimeout(function() {
        return (function()
        { hideDelayTimerId = null; HideSuggestionsDiv(); });
    } (), 300);
}
function setSearchSuggestionTimeout() {
    if (searchSuggestionTimerId)
    { clearTimeout(searchSuggestionTimerId); searchSuggestionTimerId = null; }
    searchSuggestionTimerId = setTimeout(function() {
        return (function()
        { searchJSONSuggest(); searchSuggestionTimerId = null; curSelection = -1; });
    } (), 100);
}
function getSuggestionsDivTitle() {
    if (window.issMktid == '4') return 'Suchvorschl&auml;ge';
    if (window.issMktid == '5') return 'Suggestions de recherche'; 
    if (window.issMktid == '6') return '&#12461;&#12540;&#12527;&#12540;&#12489;&#20505;&#35036;'; return 'Search suggestions';
}
function HideSuggestionsDiv()
{ curSize = 0; getSearchSuggest().innerHTML = ''; getSearchSuggest().style.display = "none"; curSelection = -1; }
function searchJSONSuggest() {
    if (suggestRequest) {
        suggestRequest.removeScriptTag();
    }
    var searchAlias = getSearchAlias();
    if (!supportedSearchAlias(searchAlias)) {
        return;
    }
    curText = getSearchBox().value; if (curText.length == 0)
    { HideSuggestionsDiv(); return; }
    var str = encodeURIComponent(curText); var suggestUrl = window.parent.document.location.protocol + '//' + window.issHost + '?' + 'method=completion' +
'&q=' + str +
'&search-alias=' + searchAlias +
'&client=' + clientId +
'&mkt=' + window.issMktid +
'&x=updateCompletion'; suggestRequest = new A9RequestClient(suggestUrl); suggestRequest.buildScriptTag(); suggestRequest.addScriptTag();
}
function updateCompletion() {
    if (suggestRequest)
    { suggestRequest.removeScriptTag(); suggestRequest = null; }
    var curPrefix = completion[0]; curSuggestions = completion[1]; displaySuggestions(curSuggestions, curPrefix);
}
function A9RequestClient(fullUrl) {
    this.fullUrl = fullUrl; this.noCacheIE = '&noCacheIE=' + (new Date()).getTime(); this.headLoc = document.getElementsByTagName("head").item(0); this.scriptId = 'JscriptId' + A9RequestClient.scriptCounter++;
}
A9RequestClient.scriptCounter = 1; A9RequestClient.prototype.buildScriptTag = function()
{ this.scriptObj = document.createElement("script"); this.scriptObj.setAttribute("type", "text/javascript"); this.scriptObj.setAttribute("charset", "utf-8"); this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE); this.scriptObj.setAttribute("id", this.scriptId); }
A9RequestClient.prototype.removeScriptTag = function() {
    try
{ this.headLoc.removeChild(this.scriptObj); }
    catch (e)
{ }
}
A9RequestClient.prototype.addScriptTag = function()
{ this.headLoc.appendChild(this.scriptObj); }
if (zwuxJQ) {
    zwuxJQ.declareAvailable('search-js-jq'); if (jQuery)
    { jQuery(function() { initSearchSuggest(); }); }
}
else
{ initSearchSuggest(); }
// end autocomplete functions
