﻿// Variable for XMLHttpRequest Object
var req;

var SearchBoxID = "ctl00_ContentPlaceHolder_MainBodyContent_autoCompleteSearchBox";
var SearchBoxID2 = "ctl00_ContentPlaceHolder_SideBarContent_autoCompleteSearchBox";
var SearchBoxID3 = "autoCompleteSearchBox";

//Creates the XMLHttpRequest taking browser also into account.
function Initialize() {
    try {
        req = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
        try {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (oc) {
            req = null;
        }
    }

    if (!req && typeof XMLHttpRequest != "undefined") {
        req = new 
        XMLHttpRequest();
    }
}

//For retreiving the KeyCode of the Key Pressed.
//document.onkeydown = keyCheck;

//Variable for holding the KeyCode of the Key pressed.
var keyId;


//Function which gives places the keycode in the corresponding variable.
function KeyDownCheck(e) {
    if (!e)
        e = window.event;

    if (window.event) {
        keyId = e.keyCode;
    }
    else if (e.which) {
        keyId = e.which;
    }
    if (keyId == 13) {
        RedirectToSearchPage();
    }
    if (keyId == 40 || keyId == 38) {
        requestSuggestions(true);
    }
}


//Function for making the async call to another page which recieves the search param and returns the word suggestions.
function requestSuggestions(flag) {
    var textbox;
    if ($(SearchBoxID)) {
        textbox = $(SearchBoxID);
        var key = textbox.value;
    }
    else if ($(SearchBoxID2)) {
        textbox = $(SearchBoxID2);
        var key = textbox.value;
    }
    else {
        textbox = $(SearchBoxID3);
        var key = $(SearchBoxID3).value;
    }
    var key = textbox.value;

    if (keyId == 13) {
        removeMarkupTag(textbox);
        cleanPlainText(textbox);
        RedirectToSearchPage();
    }
    // Make a call only if the search string has a length > 2
    if (key.length > 0) {
        // check if the key pressed is "down arrow" or "Up arrow" key.
        if (keyId != 40 && keyId != 38) {
            Initialize();
            var requestUrl = "/howtotell/AutoCompleteResponsePage.aspx?key=" + encodeURIComponent(key) + "&from=SideBar&displayLang=" + displayLang;

            if (req != null) {
                req.onreadystatechange = Process;
                req.open("GET", requestUrl, true);
                req.send(null);
            }
        }
        else if (flag == true) {
            // Code for handling up and down arrow keys.
            var currentRow = $("ActiveSuggestion").value;
            var currentRowIndex = parseInt(currentRow, 0);
            var tableElement = $("AutoCompleteSuggestions");
            var TableRows = tableElement.getElementsByTagName("TR");
            var index = 0;
            var autoCompleteDIV = tableElement.parentElement;
            var tableLength = TableRows.length;
            if (keyId == 40) {
                if (tableLength > 0 && ((currentRowIndex + 1) % tableLength) < TableRows.length) {
                    currentRowIndex += 1;
                    $("ActiveSuggestion").value = currentRowIndex % tableLength;
                    //if(currentRowIndex - 1 >=0)
                    for (index = 0; index < TableRows.length; index++) {
                        TableRows.item(parseInt(index, 0)).style.backgroundColor = "#e6ece5";

                        if (navigator.userAgent.indexOf("MSIE") >= 0) {
                            TableRows.item(parseInt(index, 0)).childNodes(0).style.color = "";
                        }
                        else {
                            TableRows[index].getElementsByTagName("td")[0].style.color = "";
                        }
                    }

                    TableRows.item(parseInt(currentRowIndex % tableLength, 0)).style.backgroundColor = "#8daa8c";
                    if (navigator.userAgent.indexOf("MSIE") >= 0) {
                        TableRows.item(parseInt(currentRowIndex % tableLength, 0)).childNodes(0).style.color = "white";
                        textbox.value = TableRows.item(parseInt(currentRowIndex % tableLength, 0)).childNodes(0).innerText;
                    }
                    else {
                        TableRows[currentRowIndex % tableLength].getElementsByTagName("td")[0].style.color = "white";
                        textbox.value = TableRows[currentRowIndex % tableLength].getElementsByTagName("td")[0].textContent;
                    }
                    tableElement.scrollTop = TableRows.item(parseInt(currentRowIndex % tableLength, 0)).offsetTop;
                }
            }
            else {
                if ((tableLength + currentRowIndex - 1) % tableLength >= 0) {

                    currentRowIndex -= (1 - tableLength);
                    $("ActiveSuggestion").value = currentRowIndex % tableLength;
                    for (index = 0; index < TableRows.length; index++) {
                        TableRows.item(parseInt(index, 0)).style.backgroundColor = "#e6ece5";
                        if (navigator.userAgent.indexOf("MSIE") >= 0) {
                            TableRows.item(parseInt(index, 0)).childNodes(0).style.color = "";
                        }
                        else {
                            TableRows[index].getElementsByTagName("td")[0].style.color = "";
                        }
                    }

                    TableRows.item(parseInt(currentRowIndex % tableLength, 0)).style.backgroundColor = "#8daa8c";
                    if (navigator.userAgent.indexOf("MSIE") >= 0) {
                        TableRows.item(parseInt(currentRowIndex % tableLength, 0)).childNodes(0).style.color = "white";
                        textbox.value = TableRows.item(parseInt(currentRowIndex % tableLength, 0)).childNodes(0).innerText;
                    }
                    else {
                        TableRows[currentRowIndex % tableLength].getElementsByTagName("td")[0].style.color = "white";
                        textbox.value = TableRows[currentRowIndex % tableLength].getElementsByTagName("td")[0].textContent;
                    }
                    tableElement.scrollTop = TableRows.item(parseInt(currentRowIndex % tableLength, 0)).offsetTop;
                }
            }
        }
    }
    else {
        HideDiv("AutoCompleteSuggestions");
    }
}


//Function for making the async call from main content of search page to another page which recieves the search param and returns the word suggestions.
function requestMainSuggestions(flag) {
    var textbox = $(SearchBoxID);
    var key = textbox.value;

    if (keyId == 13) {
        removeMarkupTag(textbox);
        cleanPlainText(textbox);
        RedirectToSearchPagefromSearch();
    }
    // Make a call only if the search string has a length > 2
    if (key.length > 0) {
        // check if the key pressed is "down arrow" or "Up arrow" key or "Left" arrow key or "right" arrow key
        if (keyId != 40 && keyId != 38 && keyId != 37 && keyId != 39) {
            Initialize();
            var requestUrl = "/howtotell/AutoCompleteResponsePage.aspx?key=" + encodeURIComponent(key) + "&from=SearchPage&displayLang=" + displayLang;

            if (req != null) {
                req.onreadystatechange = ProcessSearchPage;
                req.open("GET", requestUrl, true);
                req.send(null);
            }
        }
        else if (flag == true) {
            // Code for handling up and down arrow keys.
            var currentRow = $("ActiveSuggestion").value;
            var currentRowIndex = parseInt(currentRow, 0);
            var tableElement = $("AutoCompleteSuggestions");
            var TableRows = tableElement.getElementsByTagName("TR");
            var index = 0;
            var autoCompleteDIV = tableElement.parentElement;

            if (keyId == 40) {
                if (currentRowIndex + 1 < TableRows.length) {
                    currentRowIndex += 1;
                    $("ActiveSuggestion").value = currentRowIndex;
                    //if(currentRowIndex - 1 >=0)
                    for (index = 0; index < TableRows.length; index++) {
                        TableRows.item(parseInt(index, 0)).style.backgroundColor = "#e6ece5";
                        if (navigator.userAgent.indexOf("MSIE") >= 0) {
                            TableRows.item(parseInt(index, 0)).childNodes(0).style.color = "";
                        }
                        else {
                            TableRows[index].getElementsByTagName("td")[0].style.color = "";
                        }

                    }

                    TableRows.item(parseInt(currentRowIndex, 0)).style.backgroundColor = "#8daa8c";

                    if (navigator.userAgent.indexOf("MSIE") >= 0) {
                        TableRows.item(parseInt(currentRowIndex, 0)).childNodes(0).style.color = "white";
                        textbox.value = TableRows.item(parseInt(currentRowIndex, 0)).childNodes(0).innerText;
                    }
                    else {
                        TableRows[currentRowIndex].getElementsByTagName("td")[0].style.color = "white";
                        textbox.value = TableRows[currentRowIndex].getElementsByTagName("td")[0].textContent;
                    }

                    tableElement.scrollTop = TableRows.item(parseInt(currentRowIndex, 0)).offsetTop;
                }
            }
            else {
                if (currentRowIndex - 1 >= 0) {
                    currentRowIndex -= 1;
                    $("ActiveSuggestion").value = currentRowIndex;
                    for (index = 0; index < TableRows.length; index++) {
                        TableRows.item(parseInt(index, 0)).style.backgroundColor = "#e6ece5";
                        if (navigator.userAgent.indexOf("MSIE") >= 0) {
                            TableRows.item(parseInt(index, 0)).childNodes(0).style.color = "";
                        }
                        else {
                            TableRows[index].getElementsByTagName("td")[0].style.color = "";
                        }
                    }

                    TableRows.item(parseInt(currentRowIndex, 0)).style.backgroundColor = "#8daa8c";
                    if (navigator.userAgent.indexOf("MSIE") >= 0) {
                        TableRows.item(parseInt(currentRowIndex, 0)).childNodes(0).style.color = "white";
                        textbox.value = TableRows.item(parseInt(currentRowIndex, 0)).childNodes(0).innerText;
                    }
                    else {
                        TableRows[currentRowIndex].getElementsByTagName("td")[0].style.color = "white";
                        textbox.value = TableRows[currentRowIndex].getElementsByTagName("td")[0].textContent;
                    }
                    tableElement.scrollTop = TableRows.item(parseInt(currentRowIndex, 0)).offsetTop;
                }
            }
        }
    }
    else {
        HideDiv("AutoCompleteSuggestions");
    }
}

// Function to catch the response of the Asyn Call and then bind the resulting HTML to the DIV which is placed below the Search Text Box
function Process() {
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            if (req.responseText == "")
                HideDiv("AutoCompleteSuggestions");
            else {
                ShowDiv("AutoCompleteSuggestions");
                var AutoSuggestionsDiv = $("AutoCompleteSuggestions")
                AutoSuggestionsDiv.innerHTML = req.responseText;
                var tableRowsCount = AutoSuggestionsDiv.getElementsByTagName("TR");

                if (tableRowsCount.length > 11) {
                    AutoSuggestionsDiv.className = "div_AutoComplete";
                    AutoSuggestionsDiv.style.height = tableRowsCount.item(11).offsetTop;
                }
                else {
                    AutoSuggestionsDiv.className = "div_AutoCompleteSmall";
                    AutoSuggestionsDiv.style.height = tableRowsCount.item(tableRowsCount.length - 1).offsetTop + tableRowsCount.item(tableRowsCount.length - 1).offsetHeight;
                }
            }
        }
    }
}


// Function to catch the response of the Asyn Call and then bind the resulting HTML to the DIV which is placed below the Search Text Box
function ProcessSearchPage() {
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            if (req.responseText == "")
                HideDiv("AutoCompleteSuggestions");
            else {
                ShowMainSearchDiv("AutoCompleteSuggestions");
                var AutoSuggestionsDiv = $("AutoCompleteSuggestions")
                AutoSuggestionsDiv.innerHTML = req.responseText;
                AutoSuggestionsDiv.style.left = findPosX($(SearchBoxID), true);
                AutoSuggestionsDiv.style.top = findPosY($(SearchBoxID)) + 23;
                var tableRowsCount = AutoSuggestionsDiv.getElementsByTagName("TR");

                if (tableRowsCount.length > 11) {
                    AutoSuggestionsDiv.className = "div_AutoComplete_Search";
                    AutoSuggestionsDiv.style.height = tableRowsCount.item(11).offsetTop;
                }
                else {
                    AutoSuggestionsDiv.className = "div_AutoComplete_Search_Small";
                    AutoSuggestionsDiv.style.height = tableRowsCount.item(tableRowsCount.length - 1).offsetTop + tableRowsCount.item(tableRowsCount.length - 1).offsetHeight;
                }
            }
        }
    }
}

// code to show the DIV below the Search Box
function ShowDiv(divid) {
    var Suggestions_Div = $(divid);
    if (navigator.userAgent.indexOf("MSIE") >= 0) {
        parentelement = Suggestions_Div.parentElement;
    }
    else {
        parentelement = Suggestions_Div.parentNode;
    }
    Suggestions_Div.style.left = findPosX(parentelement, false);
    Suggestions_Div.style.top = findPosY(parentelement) + 33;
    $(divid).style.visibility = "visible";

    $("ActiveSuggestion").value = -1;
}

// code to show the DIV below the Search Box
function ShowMainSearchDiv(divid) {
    var Suggestions_Div = $(divid);
    $(divid).style.visibility = "visible";

    $("ActiveSuggestion").value = -1;
}

// code to hide the DIV below the Search Box
function HideDiv(divid) {
    $(divid).style.visibility = "hidden";
}

// code which is called on body load to hide the DIV below the Search Box.
function BodyLoad() {
    HideDiv("AutoCompleteSuggestions");
}

//Code for changing the color of the selected word in suggestions DIV and setting the selected suggestion in the Search Box.
function changeBGColor(TableRow) {
    var textBox;
    if ($(SearchBoxID)) {
        textBox = $(SearchBoxID);
    }
    else if ($(SearchBoxID2)) {
        textBox = $(SearchBoxID2);
    }
    else {
        textBox = $(SearchBoxID3);
    }
    var index = 0;

    var AutoSuggestionsDiv = $("AutoCompleteSuggestions")
    var TableRows = AutoSuggestionsDiv.getElementsByTagName("TR");

    for (index = 0; index < TableRows.length; index++) {
        TableRows.item(parseInt(index, 0)).style.backgroundColor = "#e6ece5";
        if (navigator.userAgent.indexOf("MSIE") >= 0) {
            TableRows.item(parseInt(index, 0)).childNodes(0).style.color = "";
        }
        else {
            TableRows[index].getElementsByTagName("td")[0].style.color = "";
        }
    }

    if (TableRow.style.backgroundColor == "#e6ece5" || TableRow.style.backgroundColor == "rgb(230, 236, 229)") {
        TableRow.style.backgroundColor = "#8daa8c";

        if (navigator.userAgent.indexOf("MSIE") >= 0) {
            textBox.value = TableRow.childNodes(0).innerText;
            TableRow.childNodes(0).style.color = "white";
        }
        else {
            textBox.value = TableRow.textContent;
            TableRow.getElementsByTagName("td")[0].style.color = "white";
        }
    }
    else {
        TableRow.style.backgroundColor = "#e6ece5";
    }


}

/*
* Finds the x-coordinate of an object.
*/
function findPosX(obj, isSearchPage) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;

    if (!isSearchPage) {
        if (displayLang == 'ar' || displayLang == 'he') {
            return (curleft + 32);
        }
    }
    return curleft;
}

/*
* Finds the y-coordinate of an object.
*/
function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

function RedirectToSearchPage() {
    if ($(SearchBoxID3)) {
        var searchBox = $(SearchBoxID3);
        removeMarkupTag(searchBox);
        cleanPlainText(searchBox);
        //Getting the url and verifying the location from which the search is called.
        var path = window.location.href;
        var split = path.split("/");
        //Checking only the 4 element to see if the search is called from the same directory or not (As v-root is changed).
        var text = split[4].search("aspx");
        if (split[4] == '' || text != -1) {
            //Encoding the search key for special symbols like &, + etc.
            location.href = "search.aspx?qu=" + encodeURIComponent(searchBox.value) + "&from=SideBar&displaylang=" + displayLang;
        }
        else {
            location.href = "/howtotell/search.aspx?qu=" + encodeURIComponent(searchBox.value) + "&from=SideBar&displaylang=" + displayLang;
        }
    }
    else {
        var searchBox = $(SearchBoxID)
        removeMarkupTag(searchBox);
        cleanPlainText(searchBox);
        //Encoding the search key for special symbols like &, + etc.
        location.href = "search.aspx?qu=" + encodeURIComponent(searchBox.value) + "&from=SearchPage&displaylang=" + displayLang;
    }
}

function RedirectToSearchPagefromSearch() {
    if ($(SearchBoxID)) {
        var searchBox = $(SearchBoxID);
    }
    else {
        var searchBox = $(SearchBoxID2)
    }
    removeMarkupTag(searchBox);
    cleanPlainText(searchBox);
    //Encoding the search key for special symbols like &, + etc.
    location.href = "search.aspx?qu=" + encodeURIComponent(searchBox.value) + "&from=SearchPage&displaylang=" + displayLang;
}

function SearchPage_ButtonClick() {
    if ($(SearchBoxID)) {
        var searchBox = $(SearchBoxID);
    }
    else {
        var searchBox = $(SearchBoxID2)
    }
    removeMarkupTag(searchBox);
    cleanPlainText(searchBox);
    //Encoding the search key for special symbols like &, + etc.
    location.href = "search.aspx?qu=" + encodeURIComponent(searchBox.value) + "&from=SearchPage&displaylang=" + displayLang;
}

function SearchPage_KeyEvent(e) {
    if (!e)
        e = window.event;
    keyId = e.keyCode;
    if (keyId == 13) {
        SearchPage_ButtonClick();
    }
    if (keyId == 40 || keyId == 38) {
        requestSuggestions(true);
    }
}

// Trim all leading spaces from a string.
function LTrim(InString) {
    OutString = InString;
    for (Count = 0; Count < InString.length; Count++) {
        TempChar = InString.substring(Count, Count + 1);
        if (TempChar != " ") {
            OutString = InString.substring(Count, InString.length);
            break;
        }
    }
    return (OutString);
}

// Trim all trailing spaces from a string.
function RTrim(argvalue) {
    while (1) {
        if (argvalue.substring(argvalue.length - 1, argvalue.length) != " ")
            break;

        argvalue = argvalue.substring(0, argvalue.length - 1);
    }
    return argvalue;
}

// Remove dangerous characters from the input string
// i.e. "<", ">"
function CleanInput(input) {
    return input.replace(/</g, "").replace(/>/g, "").replace(/&#/g, "");
}

// Clean plain text input
function cleanPlainText(thisField) {
    thisField.value = CleanInput(LTrim(RTrim(thisField.value)));
}

//Remove unwanted space and markup tags
function removeMarkupTag(thisField) {
    thisField.value = (thisField.value).replace("  ", " ");
    thisField.value = CleanInput(thisField.value);
}
