<!DOCTYPE html>
<html class="loading" lang="en" data-textdirection="ltr">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title>@ViewData["Title"] | Empowered Forex Trader</title>
    <link rel="apple-touch-icon" href="~/images/apple-icon120.png">
    <link rel="shortcut icon" type="image/x-icon" href="~/favicon.ico">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:300,300i,400,400i,500,500i%7COpen+Sans:300,300i,400,400i,600,600i,700,700i" rel="stylesheet">
    <!-- BEGIN VENDOR CSS-->
    <link rel="stylesheet" type="text/css" href="~/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="~/fonts/feather/style.min.css">
    <link rel="stylesheet" type="text/css" href="~/fonts/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="~/fonts/flag-icon-css/css/flag-icon.min.css">
    <link rel="stylesheet" type="text/css" href="~/css/pace.css">
    <link rel="stylesheet" type="text/css" href="~/css/unslider.css">
    <link href="~/css/datatables.css" rel="stylesheet" />
    <link rel="stylesheet" type="text/css" href="~/css/climacons.min.css">
    <link rel="stylesheet" type="text/css" href="~/css/minimal/_all.css">
    <link rel="stylesheet" type="text/css" href="~/css/square/_all.css">
    <link rel="stylesheet" type="text/css" href="~/css/flat/_all.css">
    <link rel="stylesheet" type="text/css" href="~/css/line/_all.css">
    <link rel="stylesheet" type="text/css" href="~/css/polaris/polaris.css">
    <link rel="stylesheet" type="text/css" href="~/css/futurico/futurico.css">
    <link rel="stylesheet" type="text/css" href="~/css/icheck/custom.css">
    <link rel="stylesheet" type="text/css" href="~/css/toogle.css" />
    <link href="~/css/bootstrap-datetimepicker.css" rel="stylesheet" />
    <!-- END VENDOR CSS-->
    <!-- BEGIN STACK CSS-->
    <link rel="stylesheet" type="text/css" href="~/css/bootstrap-extended.css">
    <link rel="stylesheet" type="text/css" href="~/css/colors.css">
    <link rel="stylesheet" type="text/css" href="~/css/components.css">
    <!-- END STACK CSS-->
    <!-- BEGIN Page Level CSS-->
    <link rel="stylesheet" type="text/css" href="~/css/horizontal-menu.css">
    <link rel="stylesheet" type="text/css" href="~/css/toastr.css">
    <!-- END Page Level CSS-->
    <!-- BEGIN Custom CSS-->
    <link rel="stylesheet" type="text/css" href="~/css/style.css">
    <!-- END Custom CSS-->
</head>
<body class="horizontal-layout horizontal-menu 2-columns menu-expanded" data-open="click" data-menu="horizontal-menu" data-col="2-columns">
    <!-- fixed-top-->
    <nav class="header-navbar navbar-expand-md navbar navbar-with-menu navbar-static-top navbar-light navbar-shadow navbar-border navbar-brand-center">
        <div class="navbar-wrapper">
            <div class="navbar-header">
                <ul class="nav navbar-nav flex-row">
                    <li class="nav-item mobile-menu d-md-none mr-auto">
                        <a class="nav-link nav-menu-main menu-toggle hidden-xs" href="#"><i class="ft-menu font-large-1"></i></a>
                    </li>
                    <li class="nav-item">
                        <a class="navbar-brand" href="@Url.Action("AdminAccount", "UserManagement")">
                            <img class="brand-logo" alt="stack admin logo" src="~/images/logo192.png">
                        </a>
                    </li>
                    <li class="nav-item d-md-none">
                        <a class="nav-link open-navbar-container" data-toggle="collapse" data-target="#navbar-mobile"><i class="fa fa-ellipsis-v"></i></a>
                    </li>
                </ul>
            </div>
            <div class="navbar-container container center-layout">
                <div class="collapse navbar-collapse" id="navbar-mobile">
                    <ul class="nav navbar-nav mr-auto float-left">
                        <li class="nav-item d-none d-md-block"><a class="nav-link nav-link-expand" href="#"><i class="ficon ft-maximize"></i></a></li>
                    </ul>
                    <ul class="nav navbar-nav float-right">
                        <li class="dropdown dropdown-notification nav-item">
                            <a class="nav-link nav-link-label" href="#" data-toggle="dropdown"><i class="ficon ft-mail"></i><span class="badge badge-pill badge-default badge-warning badge-default badge-up">0</span></a>
                            <ul class="dropdown-menu dropdown-menu-media dropdown-menu-right">
                                <li class="dropdown-menu-header">
                                    <h6 class="dropdown-header m-0"><span class="grey darken-2">Messages</span><span class="notification-tag badge badge-default badge-warning float-right m-0">0 New</span></h6>
                                </li>
                                <li class="scrollable-container media-list">
                                    <a href="javascript:void(0)">
                                        <div class="media">
                                            <div class="media-body">
                                                <p class="notification-text font-small-3 text-muted">No messages</p>
                                            </div>
                                        </div>
                                    </a>
                                </li>
                                <li class="dropdown-menu-footer"><a class="dropdown-item text-muted text-center" href="javascript:void(0)">Read all messages</a></li>
                            </ul>
                        </li>
                        <li class="dropdown dropdown-user nav-item">
                            <a class="dropdown-toggle nav-link dropdown-user-link" href="#" data-toggle="dropdown">
                                @if (Model.IsImpersonated)
                                {
                                    <span class="avatar avatar-online" title="User being impersonated">
                                        <img src="~/images/avatar-empty-black.png" alt="avatar">
                                        <i class="ft-eye impersonated"></i>
                                    </span>
                                }
                                else
                                {
                                    <span class="avatar avatar-online">
                                        <img src="~/images/avatar-empty-black.png" alt="avatar">
                                        <i></i>
                                    </span>
                                }
                                <span class="user-name">@Model.LoggedUserFullName</span>
                            </a>
                            <div class="dropdown-menu dropdown-menu-right">
                                <a class="dropdown-item" href="#"><i class="ft-mail"></i> My Inbox</a>
                                <div class="dropdown-divider"></div>
                                @if (!String.IsNullOrEmpty(Model.Impersonator))
                                {
                                    <a class="dropdown-item" href="@Url.Action("ReturnAdminPanel", "UserManagement")"><i class="ft-log-out"></i> Back to My Admin Panel</a>
                                }
                                <a class="dropdown-item" href="@Url.Action("Logout", "Login")"><i class="ft-power"></i> Logout</a>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>
    <!-- ////////////////////////////////////////////////////////////////////////////-->
    <!-- Horizontal navigation-->
    <div class="header-navbar navbar-expand-sm navbar navbar-horizontal navbar-fixed navbar-light navbar-without-dd-arrow navbar-shadow menu-border" role="navigation" data-menu="menu-wrapper">
        <!-- Horizontal menu content-->
        <div class="navbar-container main-menu-content container center-layout" data-menu="menu-container">
            <!-- include ../../../includes/mixins-->
            <ul class="nav navbar-nav" id="main-menu-navigation" data-menu="menu-navigation">
                <li class="nav-item">
                    <a class="nav-link mx-1" href="@Url.Action("ViewUsersAccount", "UserManagement")"><i class="ft-users"></i><span>User Mgmt.</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link mx-1" href="@Url.Action("ReportManagement", "UserManagement")"><i class="ft-book"></i><span>Report Mgmt.</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link mx-1" href="@Url.Action("EmailFormat", "UserManagement")"><i class="ft-mail"></i><span>Email Format</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link mx-1" href="@Url.Action("VPSManagement", "MT4Server")"><i class="fa fa-server"></i><span>VPS Mgmt.</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link mx-1" href="@Url.Action("SubscriptionManagement", "Publisher")"><i class="fa fa-bullhorn"></i><span>Subscription Mgmt.</span></a>
                </li>
                <li class="dropdown mega-dropdown nav-item" data-menu="megamenu">
                    <a class="dropdown-toggle nav-link mx-1" href="#" data-toggle="dropdown"><i class="fa fa-gears"></i><span>Settings</span></a>
                    <ul class="mega-dropdown-menu dropdown-menu row">
                        <li class="col-md-3" data-mega-col="col-md-3">
                            <ul class="drilldown-menu">
                                <li class="menu-list">
                                    <ul class="mega-menu-sub">
                                        <li>
                                            <a class="dropdown-item" href="@Url.Action("GetSettings", "AdminSettings")">Admin Settings</a>
                                        </li>
                                    </ul>
                                </li>
                            </ul>
                        </li>
                        <li class="col-md-3" data-mega-col="col-md-3">
                            <ul class="drilldown-menu">
                                <li class="menu-list">
                                    <ul class="mega-menu-sub">
                                        <li>
                                            <a class="dropdown-item" href="@Url.Action("GetSettings", "StartupSettings")">Startup Settings</a>
                                        </li>
                                    </ul>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
        <!-- /horizontal menu content-->
    </div>
    <!-- Horizontal navigation-->
    <partial name="_CookieConsentPartial" />
    <div class="pb-3">
        @RenderBody()
    </div>
    <!-- ////////////////////////////////////////////////////////////////////////////-->
    <footer class="footer fixed-bottom footer-light footer-border">
        <div class="clearfix blue-grey lighten-2 text-sm-center mb-0 px-2 container center-layout">
            <div class="float-md-left d-block d-md-inline-block copyright">Copyright  &copy; @DateTime.Today.Date.Year.ToString() Empowered Forex Trader - All rights reserved. </div>
        </div>
    </footer>
    <script src="~/js/jquery-3.3.1.js"></script>
    <script src="~/js/jquery-ui.min.js"></script>
    <script src="~/js/vendor.js"></script>
    <script type="text/javascript" src="~/js/jquery.sticky.js"></script>
    <script src="~/js/unslider-min.js"></script>
    <script src="~/js/icheck.min.js"></script>
    <script src="~/js/moment-with-locales.min.js"></script>
    <script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation/dist/additional-methods.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
    <script src="~/js/jqBootstrapValidation.js"></script>
    <script src="~/js/bootstrap-datetimepicker.min.js"></script>
    <script src="~/js/datatables.js"></script>
    <script src="~/js/toastr.min.js"></script>
    <script src="~/js/app-menu.js"></script>
    <script src="~/js/app.js"></script>
    <script src="~/js/datatable-api.js"></script>
    <script src="~/js/site.js"></script>
    <script type="text/javascript">
        /*-----REPORTS FORMAT-------------------*/
        function formatReportsTable(rowData) {
            var div = $('<div/>')
                .addClass('loading')
                .text('Loading...');

            $.ajax({
                url: '@Url.Action("GetListOfReportFormatRoles", "UserManagement")',
                type: "POST",
                data: {
                    reportFormatId: rowData.id
                },
                dataType: 'json',
                success: function (json) {
                    var result = '<div class="m-1">' +
                        '<table class="table">' +
                        '<thead>' +
                        '<tr>' +
                        '<th scope="col" class="text-center">Role</th>' +
                        '</tr>' +
                        '</thead>' +
                        '<tbody>';
                    if (json.length > 0) {
                        for (var i in json) {
                            result += formatReportFormatRoleTable(json[i]);
                        }
                    }
                    else {
                        result += '<tr class="even"><td valign="top" colspan="5" class="dataTables_empty">No roles found for the Report Format</td></tr>';
                    }
                    result += '</tbody></table></div>'
                    div
                        .html(result)
                        .removeClass('loading');
                }
            });

            return div;
        }

        function formatReportFormatRoleTable(d) {
            var div = '<tr role="row">' +
                '<td>' +
                '<div class="text-center">' + d.role.description + '</div>' +
                '</td>';
            return div;
        }

        function loadReportFormatData(_Id) {
            $.ajax({
                type: "POST",
                url: '@Url.Action("GetReportFormat", "UserManagement")',
                data: { id: _Id },
                cache: false,
                success: function (result) {
                    if (result != "") {
                        $("#add-report-modal").html(result);
                        $("#btn-add-report").prop('value', 'Save Changes');
                        $('#addReportModalLabel').text("Edit Report Format");
                        $('#addReportModal').modal('show');
                    }
                    else {

                    }
                },
                error: function () { }
            });
        }

        function toggleReport(id) {
            $.ajax({
                type: "post",
                url: '@Url.Action("ToggleReportFormat", "UserManagement")',
                data: { id: id }
            });
        }

       /*----USER MANAGEMENT---------------*/
        function formatUsersTable(rowData) {
            var div = $('<div/>')
                .addClass('loading')
                .text('Loading...');

            $.ajax({
                url: '@Url.Action("GetUserListForexAccounts", "UserManagement")',
                type: "POST",
                data: {
                    userId: rowData.loginId
                },
                dataType: 'json',
                success: function (json) {
                    var result = '<div class="m-1">' +
                        '<table class="table table-bordered child-table">' +
                        '<thead>' +
                        '<tr>' +
                        '<th scope="col" style="width:20%;">Forex Account</th>' +
                        '<th scope="col" style="width:15%">Server</th>' +
                        '<th scope="col" style="width:25%">Terminal</th>' +
                        '<th scope="col" style="width:20%;">Expert Advisor</th>' +
                        '<th scope="col" style="width:10%" class="text-center">Connection</th>' +
                        '</tr>' +
                        '</thead>' +
                        '<tbody>';
                    if (json.length > 0) {
                        for (var i in json) {
                            result += formatForexTable(json[i]);
                        }
                    }
                    else {
                        result += '<tr class="even"><td valign="top" colspan="5" class="dataTables_empty">No forex accounts found</td></tr>';
                    }
                    result += '</tbody></table></div>'
                    div
                        .html(result)
                        .removeClass('loading');
                }
            });

            return div;
        }

        function formatForexTable(d) {
            var div = '<tr role="row">' +
                '<td>' +
                '<div>' + d.forexAccount + '</div>' +
                '</td>' +
                '<td>' +
                '<div>' + d.server + '</div>' +
                '</td>' +
                '<td>' +
                '<div>' + d.terminal + '</div>' +
                '</td>' +
                '<td>' +
                '<div>' + d.expertAdvisor + '</div>' +
                '</td>' +
                '<td class="text-center connection-btn-' + d.expertAdvisorID + '">';

            if (d.connectionStatus == 1) {
                div += '<div class="text-primary pr-1 display-inline" title="Expert advisor running"><i class="fa fa-play"></i></div>' +
                    '<a onclick="pauseExpertAdvisor(' + d.expertAdvisorID + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Pause expert advisor"><i class="fa fa-pause"></i></a>' +
                    '<a onclick="stopExpertAdvisor(' + d.expertAdvisorID + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>';
            }
            else if (d.connectionStatus == 2) {
                div += '<a onclick="startExpertAdvisor(' + d.expertAdvisorID + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Start expert advisor"><i class="fa fa-play"></i></a>' +
                    '<div class="text-muted pr-1 display-inline disabled"><i class="fa fa-pause"></i></div>' +
                    '<div class="text-danger display-inline" title="Expert advisor not running"><i class="fa fa-stop"></i></div>';
            }
            else if (d.connectionStatus == 3) {
                div += '<a onclick="startExpertAdvisor(' + d.expertAdvisorID + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Start expert advisor"><i class="fa fa-play"></i></a>' +
                    '<div class="text-primary pr-1 display-inline" title="Expert advisor Paused"><i class="fa fa-pause"></i></div>' +
                    '<a onclick="stopExpertAdvisor(' + d.expertAdvisorID + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>';
            }
            else {
                div += '<div>---</div>';
            }

            div += '</td></tr>';

            return div;
        }

        function startExpertAdvisor(_expertAdvisorId) {
            $.ajax({
                type: "post",
                url: '@Url.Action("StartExpertAdvisor", "RegisteredUser")',
                data: { expertAdvisorInstanceId: _expertAdvisorId },
                cache: false,
                success: function (data) {
                    if (data == "0") {
                        var div = "";
                        div += '<div class="text-primary pr-1 display-inline" title="Expert advisor running"><i class="fa fa-play"></i></div>' +
                            '<a onclick="pauseExpertAdvisor(' + _expertAdvisorId + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Pause expert advisor"><i class="fa fa-pause"></i></a>' +
                            '<a onclick="stopExpertAdvisor(' + _expertAdvisorId + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>';
                        $('.connection-btn-' + _expertAdvisorId).html(div);
                    }
                    else {
                        var tr = $('.connection-btn-' + _expertAdvisorId).closest('td');
                        tr.attr('class', 'text-center connection-btn-' + data);
                        var div = "";
                        div += '<div class="text-primary pr-1 display-inline" title="Expert advisor running"><i class="fa fa-play"></i></div>' +
                            '<a onclick="pauseExpertAdvisor(' + data + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Pause expert advisor"><i class="fa fa-pause"></i></a>' +
                            '<a onclick="stopExpertAdvisor(' + data + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>';
                        $('.connection-btn-' + data).html(div);
                    }
                },
                error: function () { }
            });
        }

        function pauseExpertAdvisor(_expertAdvisorId) {
            $.ajax({
                type: "post",
                url: '@Url.Action("PauseExpertAdvisor", "RegisteredUser")',
                data: { expertAdvisorInstanceId: _expertAdvisorId },
                cache: false,
                success: function (result) {
                    if (result != "") {
                        var div = "";
                        div += '<a onclick="startExpertAdvisor(' + _expertAdvisorId + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Start expert advisor"><i class="fa fa-play"></i></a>' +
                        '<div class="text-primary pr-1 display-inline" title="Expert advisor Paused"><i class="fa fa-pause"></i></div>' +
                        '<a onclick="stopExpertAdvisor(' + _expertAdvisorId + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>';
                        $('.connection-btn-' + _expertAdvisorId).html(div);
                    }
                    else {

                    }
                },
                error: function () { }
            });
        }

        function stopExpertAdvisor(_expertAdvisorId) {
            $.ajax({
                type: "post",
                url: '@Url.Action("StopExpertAdvisor", "RegisteredUser")',
                data: { expertAdvisorInstanceId: _expertAdvisorId },
                cache: false,
                success: function (result) {
                    if (result != "") {
                        var div = "";
                        div += '<a onclick="startExpertAdvisor(' + _expertAdvisorId +')" href="javascript:void(0)" class="text-secondary pr-1" title="Start expert advisor"><i class="fa fa-play"></i></a>' +
                        '<div class="text-muted pr-1 display-inline disabled"><i class="fa fa-pause"></i></div>' +
                        '<div class="text-danger display-inline" title="Expert advisor not running"><i class="fa fa-stop"></i></div>';
                        $('.connection-btn-' + _expertAdvisorId).html(div);
                    }
                    else {

                    }
                },
                error: function () { }
            });
        }

        function loadUserData(loginId) {
            $.ajax({
                type: "POST",
                url: '@Url.Action("GetUser", "UserManagement")',
                data: { loginId: loginId },
                cache: false,
                success: function (result) {
                    if (result != "") {
                        $("#view-user-modal").html(result);

                        $('#viewUserModal').modal({
                            backdrop: false,
                            show: true
                        });

                        $("body").removeClass("modal-open");

                        $('.modal-dialog').draggable({
                            handle: ".modal-header"
                        });
                    }
                    else {

                    }
                },
                error: function () { }
            });
        }

        /*
         THIS IS MY WORK - EDUARDO - DELETE AFTER COMPLETE
         */

        

        function toggleUser(loginId) {
            $.ajax({
                type: "post",
                url: '@Url.Action("Toggle", "UserManagement")',
                data: { loginId: loginId }
            });
        }
        /*----------------------------------*/
        /*----VPS MANAGEMENT---------------*/
        function formatServersTable(rowData) {
            var div = $('<div/>')
                .addClass('loading')
                .text('Loading...');

            $.ajax({
                url: '@Url.Action("GetListMT4Terminals", "MT4Terminal")',
                type: "POST",
                data: {
                    serverId: rowData.id
                },
                dataType: 'json',
                success: function (json) {
                    var result = '<div class="m-1">' +
                        '<table id="terminal-list-' + rowData.id + '" class="table table-bordered">' +
                        '<thead>' +
                        '<tr>' +
                        '<th scope="col" style="width:15%; min-width:260px;">Terminal</th>' +
                        '<th scope="col" style="width:12%;">Username</th>' +
                        '<th scope="col" style="width:12%;">Forex Account</th>' +
                        '<th scope="col" style="width:12%">Expert Advisor</th>' +
                        '<th scope="col" style="width:12%">Script Name</th>' +
                        '<th scope="col" style="width:10%" class="text-center">EA Connection</th>' +
                        '<th scope="col" style="width:10%" class="text-center">Manage</th>' +
                        '<th scope="col" style="width:7%" class="text-center">Status</th>' +
                        '<th scope="col" style="width:10%" class="text-center">Errors</th>' +
                        '</tr>' +
                        '</thead>' +
                        '<tbody>';
                    if (json.mT4Terminals.length > 0) {
                        for (var i in json.mT4Terminals) {
                            for(var j in json.scripts) {
                                if(json.scripts[j].id == json.mT4Terminals[i].scriptId) {
                                    json.mT4Terminals[i].script = json.scripts[j];
                                }
                            }
                            result += formatTerminalTable(json.mT4Terminals[i]);
                        }
                    }
                    else {
                        result += '<tr class="even"><td valign="top" colspan="7" class="dataTables_empty">No terminals found</td></tr>';
                    }
                    result += '</tbody></table></div>'
                    div
                        .html(result)
                        .removeClass('loading');
                },
                error: function () {
                      var result = '<div class="m-1">' +
                        '<table id="terminal-list-' + rowData.id + '" class="table table-bordered">' +
                        '<thead>' +
                        '<tr>' +
                        '<th scope="col" style="width:25%; min-width:260px;">Terminal</th>' +
                        '<th scope="col" style="width:15%;">Username</th>' +
                        '<th scope="col" style="width:15%;">Forex Account</th>' +
                        '<th scope="col" style="width:15%">Expert Advisor</th>' +
                        '<th scope="col" style="width:10%" class="text-center">EA Connection</th>' +
                        '<th scope="col" style="width:10%" class="text-center">Manage</th>' +
                        '<th scope="col" style="width:10%" class="text-center">Status</th>' +
                        '</tr>' +
                        '</thead>' +
                        '<tbody>';
                     result += '<tr class="even"><td valign="top" colspan="7" class="dataTables_empty">No terminals found. Please check server URL.</td></tr>';
                     result += '</tbody></table></div>'
                    div
                        .html(result)
                        .removeClass('loading');
                }
            });

            return div;
        }

        function formatTerminalTable(d) {
            var div = '<tr role="row">' +
                '<td>' +
                    '<div>' + d.terminalInstance + '</div>' +
                '</td>' +
                '<td>' +
                    '<div>' + d.userName + '</div>' +
                '</td>' +
                '<td>' +
                    '<div>' + d.forexAccount + '</div>' +
                '</td>' +
                '<td>' +
                    '<div>' + d.expertAdvisorName + '</div>' +
                '</td>' +
                '<td>' +
                    '<div>' + (d.script ? d.script.scriptName : 'N/A') + '</div>' +
                '</td>' +
                '<td class="text-center connection-btn-' + d.id + '">';

            if (d.terminalConnectionStatus == true) {
          
                if (d.expertAdvisorConnectionStatus == 1) {
                    div += '<div class="text-primary pr-1 display-inline" title="Expert advisor running"><i class="fa fa-play"></i></div>' +
                        '<a onclick="pauseTerminal(' + d.id + ', ' + d.expertAdvisorInstanceId + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Pause expert advisor"><i class="fa fa-pause"></i></a>' +
                        '<a onclick="stopTerminal(' + d.id + ', ' + d.expertAdvisorInstanceId + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>';
                }
                else if (d.expertAdvisorConnectionStatus == 2) {
                    div += '<a onclick="startTerminal(' + d.id + ', ' + d.expertAdvisorInstanceId + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Start expert advisor"><i class="fa fa-play"></i></a>' +
                        '<div class="text-muted pr-1 display-inline disabled"><i class="fa fa-pause"></i></div>' +
                        '<div class="text-danger display-inline" title="Expert advisor not running"><i class="fa fa-stop"></i></div>';
                }
                else if (d.expertAdvisorConnectionStatus == 3) {
                    div += '<a onclick="startTerminal(' + d.id + ', ' + d.expertAdvisorInstanceId + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Start expert advisor"><i class="fa fa-play"></i></a>' +
                        '<div class="text-primary pr-1 display-inline" title="Expert advisor Paused"><i class="fa fa-pause"></i></div>' +
                        '<a onclick="stopTerminal(' + d.id + ', ' + d.expertAdvisorInstanceId + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>';
                }
                else {
                    div += '<div>---</div>';
                }
            }
            else {
                if (d.expertAdvisorInstanceID == 0) {
                    div += '<div>---</div>';
                }
                else {
                    div += '<div class="text-muted pr-1 display-inline disabled" title="Start terminal first"><i class="fa fa-play"></i></div>' +
                        '<div class="text-muted pr-1 display-inline disabled" title="Start terminal first"><i class="fa fa-pause"></i></div>' +
                        '<div class="text-muted display-inline disabled" title="Start terminal first"><i class="fa fa-stop"></i></div>';
                }
            }

            div += '</td>' +
                '<td class="text-center">' +
                '<a onclick="loadTerminalData(' + d.id + ')" href="javascript:void(0)" title="Manage Terminal" class="btn btn-icon btn-pure secondary" ><i class="fa fa-cog"></i> </a>' +
                '</td>';

            if (d.terminalConnectionStatus == true) {
                div += '<td id="terminalStatus-'+d.id+'" class="text-center terminal-status-' + d.id +'"><a onclick="return confirm(\'Are you sure you want to shutdown the terminal?\')" href="@Url.Action("DisconnectTerminal", "MT4Terminal")?terminalId=' + d.id + '" title="Shutdown terminal" class="btn btn-icon btn-pure primary"><i class="fa fa-power-off"></i></a></td>';
            }
            else {
                div += '<td id="terminalStatus-'+d.id+'" class="text-center terminal-status-' + d.id +'"><a onclick="return confirm(\'Are you sure you want to start the terminal?\')" href="@Url.Action("ConnectTerminal", "MT4Terminal")?terminalId=' + d.id + '" title="Start terminal" class="btn btn-icon btn-pure danger"><i class="fa fa-power-off"></i></a></td>';
            }

            div += '<td id="terminalError-'+d.id+'"></td></tr>';

            return div;
        }

        function startTerminal(terminalId, expertAdvisorInstanceId) {
            $.ajax({
                type: "post",
                url: '@Url.Action("StartTerminal", "MT4Terminal")',
                data: { terminalId: terminalId },
                cache: false,
                success: function (result) {
                    if (result == "0") {
                        var div = "";
                        div += '<div class="text-primary pr-1 display-inline" title="Expert advisor running"><i class="fa fa-play"></i></div>' +
                            '<a onclick="pauseTerminal(' + terminalId + ', ' + expertAdvisorInstanceId + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Pause expert advisor"><i class="fa fa-pause"></i></a>' +
                            '<a onclick="stopTerminal(' + terminalId + ', ' + expertAdvisorInstanceId + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>';
                        $('.connection-btn-' + terminalId).html(div);
                    }
                    else {
                        toastr.success('Terminal successfully started', '@ViewData["Title"] | VPS Command');
                        var tr = $('.connection-btn-' + terminalId).closest('td');
                        tr.attr('class', 'text-center connection-btn-' + terminalId);
                        var div = "";
                        div += '<div class="text-primary pr-1 display-inline" title="Expert advisor running"><i class="fa fa-play"></i></div>' +
                            '<a onclick="pauseTerminal(' + terminalId + ', ' + expertAdvisorInstanceId + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Pause expert advisor"><i class="fa fa-pause"></i></a>' +
                            '<a onclick="stopTerminal(' + terminalId + ', ' + expertAdvisorInstanceId + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>';
                        $('.connection-btn-' + terminalId).html(div);
                    }
                },
                error: function () { }
            });
        }

        function pauseTerminal(terminalId, expertAdvisorInstanceId) {
            $.ajax({
                type: "post",
                url: '@Url.Action("PauseTerminal", "MT4Terminal")',
                data: { terminalId: terminalId },
                cache: false,
                success: function (result) {
                    if (result != "") {
                        toastr.success('Terminal successfully paused', '@ViewData["Title"] | VPS Command');
                        var tr = $('.connection-btn-' + terminalId).closest('td');
                        tr.attr('class', 'text-center connection-btn-' + terminalId);
                        var div = "";
                        div += '<a onclick="startTerminal('  + terminalId + ', ' + expertAdvisorInstanceId +  ')" href="javascript:void(0)" class="text-secondary pr-1" title="Start expert advisor"><i class="fa fa-play"></i></a>' +
                        '<div class="text-primary pr-1 display-inline" title="Expert advisor Paused"><i class="fa fa-pause"></i></div>' +
                        '<a onclick="stopTerminal(' + terminalId + ', ' + expertAdvisorInstanceId + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>';
                        $('.connection-btn-' + terminalId).html(div);
                    }
                    else {

                    }
                },
                error: function () { }
            });
        }

        function stopTerminal(terminalId, expertAdvisorInstanceId) {            
             $.ajax({
                type: "post",
                url: '@Url.Action("StopTerminal", "MT4Terminal")',
                data: { terminalId: terminalId },
                cache: false,
                 success: function (result) {
                     if (result != "") {
                         toastr.success('Terminal successfully stopped', '@ViewData["Title"] | VPS Command');
                         var tr = $('.connection-btn-' + terminalId).closest('td');
                         tr.attr('class', 'text-center connection-btn-' + terminalId);
                        var div = "";
                        div += '<a onclick="startTerminal('  + terminalId + ', ' + expertAdvisorInstanceId +  ')" href="javascript:void(0)" class="text-secondary pr-1" title="Start expert advisor"><i class="fa fa-play"></i></a>' +
                        '<div class="text-muted pr-1 display-inline disabled"><i class="fa fa-pause"></i></div>' +
                             '<div class="text-danger display-inline" title="Expert advisor not running"><i class="fa fa-stop"></i></div>';
                         $('.connection-btn-' + terminalId).html(div);
                    }
                    else {
                                      
                    }
                },
                error: function () { }
            });
        
           
        }

        function loadServerData(_Id) {
            $.ajax({
                type: "POST",
                url: '@Url.Action("GetVPS", "MT4Server")',
                data: { id: _Id },
                cache: false,
                success: function (result) {
                    if (result != "") {
                        $("#add-server-modal").html(result);
                        $("#btn-add-server").prop('value', 'Save Changes');
                        $('#addServerModalLabel').text("Edit VPS");
                        $('#addServerModal').modal('show');
                    }
                    else {

                    }
                },
                error: function () { }
            });
        }

        function loadTerminalData(_terminalId) {
            $.ajax({
                type: "POST",
                url: '@Url.Action("GetTerminal", "MT4Terminal")',
                data: { terminalId: _terminalId },
                cache: false,
                success: function (result) {
                    if (result != "") {
                        $("#edit-terminal-modal").html(result);
                        $('#editTerminalModal').modal('show');
                    }
                    else {

                    }
                },
                error: function () { }
            });
        }

        function connectMT4Server(rowData) {
            $.ajax({
                type: "get",
                url: '@Url.Action("ConnectMT4Server", "MT4Server")',
                data: { id: rowData.id },
                cache: false,
                success: function (result) {
                    if (result != "") {
                        $("#connect-server-modal").html(result);
                        $('#connectServerModal').modal('show');
                        $("#btn-connect-server").prop('value', 'Connect Server');
                        $('#connectServerModalLabel').text("Connect to VPS");
                        $('#connect-server-title').text("Terminals Installed in Server:");
                    }
                    else {

                    }
                },
                error: function () { }
            });
        }

        function disconnectMT4Server(rowData) {
            $.ajax({
                type: "get",
                url: '@Url.Action("DisconnectMT4Server", "MT4Server")',
                data: { id: rowData.id },
                cache: false,
                success: function (result) {
                    if (result != "") {
                        $("#connect-server-modal").html(result);
                        $('#connectServerModal').modal('show');
                        $("#btn-connect-server").prop('value', 'Disconnect Server');
                        $('#connectServerModalLabel').text("Disconnect VPS");
                        $('#connect-server-title').text("Terminals Running in Server:");
                        var myForm = document.getElementById("connectServerForm");
                        myForm.action = "DisconnectMT4Server";
                    }
                    else {

                    }
                },
                error: function () { }
            });
        }

        function getForexCombo(selectObject) {
            var value = selectObject.value;
            var cascading = $('#ForexID');
            $(cascading).empty();
            $(cascading).append('<option value="" selected disabled>Select</option>');
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetForexAccounts", "MT4Terminal")',
                data: { userId: value },
                success: function (result) {
                    if (result != "") {
                        $.each(result, function (index, value) {
                            $(cascading).append('<option value ="' + value.id + '">' + value.forexId +  ' (' + value.server + ')</option>');
                        });
                    }
                },
                error: function (ex) {
                    alert('Failed to retrieve data.' + ex);
                }
            });
        }

        function closeError(errorId) {
             $.ajax({
                type: 'POST',
                url: '@Url.Action("CloseError", "MT4Terminal")',
                data: { errorId: errorId },
                success: function(res) {
                    location.reload();
                },
                error: function() {
                    location.reload();
                }
             })
        }

        /*----------------------------------*/

        $(document).ready(function () {

            var success = null;
            var error = null;

            error = '@ViewBag.Error'
            success = '@ViewBag.Success';

            if (success != '') {
                toastr.success(success, '@ViewData["Title"] | Empowered Forex Trader');
            }
            else if (error != '') {
                toastr.error(error, '@ViewData["Title"] | Empowered Forex Trader');
            }

            /*----VPS MANAGEMENT---------------*/
            $(document).on('hidden.bs.modal', '#addServerModal', function () {
                resetAddServerModal();
            })

            function resetAddServerModal() {
                $("#ServerName").val("");
                $("#ServerAddress").val("");
                $("#ServerDataFolder").val("");
                $("#hdnId").val("");
                $("#btn-add-server").prop('value', 'Add Server');
                $('#addServerModalLabel').text("Add VPS");
            }

            var serversTable = $('#servers-list').DataTable({
                ajax: {
                    url: '@Url.Action("GetListMT4Servers", "MT4Server")',
                    type: "POST",
                    dataSrc: ''
                },
                scrollX: true,
                scrollCollapse: true,
                columns: [
                    {
                        orderable: false,
                        className: 'px-0',
                        data: 'serverConnectionStatus',
                        render: function (data, type, row, meta) {
                            if (data == true) {
                                return '<div class="details-control"></div>';
                            }
                            else {
                                return '<div class="details-control-disabled" title="First connect server"><i class="fa fa-times-circle"></i></div>';
                            }
                        }
                    },
                    { data: 'serverName' },
                    { data: 'serverAddress' },
                    { data: 'serverDataFolder' },
                    {
                        className: 'text-center',
                        orderable: false,
                        data: 'isActive',
                        render: function (data, type, row, meta) {
                            if (data == true) {
                                return '<a class="btn btn-icon btn-pure primary"><i class="fa fa-check"></i></a>';
                            }
                            else {
                                return '<a class="btn btn-icon btn-pure danger"><i class="fa fa-times"></i></a>';
                            }
                        }
                    },
                    {
                        className: 'text-center',
                        orderable: false,
                        data: 'id',
                        render: function (data, type, row, meta) {
                            return '<a onclick="loadServerData(' + data + ')" href="javascript:void(0)" title="Edit VPS" class="btn btn-icon btn-pure secondary" ><i class="fa fa-pencil"></i> </a>';
                        }
                    },
                    {
                        className: 'text-center',
                        orderable: false,
                        data: 'id',
                        render: function (data, type, row, meta) {
                            return '<a href="@Url.Action("DeleteVPS", "MT4Server")?Id=' + data + '" onclick="return confirm(\'Are you sure you want to delete the server?\')" title="Delete VPS" class="btn btn-icon btn-pure danger"><i class="fa fa-trash"></i></a>';
                        }
                    },
                    {
                        className: 'text-center',
                        orderable: false,
                        data: 'serverConnectionStatus',
                        render: function (data, type, row, meta) {
                                if (data == true) {
                                    return '<a href="javascript:void(0)" title="Disconnect VPS" class="disconnect-vps btn btn-icon btn-pure primary"><i class="fa fa-power-off"></i> </a>';
                                }
                                else {
                                    return '<a href="javascript:void(0)" title="Connect VPS" class="connect-vps btn btn-icon btn-pure danger"><i class="fa fa-power-off"></i></a>';
                                }
                            }
                    },
                ],
                "order": [[1, 'asc']]
            });

            /**
             * This function refreshes the 'Active' column
             * by pinging the servers every 10 seconds.
             */
            setInterval(function () {
                $.ajax({
                    url: '@Url.Action("PingServers", "MT4Server")',
                    dataType: 'json',
                    success: function (json) {
                        serversTable.rows().every(function (rowIdx, tableLoop, rowLoop) {
                            var data = this.data();
                            data.isActive = json[data.id].isActive;
                            this.data(data);
                            this.draw();

                            $.ajax({
                                url: '@Url.Action("GetListMT4Terminals", "MT4Terminal")',
                                type: "POST",
                                data: {
                                    serverId: json[data.id].id
                                },
                                success: function (json) {
                                       if (json.mT4Terminals.length > 0) {
                                        for (var i in json.mT4Terminals) {
                                            if($('#terminalStatus-'+json.mT4Terminals[i].id).length > 0) {
                                                for(var e in json.errors) {
                                                        if(json.errors[e].terminalId == json.mT4Terminals[i].id) {
                                                            var err = $('#terminalError-'+json.mT4Terminals[i].id);
                                                            err.html('<div>'+json.errors[e].errorMessage+' <a href="javascript:closeError('+json.errors[e].id+')">(CLOSE)</a></div>')
                                                        }
                                                    }
                                                if(json.mT4Terminals[i].terminalConnectionStatus) {
                                                    $('#terminalStatus-'+json.mT4Terminals[i].id).html('<a onclick="return confirm(\'Are you sure you want to shutdown the terminal?\')" href="@Url.Action("DisconnectTerminal", "MT4Terminal")?terminalId=' + json.mT4Terminals[i].id + '" title="Shutdown terminal" class="btn btn-icon btn-pure primary"><i class="fa fa-power-off"></i></a>');
                                                } else {
                                                    $('#terminalStatus-'+json.mT4Terminals[i].id).html('<a onclick="return confirm(\'Are you sure you want to start the terminal?\')" href="@Url.Action("ConnectTerminal", "MT4Terminal")?terminalId=' + json.mT4Terminals[i].id + '" title="Start terminal" class="btn btn-icon btn-pure danger"><i class="fa fa-power-off"></i></a>');
                                                }
                                            }
                                        }
                                    }
                                }
                            });
                        });
                    }
                });
            }, 10000);

            $('#servers-list tbody').on('click', 'div.details-control', function () {
                var tr = $(this).closest('tr');
                var row = serversTable.row(tr);

                if (row.child.isShown()) {
                    row.child.hide();
                    tr.removeClass('shown');
                }
                else {
                    row.child(formatServersTable(row.data())).show();
                    tr.addClass('shown');
                }
            });

            $('#servers-list tbody').on('click', 'a.connect-vps', function () {
                var tr = $(this).closest('tr');
                var row = serversTable.row(tr);
                connectMT4Server(row.data())
            });

            $('#servers-list tbody').on('click', 'a.disconnect-vps', function () {
                var tr = $(this).closest('tr');
                var row = serversTable.row(tr);
                disconnectMT4Server(row.data())
            });

            $('#servers-list tbody').on('click', 'a.start-terminal', function () {
                var tr = $(this).closest('tr');
                var row = serversTable.row(tr);
                connectMT4Terminal(row.data())
            });

            $('#servers-list tbody').on('click', 'a.stop-terminal', function () {
                var tr = $(this).closest('tr');
                var row = serversTable.row(tr);
                disconnectMT4Terminal(row.data())
            });

            /*----------------------------------*/

            /*----USER MANAGEMENT---------------*/
            var usersTable = $('#users-list').DataTable({
                ajax: {
                    url: '@Url.Action("GetListOfUsers", "UserManagement")',
                    type: "POST",
                    dataSrc: ''
                },
                scrollX: true,
                scrollCollapse: true,
                columns: [
                    {
                        className: 'details-control',
                        orderable: false,
                        data: null,
                        defaultContent: '',
                    },
                    { data: 'fullName' },
                    { data: 'roleDescription' },
                    { data: 'email' },
                    {
                        className: 'text-center',
                        orderable: false,
                        data: 'loginId',
                        render: function (data, type, row, meta) {
                            return '<a onclick="loadUserData(' + data + ')" href="javascript:void(0)" title="View User Details" class="btn btn-icon btn-pure secondary" ><i class="fa fa-street-view"></i> </a>';
                        }
                    },
                    {
                        className: 'text-center',
                        orderable: false,
                        data: 'enabled',
                        render: function (data, type, row, meta) {
                            if (data == true) {
                                return '<label class="switch mb-0" style=\"display: inline-block\"><input type="checkbox" checked class="checkbox_user"><span class="slider round"></span></label>';
                            }
                            else {
                                return '<label class="switch mb-0" style=\"display: inline-block\"><input type="checkbox" class="checkbox_user"><span class="slider round"></span></label>';
                            }

                        }
                    },
                    {
                        className: 'text-center',
                        orderable: false,
                        data: 'loginId',
                        render: function (data, type, row, meta) {
                            return '<a href="@Url.Action("EditUserAccount", "UserManagement")?loginId=' + data + '" title="Edit Account" class="btn btn-icon btn-pure secondary"><i class="fa fa-pencil"></i> </a>';
                        }
                    },
                    {
                        className: 'text-center',
                        orderable: false,
                        data: 'username',
                        render: function (data, type, row, meta) {
                            return '<a href="@Url.Action("ImpersonateUser", "UserManagement")?username=' + data + '" title="Impersonate User" class="btn btn-icon btn-pure secondary"><i class="ft-eye"></i> </a>';
                        }
                    },
                ],
                "order": [[2, 'asc']]
            });

            $('#users-list tbody').on('click', 'td.details-control', function () {
                var tr = $(this).closest('tr');
                var row = usersTable.row(tr);

                if (row.child.isShown()) {
                    // This row is already open - close it
                    row.child.hide();
                    tr.removeClass('shown');
                }
                else {
                    // Open this row
                    row.child(formatUsersTable(row.data())).show();
                    tr.addClass('shown');
                }
            });

            $('#users-list tbody').on('change', 'input.checkbox_user', function () {
                var tr = $(this).closest('tr');
                var row = usersTable.row(tr);
                var data = row.data();
                toggleUser(data.loginId);
            });

            /*----------------------------------*/

            /*---------REPORT FORMAT------------*/
            $(document).on('hidden.bs.modal', '#addReportModal', function () {
                resetAddReportModal();
            })

            function resetAddReportModal() {
                $("#FilenameFormat").val("");
                $("#RegexRule").val("");
                $("#Active").checked = true;
                $("#Basic").checked = true;
                $("#Advanced").checked = true;
                $("#Expert").checked = true;
                $("#Administrator").checked = true;
                $("#Guru").checked = true;
                $("#Developer").checked = true;
                $("#hdnId").val("");
                $("#btn-add-report").prop('value', 'Add Report Format');
                $('#addReportModalLabel').text("Add Report Format");
            }

            var reportsTable = $('#reports-list').DataTable({
                ajax: {
                    url: '@Url.Action("GetListOfReportFormats", "UserManagement")',
                    type: "POST",
                    dataSrc: ''
                },
                scrollX: true,
                scrollCollapse: true,
                columns: [
                    {
                        className: 'details-control',
                        orderable: false,
                        data: null,
                        defaultContent: '',
                    },
                    { data: 'filenameFormat' },
                    { data: 'regexRule' },
                    {
                        className: 'text-center',
                        orderable: false,
                        data: 'active',
                        render: function (data, type, row, meta) {
                            if (data == true) {
                                return '<label class="switch mb-0" style=\"display: inline-block\"><input type="checkbox" checked class="checkbox_report"><span class="slider round"></span></label>';
                            }
                            else {
                                return '<label class="switch mb-0" style=\"display: inline-block\"><input type="checkbox" class="checkbox_report"><span class="slider round"></span></label>';
                            }

                        }
                    },
                    {
                        className: 'text-center',
                        orderable: false,
                        data: 'id',
                        render: function (data, type, row, meta) {
                            return '<a onclick="loadReportFormatData(' + data + ')" href="javascript:void(0)" title="Edit Report Format" class="btn btn-icon btn-pure secondary" ><i class="fa fa-pencil"></i> </a>';
                        }
                    },
                    {
                        className: 'text-center',
                        orderable: false,
                        data: 'id',
                        render: function (data, type, row, meta) {
                            return '<a href="@Url.Action("DeleteFileFormat", "UserManagement")?Id=' + data + '" onclick="return confirm(\'Are you sure you want to delete the report format?\')" title="Delete Report Format" class="btn btn-icon btn-pure danger"><i class="fa fa-trash"></i></a>';
                        }
                    },
                ],
                "order": [[2, 'asc']]
            });

            $('#reports-list tbody').on('click', 'td.details-control', function () {
                var tr = $(this).closest('tr');
                var row = reportsTable.row(tr);

                if (row.child.isShown()) {
                    // This row is already open - close it
                    row.child.hide();
                    tr.removeClass('shown');
                }
                else {
                    // Open this row
                    row.child(formatReportsTable(row.data())).show();
                    tr.addClass('shown');
                }
            });

            $('#reports-list tbody').on('change', 'input.checkbox_report', function () {
                var tr = $(this).closest('tr');
                var row = reportsTable.row(tr);
                var data = row.data();
                toggleReport(data.id);
            });
        });

        /*----SUBSCRIPTION MANAGEMENT---------------*/

        
        function formatPublishersTable(rowData) {
            var div = $('<div/>')
                .addClass('loading')
                .text('Loading...');

            $.ajax({
                url: '@Url.Action("GetListOfSubscribers", "Publisher")',
                type: "POST",
                data: {
                    publisherId: rowData.id
                },
                dataType: 'json',
                success: function (json) {
                    var result = '<div class="m-1">' +
                        '<table id="subscriber-list-' + rowData.id + '" class="table table-bordered">' +
                        '<thead>' +
                        '<tr>' +
                        '<th scope="col" style="width:10%;">User Name</th>'+
                        '<th scope="col" style="width:10%;">Forex Account</th>'+
                        '<th scope="col" style="width:10%;">Server</th>'+
                        '<th scope="col" style="width:10%" class="text-center">Terminal</th>'+
                        '<th scope="col" style="width:10%" class="text-center">Expert Advisor</th>'+
                        '<th scope="col" style="width:10%" class="text-center">Status</th>'+
                        '<th scope="col" style="width:10%" class="text-center">Connection</th>'+
                        '<th scope="col" style="width:10%; min-width:80px;" class="text-center">Modify</th>'+
                        '</tr>' +
                        '</thead>' +
                        '<tbody>';
                    if (json.length > 0) {
                        for (var i in json) {
                            result += formatSubscriberTable(json[i]);
                        }
                    }
                    else {
                        result += '<tr class="even"><td valign="top" colspan="7" class="dataTables_empty">No subscribers found</td></tr>';
                    }
                    result += '</tbody></table></div>'
                    div
                        .html(result)
                        .removeClass('loading');
                },
                error: function () {
                    var result = '<div class="m-1">' +
                        '<table id="subscriber-list-' + rowData.id + '" class="table table-bordered">' +
                        '<thead>' +
                        '<tr>' +
                        '<th scope="col" style="width:10%;">User Name</th>'+
                        '<th scope="col" style="width:10%;">Forex Account</th>'+
                        '<th scope="col" style="width:10%;">Server</th>'+
                        '<th scope="col" style="width:10%" class="text-center">Terminal</th>'+
                        '<th scope="col" style="width:10%" class="text-center">Expert Advisor</th>'+
                        '<th scope="col" style="width:10%" class="text-center">Status</th>'+
                        '<th scope="col" style="width:10%" class="text-center">Connection</th>'+
                        '<th scope="col" style="width:10%; min-width:80px;" class="text-center">Modify</th>'+
                        '</tr>' +
                        '</thead>' +
                        '<tbody>';
                     result += '<tr class="even"><td valign="top" colspan="7" class="dataTables_empty">No subscribers found, check publisher info.</td></tr>';
                     result += '</tbody></table></div>'
                    div
                        .html(result)
                        .removeClass('loading');
                }
            });

            return div;
        }

        function formatSubscriberTable(d) {
            var div = '<tr role="row">' +
                '<td>' +
                    '<div>' + d.userName + '</div>' +
                '</td>' +
                '<td>' +
                    '<div>' + d.forexAccount + '</div>' +
                '</td>' +
                '<td>' +
                    '<div>' + d.server.serverName + '</div>' +
                '</td>' +
                '<td>' +
                    '<div>' + d.terminalName + '</div>' +
                '</td>' +
                '<td>' +
                    '<div>' + d.expertAdvisorName + '</div>' +
                '</td>';
          
            if (d.terminalConnectionStatus == true) {
                div += '<td id="terminalStatus-' + d.terminalId + '" class="text-center terminal-status-' + d.terminalId + '"><a onclick="return confirm(\'Are you sure you want to shutdown the terminal?\')" href="@Url.Action("DisconnectTerminal", "Publisher")?terminalId=' + d.terminalId + '&id=' + d.id +  '" title="Shutdown terminal" class="btn btn-icon btn-pure primary"><i class="fa fa-power-off"></i></a></td>';
            }
            else {
                div += '<td id="terminalStatus-' + d.terminalId + '" class="text-center terminal-status-' + d.terminalId + '"><a onclick="return confirm(\'Are you sure you want to start the terminal ' + d.terminalId + '?\')" href="@Url.Action("ConnectTerminal", "Publisher")?terminalId=' + d.terminalId + '&id=' + d.id + '" title="Start terminal" class="btn btn-icon btn-pure danger"><i class="fa fa-power-off"></i></a></td>';
            }
            if (d.terminalConnectionStatus == true) {
                
                if (d.expertAdvisorConnectionStatus == 1) {
                    div += '<td class=" text-center terminal-' + d.terminalId + '">' +
                        '<div style="padding-right: 9px;" class="text-primary display-inline" title = "Expert advisor running" > <i class="fa fa-play"></i></div > ' +
                        '<a onclick="pauseEATerminal(' + d.terminalId + ', ' + d.id + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Pause expert advisor"><i class="fa fa-pause"></i></a>' +
                        '<a onclick="stopEATerminal(' + d.terminalId + ', ' + d.id + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>' +
                        '</td>';
                }
                else if (d.expertAdvisorConnectionStatus == 2) {
                    div += '<td class=" text-center terminal-' + d.terminalId + '">' +
                        '<a onclick="startEATerminal(' + d.terminalId + ', ' + d.id + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Start expert advisor"><i class="fa fa-play"></i></a>' +
                        '<div class="text-muted pr-1 display-inline disabled"><i class="fa fa-pause"></i></div>' +
                        '<div class="text-danger display-inline" title="Expert advisor not running"><i class="fa fa-stop"></i></div>' +
                        '</td>';
                }
                else if (d.expertAdvisorConnectionStatus == 3) {
                    div += '<td class=" text-center terminal-' + d.terminalId + '">' +
                        '<a onclick="startEATerminal(' + d.terminalId + ', ' + d.id + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Start expert advisor"><i class="fa fa-play"></i></a>' +
                        '<div class="text-primary pr-1 display-inline" title="Expert advisor Paused"><i class="fa fa-pause"></i></div>' +
                        '<a onclick="stopEATerminal(' + d.terminalId + ', ' + d.id + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>' +
                        '</td>';
                }
                else {
                    div += '<td>' +
                        '<div>---</div>' +
                        '</td>';
                }
            }
            else {
                div += '<td class=" text-center terminal-' + d.terminal + '">' +
                    '<div class="text-muted pr-1 display-inline disabled" title="Start terminal first"><i class="fa fa-play"></i></div>' +
                    '<div class="text-muted pr-1 display-inline disabled" title="Start terminal first"><i class="fa fa-pause"></i></div>' +
                    '<div class="text-muted display-inline disabled" title="Start terminal first"><i class="fa fa-stop"></i></div>'
                    '</td>';
            }

            div += '</td>' +
                '<td class="text-center">' +
                '<a onclick="loadSubscriberData(' + d.id + ')" href="javascript:void(0)" title="Manage Subscriber" class="btn btn-icon btn-pure secondary" ><i class="fa fa-cog"></i> </a><a href="@Url.Action("DeleteSubscriber", "Publisher")?Id=' + d.id + '" onclick="return confirm(\'Are you sure you want to remove this subscriber?\')" title="Delete Subscriber"class="btn btn-icon btn-pure danger"><i class="fa fa-trash"></i></a>' +
                '</td>';

            return div;
        }

    function form_submit_addpub() {
        document.getElementById("addPublisherForm").submit();
    }

    function form_submit_addsub() {
        document.getElementById("addSubscriberForm").submit();
        }

       
    function getForexForPub(selectObject) {
            var value = selectObject.value;
            var cascading = $('#PubForexAccount');
            $(cascading).empty();
            $(cascading).append('<option value="" selected disabled>Select</option>');
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetAvailableForexAccounts", "Publisher")',
                data: { userId: value },
                success: function (result) {
                    if (result != "") {
                        $.each(result, function (index, value) {
                            $(cascading).append('<option value ="' + value.id + '">' + value.forexId +  ' (' + value.server + ')</option>');
                        });
                    }
                },
                error: function (ex) {
                    alert('Failed to retrieve data.' + ex);
                }
            });
        }
    function getForexForEditPub(selectObject, forexId) {
            var value = selectObject.value;
            var cascading = $('#EditPubForexAccount');
            $(cascading).empty();
            $(cascading).append('<option value="" selected disabled>Select</option>');
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetAvailableEditForexAccounts", "Publisher")',
                data: { userId: value, forexId: forexId },
                success: function (result) {
                    if (result != "") {
                        $.each(result, function (index, value) {
                            $(cascading).append('<option value ="' + value.id + '">' + value.forexId +  ' (' + value.server + ')</option>');
                        });
                    }
                },
                error: function (ex) {
                    alert('Failed to retrieve data.' + ex);
                }
            });
        }
            function getForexForSub(selectObject) {
            var value = selectObject.value;
            var dropdown = $('#SubForexAccount');
            $(dropdown).empty();
            $(dropdown).append('<option value="" selected disabled>Select</option>');
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetAvailableForexAccounts", "Publisher")',
                data: { userId: value },
                success: function (result) {
                    if (result != "") {
                        $.each(result, function (index, value) {
                            $(dropdown).append('<option value ="' + value.id + '">' + value.forexId +  ' (' + value.server + ')</option>');
                        });
                    }
                },
                error: function (ex) {
                    alert('Failed to retrieve data.' + ex);
                }
            });
        }
    function getForexForEditSub(selectObject, forexId) {
            var value = selectObject.value;
            var cascading = $('#EditSubForexAccount');
            $(cascading).empty();
            $(cascading).append('<option value="" selected disabled>Select</option>');
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetAvailableEditForexAccounts", "Publisher")',
                data: { userId: value, forexId: forexId },
                success: function (result) {
                    if (result != "") {
                        $.each(result, function (index, value) {
                            $(cascading).append('<option value ="' + value.id + '">' + value.forexId +  ' (' + value.server + ')</option>');
                        });
                    }
                },
                error: function (ex) {
                    alert('Failed to retrieve data.' + ex);
                }
            });
    }

                function getTerminalsForServerSubEdit(selectObject) {
            var value = selectObject.value;
            var cascading = $('#EditSubTerminalForServer');
            $(cascading).empty();
            $(cascading).append('<option value="" selected disabled>Select</option>');
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetListMT4Terminals", "MT4Terminal")',
                data: { serverId: value },
                success: function (result) {
                    if (result != "") {
                        $.each(result.mT4Terminals, function (index, value) {
                            
                            $(cascading).append('<option value ="' + value.id + '">' + value.terminalInstance + '</option>');
                        });
                    }
                },
                error: function (ex) {
                    alert('Failed to retrieve data.' + ex);
                }
            });
        }

        function getTerminalsForServerSub(selectObject) {
            var value = selectObject.value;
            var cascading = $('#SubTerminalForServer');
            $(cascading).empty();
            $(cascading).append('<option value="" selected disabled>Select</option>');
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetListMT4Terminals", "MT4Terminal")',
                data: { serverId: value },
                success: function (result) {
                    if (result != "") {
                        $.each(result.mT4Terminals, function (index, value) {
                            
                            $(cascading).append('<option value ="' + value.id + '">' + value.terminalInstance + '</option>');
                        });
                    }
                },
                error: function (ex) {
                    alert('Failed to retrieve data.' + ex);
                }
            });
        }

                        function getTerminalsForServerPubEdit(selectObject) {
            var value = selectObject.value;
                            var cascading = $('#EditPubTerminalForServer');
            $(cascading).empty();
            $(cascading).append('<option value="" selected disabled>Select</option>');
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetListMT4Terminals", "MT4Terminal")',
                data: { serverId: value },
                success: function (result) {
                    if (result != "") {
                        $.each(result.mT4Terminals, function (index, value) {
                            
                            $(cascading).append('<option value ="' + value.id + '">' + value.terminalInstance + '</option>');
                        });
                    }
                },
                error: function (ex) {
                    alert('Failed to retrieve data.' + ex);
                }
            });
        }

        function getTerminalsForServerPub(selectObject) {
            var value = selectObject.value;
            var cascading = $('#PubTerminalForServer');
            $(cascading).empty();
            $(cascading).append('<option value="" selected disabled>Select</option>');
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetListMT4Terminals", "MT4Terminal")',
                data: { serverId: value },
                success: function (result) {
                    if (result != "") {
                        $.each(result.mT4Terminals, function (index, value) {
                            
                            $(cascading).append('<option value ="' + value.id + '">' + value.terminalInstance + '</option>');
                        });
                    }
                },
                error: function (ex) {
                    alert('Failed to retrieve data.' + ex);
                }
            });
        }

        function startEATerminal(terminalId, id) {            
            $.ajax({
                type: "post",
                url: '@Url.Action("StartTerminal", "Publisher")',
                data: {
                    terminalId: terminalId,
                    id: id
                },
                cache: false,
                success: function (result) {
                    if (result == "0") {
                        var div = "";
                        div += '<div class="text-primary pr-1 display-inline" title="Expert advisor running"><i class="fa fa-play"></i></div>' +
                            '<a onclick="pauseEATerminal(' + terminalId + ', ' + id + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Pause expert advisor"><i class="fa fa-pause"></i></a>' +
                            '<a onclick="stopEATerminal(' + terminalId + ', ' + id + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>';
                        $('.connection-btn-' + terminalId).html(div);
                    }
                    else {
                        toastr.success('Terminal successfully started', '@ViewData["Title"] | VPS Command');
                        var tr = $(".text-center.terminal-" + terminalId);
                
                        var div = "";
                        div += '<td class=" text-center terminal-' + terminalId + '">' +
                            '<div style="padding-right: 9px;" class="text-primary  display-inline" title = "Expert advisor running" > <i class="fa fa-play"></i></div > ' +
                            '<a onclick="pauseEATerminal(' + terminalId + ', ' + id + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Pause expert advisor"><i class="fa fa-pause"></i></a>' +
                            '<a onclick="stopEATerminal(' + terminalId + ', ' + id + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>' +
                            '</td>';
                        tr.replaceWith(div);
                        //$(".text-center.runningTerminal").html(div);
                    }
                },
                error: function () { }
            });
        }

        function pauseEATerminal(terminalId, id) {
    
            $.ajax({
                type: "post",
                url: '@Url.Action("PauseTerminal", "Publisher")',
                data: {
                    terminalId: terminalId,
                    id: id
                },
                cache: false,
                success: function (result) {
                    if (result != "") {
                        toastr.success('Terminal successfully paused', '@ViewData["Title"] | VPS Command');
                        var tr = $(".text-center.terminal-" + terminalId);
                        
                        var div = "";
                        div += '<td class=" text-center terminal-' + terminalId + '">' +
                            '<a onclick="startEATerminal(' + terminalId + ', ' + id + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Start expert advisor"><i class="fa fa-play"></i></a>' +
                            '<div class="text-primary pr-1 display-inline" title="Expert advisor Paused"><i class="fa fa-pause"></i></div>' +
                            '<a onclick="stopEATerminal(' + terminalId + ', ' + id + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>' +
                            '</td>';
                        tr.replaceWith(div);
                    }
                    else {

                    }
                },
                error: function () { }
            });
        }

        function stopEATerminal(terminalId, id) {
     
             $.ajax({
                type: "post",
                url: '@Url.Action("StopTerminal", "Publisher")',
                 data: {
                     terminalId: terminalId,
                     id: id
                 },
                cache: false,
                 success: function (result) {
                     if (result != "") {
                         toastr.success('Terminal successfully stopped', '@ViewData["Title"] | VPS Command');
                         var tr = $(".text-center.terminal-" + terminalId);
                         
                        var div = "";
                         div += '<td class=" text-center terminal-' + terminalId + '">' +
                             '<a onclick="startEATerminal(' + terminalId + ', ' + id + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Start expert advisor"><i class="fa fa-play"></i></a>' +
                             '<div class="text-muted pr-1 display-inline disabled"><i class="fa fa-pause"></i></div>' +
                             '<div class="text-danger display-inline" title="Expert advisor not running"><i class="fa fa-stop"></i></div>' +
                             '</td>';
                         tr.replaceWith(div);
                    }
                    else {
                                      
                    }
                },
                error: function () { }
            });
        
           
        }

    function loadPublisherData(Id) {
            $.ajax({
                type: "GET",
                url: '@Url.Action("GetPublisher", "Publisher")',
                data: { id: Id },
                cache: false,
                success: function (result) {
                    if (result != "") {
                        $("#edit-pub-modal").html(result);
                        $('#editPubModal').modal('show');
                    }
                    else {

                    }
                },
                error: function () { }
            });
        }
            function loadSubscriberData(Id) {
            $.ajax({
                type: "GET",
                url: '@Url.Action("GetSubscriber", "Publisher")',
                data: { id: Id },
                cache: false,
                success: function (result) {
                    if (result != "") {
                        $("#edit-sub-modal").html(result);
                        $('#editSubModal').modal('show');
                    }
                    else {

                    }
                },
                error: function () { }
            });
        }



$(document).ready(function () {

            $('#addPublisherForm select').change(function () {
                if (parseInt($("#PubForexAccount").val()) > 0) {
                    $("#btn-add-publisher").removeAttr("disabled");
                } else {
                    $("#btn-add-publisher").attr("disabled", true);
                }
            });

            $('#addSubscriberForm select').change(function () {
                if (parseInt($("#SubForexAccount").val()) > 0) {
                    $("#btn-add-subscriber").removeAttr("disabled");
                } else {
                    $("#btn-add-subscriber").attr("disabled", true);
                }
            });

    var publisherTable = $('#publisher-list').DataTable({
                ajax: {
                    url: '@Url.Action("GetListOfPublishers", "Publisher")',
                    type: "POST",
                    dataSrc: ''
                },
                scrollX: true,
                scrollCollapse: true,
                columns: [
                    {
                        orderable: false,
                        className: 'px-0',
                        data: 'id',
                        render: function (data, type, row, meta) {
                            return '<div class="details-control"></div>';
                        }
                    },
                    { data: 'userName' },
                    { data: 'forexAccount' },
                    { data: 'serverName' },
                    { data: 'terminalName' },
                    { data: 'expertAdvisorName' },
                    {
                        className: 'text-center',
                        orderable: false,
                        data: 'terminalConnectionStatus',
                        render: function (data, type, row, meta) {
                            if (data == true) {
                                return '<td id="terminalStatus-' + row.terminalId + '" class="text-center terminal-status-' + row.terminalId + '"><a onclick="return confirm(\'Are you sure you want to shutdown the terminal?\')" href="@Url.Action("DisconnectTerminal", "Publisher")?terminalId=' + row.terminalId + '&id=' + row.id + '" title="Shutdown terminal" class="btn btn-icon btn-pure primary"><i class="fa fa-power-off"></i></a></td>';
                            }
                            else {
                                return '<td id="terminalStatus-' + row.terminalId + '" class="text-center terminal-status-' + row.terminalId + '"><a onclick="return confirm(\'Are you sure you want to start the terminal?\')" href="@Url.Action("ConnectTerminal", "Publisher")?terminalId=' + row.terminalId + '&id=' + row.id + '" title="Start terminal" class="btn btn-icon btn-pure danger"><i class="fa fa-power-off"></i></a></td>';
                            }
                        }
                    },
                    {
                        
                        orderable: false,
                        data: 'expertAdvisorConnectionStatus',
                        render: function (data, type, row) {
                            if (row.terminalConnectionStatus == false) {
                                var div = "";
                                div += '<td class="text-center">' +
                                    '<div class="text-muted pr-1 display-inline disabled" title="Start terminal first"><i class="fa fa-play"></i></div>' +
                                    '<div class="text-muted pr-1 display-inline disabled" title="Start terminal first"><i class="fa fa-pause"></i></div>' +
                                    '<div class="text-muted display-inline disabled" title="Start terminal first"><i class="fa fa-stop"></i></div>'
                                '</td>';
                                return div;
                            }
                            
                           else if (data == 1) {
                                var div = "";
                                div = '<td class=" text-center terminal-' + row.terminalId + '">' +
                                    '<div style="padding-right: 9px;" class="text-primary display-inline" title = "Expert advisor running" > <i class="fa fa-play"></i></div > ' +
                                    '<a onclick="pauseEATerminal(' + row.terminalId + ', ' + row.id + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Pause expert advisor"><i class="fa fa-pause"></i></a>' +
                                    '<a onclick="stopEATerminal(' + row.terminalId + ', ' + row.id + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>' +
                                    '</td>';
                                
                                return div;
                                }
                            else if (data == 2) {
                                var div = "";
                                div = '<td class=" text-center terminal-' + row.terminalId + '">' +
                                    '<a onclick="startEATerminal(' + row.terminalId + ', ' + row.id + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Start expert advisor"><i class="fa fa-play"></i></a>' +
                                        '<div class="text-muted pr-1 display-inline disabled"><i class="fa fa-pause"></i></div>' +
                                        '<div class="text-danger display-inline" title="Expert advisor not running"><i class="fa fa-stop"></i></div>' +
                                    '</td>';
                                
                                return div;
                                }
                            else if (data == 3) {
                                var div = "";
                                div = '<td class=" text-center terminal-' + row.terminalId + '">' +
                                    '<a onclick="startEATerminal(' + row.terminalId + ', ' + row.id + ')" href="javascript:void(0)" class="text-secondary pr-1" title="Start expert advisor"><i class="fa fa-play"></i></a>' +
                                    '<div class="text-primary pr-1 display-inline" title="Expert advisor Paused"><i class="fa fa-pause"></i></div>' +
                                    '<a onclick="stopEATerminal(' + row.terminalId + ', ' + row.id + ')" href="javascript:void(0)" class="text-secondary" title="Stop expert advisor"><i class="fa fa-stop"></i></a>' +
                                    '</td>';
                                
                                return div;
                                }
                                else {
                                    return '<td>' +
                                        '<div>---</div>' +
                                        '</td>';
                                }
                        },
                        createdCell: function (cell, cellData, rowData) {                            
                            $(cell).addClass(" text-center terminal-" + rowData.terminalId);
                        }
                    },
                    {
                        className: 'text-center',
                        orderable: false,
                        data: 'id',
                        render: function (data, type, row, meta) {
                            return '<a onclick="loadPublisherData(' + data + ')" href="javascript:void(0)" title="Manage Publisher" class="btn btn-icon btn-pure secondary" ><i class="fa fa-cog"></i> </a><a href="@Url.Action("DeletePublisher", "Publisher")?Id=' + data + '" onclick="return confirm(\'Are you sure you want to delete this publisher?\')" title="Delete Publsiher" class="btn btn-icon btn-pure danger"><i class="fa fa-trash"></i></a>';
                        }
                    },

                ],
                "order": [[1, 'asc']]
    });

        $('#publisher-list tbody').on('click', 'div.details-control', function () {
        var tr = $(this).closest('tr');
        var row = publisherTable.row(tr);

        if (row.child.isShown()) {
            row.child.hide();
            tr.removeClass('shown');
        }
        else {
            row.child(formatPublishersTable(row.data())).show();
            tr.addClass('shown');
        }
        });
});


    </script>
</body>
</html>