﻿var folderTypes =
{
    General: 1,
    History: 2,
    Managed: 3,
    Group: 4
};

var favoriteSavingResultType =
{
    Saved: 0,
    Duplicate: 1,
    Error: 2
};

function popup(popupId, procSmartDropDivId, procNumTxtId, procYearTxtId, procMonthTxtId, containerDivId, foldersDivId,
    newFolderDivId, saveBtnDivId, documentId)
{
    var popupId = this.popupId = popupId;
    var procSmartDropDivId = procSmartDropDivId;
    var procNumTxtId = procNumTxtId;
    var procYearTxtId = procYearTxtId;
    var procMonthTxtId = procMonthTxtId;
    var $containerDivId = $j('#' + containerDivId);
    var foldersDivId = foldersDivId;
    var newFolderDivId = newFolderDivId;
    var saveBtnDivId = saveBtnDivId;
    var documentId = documentId;
    var $folderRadiosDiv = {};
    var selectedFolderId = 0;
    var folders = [];
    var generalFolder = {};

    //set SelectedFolderId data member
    this.SetSelectedFolderId = function(folderId)
    {
        selectedFolderId = folderId;
    }
    // Returns a jQuery object wrapping the DOM element with the specified id
    var FindElement = function(id)
    {
        return $containerDivId.find('#' + id);
    };

    // param "result": The GetUserFolders result from the server
    this.InitFolders = function(result)
    {
        try
        {
            if (result)
            {
                $folderRadiosDiv = FindElement('folderRadiosDiv');

                // clear the array
                folders = [];

                for (var i = 0; i < result.length; i++)
                {
                    AddFolderLocal(result[i].Key, result[i].Value1, result[i].Value2, false);
                }
            }
        }
        catch (ex)
        {
            alert(ex);
        }
    };

    this.AddFolderLocal = function(id, name, type, doSelect)
    {
        AddFolderLocal(id, name, type, true);
    };

    var AddFolderLocal = function(id, name, type, doSelect)
    {

        // create folder object from the key-value-pair
        var folder = { id: id, name: name, type: type };

        // add to collection
        folders.push(folder);

        // check if this is the user's general folder
        if (folder.type == folderTypes['General'])
        {
            generalFolder = folder;
            doSelect = true;
            selectedFolderId = id;
        }

        popupId = popupId;

        $j('<input type="radio" name="folderRadios' + popupId + '" />')
            .appendTo($folderRadiosDiv)
            .attr('checked', doSelect ? 'checked' : '')
            .bind('click', function() { selectedFolderId = folder.id })
            .after(folder.name + '<br />');
    };

    var SaveOnEnter = function()
    {
        utility.ClickElement(FindElement('saveBtn').attr('id'));
        return false;
    };

    var CreateFolderOnEnter = function()
    {
        utility.ClickElement(FindElement('createFolderBtn').attr('id'));
        return false;
    };

    // private and public
    var SwitchDivs = this.SwitchDivs = function()
    {
        var foldersContainerDiv = document.getElementById(foldersDivId);
        var createNewFolderDiv = document.getElementById(newFolderDivId);

        foldersContainerDiv.style.display = foldersContainerDiv.style.display == 'none' ? '' : 'none';
        createNewFolderDiv.style.display = createNewFolderDiv.style.display == 'none' ? '' : 'none';

        // Toggle enter-pressed event-handlers
        if (createNewFolderDiv.style.display == 'none')
        {
            eventMgr.RegisterForInputKeyEvent(13, SaveOnEnter);
            FindElement('nameTxt').focus();
        }
        else
        {
            eventMgr.RegisterForInputKeyEvent(13, CreateFolderOnEnter);
            FindElement('newFolderNameTxt').focus();
        }
    };

    this.SaveQuery = function()
    {
        if (folders.length > 0)
        {
            var reEmail = /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/;

            var name = FindElement('nameTxt').get(0).value;
            var userEmail = FindElement('userEmailTxt').get(0).value;
            var doSmartAgent = FindElement('smartAgentCheckBox').get(0).checked;
            var description;
            
            if (document.getElementById("ctl00_searchDescriptionWUC_nonWordsInnerDiv"))
            {
                description = document.getElementById("ctl00_searchDescriptionWUC_nonWordsInnerDiv").innerHTML;
            }
            else
            {
                description = "";
            }
            
            if (name == '')
            {
                alert('חובה לתת שם לשאילתה');
                return;
            }

            if (doSmartAgent)
            {
                if (!Validate("userEmailTxt", reEmail, "מייל לא תקין"))
                {
                    return;
                }
            }
            else
            {
                userEmail = "";
            }

            ajaxHelper.ShowProgress('SaveQuery', saveBtnDivId);
            SearchEngineService.SaveQuery(selectedFolderId, name, userEmail, doSmartAgent, description, SaveQuery_Complete);
        }
        else
        {
            ajaxHelper.ShowError();
        }
    };

    var SaveQuery_Complete = function(args)
    {
        ajaxHelper.HideProgress('SaveQuery');

        alert(args == true ? "השאילתה נשמרה בהצלחה!" : "השמירה נכשלה נסה שוב מאוחר יותר!");

        HidePopup();
    };

    this.AddComment = function()
    {
        if (folders.length > 0)
        {
            var name = FindElement('nameTxt').get(0).value;
            var body = FindElement('commentBodyArea').get(0).value;

            if (name == '' || body == '')
            {
                alert('חובה להקליד כותרת ותוכן להערה.');
                return;
            }

            ajaxHelper.ShowProgress('AddComment', saveBtnDivId);
            SearchEngineService.AddComment(selectedFolderId, documentId, name, body, AddComment_Complete);
        }
        else
        {
            ajaxHelper.ShowError();
        }
    };

    var AddComment_Complete = function(args)
    {
        ajaxHelper.HideProgress('AddComment');

        if (args)
        {
            alert('ההערה התווספה למסמך בהצלחה!');
            docManager.GetComments();
        }
        else
        {
            alert('השמירה נכשלה נסה שוב מאוחר יותר!');
        }

        HidePopup();
    };

    this.AddFavorite = function(title, body)
    {
        if (folders.length > 0)
        {
            ajaxHelper.ShowProgress('AddFavorite', saveBtnDivId);
            SearchEngineService.AddFavorite(selectedFolderId, documentId, AddFavorite_Complete);

        }
        else
        {
            ajaxHelper.ShowError();
        }
    };

    var AddFavorite_Complete = function(args)
    {
        ajaxHelper.HideProgress('AddFavorite');

        switch (args)
        {
            case favoriteSavingResultType.Saved:
                alert("!המסמך התווסף למועדפים בהצלחה");
                break;
            case favoriteSavingResultType.Duplicate:
                alert("!המסמך כבר קיים בתיק הנבחר");
                break;
            case favoriteSavingResultType.Saved:
            default:
                alert("השמירה נכשלה נסה שוב מאוחר יותר!");
                break;
        }
        HidePopup();
    };

    this.AddFolder = function()
    {
        var txt = FindElement('newFolderNameTxt').get(0);
        if (txt.value == '')
        {
            alert('אנא הקלד שם לתיק');
        }
        else
        {
            if (utility.FindMatch(folders, function(folder) { return folder.name == txt.value; }) != null)
            {
                // folder name is not unique: show error
                alert('יש לתת שם יחודי לתיק');
            }
            else
            {
                ajaxHelper.ShowProgress('AddFolder', folderPopupMgr.newFolderDivId);

                var procTypeId = smartDropManager.GetSmartDropValue(procSmartDropDivId);
                var procType = smartDropManager.GetSmartDropText(procSmartDropDivId);
                var procNum = document.getElementById(procNumTxtId).value;
                var procMonth = document.getElementById(procMonthTxtId).value;
                var procYear = document.getElementById(procYearTxtId).value;

                SearchEngineService.AddFolder(txt.value, procTypeId, procType, procNum, procMonth, procYear, AddFolder_Complete);
            }
        }
    };

    var AddFolder_Complete = function(result)
    {
        ajaxHelper.HideProgress('AddFolder');
        if (result)
        {
            //update folder list in the popups
            var popup;
            for (var i = 0; i < folderPopupMgr.popups.length; i++)
            {
                popup = folderPopupMgr.FindPopup(folderPopupMgr.popups[i].popupId);
                popup.AddFolderLocal(result.Key, result.Value1, result.Value2, true);
                popup.SetSelectedFolderId(result.Key);
            }
            //AddFolderLocal(result.Key, result.Value1, result.Value2, true);
            //selectedFolderId = result.Key;

            // Show the folder-radios div
            SwitchDivs();
        }
        else
        {
            alert('הוספת תיק נכשלה. אנא וודא שלתיק יש שם יחודי, או נסה שוב מאוחר יותר');
        }
    };

    var ShowPopup = this.ShowPopup = function()
    {
        if (folders.length > 0)
        {
            // Notify: Popup about to be shown
            eventMgr.Raise(eventMgr.onBeforeShowPopupEvent);

            // Show the popup
            $find(popupId).show();

            // save if user presses enter key (key-code 13)
            eventMgr.RegisterForInputKeyEvent(13, SaveOnEnter);
            // close if user presses escape key (key-code 27)
            eventMgr.RegisterForInputKeyEvent(27, function() { utility.ClickElement(FindElement('closeBtn').attr('id')) });
            FindElement('nameTxt').focus();
            $j("#documentFrame").css("display", "none");
        }
        else
        {
            alert('עליך להתחבר כדי לשמור שאילתות.');
        }
    };

    var HidePopup = this.HidePopup = function()
    {
        if (document.getElementById(newFolderDivId).style.display != 'none')
        {
            // Hide the create-new-folder div instead of closing
            SwitchDivs();
        }
        else
        {
            // Hide the popup
            $find(popupId).hide();
            $j("#documentFrame").css("display", "block");
            // unregister for key-press events
            eventMgr.UnRegisterForInputKeyEvent(13);
            eventMgr.UnRegisterForInputKeyEvent(27);

            // Notify: popup hidden
            eventMgr.Raise(eventMgr.onAfterHidePopupEvent);
        }
    };
};

var folderPopupMgr =
{
    popups: [],

    AddPopup: function(popupId, procSmartDropDivId, procNumTxtId, procYearTxtId, procMonthTxtId, containerDivId,
        foldersDivId, newFolderDivId, saveBtnDivId, documentId, saveBtnId, createBtnId)
    {
        try
        {
            var folderPopup = new popup(
                popupId,
                procSmartDropDivId,
                procNumTxtId,
                procYearTxtId,
                procMonthTxtId,
                containerDivId,
                foldersDivId,
                newFolderDivId,
                saveBtnDivId,
                documentId,
                saveBtnId,
                createBtnId
            );

            folderPopupMgr.popups.push(folderPopup);
        }
        catch (ex)
        {
            alert(ex);
        }
    },

    // Initializes all popups
    Init: function()
    {
        // Load folders
        SearchEngineService.GetUserFolders(folderPopupMgr.GetUserFolders_Complete,
                                           folderPopupMgr.GetUserFolders_Error,
                                           folderPopupMgr.GetUserFolders_Timeout);
    },

    GetUserFolders_Complete: function(result)
    {
        for (var i = 0; i < folderPopupMgr.popups.length; i++)
        {
            folderPopupMgr.popups[i].InitFolders(result);
        }
    },

    GetUserFolders_Error: function(err)
    {
        alert("אירעה שגיאה בזמן טעינת התיקיות של המשתמש\r\n" + err._message);
    },
    
    GetUserFolders_Timeout: function(msg)
    {
        alert("הבקשה לטעינת התיקיות של המשתמש לא נענתה");
    },

    FindPopup: function(popupId)
    {
        if (!popupId && folderPopupMgr.popups.length == 1)
        {
            // PopupId was not specified and there is only one popup: return it
            return folderPopupMgr.popups[0];
        }
        else
        {
            for (var i = 0; i < folderPopupMgr.popups.length; i++)
            {
                if (folderPopupMgr.popups[i].popupId == popupId)
                    return folderPopupMgr.popups[i];
            }
        }
    },

    SwitchDivs: function(popupId)
    {
        var popup = folderPopupMgr.FindPopup(popupId);
        popup.SwitchDivs();
    },

    AddFolderLocal: function(popupId, id, name, type, doSelect)
    {
        var popup = folderPopupMgr.FindPopup(popupId);
        popup.AddFolderLocal(id, name, type, doSelect);
    },

    SaveQuery: function(popupId)
    {
        var popup = folderPopupMgr.FindPopup(popupId);
        popup.SaveQuery();
    },

    AddComment: function(popupId)
    {
        var popup = folderPopupMgr.FindPopup(popupId);
        popup.AddComment();
    },

    AddFavorite: function(popupId)
    {
        var popup = folderPopupMgr.FindPopup(popupId);
        popup.AddFavorite();
    },

    AddFolder: function(popupId)
    {
        var popup = folderPopupMgr.FindPopup(popupId);
        popup.AddFolder();
    },

    ShowPopup: function(popupId)
    {
        var popup = folderPopupMgr.FindPopup(popupId);
        popup.ShowPopup();
    },

    HidePopup: function(popupId)
    {
        var popup = folderPopupMgr.FindPopup(popupId);
        popup.HidePopup();
    }

};

function Validate(field, regexp, warning)
{
    var element = document.getElementById(field);

    if (element)
    {
        var re = new RegExp(regexp);

        element.value = element.value.trim();

        if (element.value == "" || !element.value.match(re))
        {
            alert(warning);
            element.select();
            return false;
        }
    }

    return true;
}
