﻿// Go to Yaskawa Motomans website (onclick of the logo in header)
function GoToYaskawaMotomanHome()
{
    window.open("https://www.motoman.com", "_blank");
}

// Go to RobotPro home page
function GoToHome()
{
    var homePagePath = GetBaseUrl() + "View/Home.aspx";
    window.open(homePagePath, "_self");
}

// Show help in new tab/window
function ShowHelp()
{
    var helpPath = GetBaseUrl() + "ExtFiles/WebHelp/RobotPro_Help.htm";
    window.open(helpPath, "_blank");
}

// Show PopUp if session is about to timeout
function ShowSessionTimeoutPopUp()
{
    var sPage = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
    if (sPage.toLowerCase().indexOf("login") !== -1) // Only need to do on Login page
    {
        var loginPagePath = GetBaseUrl() + "Account/Login.aspx";
        // Reopen login page in attempt to keep session from completely dying and causing error when try to login
        window.open(loginPagePath, "_self");
    }
    else
    {
        var divSessionTimeout = document.getElementById('divSessionTimeout');
        if (divSessionTimeout !== null)
        {
            divSessionTimeout.style.display = 'block';
            PositionPopUpContents();
        }
    }
}

// Redirect to timeout page (or refresh login page if already on)
function SessionTimeoutRedirect()
{
    var sPage = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
    if (sPage.toLowerCase().indexOf("login") !== -1) // Only need to do on Login page
    {
        var loginPagePath = GetBaseUrl() + "Account/Login.aspx";
        // Reopen login page
        window.open(loginPagePath, "_self");
    }
    else
    {
        var loginPagePath = GetBaseUrl() + "SessionTimeout.html";
        // Go to timeout page
        window.open(loginPagePath, "_self");
    }
}

// Get the beginning part of the url that corresponds to the base/root folder of the website
// i.e. localhost:30659/ OR https://robotpro.motoman.com/RobotPro OR https://robotpro.motoman.com/RobotProTest
function GetBaseUrl()
{
    var rootFolder = "";

    var pathName = window.location.pathname;
    if (pathName.startsWith('/') && pathName.length > 1)
    {
        pathName = pathName.substring(1, pathName.length);
    }

    var partsOfPath = pathName.split('/');
    if (partsOfPath.length > 1)
    {
        if (partsOfPath[0] !== null && partsOfPath[0].length > 0 && partsOfPath[0].toLowerCase().indexOf("robotpro") !== -1)
        {
            rootFolder = partsOfPath[0] + "/";
        }
    }

    var rootPath = window.location.origin + "/" + rootFolder;
    //alert("window.location.origin = " + window.location.origin + "\n" + "pathName = " + pathName + "\n" + "rootFolder = " + rootFolder + "\n" + "rootPath = " + rootPath);
    return rootPath;
}

// This is called everytime the page loads
$(function ()
{ // This is equivalent to $(document).ready(function(){}); and is executed as soon as the DOM is parsed

    // Determine if wait message should be shown at page load
    var waitMessage = 'hide';
    var sPage = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
    if (sPage.toLowerCase().indexOf("troubleshoot.aspx") !== -1 ||
        sPage.toLowerCase().indexOf("troubleshooting.aspx") !== -1 ||
        sPage.toLowerCase().indexOf("proc.aspx") !== -1 ||
        sPage.toLowerCase().indexOf("procoverview.aspx") !== -1) // Only need to do on these pages
    {
        waitMessage = 'show';
    }
    else
    {
        ShowHideWait("hide");
    }
    ShowHideWaitMessage(waitMessage);

    // Try to make sure the user refreshes their cache if necessary
    if (sPage.toLowerCase().indexOf("login") !== -1) // Only need to do on Login page
    {
        var divRefresh = document.getElementById("divRefresh8");
        if (divRefresh !== null)
        {
            $(divRefresh).css("display", "none");
        }
    }

    // This is to size the PopUps to fill screen
    SizePopUp();

    //$(window).load(function ()
    //{
    //    //// This is to set up the wait cursor
    //    //SetUpSpinner();
    //    //// This is to center the PopUps contents in the screen
    //    //PositionPopUpContents();
    //    // This is to set up the Ajax ComboBoxes
    //    SetupAjaxCombos();

    //    // This is to hide the wait cursor that was set from client click of button,
    //    // should be last function called
    //    ShowHideWait("hide");
    //});
});

$(window).on("load", function () {
    //// This is to set up the wait cursor
    //SetUpSpinner();
    //// This is to center the PopUps contents in the screen
    //PositionPopUpContents();
    // This is to set up the Ajax ComboBoxes
    SetupAjaxCombos();

    // This is to hide the wait cursor that was set from client click of button,
    // should be last function called
    ShowHideWait("hide");
});

// ******************* Begin displaying of PopUp *******************
// This is to size the PopUps to fill screen and center contents
function SizePopUp()
{
    try
    {
        //$('.PopUpContents').css("display", "none"); -- This no longer needed after update to jQuery

        // Get the body dimensions
        var $body = $(this.ie6 ? document.body : document); // using document in ie6 causes a crash
        var bodyHeight = $body.height() - 1;
        var bodyWidth = $body.width();

        // All PopUps should use the class 'PopUp' so that is how we can set them
        $('.PopUp').css("height", (bodyHeight + "px"));
        $('.PopUp').css("width", (bodyWidth + "px"));
    }
    catch (err)
    {
        //alert ("Couldn't center.")
    }
}

// This center contents on the screen for a PopUp
function PositionPopUpContents()
{
    try
    {
        // Set size the PopUp to fill screen
        SizePopUp();

        var tblWrapperWidthMax = -1;
        $('.tblWrapper').each(function (index, el)
        {
            tblWrapperWidthMax = $(this).width();
            return false;
        });
        if (tblWrapperWidthMax !== -1)
        {
            $('.PopUp').css("width", (tblWrapperWidthMax + "px"));
        }

        // The PopUps contents should use the class 'PopUpContents' so that is how we can set them
        $('.PopUpContents').css("display", "inline-block");
        $('.PopUpContents').css("position", "fixed");

        $('.PopUpContents').each(function (index, el)
        {
            // Center the PopUp contents
            el.centerPopUp();
        });
    }
    catch (err)
    {
        //alert ("Couldn't center.")
    }
}

// For each div element with a class of 'PopUpContents', center to page (window) by calculation
function CenterPopUp()
{
    try
    {
        // The PopUps contents should use the class 'PopUpContents' so that is how we can set them
        $('.PopUpContents').each(function (index, el)
        {
            // Center the PopUp contents
            el.centerPopUp();
        });
    }
    catch (err)
    {
        //alert ("Couldn't center.")
    }
}

// Center the PopUp contents
HTMLDivElement.prototype.centerPopUp = function ()
{
    try
    {
        if ($(this).attr("id") === "divProductNavigation")
        {
            var divProductNavigationPadding = parseInt($(this).css('padding-top')) + parseInt($(this).css('padding-bottom'));
            $(this).css("min-height", ($(window).height() - divProductNavigationPadding - 1) + "px");
        }

        var topPos = 0;
        if ($(this).outerHeight() < $(window).height())
        {
            // For absolute position
            //topPos = Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop());
            // For fixed position
            topPos = Math.max(0, (($(window).height() - $(this).outerHeight()) / 2));
            $(this).css("top", topPos + "px");
        }
        else
        {
            if ($(this).attr("id") === "divPopUpProductSelection")  // This is for product selections to not have the Cancel button off bottom of page
            {
                var divProdSelection = document.getElementById("divProdSelection");
                if (divProdSelection !== null)
                {
                    CalculateDivHeight(this, divProdSelection);
                }
            }
            else if ($(this).attr("id") === "divPopUpManageShare")  // This is for sharing member selection to not have the Cancel button off bottom of page
            {
                var divManageShare = document.getElementById("divManageShare");
                if (divManageShare !== null)
                {
                    CalculateDivHeight(this, divManageShare);
                }

                var divAddShare = document.getElementById("divAddShare");
                if (divAddShare !== null)
                {
                    CalculateDivHeight(this, divAddShare);
                }
            }
            else if ($(this).attr("id") === "divViewErrorLog")  // This is for error log to not have the Close button off bottom of page
            {
                var divErrorLog = document.getElementById("divErrorLog");
                if (divErrorLog !== null)
                {
                    CalculateDivHeight(this, divErrorLog);

                    var divErrorDescription = document.getElementById("divErrorDescription");
                    if (divErrorDescription !== null)
                    {
                        $(divErrorDescription).height($(divErrorLog).height());
                        //CalculateDivHeight(this, divErrorDescription);
                    }
                }
            }
            else if ($(this).attr("id") === "divViewRefreshLog")  // This is for error log to not have the Close button off bottom of page
            {
                var divRefreshLog = document.getElementById("divRefreshLog");
                if (divRefreshLog !== null)
                {
                    CalculateDivHeight(this, divRefreshLog);
                }
            }
            else  // This is for making sure all other Pop-Up dialogs fit on the screen (i.e. ProductInfoBlock not having Close button off bottom of page)
            {
                var minHeight = $(this).height();
                $('.tdContent').each(function (index, el)
                {
                    $(this).css("min-height", (minHeight + "px"));
                    return false;
                });
            }

            //// For absolute position
            //if (parseInt($(this).css("top")) > $(window).scrollTop())
            //{
            //    topPos = Math.max(0, $(window).scrollTop());
            //}
            //else if (parseInt($(this).css("top")) + $(this).outerHeight() < $(window).scrollTop() + $(window).height())
            //{
            //    topPos = $(window).scrollTop() -$(this).outerHeight() + $(window).height() -1; 
            //}
            // For fixed position
            topPos = -1 * $(window).scrollTop();
            if (topPos < 0 && $(this).outerHeight() > 0)
            {
                if ($(this).outerHeight() + topPos < $(window).height())
                {
                    topPos = $(window).height() - $(this).outerHeight();
                }
            }
            $(this).css("top", topPos + "px");
        }

        var tblWrapperWidthMax = -1;
        $('.tdContent').each(function (index, el) {
            var tblWrapperPadding = parseInt($(this).css('padding-left')) + parseInt($(this).css('padding-right'));
            if (tblWrapperPadding !== -1)
            {
                tblWrapperWidthMax = $(this).width() - tblWrapperPadding - 10;
                return false;
            }
        });

        if (tblWrapperWidthMax !== -1)
        {
            $(this).css("max-width", (tblWrapperWidthMax + "px"));
        }

        var leftPos = 0;
        if ($(this).outerWidth() !== 0 && $(this).outerWidth() < $(window).width())
        {
            //// For absolute position
            //leftPos = Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft());
            // For fixed position
            leftPos = Math.max(0, ($(window).width() - $(this).outerWidth()) / 2); // For fixed position
            $(this).css("left", leftPos + "px");
        }
        else
        {
            //// For absolute position
            //if (parseInt($(this).css("left")) > $(window).scrollLeft())
            //{
            //    leftPos = Math.max(0, $(window).scrollLeft())
            //    $(this).css("left", leftPos + "px");
            //}
            //else if (parseInt($(this).css("left")) + $(this).outerWidth() < $(window).scrollLeft() + $(window).width())
            //{
            //    //leftPos = $(window).scrollLeft() - $(this).outerWidth() + $(window).width() - 1; // For absolute position
            //    leftPos = -1 * ($(window).scrollLeft() + $(this).outerWidth() + $(window).width() - 1);
            //    $(this).css("left", leftPos + "px");
            //}
            // For fixed position
            leftPos = -1 * $(window).scrollLeft();
            if (leftPos < 0 && $(this).outerWidth() > 0)
            {
                if ($(this).outerWidth() + leftPos < $(window).width())
                {
                    leftPos = $(window).width() - $(this).outerWidth();
                }
            }
            $(this).css("left", leftPos + "px");
        }

        return this;
    }
    catch (err)
    {
        //alert ("Couldn't center.");
    }
};

// This is to calculate the height of the grid in popups not to have the Cancel button off bottom of page
function CalculateDivHeight(popUp, div)
{
    var initialSelHeight = $(div).height();
    var initialPopHeight = $(popUp).height();
    var outerHeightDiff = $(popUp).outerHeight() - $(popUp).height();
    var hght = $(window).height() - outerHeightDiff - 1;
    if (hght < 400)
    {
        hght = 400;
    }
    $(popUp).height(hght);
    $(div).height(initialSelHeight - (initialPopHeight - hght));
}
// ******************** End displaying of PopUp ********************

// This goes through all ajax comboboxes and sets their list width equal to their textbox width
function SetupAjaxCombos()
{
    var cmbs = $('.ajax__combobox_itemlist');
    for (i = 0; i < cmbs.length; i++)
    {
        // Find textbox for this itemlist
        var cmb = cmbs[i];
        var sID = cmb.id;
        var sRootName = sID.substring(0, sID.lastIndexOf("_") + 1);
        var sTxtBox = sRootName + "TextBox";
        // Set width of list equal to width of textbox
        var txtBox = document.getElementById(sTxtBox);
        if (txtBox !== null)
        {
            var txtWidth = $(txtBox).width() + 2;
            $(cmb).css('width', txtWidth);
            $(cmb).css('minWidth', txtWidth);
            $(cmb).css('maxWidth', txtWidth);

            sRootName = sID.substring(0, sID.lastIndexOf("_"));
            sRootName = sRootName.substring(0, sRootName.lastIndexOf("_"));
            var ajaxComboBox = document.getElementById(sRootName);
            if (ajaxComboBox !== null)
            {
                if ($(ajaxComboBox).hasClass("ReadOnly") && !$(ajaxComboBox).hasClass("aspNetDisabled"))
                {
                    txtBox.disabled = true;
                    //$(txtBox).css('background-color', 'white!important'); // The !important breaks setting color in FireFox and Chrome
                    txtBox.style.setProperty("background-color", "white", "important");
                    txtBox.style.setProperty("color", "black", "important");
                }
                else if ($(ajaxComboBox).hasClass("aspNetDisabled") || txtBox.disabled === true)
                {
                    //$(txtBox).css('background-color', '#AFAFAF!important'); // The !important breaks setting color in FireFox and Chrome
                    txtBox.style.setProperty("background-color", "#AFAFAF", "important");
                    txtBox.style.setProperty("color", "#666666", "important");
                }
            }
        }
    }
}

// This shows/hides the wait spinner
function ShowHideWait(whatToDo)
{
    var divPopUp = document.getElementById('divWait');
    if (divPopUp !== null)
    {
        try
        {
            if (whatToDo.toLowerCase() === 'show')
            {
                //ShowHideWaitMessage('hide');
                divPopUp.style.display = 'block';
            }
            else if (whatToDo.toLowerCase() === 'hide')
            {
                divPopUp.style.display = 'none';
            }
        }
        catch (err)
        {
            //alert ("Error with spinner.");
        }
    }
}

// This hides the wait message
function ShowHideWaitMessage(whatToDo)
{
    var divWaitWhilePageLoading = document.getElementById('divWaitWhilePageLoading');
    if (divWaitWhilePageLoading !== null)
    {
        if (whatToDo.toLowerCase() === 'show')
        {
            divWaitWhilePageLoading.style.display = 'block';
        }
        else if (whatToDo.toLowerCase() === 'hide')
        {
            divWaitWhilePageLoading.style.display = 'none';
        }
    }
}

// This sets up the wait spinner
function SetUpSpinner()
{
    var target = document.getElementById('tdSpinner');
    if (target !== null)
    {
        var opts =
        {
            lines: 15, // The number of lines to draw
            length: 0, // The length of each line
            width: 18, // The line thickness
            radius: 52, // The radius of the inner circle
            corners: 1, // Corner roundness (0..1)
            rotate: 0, // The rotation offset
            direction: 1, // 1: clockwise, -1: counterclockwise
            color: '#FFFFFF', // #rgb or #rrggbb or array of colors
            speed: 0.7, // Rounds per second
            trail: 50, // Afterglow percentage
            shadow: false, // Whether to render a shadow
            hwaccel: false, // Whether to use hardware acceleration
            className: 'spinner', // The CSS class to assign to the spinner
            zIndex: 2e9, // The z-index (defaults to 2000000000)
            top: 'auto', // Top position relative to parent in px
            left: 'auto', // Left position relative to parent in px
            id: 'spinner'
        };
        var spinner = new Spinner(opts).spin(target);
    }
}
