﻿var resultList; // Div Element
var ListSearchTb; // Textbox element
var CurrentResultList = new Array; // JS-Array
var CurrentMarkerResultList; // index
var itemSelected = false; // if a item was clicked, and the corresponding site is loading ... this is set to true ???
var itemClicked = false;

function ListSearchFocus(e) {
    // ... in code behind datei machen?
    tb = ListSearchTb;
    
    ListSearchChangeTextboxStyleActive();
    // Position of tb ... das sollte man nur einmal aufrufen! also hier!
    tbPos = GetElementPosition(tb);
    
    // Init the result list div
    resultList = document.createElement("div");
    resultList.style.position = "absolute";
    resultList.style.top = (tbPos.y + 24) + "px";
    resultList.style.left = (tbPos.x - 45) + "px";
    resultList.style.borderTop = "solid 1px #99CC33";
    resultList.style.borderLeft = "solid 1px #99CC33";
    resultList.style.borderRight = "solid 1px #99CC33";
    resultList.style.borderBottom = "solid 1px #99CC33";
    resultList.style.backgroundColor = "#FFFFFF";
    resultList.style.fontSize = "12px";
    resultList.style.minWidth = "240px";
    resultList.style.display = "none";
    resultList.style.padding = "5px";
    // NEW 11.01.2010
    resultList.style.zIndex = "100";
    
    document.body.appendChild(resultList);
    // Init result list
    CurrentResultList = new Array();
    CurrentMarkerResultList = -1;
    
    // Init the hidden selectedIDs Field if appropriate behav is set
    if (ListSearchObjectSelectedBehavior == 2)
        document.getElementById("listSearchSelectedIds").value = "";

    itemClicked = false;
}

function ListSearchBlur(e) {
    tb = ListSearchTb;
    
    // Because, otherwise, the list first disapears, and nobody can click on it!
    // Only a problem in IE
    //ListSearchChangeTextboxStyleInactive();
    //setTimeout("document.body.removeChild(resultList); resultList.style.display = \"none\";", 100);
    setTimeout("ListSearchTerminateResults(ListSearchTb)", 250);
    
    //ListSearchTerminateResults(ListSearchTb);
}

// If "Enter" was pressed in any item
function ListSearchTerminateResults(tb) {
    resultList.style.display = "none";
    document.body.removeChild(resultList);
    ListSearchChangeTextboxStyleInactive();

    if (itemClicked == false)
        tb.value = "";

    // Check if a limitation of search process is given
    tb.disabled = false;
    if (document.getElementById("listSearchSelectedIds").value == "")
        numSelectedObjects = 0;
    else {
        selectedObjectIds = document.getElementById("listSearchSelectedIds").value.split("-");
        numSelectedObjects = selectedObjectIds.length;
    }
    if (ListSearchLimitSearchProcesses > 0) {
        // Now we have a limitation
        if (numSelectedObjects >= ListSearchLimitSearchProcesses) {
            // Disable the serachbox
            tb.value = "";
            tb.disabled = true;
        }
    }
}

// Key Down Event - No Postback on Enter!!!
function ListSearchKeyDown(e) {
    var nr = document.all ? window.event.keyCode : e.which;
    if (nr == 13) // No Postback on enter key
        return false;
    else
        return true;
}
// Key Up Event
var ListSearchString = "";
function ListSearchKeyUp(e) {
    // Get Key which was pressed
    var nr = document.all ? window.event.keyCode : e.which;
    
    if (nr == 40) {
        //alert("Key down");
        if (CurrentMarkerResultList + 1 < CurrentResultList.length) {
            CurrentMarkerResultList = CurrentMarkerResultList + 1;
            ListSearchUpdateHighlightResultList2(CurrentMarkerResultList);
        }
    }
    else if (nr == 38) {
        //alert("Key up");
        if (CurrentMarkerResultList > -1) {
            CurrentMarkerResultList = CurrentMarkerResultList - 1;
            ListSearchUpdateHighlightResultList2(CurrentMarkerResultList);
        }
    }
    else if (nr == 13) {
        //alert("Enter");
        if (CurrentMarkerResultList > -1) {
            // Handle the selectedObject event
            OnSelectedObject();
            // Fake the blur event of the tb.
            ListSearchTb.blur();
        }
        return false;
    }
    else {
        // All other input
        tb = ListSearchTb;
        // Check for space input
        if (ListSearchString.length == 0 && tb.value == " ") {
            return;
        }
        else {
            ListSearchString = tb.value;
            ListSearchString = ListSearchString.toLowerCase();
        }

        if (ListSearchString.length > 0) {
            // Search for results
            IntermediateArray = new Array();
            MaxResults = 10;
            MoreResults = false;
            for (i = 0; i < ListSearchDataArray.length; i++) {
                test = ListSearchDataArray[i].Title.toLowerCase();
                orig = ListSearchDataArray[i].Title;
                start_ind = test.indexOf(ListSearchString);
                // Found something
                if (start_ind != -1) {
                    if (IntermediateArray.length >= MaxResults) {
                        // Reaching this point means, we have found more than MaxResults
                        MoreResults = true;
                        break;
                    }
                    IntermediateArray.push(ListSearchDataArray[i]);
                    h_text = orig.substring(0, start_ind) + "<span style=\"color:#FB9806; font-weight:bold;\">" + orig.substring(start_ind, start_ind + ListSearchString.length) + "</span>" + orig.substring(start_ind + ListSearchString.length); // FF0000
                    IntermediateArray[IntermediateArray.length - 1].HighlightedText = h_text;
                }
            }

            if (IntermediateArray.length > 0) {
                // If found something
                CurrentResultList = IntermediateArray;

                tb.style.backgroundColor = "#FFFFFF";
                tb.style.border = "solid 1px #FFFFFF";
                document.getElementById(DivTbListSearch).style.backgroundColor = "#FFFFFF";

                ListSearchShowResult(tb, IntermediateArray, MoreResults);

                // TODO: Update the ResultList Highlightings!!!
                // Net nötig, da ShowResults das im Prinzip übernimmt!
                // Aber den Marker setzen wir wieder auf -1
                CurrentMarkerResultList = -1;
            }
            else {
                // No results found
                ListSearchChangeTextboxStyleNoResults();

                if (CurrentResultList.length == 0) {
                    ListSearchHideResult();
                }
            }
        }
        else {
            // No Text was entered (case if there was input, then input deleted)
            // In this case -> no onFocus or onBlur event happens and if the former
            // State of the Textbox was "NoResults" we have to remove the red color and so on...
            tb.style.backgroundColor = "#FFFFFF";
            tb.style.border = "solid 1px #FFFFFF";
            document.getElementById(DivTbListSearch).style.backgroundColor = "#FFFFFF";
            // Also hide the ResultList
            resultList.style.display = "none";
        }
    }
}

function ListSearchShowResult(tb, res, more) {
    // Clear result List
    resultList.innerHTML = "";
    // Iterate all Items
    for (i = 0; i < res.length; i++) {
        curResLink = document.createElement("a");
//        if (ListSearchObjectSelectedBehavior == 1)
//            curResLink.setAttribute("href", res[i].LinkToBo);
//        else {
//            curResLink.setAttribute("href", "");
//            curResLink.setAttribute("onclick", "OnSelectedObject();");
//        }
        curResLink.setAttribute("onclick", "OnSelectedObject(); return false;");
        
        curRes = document.createElement("div");
        curRes.setAttribute("id", "ListSearchResultItem_" + i);
        curRes.setAttribute("style", "color:#000000; padding:0px; cursor:pointer;");
        curRes.setAttribute("onmouseover", "ListSearchUpdateHighlightResultList2(" + i + "); CurrentMarkerResultList=" + i + ";");
        curRes.setAttribute("onmouseout", "this.style.backgroundColor = '#FFFFFF'; this.style.color = '#000000';");
        // OnSelectedObject();
        //curRes.setAttribute("onclick", "RedirectToObject(); MarkTextboxForSelectedItem();");
        //elementHTML = "<div onclick=\"RedirectToObject(); MarkTextboxForSelectedItem();\" onmouseover=\"ListSearchUpdateHighlightResultList2(" + i + "); CurrentMarkerResultList=" + i + ";\" style=\"float:left; margin:5px 0px 5px 5px; padding-right:10px; width:25px; height:18px; background-image:url('/Pictures/" + res[i].ImgPath + "'); background-repeat:no-repeat; background-position:center center; overflow:hidden; cursor:pointer;\"></div>";
        //elementHTML += "<div onclick=\"RedirectToObject(); MarkTextboxForSelectedItem();\" onmouseover=\"ListSearchUpdateHighlightResultList2(" + i + "); CurrentMarkerResultList=" + i + ";\" style=\"float:left; height:18px; padding-top:7px; margin-right:10px; color:#000000; cursor:pointer;\">" + res[i].HighlightedText + "</div>";
        curRes.setAttribute("onclick", "OnSelectedObject();");
        elementHTML = "<div onclick=\"OnSelectedObject();\" onmouseover=\"ListSearchUpdateHighlightResultList2(" + i + "); CurrentMarkerResultList=" + i + ";\" style=\"float:left; margin:5px 0px 5px 5px; padding-right:10px; width:25px; height:18px; background-image:url('/Pictures/" + res[i].ImgPath + "'); background-repeat:no-repeat; background-position:center center; overflow:hidden; cursor:pointer;\"></div>";
        elementHTML += "<div onclick=\"OnSelectedObject();\" onmouseover=\"ListSearchUpdateHighlightResultList2(" + i + "); CurrentMarkerResultList=" + i + ";\" style=\"float:left; height:18px; padding-top:7px; margin-right:10px; color:#000000; cursor:pointer;\">" + res[i].HighlightedText + "</div>";
        elementHTML += "<div style=\"clear:left;\"></div>";
        curRes.innerHTML = elementHTML;
        
        curResLink.appendChild(curRes);
        
        resultList.appendChild(curResLink);
        resultList.style.display = "";
    }
    // More results indicator
    if (more) {
        //resultList.style.height = "280px";
        //resultList.style.overflow = "scroll";
        
        moreDiv = document.createElement("div");
        moreDiv.setAttribute("style", " width:240px; margin:10px 5px 5px 5px; font-size:10px;");
        moreDiv.innerHTML = ResListSearchMoreResultsText;
        resultList.appendChild(moreDiv);
    }
    //else {
    //    resultList.style.height = "";
    //    resultList.style.overflow = "";
    //}
}
function ListSearchHideResult() {
    resultList.style.display = "none";
}
function ListSearchUpdateHighlightResultList2(listindex) {
    CurrentMarkerResultList = listindex; // If update comes from mouse movement
    for (i = 0; i < CurrentResultList.length; i++) {
        d = document.getElementById("ListSearchResultItem_" + i);
        d.style.backgroundColor = "#FFFFFF";
        d.style.color = "#000000";
    }
    high_item = document.getElementById("ListSearchResultItem_" + CurrentMarkerResultList);
    if (high_item != null) {
        high_item.style.backgroundColor = "#99CC33";
        high_item.style.color = "#FFFFFF";
    }
}

function OnSelectedObject() {
    itemClicked = true;
    
    if (ListSearchObjectSelectedBehavior == 1) {
        RedirectToObject();
        MarkTextboxForSelectedItem();
    }
    else if (ListSearchObjectSelectedBehavior == 2) {
        // Insert the selected id to the hidden field
        if (document.getElementById("listSearchSelectedIds").value != "") {
            document.getElementById("listSearchSelectedIds").value = document.getElementById("listSearchSelectedIds").value + "-" + CurrentResultList[CurrentMarkerResultList].BoID;
        }
        else {
            document.getElementById("listSearchSelectedIds").value = CurrentResultList[CurrentMarkerResultList].BoID;
        }
        // Insert a new selected object
        InsertSelectedObject();
    }
}

function RedirectToObject() {
    document.location = CurrentResultList[CurrentMarkerResultList].LinkToBo;
}

// function MarkTextboxForSelectedItem(showLoader)
function MarkTextboxForSelectedItem() {
    if (arguments.length > 0)
        showLoader = arguments[0];
    else
        showLoader = true;
    
    itemSelected = true;
    if (showLoader) {
        document.getElementById("tbLoader").style.display = "block";
        ListSearchTb.style.width = "180px";
    }
    ListSearchTb.value = CurrentResultList[CurrentMarkerResultList].Title;
}

function InsertSelectedObject() {
    // Get the div including the selected objects
    divSelectedObjects = document.getElementById("tbSelectedItems");
    // Make it visible
    divSelectedObjects.style.display = "block";
    // Get the new bo-id of the selected item
    selected_obj_id = CurrentResultList[CurrentMarkerResultList].BoID;
    // Create the new selected object div
    newSelectedObject = document.createElement("div");
    newSelectedObject.setAttribute("id", "selected_obj_id_" + selected_obj_id);
    newSelectedObject.setAttribute("style", "background-color:#99CC33; padding:3px 3px 1px 3px; float:left; height:17px; border:1px solid #FFFFFF; color:#FFFFFF;");
    newSelectedObject.innerHTML = CurrentResultList[CurrentMarkerResultList].Title + "&nbsp;<a onclick=\"RemoveSelectedObject(" + selected_obj_id + ")\" style=\"cursor:pointer; font-weight:bold; color:#FFFFFF;\">x</a>";
    // Append the new div
    divSelectedObjects.appendChild(newSelectedObject);
}

function RemoveSelectedObject(obj_id) {
    // Remove the obj_id from the hidden field
    selectedIds = document.getElementById("listSearchSelectedIds").value.split("-");
    for (i = 0; i < selectedIds.length; i++) {
        if (selectedIds[i] == obj_id) {
            selectedIds.splice(i, 1);
            break;
        }
    }
    document.getElementById("listSearchSelectedIds").value = "";
    for (i = 0; i < selectedIds.length; i++) {
        if (i == 0) {
            document.getElementById("listSearchSelectedIds").value = selectedIds[i];
        }
        else {
            document.getElementById("listSearchSelectedIds").value = document.getElementById("listSearchSelectedIds").value + "-" + selectedIds[i];
        }
    }
    
    // Get the div including the selected objects
    divSelectedObjects = document.getElementById("tbSelectedItems");
    // Remove according div
    divSelectedObjects.removeChild(document.getElementById("selected_obj_id_" + obj_id));
    
    // Reset the textbox
    ListSearchChangeTextboxStyleInactive();
    // Check if a limitation of search process is given
    ListSearchTb.disabled = false;
    if (document.getElementById("listSearchSelectedIds").value == "")
        numSelectedObjects = 0;
    else {
        selectedObjectIds = document.getElementById("listSearchSelectedIds").value.split("-");
        numSelectedObjects = selectedObjectIds.length;
    }
    if (ListSearchLimitSearchProcesses > 0) {
        // Now we have a limitation
        if (numSelectedObjects >= ListSearchLimitSearchProcesses) {
            // Disable the serachbox
            ListSearchTb.value = "";
            ListSearchTb.disabled = true;
        }
    }
}


// EXTERNAL FUNCTION SUPPORT
function ListSearchBoxFocus() {
    ListSearchTb.focus();
}
function ListSearchResetControl() {
    // Flush the hidden field
    document.getElementById("listSearchSelectedIds").value = "";
    // Flush the selected objects
    document.getElementById("tbSelectedItems").innerHTML = "";
    // Set textbox to default
    ListSearchChangeTextboxStyleInactive();
    
    itemClicked = false;
}
function ListSearchGetSelectedObjectID() {
    if (document.getElementById("listSearchSelectedIds").value == "")
        return -1;
    else
        return document.getElementById("listSearchSelectedIds").value;
}


// HELPER FUNCTIONS
// Get the Position of the Element
function GetElementPosition(tb) {

    var pos = { x: 0, y: 0 };

    LS_imageOffsetY = tb.offsetTop;
    LS_imageOffsetX = tb.offsetLeft;
    obj = tb.offsetParent;
    do {
        LS_imageOffsetX += obj.offsetLeft;
        LS_imageOffsetY += obj.offsetTop;
    } while (obj = obj.offsetParent);

    pos.x = LS_imageOffsetX;
    pos.y = LS_imageOffsetY;

    return pos;
}
// Changes the Style of the Textbox to an active state
function ListSearchChangeTextboxStyleActive() {
    tb = ListSearchTb;
    tb.value = "";
    tb.style.color = "#000000";
}
// Changes the Style of the Textbox to an inactive state
function ListSearchChangeTextboxStyleInactive() {
    tb = ListSearchTb;
    tb.disabled = false;
    tb.style.color = "#999999";
    if (itemSelected == false)
        tb.value = ResListSearchTextBoxInfoString;
    tb.style.backgroundColor = "#FFFFFF";
    tb.style.border = "solid 1px #FFFFFF";
    document.getElementById(DivTbListSearch).style.backgroundColor = "#FFFFFF";
}
// Changes the Style of the Textbox to an "NoResults" state
function ListSearchChangeTextboxStyleNoResults() {
    tb.style.backgroundColor = "#FB9806"; // FF0000
    tb.style.border = "solid 1px #FB9806"; // FF0000
    document.getElementById(DivTbListSearch).style.backgroundColor = "#FB9806"; // FF0000
}

