
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Cookie functions
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//





//////////////////////////////////////////////////////
// OLD username and and password functions
// No longer used
//////////////////////////////////////////////////////


function GetLoginUsernameFromCookie() {
    return getCookie("ST-Login-Username");
}

function GetLoginPasswordFromCookie() {
    var encrypttype = getCookie("ST-Login-Base");
    var encypted = getCookie("ST-Login-Password");
    var decrypted = encypted;
    if (encrypttype && encrypttype === "146")
        decrypted = Decrypt146(encypted);
    return decrypted;
}

function SetLoginUsernameCookie(username) {
    return setCookie("ST-Login-Username", username, 365);
}

function SetLoginPasswordCookie(password) {
    var encypted146 = Encrypt146(password);
    setCookie("ST-Login-Password", encypted146, 365);
    setCookie("ST-Login-Base", "146", 365);
}




//////////////////////////////////////////////////////
// New login username and and password functions
// Supercedes old functions above on 8/15/2024
//////////////////////////////////////////////////////

function GetStEncryptedLoginUsernameFromCookie() {
    var stencypted = getCookie("ST-otoken");
    if (stencypted != null && stencypted.length > 0)
        return stencypted;

    // Old format, phased out 8/15/2024
    return getCookie("ST-Login-Username");
}

function GetStEncryptedLoginPasswordFromCookie() {
    var stencypted = getCookie("ST-btoken");
    if (stencypted != null && stencypted.length > 0)
        return stencypted;

    // Old format, phased out 8/15/2024
    var encrypttype = getCookie("ST-Login-Base");
    var encypted = getCookie("ST-Login-Password");
    var decrypted = encypted;
    if (encrypttype && encrypttype === "146")
        decrypted = Decrypt146(encypted);
    return decrypted;
}

function SetStEncryptedLoginUsernameCookie(username) {
    return setCookie("ST-otoken", username, 365);
}

function SetStEncryptedLoginPasswordCookie(password) {
    setCookie("ST-btoken", password, 365);
    setCookie("ST-Login-Base", "100", 365);
}


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//




var bSavingDockManagerLayoutToCookie = false;
var bLoadingDockManagerLayoutFromCookie = false;

/**
 * Save all the dock manager pages to a cookie so they can be restored upon startup
 * */
function SaveDockManagerLayoutToCookie() {

    try {

        if (bLoadingDockManagerLayoutFromCookie)
            return false;
        bSavingDockManagerLayoutToCookie = true;

        var DocumentHostPanes = FindDocumentHostPanes();
        if (!DocumentHostPanes)
            return false;

        // Hackishly bad, need improvement because there could be multiple panes with the same content type
        var SelectedContentType = "HOMEALLVIEWS";
        if (this.dockManager.activePane)
             SelectedContentType = this.dockManager.activePane.STCONTENTTYPE;
        else SelectedContentType = $('input[id="HiddenSelectedContentTypeId"]').val();

        // Iterate over array of panels
        var DocumentPanesArray = [];
        for (ContentPane of DocumentHostPanes) {

            //ContentPane.STCONTENTTYPE: "HOMEALLVIEWS"
            //ContentPane.header: "Home (All Views)"
            var bSelected = false;
            if (SelectedContentType == ContentPane.STCONTENTTYPE)
                bSelected = true;

            // Add a new pane to the array
            const DocumentPane = { STCONTENTTYPE: ContentPane.STCONTENTTYPE, header: ContentPane.header, UniqueId: ContentPane.UniqueId, ValueString: ContentPane.ValueString, FilterJsonString: ContentPane.FilterJsonString, SettingsJsonString: ContentPane.SettingsJsonString, Selected: bSelected };
            DocumentPanesArray.push(DocumentPane);
        }

        // Save to cookie
        var sDocumentPanesArray = JSON.stringify(DocumentPanesArray);
        localStorage.setItem("ST-DocumentPanesArray", sDocumentPanesArray);
        //setCookie("ST-DocumentPanesArray", sDocumentPanesArray, 365);

        // Success
        return true;
    }
    catch (err) {
        // Bad
    }
    finally {
        bSavingDockManagerLayoutToCookie = false;
    }
}


/**
 * Load all the dock manager panes from cookie
 * */
function LoadDockManagerLayoutFromCookie() {

    try {

        if (bLoadingDockManagerLayoutFromCookie)
            return;
        bLoadingDockManagerLayoutFromCookie = true;

        var DocumentHostPanes = FindDocumentHostPanes();
        if (!DocumentHostPanes)
            return false;

        // Load the array string from cookie
        // Try localStorage first, then cookie
        var sDocumentPanesArray = localStorage.getItem("ST-DocumentPanesArray");
        if (!sDocumentPanesArray)
            sDocumentPanesArray = getCookie("ST-DocumentPanesArray");
        if (!sDocumentPanesArray)
            return false;

        // Convert string to array
        var DocumentPanesArray = JSON.parse(sDocumentPanesArray);
        if (!DocumentPanesArray)
            return false;
        if (!DocumentPanesArray.length)
            return false;

        // Iterate over the array
        // Add panels for each item in the array
        var SelectedContentType = "HOMEALLVIEWS";
        var nItems = DocumentPanesArray.length;
        for (var i = 0; i < nItems; i++) {

            // Add panel
            var DocumentPane = DocumentPanesArray[i];
            if (DocumentPane) {

                // Show the panel
                AddDocumentTab(DocumentPane.STCONTENTTYPE, DocumentPane.UniqueId, DocumentPane.ValueString, DocumentPane.header, DocumentPane.FilterJsonString, DocumentPane.SettingsJsonString);

                // Remember the selected content type so it can be made active
                if (DocumentPane.Selected)
                    SelectedContentType = DocumentPane.STCONTENTTYPE;
            }
        }

        // Set the active pane, which will cause it to reload content
        ActivateDocumentTabByContentType(SelectedContentType);

        // Success!
        return true;
    }
    catch (err) {
        // Bad
    }
    finally {
        bLoadingDockManagerLayoutFromCookie = false;

        // No panels? Then add HomeAllViews
        var nContentPanels = GetNumContentPanes();
        if (!nContentPanels)
            ShowHomeAllViews();
    }

    return false;
}






/**
 * Load the splitter sizes from a cookie
 * */
function LoadSplitterPaneSizesFromCookie() {

    // Got a cookie?
    var sSplitterPaneSizes = getCookie("ST-SplitterPaneSizes");
    if (!sSplitterPaneSizes)
        return;

    try {
        //console.log("LoadSplitterPaneSizesFromCookie Start: " + sSplitterPaneSizes);

        // Array of pane sizes
        //var SplitterPaneSizes = JSON.parse(sSplitterPaneSizes);
        var SplitterPaneSizes = sSplitterPaneSizes.split(',');
        if (!SplitterPaneSizes)
            return;
        if (SplitterPaneSizes.length == 0)
            return;

        // 3 panes
        if (SplitterPaneSizes.length == 3) {
            var PaneSize1 = SplitterPaneSizes[0];
            var PaneSize2 = SplitterPaneSizes[1];
            var PaneSize3 = SplitterPaneSizes[2];

            //console.log("LoadSplitterPaneSizesFromCookie Split: " + PaneSize1 + ", " + PaneSize2 + ", " + PaneSize3);

            // Good values?
            if (!$.isNumeric(PaneSize1))
                return;
            if (!$.isNumeric(PaneSize2))
                return;
            if (!$.isNumeric(PaneSize3))
                return;

            var dPaneSize1 = parseFloat(PaneSize1);
            var dPaneSize2 = parseFloat(PaneSize2);
            var dPaneSize3 = parseFloat(PaneSize3);

            // Set the splitter sizes
            SetSplitterPaneSize(0/*nSplitterPane*/, dPaneSize1);
            SetSplitterPaneSize(1/*nSplitterPane*/, dPaneSize2);
            SetSplitterPaneSize(2/*nSplitterPane*/, dPaneSize3);

            //console.log("LoadSplitterPaneSizesFromCookie End: " + dPaneSize1 + ", " + dPaneSize2 + ", " + dPaneSize3);
        }
    }
    catch (err) {
        // Bad
    }
    finally {
    }
}



/**
 * Save the splitter sizes to a cookie
 * */
function SaveSplitterPaneSizesToCookie() {

    var PaneSize1 = GetSplitterPaneSize(0/*nSplitterPane*/);
    var PaneSize2 = GetSplitterPaneSize(1/*nSplitterPane*/);
    var PaneSize3 = GetSplitterPaneSize(2/*nSplitterPane*/);

    // Good values?
    if (!$.isNumeric(PaneSize1))
        return;
    if (!$.isNumeric(PaneSize2))
        return;
    if (!$.isNumeric(PaneSize3))
        return;
    if (PaneSize1 < 0)
        return;
    if (PaneSize2 < 0)
        return;
    if (PaneSize3 < 0)
        return;

    // Save
    var sSplitterPaneSizes = PaneSize1 + "," + PaneSize2 + "," + PaneSize3;
    setCookie("ST-SplitterPaneSizes", sSplitterPaneSizes, 365);

    //console.log("SaveSplitterPaneSizesToCookie: " + sSplitterPaneSizes);
}


/**
 * Load the "pinned" status of a panel from a cookie
 * */
function LoadPanelPinnedFromCookie(ContentId, DefaultValue) {

    var sIsPinned = localStorage.getItem("ST-" + ContentId + "-IsPinned");
    if (!sIsPinned)
        sIsPinned = getCookie("ST-" + ContentId + "-IsPinned");

    if (sIsPinned) {
        var IsPinned = (sIsPinned === 'true');
        return IsPinned;
    }
    return DefaultValue;
}

function LoadFilterPanelPinnedFromCookie() {

    var IsPinned = LoadPanelPinnedFromCookie("FilterPane", false);
    var Pane = FindPaneByContentId("FilterPane");
    if (Pane)
        Pane.isPinned = IsPinned;
}

function LoadPropertiesPanelPinnedFromCookie() {

    var IsPinned = LoadPanelPinnedFromCookie("PropertyPane", false);
    var Pane = FindPaneByContentId("PropertyPane");
    if (Pane)
        Pane.isPinned = IsPinned;
}

function LoadSettingsPanelPinnedFromCookie() {

    var IsPinned = LoadPanelPinnedFromCookie("SettingsPane", false);
    var Pane = FindPaneByContentId("SettingsPane");
    if (Pane)
        Pane.isPinned = IsPinned;
}


/**
 * Save the "pinned" status of a panel to a cookie
 * */
function SavePanelPinnedToCookie(ContentId, IsPinned) {

    var sIsPinned = "false";
    if (IsPinned)
        sIsPinned = "true";
    localStorage.setItem("ST-" + ContentId + "-IsPinned", sIsPinned);
    //setCookie("ST-" + ContentId + "-IsPinned", sIsPinned, 365);
}

function SaveFilterPanelPinnedToCooke() {

    SavePanelPinnedToCookie("FilterPane", true);
}

function SavePropertyPanelPinnedToCooke() {

    SavePanelPinnedToCookie("PropertyPane", true);
}

function SaveSettingsPanelPinnedToCooke() {

    SavePanelPinnedToCookie("SettingsPane", true);
}






/**
 * Load the width of the "Property" panel (at the right) from a cookie
 * */
function LoadPropertyPanelWidthFromCookie() {

}


/**
 * Save the width of the "Property" panel (at the right) to a cookie
 * */
function SavePropertyPanelWidthToCookie() {

}

function LoadPaneLayoutStringFromCookie(ContentType) {

    if (!ContentType)
        return "";

    var CookieName = "ST-Layout-" + ContentType;

    if (!bSmallSizeApp) {
        // Add a distinguishing suffix to differentiate tabs
        var UniqueId = GetSelectedContentPaneUniqueId();
        CookieName += "-" + UniqueId;
    }

    var LayoutString = localStorage.getItem(CookieName);
    if (!LayoutString)
        LayoutString = getCookie(CookieName);

    // Add column widths to names
    LayoutString = AddColumnWidthsToLayoutString(ContentType, LayoutString);

    return LayoutString;
}

function AddColumnWidthsToLayoutString(ContentType, LayoutString) {

    if (!LayoutString)
        return LayoutString;

    var NewLayoutString = "";
    var ColumnNames = LayoutString.split(',');

    // Load column widths from cookies
    for (i = 0; i < ColumnNames.length; ++i) {
        var sColumnName = ColumnNames[i];
        var ColumnWidth = LoadColumnWidthFromCookie(ContentType, sColumnName);
        if (ColumnWidth)
            sColumnName = sColumnName + "{width:" + ColumnWidth + "}";

        // Add the column to the new string
        if (NewLayoutString)
            NewLayoutString = NewLayoutString + ",";
        NewLayoutString = NewLayoutString + sColumnName;
    }

    return NewLayoutString;
}

function LoadPaneFilterJsonStringFromCookie(ContentType) {

    if (!ContentType)
        return "";

    if (!bSmallSizeApp) {
        // Add a distinguishing suffix to differentiate tabs
        var UniqueId = GetSelectedContentPaneUniqueId();
        ContentType += "-" + UniqueId;
    }

    var CookieName = "ST-Filter-" + ContentType;
    //console.log("LoadPaneFilterJsonStringFromCookie: " + CookieName);
    return getCookie(CookieName);
}

function LoadPaneSettingsJsonStringFromCookie(ContentType) {

    if (!ContentType)
        return "";

    if (!bSmallSizeApp) {
        // Add a distinguishing suffix to differentiate tabs
        var UniqueId = GetSelectedContentPaneUniqueId();
        ContentType += "-" + UniqueId;
    }

    var CookieName = "ST-Settings-" + ContentType;
    return getCookie(CookieName);
}

function LoadSelectedPaneLayoutStringFromCookie() {

    var ContentType = GetSelectedContentType();
    if (!ContentType)
        return "";
    return LoadPaneLayoutStringFromCookie(ContentType);
}

function LoadSelectedPaneFilterJsonStringFromCookie() {

    var ContentType = GetSelectedContentType();
    if (!ContentType)
        return "";
    return LoadPaneFilterJsonStringFromCookie(ContentType);
}

function LoadSelectedPaneSettingsJsonStringFromCookie() {

    var ContentType = GetSelectedContentType();
    if (!ContentType)
        return "";
    return LoadPaneSettingsJsonStringFromCookie(ContentType);
}






function SaveSelectedPaneLayoutStringToCookie(LayoutString) {

    var ContentType = GetSelectedContentType();
    if (!ContentType)
        return;

    if (!bSmallSizeApp) {
        // Add a distinguishing suffix to differentiate tabs
        var UniqueId = GetSelectedContentPaneUniqueId();
        ContentType += "-" + UniqueId;
    }

    var CookieName = "ST-Layout-" + ContentType;
    localStorage.setItem(CookieName, LayoutString);

    if (!LayoutString || LayoutString == null || LayoutString.length == 0)
        deleteCookie(CookieName);
    //setCookie(CookieName, LayoutString, 365);
}

function SaveSelectedPaneFilterJsonStringToCookie(JsonFilterString) {

    var ContentType = GetSelectedContentType();
    if (!ContentType)
        return;

    SaveContentTypeFilterJsonStringToCookie(ContentType, JsonFilterString);
}

function SaveContentTypeFilterJsonStringToCookie(ContentType, JsonFilterString) {

    if (!ContentType)
        return;

    if (!bSmallSizeApp) {
        // Add a distinguishing suffix to differentiate tabs
        var UniqueId = GetSelectedContentPaneUniqueId();
        ContentType += "-" + UniqueId;
    }

    var CookieName = "ST-Filter-" + ContentType;
    //console.log("SaveContentTypeFilterJsonStringToCookie: " + CookieName);
    setCookie(CookieName, JsonFilterString, 365);
}

function SaveSelectedPaneSettingsJsonStringToCookie(SettingsJsonString) {

    var ContentType = GetSelectedContentType();
    if (!ContentType)
        return;

    if (!bSmallSizeApp) {
        // Add a distinguishing suffix to differentiate tabs
        var UniqueId = GetSelectedContentPaneUniqueId();
        ContentType += "-" + UniqueId;
    }

    var CookieName = "ST-Settings-" + ContentType;
    setCookie(CookieName, SettingsJsonString, 365);
}





function LoadReportActiveTabToCookie(ReportPathname) {

    if (!ReportPathname)
        return;
    ReportPathname = ReportPathname.replace(/\\/g, '');
    ReportPathname = ReportPathname.replace(/ /g, '');
    ReportPathname = ReportPathname.replace(/\./g, '');

    var CookieName = "ST-ReportActiveTab-" + ReportPathname;
    var ActiveTab = getCookie(CookieName);
    if (!ActiveTab)
        ActiveTab = "1"; // Preview tab
    return ActiveTab;
}

function SaveReportActiveTabToCookie(ReportPathname, ActiveTab) {

    if (!ReportPathname)
        return;
    ReportPathname = ReportPathname.replace(/\\/g, '');
    ReportPathname = ReportPathname.replace(/ /g, '');
    ReportPathname = ReportPathname.replace(/\./g, '');

    var CookieName = "ST-ReportActiveTab-" + ReportPathname;
    setCookie(CookieName, ActiveTab, 1/*days*/);
}




function SaveColumnWidthToCookie(ContentType, ColumnKey, ColumnWidth) {

    if (!bSmallSizeApp) {
        // Add a distinguishing suffix to differentiate tabs
        var UniqueId = GetSelectedContentPaneUniqueId();
        ContentType += "-" + UniqueId;
    }

    ColumnKey = ReplaceAllColumnNameTags(ColumnKey, false/*bWithTagName*/);

    var CookieName = "ST-ColumnWidth-" + ContentType + "-" + ColumnKey;
    localStorage.setItem(CookieName, ColumnWidth);
    //setCookie(CookieName, ColumnWidth, 365);
}

function LoadColumnWidthFromCookie(ContentType, ColumnKey) {

    if (!bSmallSizeApp) {
        // Add a distinguishing suffix to differentiate tabs
        var UniqueId = GetSelectedContentPaneUniqueId();
        ContentType += "-" + UniqueId;
    }

    ColumnKey = ReplaceAllColumnNameTags(ColumnKey, false/*bWithTagName*/);

    var CookieName = "ST-ColumnWidth-" + ContentType + "-" + ColumnKey;
    var ColumnWidth = localStorage.getItem(CookieName);
    if (ColumnWidth)
        return parseInt(ColumnWidth);
    return getCookie(CookieName);
}

function ClearSelectedPaneColumnWidths() {

    var ContentType = GetSelectedContentType();
    if (!ContentType)
        return;

    ClearAllColumnWidths(ContentType);
}

function ClearAllColumnWidths(ContentType) {

    // Clear all cookies that start with this name
    var CookiePrefix = "ST-ColumnWidth-" + ContentType + "-";
    deleteAllCookiesByPrefix(CookiePrefix)
}

function DeleteContentCookies(ContentType, UniqueId) {

    // Delete all cookies for this content type
    // Examples
    //      ST-Filter-PROJECTSGRID-uid-168934207605313-5
    if (!ContentType)
        return;

    // Delete filter cookie
    var FilterCookieName = "ST-Filter-" + ContentType;
    deleteCookie(FilterCookieName);
    FilterCookieName += "-" + UniqueId;
    deleteCookie(FilterCookieName);

    // Delete settings cookie
    var SettingsCookieName = "ST-Settings-" + ContentType;
    deleteCookie(SettingsCookieName);
    SettingsCookieName += "-" + UniqueId;
    deleteCookie(SettingsCookieName);

    // Delete layout cookie
    var LayoutCookieName = "ST-Layout-" + ContentType;
    deleteCookie(LayoutCookieName);
    LayoutCookieName += "-" + UniqueId;
    deleteCookie(LayoutCookieName);

    // Delete column width cookie
    var ColumnWidthCookieName = "ST-ColumnWidth-" + ContentType;
    deleteCookie(ColumnWidthCookieName);
    ColumnWidthCookieName += "-" + UniqueId;
    deleteAllCookiesByPrefix(ColumnWidthCookieName);
}





function SaveColumnFixedToCookie(ContentType, ColumnKey, bIsFixed) {

    if (!bSmallSizeApp) {
        // Add a distinguishing suffix to differentiate tabs
        var UniqueId = GetSelectedContentPaneUniqueId();
        ContentType += "-" + UniqueId;
    }

    var CookieName = "ST-ColumnFixed-" + ContentType + "-" + ColumnKey;
    console.log("SaveColumnFixedToCookie: " + CookieName + ", " + bIsFixed);

    if (bIsFixed)
        setCookie(CookieName, bIsFixed, 365);
    else
        deleteCookie(CookieName);
}

function LoadColumnFixedFromCookie(ContentType, ColumnKey) {

    if (!bSmallSizeApp) {
        // Add a distinguishing suffix to differentiate tabs
        var UniqueId = GetSelectedContentPaneUniqueId();
        ContentType += "-" + UniqueId;
    }

    var CookieName = "ST-ColumnFixed-" + ContentType + "-" + ColumnKey;
    return getCookie(CookieName);
}




/**
 * Prompt (Yes/No) then restore all defaults
 * */
function RestoreDefaults() {

    var msg = "Are you sure you wish to restore all views to defaults?\r\n\r\nThis will remove all settings you have made. Tab contents will be replaced with defaults. The layout will revert to original settings.\r\n\r\nRestore to default?";
    var proceedobject = "Restore Default Views";

    var prompt = { sTitle: "Restore Default Views", sPrompt: msg, MbButtons: 4/*StMessageBoxButtons.YesNo*/ };
    OpenMessageBox(prompt, RestoreDefaultsCallback, proceedobject);
}

function RestoreDefaultsCallback(prompt, proceedobject) {

    deleteAllCookies();

    // Delete specific local storage
    localStorage.clear();
    //localStorage.removeItem("ST-DocumentPanesArray");

    ToastMessage("", "All user choices reverted to default");

    // TO REFRESH THE PAGE
    window.location = ""; 

    // Open the login dialog again (because login values are stored in cookies, and they have been erased)
    //OpenLoginDialogFromCookieValues();
}








function GetCollapsedRecordIdsCookieAsArray() {
    var sRecordIds = GetCollapsedRecordIdsCookie();
    var RecordIds = [];
    if (sRecordIds && sRecordIds.length > 0)
        RecordIds = sRecordIds.split('~');
    return RecordIds;
}

function GetCollapsedRecordIdsCookie() {

    var ContentType = GetSelectedContentType();
    if (!ContentType)
        return;

    var sName = "ST-CollapsedGridIds-" + ContentType
    return getCookie(sName);
}

function SetCollapsedRecordIdsCookie(sRecordIds) {

    var ContentType = GetSelectedContentType();
    if (!ContentType)
        return;

    var sName = "ST-CollapsedGridIds-" + ContentType
    return setCookie(sName, sRecordIds, 365);
}

function RemoveIdFromCollapsedCookie(sRecordId) {

    if (!sRecordId)
        return;
    var ContentType = GetSelectedContentType();
    if (!ContentType)
        return;

    // Remove from list and save the new list
    var RecordIds = GetCollapsedRecordIdsCookieAsArray();
    var idx = RecordIds.indexOf(sRecordId);
    if (idx >= 0) {
        RecordIds.splice(idx, 1);
        sRecordIds = RecordIds.join("~");
        SetCollapsedRecordIdsCookie(sRecordIds);
    }
}

function AddIdToCollapsedCookie(sRecordId) {

    if (!sRecordId)
        return;
    var ContentType = GetSelectedContentType();
    if (!ContentType)
        return;

    // Add to list and save the new list
    var RecordIds = GetCollapsedRecordIdsCookieAsArray();
    var idx = RecordIds.indexOf(sRecordId);
    if (idx < 0) {
        RecordIds.push(sRecordId);
        sRecordIds = RecordIds.join("~");
        SetCollapsedRecordIdsCookie(sRecordIds);
    }
}






function GetCollapsedPropertiesCookie() {

    var SelectedTableId = $('input[id="HiddenSelectedTableId"]').val();
    if (!SelectedTableId)
        SelectedTableId = "UnknownTable";

    var sName = "ST-CollapsedProperties-" + SelectedTableId
    return getCookie(sName);
}

function SetCollapsedPropertiesCookie(sProperties) {

    var SelectedTableId = $('input[id="HiddenSelectedTableId"]').val();
    if (!SelectedTableId)
        SelectedTableId = "UnknownTable";

    var sName = "ST-CollapsedProperties-" + SelectedTableId
    return setCookie(sName, sProperties, 365);
}

function GetHasManualCollapsedPropertiesCookie() {

    var SelectedTableId = $('input[id="HiddenSelectedTableId"]').val();
    if (!SelectedTableId)
        SelectedTableId = "UnknownTable";

    var sName = "ST-CollapsedManuallyProperties-" + SelectedTableId
    return getCookie(sName);
}

function SetHasManuallyCollapsedPropertiesCookie() {

    var SelectedTableId = $('input[id="HiddenSelectedTableId"]').val();
    if (!SelectedTableId)
        SelectedTableId = "UnknownTable";

    var sName = "ST-CollapsedManuallyProperties-" + SelectedTableId
    return setCookie(sName, "true", 365);
}


function RemovePropertyFromCollapsedCookie(sProperty) {

    if (!sProperty)
        return;

    // Remove from list and save the new list
    var Properties = GetCollapsedPropertiesCookieAsArray();
    var idx = Properties.indexOf(sProperty);
    if (idx >= 0) {
        Properties.splice(idx, 1);
        sProperties = Properties.join("~");
        SetCollapsedPropertiesCookie(sProperties);
    }
}

function AddPropertyToCollapsedCookie(sProperty) {

    if (!sProperty)
        return;

    // Add to list and save the new list
    var Properties = GetCollapsedPropertiesCookieAsArray();
    var idx = Properties.indexOf(sProperty);
    if (idx < 0) {
        Properties.push(sProperty);
        sProperties = Properties.join("~");
        SetCollapsedPropertiesCookie(sProperties);
    }
}

function GetCollapsedPropertiesCookieAsArray() {
    var sProperties = GetCollapsedPropertiesCookie();
    var Properties = [];
    if (sProperties && sProperties.length > 0)
        Properties = sProperties.split('~');
    return Properties;
}






function AddFilterTreeNodeToCookies(ParentTreePath, NodeText, NodeValue, NodeType) {
    var sName = "ST-FilterTreeNode-" + ParentTreePath + "*" + NodeValue;
    return setCookie(sName, NodeText + "^" + NodeValue + "^" + NodeType, 60/*days*/);
}


function GetAllFilterTreeNodeCookies(ParentPathsArray, NodeNamesArray, NodeValuesArray, NodeTypesArray) {

    var StartsWithPrefix = "ST-FilterTreeNode-";
    var CookieNamesArray = [];
    var CookieValuesArray = [];
    var CookieTypesArray = [];
    findAllCookiesByPrefix(StartsWithPrefix, CookieNamesArray, CookieValuesArray, CookieTypesArray);

    for (i = 0; i < CookieNamesArray.length; ++i) {
        var CookieName = CookieNamesArray[i];
        CookieName = CookieName.replace(StartsWithPrefix, "");
        var CookieNameParts = CookieName.split("*");
        if (!CookieNameParts || CookieNameParts.length < 2)
            continue;
        var ParentPath = CookieNameParts[0];
        if (!ParentPath)
            continue;

        var CookieValue = CookieValuesArray[i];
        var CookieValueParts = CookieValue.split("^");
        if (!CookieValueParts || CookieValueParts.length < 3)
            continue;
        var NodeName = CookieValueParts[0];
        var NodeValue = CookieValueParts[1];
        var NodeType = CookieValueParts[2];

        ParentPathsArray.push(ParentPath);
        NodeNamesArray.push(NodeName);
        NodeValuesArray.push(NodeValue);
        NodeTypesArray.push(NodeType);
    }
}




function GetFilterFavoriteIdsCookie(FilterFavoriteType) {

    if (!LastFilterTypeText)
        return;

    var sName = "ST-FilterFavorites-" + FilterFavoriteType
    return getCookie(sName);
}

function SetFilterFavoritedIdsCookie(FilterFavoriteType, sRecordIds) {

    if (!LastFilterTypeText)
        return;

    var sName = "ST-FilterFavorites-" + FilterFavoriteType
    return setCookie(sName, sRecordIds, 365);
}





function GetFullSizeAppFromCookie() {
    return getCookie("ST-FullSizeApp");
}


function SetFullSizeAppCookie(bFullSizeApp) {
    var sFullSizeApp = bFullSizeApp ? "1" : "0";
    return setCookie("ST-FullSizeApp", sFullSizeApp, 365);
}




function GetDeferRefreshSecondsFromCookie() {
    var seconds = getCookie("ST-DeferRefresh");
    if (seconds == null)
        return 31;

    seconds = Math.max(5, Number(seconds));
    seconds = Math.min(1000, Number(seconds));
    return seconds;
}


function SetDeferRefreshSecondsCookie(seconds) {
    seconds = Math.max(5, Number(seconds));
    seconds = Math.min(1000, Number(seconds));
    setCookie("ST-DeferRefresh", seconds, 365);
}






function LoadAutoRefreshMinutesFromCookie() {
    var nMinutes = getCookie("ST-AutoRefreshMinutes");
    if (nMinutes == null)
        return 5;

    nMinutes = Math.max(0, Number(nMinutes));
    nMinutes = Math.min(1000, Number(nMinutes));
    return nMinutes;
}

function LoadAutoRefreshCheckedFromCookie() {
    var bChecked = getCookie("ST-AutoRefreshChecked");
    if (!bChecked || bChecked == null)
        return false;
    return bChecked;
}

function SaveAutoRefreshMinutesToCookie(nMinutes) {
    setCookie("ST-AutoRefreshMinutes", nMinutes, 365);
}

function SaveAutoRefreshCheckedToCookie(bChecked) {
    setCookie("ST-AutoRefreshChecked", bChecked, 365);
}





function LoadToasterDisplaySecondsFromCookie() {
    var nSeconds = getCookie("ST-ToasterDisplaySeconds");
    if (nSeconds == null)
        return 10;

    nSeconds = Math.max(1, Number(nSeconds));
    nSeconds = Math.min(120, Number(nSeconds));
    return nSeconds;
}

function LoadToasterDisplayCheckedFromCookie() {
    var bChecked = getCookie("ST-ToasterDisplayChecked");
    if (bChecked == null)
        return true;
    return bChecked;
}

function SaveToasterDisplaySecondsToCookie(nSeconds) {
    setCookie("ST-ToasterDisplaySeconds", nSeconds, 365);
}

function SaveToasterDisplayCheckedToCookie(bChecked) {
    setCookie("ST-ToasterDisplayChecked", bChecked, 365);
}





function LoadBarcodeClearSecondsFromCookie() {
    var nSeconds = getCookie("ST-BarcodeClearSeconds");
    if (nSeconds == null)
        return 60;

    nSeconds = Math.max(20, Number(nSeconds));
    nSeconds = Math.min(64800, Number(nSeconds));
    return nSeconds;
}

function SaveGanttScaleToLocalStorage(ContentType, GanttScale) {

    if (!ContentType)
        return;
    if (!GanttScale)
        return;

    var CookieName = "ST-GanttScale-" + ContentType;
    var sGanttScale = JSON.stringify(GanttScale);
    localStorage.setItem(CookieName, sGanttScale);
}

function LoadGanttScaleFromLocalStorage(ContentType) {

    if (!ContentType)
        return null;

    var CookieName = "ST-GanttScale-" + ContentType;
    var sGanttScale = localStorage.getItem(CookieName);
    if (!sGanttScale)
        return null;

    try {
        return JSON.parse(sGanttScale);
    }
    catch (e) {
        return null;
    }
}


function LoadBarcodeClearCheckedFromCookie() {
    var bChecked = getCookie("ST-BarcodeClearChecked");
    if (bChecked == null)
        return true;
    return bChecked;
}

function SaveBarcodeClearSecondsToCookie(nSeconds) {
    setCookie("ST-BarcodeClearSeconds", nSeconds, 365);
}

function SaveBarcodeClearCheckedToCookie(bChecked) {
    setCookie("ST-BarcodeClearChecked", bChecked, 365);
}



//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Simplest set/get functions
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//

function setCookie(name, value, days) {

    // Each virtual directory has it's own cookies
    if (VirtualDirectory)
        name = name + "[" + VirtualDirectory.replaceAll('/', '') + "]";

    // Cannot have \r\n in string
    if (typeof value === 'string' || value instanceof String) {
        value = value.replace(/\r/g, "!CR!");
        value = value.replace(/\n/g, "!NL!");
    }

    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + ";secure " + expires + "; path=/";
}

function getCookie(name) {

    // Each virtual directory has it's own cookies
    if (VirtualDirectory)
        name = name + "[" + VirtualDirectory.replaceAll('/', '') + "]";

    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length).replace(/!CR!/g, "\r").replace(/!NL!/g, "\n");
    }
    return null;
}

function deleteCookie(cookiename) {
    var d = new Date();
    d.setDate(d.getDate() - 1);
    var expires = ";expires=" + d;
    var name = cookiename;
    //alert(name);
    var value = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function deleteAllCookies() {

    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
        var spcook = cookies[i].split("=");
        deleteCookie(spcook[0]);
    }
}

function deleteAllCookiesByPrefix(StartsWithPrefix) {

    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
        var spcook = cookies[i].split("=");
        var cookiename = spcook[0];
        cookiename = cookiename.trim();
        var bStartsWith = cookiename.lastIndexOf(StartsWithPrefix) === 0;
        if (bStartsWith)
            deleteCookie(cookiename);
    }
}

function findAllCookiesByPrefix(StartsWithPrefix, NodeNamesArray, NodeValuesArray, NodeTypesArray) {

    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
        var spcook = cookies[i].split("=");
        var cookiename = spcook[0];
        cookiename = cookiename.trim();
        var bStartsWith = cookiename.lastIndexOf(StartsWithPrefix) === 0;
        if (bStartsWith) {
            var cookievalue = getCookie(cookiename);
            NodeNamesArray.push(cookiename);
            NodeValuesArray.push(cookievalue);
            NodeTypesArray.push(cookievalue);
        }
    }
}

