
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Search functions
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//


/**
 * onkeydown event
 * A key was pressed in the search input text box
 * Search for that text in the active content pane
 * @param {any} event
 */
function OnSearchKeyUp(event) {

    if (!event)
        return;
    if (!event.currentTarget)
        return;

    var element = event.currentTarget;
    var SearchInputTextboxObject = $(element);
    var SearchInputTextboxId = SearchInputTextboxObject.attr('id');
    var SearchText = SearchInputTextboxObject.val();

    //console.log("OnSearchKeyUp: " + SearchText);

    if (event.key === "Enter") {
        event.preventDefault(); // Ensure it is only this code that runs
        PerformSearchInParentDiv(SearchInputTextboxObject, SearchText);
    } else if (event.key === "Escape") {

        CloseSearchInput(SearchInputTextboxObject);
    }
    else if (event.which == 114/*F3*/) {
        // Do nothing. F3 is handled in keydown
        // But we need to prevent another search, so do nothing here
    }
    else if (event.key === "Shift"/*F3*/) {
        // Do nothing. SHIFT+F3 is handled in keydown
        // But we need to prevent another search, so do nothing here
    }
    else {
        PerformSearchInParentDiv(SearchInputTextboxObject, SearchText);
    }
}



/**
 * Used for Special keys only
 * @param {any} event
 * @returns
 */
function OnSearchKeyDown(event) {

    if (!event)
        return;
    if (!event.currentTarget)
        return;

    var element = event.currentTarget;
    var SearchInputTextboxObject = $(element);
    var SearchInputTextboxId = SearchInputTextboxObject.attr('id');
    var SearchText = SearchInputTextboxObject.val();

    //console.log("OnSearchKeyDown: " + SearchText);

    if (event.which == 114/*F3*/) {
        var bNext = !event.shiftKey;
        event.preventDefault(); // Ensure it is only this code that runs
        PerformNextSearchInParent(SearchInputTextboxObject, SearchText, bNext);
        return false;
    }
}


var SearchInputWidth = 150;

function OnSearchInputFocusIn(event) {

    if (!event)
        return;
    if (!event.currentTarget)
        return;

    var element = event.currentTarget;
    var SearchInputTextElement = $(element);
    var SearchInputTextElementId = SearchInputTextElement.attr('id');
    var SearchText = SearchInputTextElement.val();

    OpenSearchInput(SearchInputTextElement);
}

function OnSearchInputFocusOut(event) {

    if (!event)
        return;
    if (!event.currentTarget)
        return;

    var element = event.currentTarget;
    var SearchInputTextElement = $(element);
    var SearchInputTextElementId = SearchInputTextElement.attr('id');
    var SearchText = SearchInputTextElement.val();

    CloseSearchInput(SearchInputTextElement);
}


function OpenSearchInput(SearchInputTextElement) {
    SearchInputTextElement.animate({
        width: SearchInputWidth + "px",
        opacity: 1
    }, 400);
}

function CloseSearchInput(SearchInputTextElement) {
    SearchInputTextElement.animate({
        width: "0px",
        opacity: 0
    }, 250);
}


/**
 * onclick event
 * The search button was clicked
 * Open the search input text box
 * @param {any} event
 */
function OnSearchButtonClick(event) {

    if (!event)
        return;
    if (!event.currentTarget)
        return;

    var element = event.currentTarget;
    var SearchButtonElement = $(element);
    var InputTextId = $(SearchButtonElement).attr('inputtextid');
    var SearchButtonElementId = SearchButtonElement.attr('id');
    SearchInputTextElement = GetSearchInputTextboxFromSearchButton(SearchButtonElement);
    if (!SearchInputTextElement)
        return;

    OpenSearchInput(SearchInputTextElement);
    SearchInputTextElement.focus();

    //alert(SearchInputElement.val());
}


/**
 * This function is called by onclick from a ribbon button
 * Find the Search button in the active pane, and call it to perform a search
 * If the active pane has no search button then alert the user
 * @param {any} event
 */
function ClickActiveContentSearchButton(event) {

    var SelectedContentPartialViewDivElement = GetSelectedContentPartialViewDivElement();
    if (!SelectedContentPartialViewDivElement)
        return;
    var PartialViewDivId = $(SelectedContentPartialViewDivElement).attr('id');
    if (!PartialViewDivId)
        return;

    // searchbutton
    var SearchButton = $(SelectedContentPartialViewDivElement).find('.searchbutton');
    if (!SearchButton || SearchButton.length == 0) {
        ToastError("", "You cannot search the selected page");
        return;
    }
    var SearchButtonDomElement = SearchButton.get(0);
    if (!SearchButtonDomElement) {
        ToastError("", "You cannot search the selected page");
    return;
    }

    var InputTextId = $(SearchButton).attr('inputtextid');

    var NewEvent = {};
    NewEvent.currentTarget = SearchButton;
    OnSearchButtonClick(NewEvent);
    //$(SearchButton).click(event);

    //alert("ClickActiveContentSearchButton");
}




/**
 * Find the search input text field that belongs to this search button
 * @param {any} btnelement
 */
function GetSearchInputTextboxFromSearchButton(btnelement) {

    if (!btnelement)
        return null;
    var InputTextId = $(btnelement).attr('inputtextid');
    if (!InputTextId)
        return null;
    return $("#" + InputTextId);
}


/**
 * Go up parents until a "searchable" parent is found
 * This is normally the div will all the content
 * @param {any} ElementObject
 */
function FindSearchableParentDivFromElement(ElementObject) {

    try {
        if (!ElementObject)
            return null;
        if (ElementObject.hasClass('searchablediv'))
            return ElementObject;

        var Parent = ElementObject.parent();
        if (!Parent)
            return null;
        if (!Parent.length)
            return null;
        if (Parent.hasClass('searchablediv'))
            return Parent;
        if (Parent.is('body'))
            return null;

        return FindSearchableParentDivFromElement(Parent);
    }
    catch (e) {
        console.log("FindSearchableParentDivFromElement Error: " + e);
        return null;
    }
}

function RemoveSelectionFromDiv(SearchableParentDiv) {

    if (!SearchableParentDiv)
        return;

    var SearchableItems = SearchableParentDiv.find('.searchableitem');
    if (SearchableItems && SearchableItems.length > 0) {
        SearchableItems.removeClass('searchselected');
    }
}




/**
 * Select items that match this text
 * @param {any} ElementObject
 * @param {any} SearchText
 */
function PerformSearchInParentDiv(ElementObject, SearchText) {

    if (!ElementObject)
        return;

    var SearchTextLowerCase = SearchText.toLowerCase();
    if (SearchText.length < 1)
        return;

    // Find the parent to search within
    var SearchableParentDiv = FindSearchableParentDivFromElement(ElementObject);
    if (!SearchableParentDiv) {
        ToastError("Oops, there's no searchablediv to search inside");
        return;
    }

    // Search for all items that are marked "searchable" with a special class
    var SearchableItems = SearchableParentDiv.find('.searchableitem');
    if (SearchableItems && SearchableItems.length > 0) {

        // Begin by removing the class (to clear the preview search results)
        SearchableItems.removeClass('searchselected');
        SearchableItems.removeClass('searchcurrent');
        //console.log("Search results: " + SearchableItems.length);

        var SelectedItems = SearchableItems.filter(function () { return $(this).text().toLowerCase().indexOf(SearchTextLowerCase) >= 0; });
        if (SelectedItems && SelectedItems.length > 0) {

            // Select items
            SelectedItems.addClass('searchselected');

            // Select the first one
            // F3 will select the next one
            $(SelectedItems[0]).addClass('searchcurrent');

            // Expand parent nodes in filter tree
            FilterTreeExpandAllNodes(SelectedItems)

            // Make it visible
            ScrollIntoViewIfNeeded(SelectedItems[0]);

            // Automatically unselect after a while so it's not ugly
            // Hmmm, page became unresponsive???
            //setTimeout(function () { RemoveSelectionFromDiv(SearchableParentDiv); }, (1000 * 60 * 2) );
        }
    }
}


/**
 * Search Next/Previous (F3 and SHIFT+F3)
 * @param {any} ElementObject
 * @param {any} SearchText
 * @param {any} bSearchNext
 * @returns
 */
function PerformNextSearchInParent(ElementObject, SearchText, bSearchNext) {

    if (!ElementObject)
        return;

    var SearchTextLowerCase = SearchText.toLowerCase();
    if (SearchText.length < 1)
        return;

    // Find the parent to search within
    var SearchableParentDiv = FindSearchableParentDivFromElement(ElementObject);
    if (!SearchableParentDiv) {
        ToastError("Oops, there's no searchablediv to search inside");
        return;
    }

    // Search for all items that are marked "selected" with a special class
    var SelectedItems = SearchableParentDiv.find('.searchselected');
    if (SelectedItems && SelectedItems.length > 0) {

        // Find the current "selected" item
        // Search "Next" or "Previous" relative to this item
        // Get index of next item
        var idxNext = 0;
        var CurrentItem = SearchableParentDiv.find('.searchcurrent');
        if (CurrentItem && CurrentItem.length > 0) {
            var idxItem = SelectedItems.index(CurrentItem);
            //console.log("CurrentItem idx: " + idxItem);
            if (idxItem >= 0 && idxItem < SelectedItems.length) {
                idxNext = (bSearchNext ? idxItem+1 : idxItem-1);
                if (idxNext < 0)
                    idxNext = SelectedItems.length-1;
                if (idxNext >= SelectedItems.length)
                    idxNext = 0;
                CurrentItem.removeClass('searchcurrent');
            }
        }

        //console.log("NextItem idx: " + idxNext);

        // Select the next item, scroll into view, and toast the text
        if (idxNext >= 0 && idxNext < SelectedItems.length) {

            var NextItemObject = $(SelectedItems[idxNext]);
            if (!NextItemObject || NextItemObject.length == 0)
                return;
            var NextItemElement = NextItemObject[0];

            // Select the next item
            NextItemObject.addClass('searchcurrent');

            // Expand parent nodes in filter tree
            FilterTreeExpandToNode(NextItemObject);

            // Make it visible
            ScrollIntoViewIfNeeded(NextItemElement);

            // Tell the user which one was selected
            var sItemText = NextItemObject.text();
            if (sItemText && sItemText.length > 0) {
                ToastClear();
                ToastMessage("", sItemText);
            }
        }
    }
}




