﻿// Instantiate the HarborSales namespace (if necessary)
if (typeof (HarborSales) == "undefined") HarborSales = {};

// Instantiate the HarborSales.Portal namespace (if necessary)
if (typeof (HarborSales.Portal) == "undefined") HarborSales.Portal = {};

// Instantiate the HarborSales.Portal.Modules namespace (if necessary)
if (typeof (HarborSales.Portal.Modules) == "undefined") HarborSales.Portal.Modules = {};

if (typeof (HarborSales.Portal.Modules.ControlPanel) == "undefined") {
    HarborSales.Portal.Modules.ControlPanel = {
        // Private Members
        _selectedJobId: -1,
        _selectedNotificationId: -1,

        // Private Functions
        _setup: function (target) {

            $("#tblJobGrid").jqGrid({
                colNames: ['#', 'Created By', 'Job', 'Status', 'Start', 'End', 'Info', '', '', ''],
                colModel: [
                    { name: 'Id', index: 'Id', width: 30, sorttype: 'int' },
                    { name: 'CreatedByName', index: 'CreatedByName', width: 100, sorttype: 'int' },
                    { name: 'ShortName', index: 'ShortName', width: 100, align: 'left' },
                    { name: 'StatusName', index: 'StatusName', width: 80, align: 'left' },
                    { name: 'ExecutionStartDateTimeString', index: 'ExecutionStartDateTimeString', width: 112, align: 'left' },
                    { name: 'ExecutionEndDateTimeString', index: 'ExecutionEndDateTimeString', width: 112, align: 'left' },
                    { name: 'Output', index: 'Output', width: 30, align: 'center', sortable: false },
                    { name: 'DocumentId', index: 'DocumentId', hidden: true },
                    { name: 'DocumentFileName', index: 'DocumentFileName', hidden: true },
                    { name: 'Download', index: 'Download', width: 30, align: 'center', sortable: false }
                ],
                localReader: {
                    root: "Jobs",
                    repeatitems: false
                },
                caption: "Jobs",
                height: 185,
                sortname: "Id",
                sortorder: "desc",
                gridComplete: function () {
                    // need to add a button for downloading the pdf if the documentid is > 0
                    var grid = $("#tblJobGrid");
                    var ids = $(grid).getDataIDs();
                    var documentId = 0;
                    var fileName = '';
                    var documentButton = '';
                    var outputButton = '';
                    for (var i = 0; i < ids.length; i++) {
                        var id = ids[i];
                        documentId = $(grid).getRowData(id)['DocumentId'];
                        fileName = $(grid).getRowData(id)['DocumentFileName'];
                        if (documentId == '0' || documentId == '') {
                            documentButton = '';
                        } else {
                            documentButton = "<button type=\"button\" onclick=\"HarborSales.Portal.Modules.ControlPanel.getJobDocument('" + documentId + "');\" title=\"Download " + fileName + "\" class=\"ui-button ui-state-default ui-corner-all ui-priority-secondary\"><span class=\"ui-icon ui-icon-document\" /></button>";
                        }
                        outputButton = "<button type=\"button\" onclick=\"HarborSales.Portal.Modules.ControlPanel.getJobOutput('" + id + "');\" title=\"View Output\" class=\"ui-button ui-state-default ui-corner-all ui-priority-secondary\"><span class=\"ui-icon ui-icon-newwin\" /></button>";

                        $(grid).setRowData(id, { Output: outputButton });
                        $(grid).setRowData(id, { Download: documentButton });
                    }
                },
                onSelectRow: function (id) {
                    HarborSales.Portal.Modules.ControlPanel._selectedJobId = id;
                }
            }).toolbarButtonAdd('#t_tblJobGrid', {
                caption: "Refresh",
                title: "Refresh the job information",
                buttonicon: "ui-icon ui-icon-pencil",
                position: "first",
                onClickButton: function () {
                    // make the call to populate the grids
                    HarborSales.Portal.Modules.ControlPanel.refreshGrids(true);
                }
            });

            $("#tblNotificationGrid").jqGrid({
                colNames: ['Id', 'Created', 'Type', 'Title', 'Message'],
                colModel: [
                    { name: 'Id', index: 'Id', hidden: true, sorttype: 'int' },
                    { name: 'CreatedDtmString', index: 'CreatedDtmString', width: 120, align: 'left' },
                    { name: 'TypeName', index: 'TypeName', width: 80, align: 'left', hidden: true },
                    { name: 'Title', index: 'Title', width: 200, align: 'left' },
                    { name: 'Message', index: 'Message', width: 200, align: 'left' }
                ],
                localReader: {
                    root: "Notifications",
                    repeatitems: false
                },
                caption: "Notifications",
                height: 191,
                sortname: "Id",
                sortorder: "desc",
                gridComplete: function () {
                },
                onSelectRow: function (id) {
                    HarborSales.Portal.Modules.ControlPanel._selectedNotificationId = id;
                }
            }).toolbarButtonAdd('#t_tblNotificationGrid', {
                caption: "Refresh",
                title: "Refresh the notification information",
                buttonicon: "ui-icon ui-icon-pencil",
                position: "first",
                onClickButton: function () {
                    // make the call to populate the grids
                    HarborSales.Portal.Modules.ControlPanel.refreshGrids(true);
                }
            }).toolbarButtonAdd('#t_tblNotificationGrid', {
                caption: "Clear All",
                title: "Clear all notifications",
                buttonicon: "ui-icon ui-icon-pencil",
                position: "first",
                onClickButton: function () {

                    var userId = $('.userIdContainer input[type=hidden]').val();

                    jQuery.ajax({
                        type: "POST",
                        url: "/Services/CEPService.asmx/AcknowledgeAllNotifications",
                        data: "{'userId':" + userId + "}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            $('#SlidingPanel_NotificationCount').html(data.d.PendingNotificationCount);
                            rebindjsonLocal($("#tblNotificationGrid"), data.d);
                        }
                    });
                }
            }).toolbarButtonAdd('#t_tblNotificationGrid', {
                caption: "Clear",
                title: "Clear selected notification",
                buttonicon: "ui-icon ui-icon-pencil",
                position: "first",
                onClickButton: function () {
                    var data = $("#tblNotificationGrid").getRowData(HarborSales.Portal.Modules.ControlPanel._selectedNotificationId);
                    if (!data.Id) {
                        alert('Please select a record to clear.');
                    } else {
                        jQuery.ajax({
                            type: "POST",
                            url: "/Services/CEPService.asmx/AcknowledgeNotification",
                            data: "{'notificationId':" + HarborSales.Portal.Modules.ControlPanel._selectedNotificationId + "}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (ackData) {
                                $('#SlidingPanel_NotificationCount').html(ackData.d.PendingNotificationCount);
                                rebindjsonLocal($("#tblNotificationGrid"), ackData.d);
                            }
                        });
                    }
                }
            });

            // setup the change password button
            //            $('#btnChangePassword').delegate('', 'click', function () { __doPostBack('dnn$dnnUSER$cmdRegister', ''); });

            // setup the sliding panel gear
            $("#SlidingPanel_Tab ul").click(function () {
                if ($("#SlidingPanel_NotificationCount").attr("slideState") == 'closed') {
                    $("#SlidingPanel_Overlay").fadeIn();
                    $("#SlidingPanel_NotificationCount").attr("slideState", 'open');
                    $("div#SlidingPanel_Main").slideDown();
                    $('#SlidingPanel_NotificationCount').removeClass("ui-state-highlight");

                    // make the call to populate the grids
                    HarborSales.Portal.Modules.ControlPanel.refreshGrids(true);
                } else {
                    $("#SlidingPanel_Overlay").fadeOut();
                    $("#SlidingPanel_NotificationCount").attr("slideState", 'closed');
                    $("div#SlidingPanel_Main").slideUp();
                }
            });

            // add overlay if not present
            if ($('#SlidingPanel_Overlay').length == 0) {
                var overlay = document.createElement('div');
                $(overlay).addClass('ui-helper-hidden')
                // this is added manually due to an issue with fadeOut not properly recognizing an elements opacity 
                // from css and therefor not resetting it properly when the fadeOut completes
                    .attr('style', 'filter:alpha(opacity=55); opacity:0.55;')
                    .attr('id', 'SlidingPanel_Overlay');

                $('body').append(overlay);
            }
        },

        // Public Functions
        EnableSlidingPanel: function (enable) {
            if (enable) {
                if ($('.dnnControlPanel').length > 0) {
                    $('#SlidingPanel').css('top', '41px');
                } else {
                    $('#SlidingPanel').css('top', '0');
                }
                $('.cts-auth-only').show();
            } else {
                $('#SlidingPanel').css('top', '0');
                $('.cts-auth-only').hide();
            }
        },

        refreshGrids: function (globalFlag) {
            // make the call to populate the grids

            var userId = $('.userIdContainer input[type=hidden]').val();
            var jobName = $('.filterTypeContainer').val();

            var jobTypeId = 0;
            if (jobName == 'Email') {
                jobTypeId = 2;
            }
            if (jobName == 'Print') {
                jobTypeId = 1;
            }

            jQuery.ajax({
                type: "POST",
                url: "/Services/CEPService.asmx/GetControlPanelJobGridData",
                data: '{"userId":"' + userId + '","jobType":"' + jobTypeId + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    rebindjsonLocal($("#tblJobGrid"), data.d);
                },
                error: function (xhr, status, error) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                }
            });

            jQuery.ajax({
                type: "POST",
                url: "/Services/CEPService.asmx/GetControlPanelNotificationGridData",
                data: '{"userId":"' + userId + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    rebindjsonLocal($("#tblNotificationGrid"), data.d);
                },
                error: function (xhr, status, error) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                }
            });

        },
        getJobOutput: function (jobId) {
            jQuery.ajax({
                type: "POST",
                url: "/Services/CEPService.asmx/GetJobOutput",
                data: "{'jobId':" + jobId + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    if (data != null && data.d != null && data.d.JobOutput != null && data.d.JobOutput != '') {
                        alert(data.d.JobOutput.replace('<br/>', '\n\r')); 
                    } else {
                        alert("This job has no output message at this time.");
                    }
                }
            });
        },
        getJobDocument: function (documentId) {
            //var url = 'DesktopModules/Gemini.UI.Portal.Modules.Reports/ReportPdfLoader.aspx?DocumentId=' + documentId;
            //PDFLoader(url, '');
            //$('#framePdfLoader').attr('src', 'DesktopModules/HarborSales.Portal.Modules.ControlPanel/ControlPanelReport.aspx?documentId=' + documentId);
            $('#framePdfLoader').attr('src', '/Services/CEPService.asmx/GetDocument?documentId=' + documentId);
        },
        notificationServiceCall: function () {
            // make the service call to check for notifications
            var userId = $('.userIdContainer input[type=hidden]').val();

            jQuery.ajax({
                type: "POST",
                url: "/Services/CEPService.asmx/GetPendingNotificationCount",
                data: "{'userId':" + userId + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    $('#SlidingPanel_NotificationCount').html(data.d.PendingNotificationCount);

                    // if there are any new notifications, then update the count and signal to the user
                    //                    if (data.d.NewNotificationsExist) {
                    //                        $('#SlidingPanel_NotificationCount').addClass("ui-state-highlight");
                    //                        $('#SlidingPanel_NotificationCount').effect("pulsate", { times: 3 }, 1000);
                    //                    }
                }
            });

        }
    };
}

$(document).ready(function () {
    HarborSales.Portal.Modules.ControlPanel._setup();
});
