﻿var folderTypes =
{
    General: 1,
    History: 2,
    Managed: 3,
    Group: 4
}

var folderMgr =
{
    folders: [],
    generalDivId: 'generalFolderDiv',
    historyDivId: 'historyFolderDiv',
    managedDivId: 'managedFolderDiv',
    groupDivId: 'groupFolderDiv',
    foldersListDiv: 'foldersDiv',
    isMultiView: true, // true indicates that toggle and delete buttons will be visible on folder titles
    isInitialized: false, //indicates if Init method has already been called
    isQueriesInit: false,
    isHistoryInit: false,

    // The Init function is designed for Search.aspx
    // param bool "autoLoadAndMultiView": false to indicate that folders will be displayed singly and should not be auto-loaded on startup,
    //      false to indicate that folders may be displayed in groups (which means the toggle and delete buttons will be visible)
    //      and will be auto-loaded on startup
    Init: function(autoLoadAndMultiView)
    {
        folderMgr.isMultiView = autoLoadAndMultiView;

        if (autoLoadAndMultiView)
        {
            //ajaxHelper.ShowProgress(folderMgr.historyDivId, folderMgr.historyDivId);
            //ajaxHelper.ShowProgress(folderMgr.generalDivId, folderMgr.generalDivId);
            //ajaxHelper.ShowProgress(folderMgr.managedDivId, folderMgr.managedDivId);

            //SearchEngineService.GetFolderSearchesHtmlByType(folderMgr.historyDivId, folderTypes['History'], folderMgr.LoadQueries_Complete);
            //SearchEngineService.GetFolderSearchesHtmlByType(folderMgr.generalDivId, folderTypes['General'], folderMgr.LoadQueries_Complete);
            //SearchEngineService.GetFolderSearchesHtmlByType(folderMgr.groupDivId, folderTypes['Group'], folderMgr.LoadQueries_Complete);
            //SearchEngineService.GetManagedFoldersHtml(folderMgr.managedDivId, folderMgr.GetManagedFoldersHtml_Complete);
	    
	    folderMgr.isInitialized = true;
        }
    },

    fillTdQueries: function() {
        if (!folderMgr.isQueriesInit) {
            ajaxHelper.ShowProgress(folderMgr.generalDivId, folderMgr.generalDivId);
            ajaxHelper.ShowProgress(folderMgr.managedDivId, folderMgr.managedDivId);

            SearchEngineService.GetFolderSearchesHtmlByType(folderMgr.generalDivId, folderTypes['General'], folderMgr.LoadQueries_Complete);
            SearchEngineService.GetFolderSearchesHtmlByType(folderMgr.groupDivId, folderTypes['Group'], folderMgr.LoadQueries_Complete);
            SearchEngineService.GetManagedFoldersHtml(folderMgr.managedDivId, folderMgr.GetManagedFoldersHtml_Complete);
            folderMgr.isQueriesInit = true;
        }
    },

    fillTdHistory: function() {
        if (!folderMgr.isHistoryInit) {
            ajaxHelper.ShowProgress(folderMgr.historyDivId, folderMgr.historyDivId);

            SearchEngineService.GetFolderSearchesHtmlByType(folderMgr.historyDivId, folderTypes['History'], folderMgr.LoadQueries_Complete);
            folderMgr.isHistoryInit = true;
        }
    },

    //-------------------------------------------------------------------------------------------------
    //  DOM EVENTS
    //-------------------------------------------------------------------------------------------------

    ToggleQueries: function(titleDivChild)
    {
        var $div = $j(titleDivChild).parent();
        var image = $div.find('#expanderImg').get(0);

        if (!image) return;

        utility.ToggleElement($div.next().get(0));

        image.src = image.src.indexOf('defaultscreen') > -1
            ? 'Images/DocumentIcons/icon_fullscreen.gif' : 'Images/DocumentIcons/icon_defaultscreen.gif';
        image.title = image.alt.indexOf('הצג') > -1 ? 'החבא שאילתות' : 'הצג שאילתות';
    },

    AttachClueTips: function()
    {
        //alert('AttachClueTips');

        // unbind all cluetip events
        $j('.queryPopup').unbind();

        // rebind
        $j('.queryPopup').cluetip({
            width: 415,
            closeText: '<img src="Images/close_rss.gif" alt="סגור" />',
            cluetipClass: 'koldin',
            mouseOutClose: true,
            titleAttribute: 'ctTitle',
            closePosition: 'title',
            showTitle: false,
            positionBy: 'bottomTop',
            ajaxProcess: function(data)
            {
                // Parse message out of xml and wrap in a div
                return '<div style="text-align:right">' + $j(data).find('string').text() + '</div>';
            },
            ajaxSettings: {
                dataType: 'xml'
            }
        });

        // Fix IE6 combo-box z-index problem
        $j('#cluetip').bgiframe();
    },

    //-------------------------------------------------------------------------------------------------
    //  FOLDER MANAGEMENT
    //-------------------------------------------------------------------------------------------------

    FindFolder: function(folderId)
    {
        for (var i = 0; i < folderMgr.folders.length; i++)
        {
            if (folderMgr.folders[i].folderId == folderId)
            {
                return folderMgr.folders[i];
            }
        }

        return null;
    },

    RegisterFolder: function(folderId, divId)
    {
        // Save the folder's Id and target in memory
        folderMgr.folders.push({ folderId: folderId, divId: divId });
    },

    DeleteFolder: function(folderId, divId)
    {
        // Make sure the folder and its div are registered
        if (folderMgr.FindFolder(folderId) == null)
            folderMgr.RegisterFolder(folderId, divId);

        SearchEngineService.FolderHasContent(folderId, folderMgr.FolderHasContent_Complete);
    },

    FolderHasContent_Complete: function(result)
    {
        if (result)
        {
            var confirmed = false;

            //
            // Request appropriate confirmation
            //
            if (result.Result)
                confirmed = confirm('התקיה שביקשת למחוק אינה ריקה! האם אתה בטוח שברצונך למחוק את התקיה וכל התוכן שלה?');
            else
                confirmed = confirm('האם אתה בטוח שברצונך למחוק את התקיה?');

            if (confirmed)
                SearchEngineService.DeleteFolder(result.Info, folderMgr.DeleteFolder_Complete);
        }
        else
        {
            ajaxHelper.ShowError();
        }
    },

    DeleteFolder_Complete: function(result)
    {
        if (result && result.Result)
        {
            // Remove the folder from the html
            $j('#' + folderMgr.FindFolder(result.Info).divId).remove();

            alert("התקיה הוסרה בהצלחה!");
        }
        else
        {
            ajaxHelper.ShowError();
        }
    },

    // Loads the returned html into the managed-folder div, or hides the div (for IE) if there are no managed folders
    GetManagedFoldersHtml_Complete: function(result)
    {
        if (result && result.Result != '')
        {
            ajaxHelper.HideProgress(result.Target, result.Result);
            folderMgr.AttachClueTips();
        }
        else
        {
            // hide the div (for IE)
            utility.HideElement(folderMgr.managedDivId);
        }
    },

    //-------------------------------------------------------------------------------------------------
    //  QUERIES / SEARCHES
    //-------------------------------------------------------------------------------------------------

    // Hides the progress gif for the operation, inserts the html, re-attaches cluetips to all query-descriptions, and pushes
    // the returned folder into the folders collection if it does not already exist
    LoadQueries_Complete: function(result)
    {
        //alert('LoadQueries_Complete');

        if (result)
        {
            ajaxHelper.HideProgress(result.Target, result.Result)

            //Remove smart agent td's from history folder dive
            if (result.Target == "historyFolderDiv")
            {
                $j("#tmpStringToWorkTo").html(result.Result);
                $j("#tmpStringToWorkTo").find(".queriesDiv .MainResultsTable tr:first td:eq(4)").remove();
                $j("#tmpStringToWorkTo").find(".queriesDiv .MainResultsTable").each(function()
                {
                    $j(this).find("tr.QueriesRows").each(function()
                    {
                        $j(this).find("td:eq(4)").remove();
                    });
                });
                document.getElementById(result.Target).innerHTML = $j("#tmpStringToWorkTo").html();
                $j("#tmpStringToWorkTo").html();
            }
            else if ((result.Target == "divQueries" || result.Target == "generalFolderDiv") && $j(".isSmartAgentHd").val() == "False")
            {
                $j("#tmpStringToWorkTo").html(result.Result);
                $j("#tmpStringToWorkTo").find(".queriesDiv .MainResultsTable tr:first td:eq(4)").remove();
                $j("#tmpStringToWorkTo").find(".queriesDiv .MainResultsTable").each(function()
                {
                    $j(this).find("tr.QueriesRows").each(function()
                    {
                        $j(this).find("td:eq(4)").remove();
                    });
                });
                document.getElementById(result.Target).innerHTML = $j("#tmpStringToWorkTo").html();
                $j("#tmpStringToWorkTo").html();
            }
            else
            {
                document.getElementById(result.Target).innerHTML = result.Result;
            }

            if ($j(".isSmartAgentHd").val() == "True")
            {
                intId = setTimeout("folderMgr.SmartAgentManagement()", 1000);
            }
            if (result.Info && folderMgr.FindFolder(result.Info) === null)
            {
                // Save the folder's Id and target in memory
                folderMgr.RegisterFolder(result.Info, result.Target)
            }

            // rebind cluetips
            folderMgr.AttachClueTips();
        }
    },

    //Smart Agent Management
    SmartAgentManagement: function()
    {
        //Add Click Event For Each Checkbox
        $j("#divQueries .queriesDiv .MainResultsTable tr.QueriesRows .smartAgentCheckBox").each(function()
        {
            var checkBox = $j(this).find("input:checkbox");
            checkBox.unbind();
            checkBox.click(function()
            {
                var isChecked = $j(this).attr("checked");
                if (isChecked)
                {
                    //Show the popup div of insert email
                    $j(this).parent().parent().find(".div_to_popup").css("display", "");
                    $j(this).parent().parent().find(".div_to_popup").addClass("pop");
                    $j("#opacityDiv").css("display", "");

                    //Add Click Event For Save Button
                    $j(this).parent().parent().parent().find(".updateSmartAgentBtn").each(function()
                    {
                        $j(this).unbind();
                        $j(this).click(function()
                        {
                            var searchId = $j(this).parent().parent().parent().parent().find(".smartAgentCheckBox").attr("cbId");
                            var folderId = $j(this).parent().parent().parent().parent().find(".smartAgentCheckBox").attr("cbFolderId");
                            var divId = $j(this).parent().parent().parent().parent().find(".smartAgentCheckBox").attr("cbContainerClientId");
                            var email = $j(this).parent().parent().find(".EmailText").val();
                            $j(this).parent().parent().parent().css("display", "none");
                            $j(this).parent().parent().parent().removeClass("pop");
                            $j("#opacityDiv").css("display", "none");
                            folderMgr.UpdateSmartAgentSearch(searchId, folderId, divId, true, email);
                        });
                    });

                    //Add Click Event For Close Button
                    $j(this).parent().parent().find(".closeSmartAgentBtn").each(function()
                    {
                        $j(this).unbind();
                        $j(this).click(function()
                        {
                            $j(this).parent().parent().find(".smartAgentCheckBox").find("input:checkbox").attr("checked", !isChecked);
                            $j(this).parent().css("display", "none");
                            $j(this).parent().removeClass("pop");
                            $j("#opacityDiv").css("display", "none");
                        });
                    });
                }
                else
                {
                    var searchIdToUpdate = $j(this).parent().attr("cbId");
                    var folderIdToUpdate = $j(this).parent().attr("cbFolderId");
                    var divIdToUpdate = $j(this).parent().attr("cbContainerClientId");
                    folderMgr.UpdateSmartAgentSearch(searchIdToUpdate, folderIdToUpdate, divIdToUpdate, false, "");
                }
            });
        });
    },

    // Loads a lazy-loading folder's queries
    LoadFolderQueries: function(divId, folderId, showFloatingProgress)
    {
        showFloatingProgress ? ajaxHelper.ShowProgress() : ajaxHelper.ShowProgress(divId, divId);

        SearchEngineService.GetFolderSearchesHtmlById(divId, folderId, folderMgr.isMultiView, folderMgr.LoadQueries_Complete);
    },

    DeleteSearch: function(searchId, folderId, divId)
    {
        // Make sure the folder and its div are registered
        if (folderMgr.FindFolder(folderId) == null)
            folderMgr.RegisterFolder(folderId, divId);

        if (confirm("האם אתה בטוח שברצונך למחוק שאילתה זו? שים לב! עם המחיקה תימחק גם הבקשה לסוכן החכם"))
        {
            SearchEngineService.DeleteSearch(searchId, folderId, folderMgr.DeleteSearch_Complete);
        }
    },

    DeleteSearch_Complete: function(result)
    {
        if (result && result.Result === true)
        {
            alert("השאילתה הוסרה בהצלחה!");

            if (result.Info)
            {
                var folder = folderMgr.FindFolder(result.Info);

                if (folder)
                    folderMgr.LoadFolderQueries(folder.divId, folder.folderId, true)
            }
        }
        else
        {
            alert("השמירה נכשלה נסה שוב מאוחר יותר!");
        }
    },

    UpdateSmartAgentSearch: function(searchId, folderId, divId, isSmartAgentActive, smartAgentEmail)
    {
        // Make sure the folder and its div are registered
        //var isSmartAgentActive = container.find("input:checkbox").attr("checked"); //FindElement('smartAgentCheckBox').get(0).checked;
        if (folderMgr.FindFolder(folderId) == null)
        {
            folderMgr.RegisterFolder(folderId, divId);
        }
        SearchEngineService.UpdateSearch(searchId, folderId, isSmartAgentActive, smartAgentEmail, folderMgr.UpdateSmartAgentSearch_Complete);
    },

    UpdateSmartAgentSearch_Complete: function(result)
    {
        if (result && result.Result === true)
        {
            alert("השאילתה עודכנה בהצלחה!");

            if (result.Info)
            {
                var folder = folderMgr.FindFolder(result.Info);

                if (folder)
                    folderMgr.LoadFolderQueries(folder.divId, folder.folderId, true)
            }
        }
        else
        {
            alert("השמירה נכשלה נסה שוב מאוחר יותר!");
        }
    }
};
