/* Minification failed. Returning unminified contents.
(1135,61-62): run-time error JS1195: Expected expression: >
(1135,82-83): run-time error JS1004: Expected ';': )
(1135,99-100): run-time error JS1195: Expected expression: >
(1136,62-63): run-time error JS1195: Expected expression: >
(1136,83-84): run-time error JS1004: Expected ';': )
(1136,100-101): run-time error JS1195: Expected expression: >
(1138,59-60): run-time error JS1195: Expected expression: >
(1138,94-95): run-time error JS1004: Expected ';': )
(1138,108-109): run-time error JS1003: Expected ':': )
(1139,60-61): run-time error JS1195: Expected expression: >
(1139,95-96): run-time error JS1004: Expected ';': )
(1142,47-51): run-time error JS1197: Too many errors. The file might not be a JavaScript file: html
 */
var SESSION_EXPIRATION_HTTP_STATUS_CODE = 401;

function addDays(date, numberOfDays) {
    var milliSecondsPerDay = 24 * 60 * 60 * 1000;

    return new Date(date.getTime() + numberOfDays * milliSecondsPerDay);
}

function today() {
    return new Date(new Date().setHours(0, 0, 0, 0));
}

function tomorrow() {
    return addDays(today(), 1);
}

function ajaxSessionTimeoutOccurred(jqXHR) {
    return jqXHR.status == SESSION_EXPIRATION_HTTP_STATUS_CODE;
};

$(document).ajaxError(function (event, jqXHR) {
    if (ajaxSessionTimeoutOccurred(jqXHR)) {
        alert("For security purposes, your session has expired due to inactivity. You will now be taken to the logon page so that you can establish a new session.");
        // we can simply refresh the current page and the built-in authentication will handle the redirect for us.
        window.location.reload();
        return false;
    }
});;
Grinder = {};
Admin = {};

Grinder.Core = Grinder.Core || {};
Grinder.Core = {

    initializePage: function() {
        $("#siteMessageWindow").kendoWindow({
            modal: true,
            resizable: false,
            width: "370px",
            visible: false
        });
    },

    setRadioValue: function (name, selectedValue) {
        $('input[name="' + name + '"][value="' + selectedValue + '"]').prop('checked', true);
    },
    
    booleanToBit: function (input) {
        if (input)
            return 1;
        else
            return 0;
    },

    cancelEvent: function (event) {
        if (event.preventDefault) {
            event.preventDefault();
        }
        else {
            event.returnValue = false;
        }
    },

    resetFormValidation: function ($form) {

        $form.removeData('validator');
        $form.removeData('unobtrusiveValidation');

        //reset unobtrusive validation summary, if it exists
        $form.find("[data-valmsg-summary=true]")
            .removeClass("validation-summary-errors")
            .addClass("validation-summary-valid")
            .find("ul").empty();

        //reset unobtrusive field level, if it exists
        $form.find("[data-valmsg-replace]")
            .removeClass("field-validation-error")
            .addClass("field-validation-valid")
            .empty();

        $.validator.unobtrusive.parse($form);
    },
};;
//create the area's namespace or get it if it already exists
Grinder.Dashboard = Grinder.Dashboard || {};
Grinder.Dashboard = {
    initializePage: function() {
        var _$busyIndicator = $("#busyIndicator");

        _$busyIndicator.kendoWindow({
            actions: {},
            height: "50px",
            modal: true,
            resizable: false,
            width: "170px",
            visible: false,
            title: $("#loadingText").val() //"Reticulating splines"
        });

        Grinder.Dashboard.loadGrids();
    },

    hideBusyIndicator: function() {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.close();
    },

    showBusyIndicator: function(message) {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.title(message);
        kendoWindow.center();
        kendoWindow.open();
    },

    loadGrids: function() {
        Grinder.Dashboard.showBusyIndicator();

        Grinder.Dashboard.showYearlyStats();
        Grinder.Dashboard.showStoryStats();
        Grinder.Dashboard.showMarketStats();
    },

    showYearlyStats: function() {

        var _$dataSource;

        _$dataSource = new kendo.data.DataSource({
            schema: {
                model: {
                    id: "Year",
                    fields: {
                        Year: {},
                        Submissions: {},
                        Acceptances: {},
                        RejectionsForm: {},
                        RejectionsPersonal: {},
                        StoriesSubmitted: {},
                        AmountEarned: {}
                    }
                }
            },
            sort: { field: "Year", dir: "desc" },
            transport: {
                read: function(options) {
                    $.ajax({
                        url: "Dashboard/YearlyStats",
                        dataType: "json",
                        success: function(result) {
                            options.success(result);
                        }
                    });
                }
            }
        });

        $("#yearlyStats").kendoGrid({
            columns: [
                {
                    field: "Year",
                    title: "Year",
                    width: 250
                },
                {
                    field: "Submissions",
                    title: "Submissions",
                    width: 110
                },
                {
                    field: "Acceptances",
                    title: "Acceptances",
                    width: 110
                },
                {
                    field: "RejectionsForm",
                    title: "Rejections, Form",
                    width: 110
                },
                {
                    field: "RejectionsPersonal",
                    title: "Rejections, Personal",
                    width: 110
                },
                {
                    field: "AmountEarned",
                    title: "Amount Earned",
                    width: 110,
                    template: '#=AmountEarned.toFixed(2)#'
                },
            ],
            dataSource: _$dataSource,
            sortable: true,
            scrollable: false
        });
    },

    showStoryStats: function() {
        Grinder.Dashboard.showBusyIndicator();

        var _$dataSource;

        _$dataSource = new kendo.data.DataSource({
            schema: {
                model: {
                    id: "PieceID",
                    fields: {
                        PieceID: {},
                        Title: {},
                        Submissions: {},
                        Acceptances: {},
                        RejectionsForm: {},
                        RejectionsPersonal: {},
                        AmountEarned: {}
                    }
                }
            },
            sort: { field: "Title"},
            transport: {
                read: function(options) {
                    $.ajax({
                        url: "Dashboard/StoryStats",
                        dataType: "json",
                        success: function(result) {
                            options.success(result);
                        }
                    });
                }
            }
        });

        $("#storyStats").kendoGrid({
            columns: [
                {
                    field: "Title",
                    title: "Title",
                    width: 250
                },
                {
                    field: "Submissions",
                    title: "Submissions",
                    width: 110
                },
                {
                    field: "Acceptances",
                    title: "Acceptances",
                    width: 110
                },
                {
                    field: "RejectionsForm",
                    title: "Rejections, Form",
                    width: 110
                },
                {
                    field: "RejectionsPersonal",
                    title: "Rejections, Personal",
                    width: 110
                },
                {
                    field: "AmountEarned",
                    title: "Amount Earned",
                    width: 110,
                    template: '#=AmountEarned.toFixed(2)#'
                },
            ],
            dataSource: _$dataSource,
            sortable: true,
            scrollable: false
        });
    },

    showMarketStats: function() {
        Grinder.Dashboard.showBusyIndicator();

        var _$dataSource;

        _$dataSource = new kendo.data.DataSource({
            schema: {
                model: {
                    id: "MarketID",
                    fields: {
                        MarketID: {},
                        Name: {},
                        Submissions: {},
                        Acceptances: {},
                        RejectionsForm: {},
                        RejectionsPersonal: {},
                        AmountEarned: {}
                    }
                }
            },
            transport: {
                read: function(options) {
                    $.ajax({
                        url: "Dashboard/MarketStats",
                        dataType: "json",
                        success: function(result) {
                            options.success(result);
                            Grinder.Dashboard.hideBusyIndicator();
                        }
                    });
                }
            }
        });

        $("#marketStats").kendoGrid({
            columns: [
                {
                    field: "Name",
                    title: "Name",
                    template: "<a href='/Market/Index?id=#= MarketID #'>#= Name #</a>",
                    width: 250
                },
                {
                    field: "Submissions",
                    title: "Submissions",
                    width: 110
                },
                {
                    field: "Acceptances",
                    title: "Acceptances",
                    width: 110
                },
                {
                    field: "RejectionsForm",
                    title: "Rejections, Form",
                    width: 110
                },
                {
                    field: "RejectionsPersonal",
                    title: "Rejections, Personal",
                    width: 110
                },
                {
                    field: "AmountEarned",
                    title: "Amount Earned",
                    width: 110,
                    template: '#=AmountEarned.toFixed(2)#'
                },
            ],
            dataSource: _$dataSource,
            sortable: true,
            scrollable: false
        });
    },

    toggleYearlyStats: function() {
        if ($("#toggleYearlyStatsButton").text() == "[-]") {
            $("#yearlyStats").hide();
            $("#toggleYearlyStatsButton").text("[+]");
        } else {
            $("#yearlyStats").show();
            $("#toggleYearlyStatsButton").text("[-]");
        }
    },

    toggleStoryStats: function() {
        if ($("#toggleStoryStatsButton").text() == "[-]") {
            $("#storyStats").hide();
            $("#toggleStoryStatsButton").text("[+]");
        } else {
            $("#storyStats").show();
            $("#toggleStoryStatsButton").text("[-]");
        }
    },

    toggleMarketStats: function() {
        if ($("#toggleMarketStatsButton").text() == "[-]") {
            $("#marketStats").hide();
            $("#toggleMarketStatsButton").text("[+]");
        } else {
            $("#marketStats").show();
            $("#toggleMarketStatsButton").text("[-]");
        }
    }
};

Grinder.DashboardImport = Grinder.DashboardImport || {};
Grinder.DashboardImport = {
    initializePage: function () {
        $("#btnCancel").on("click", function () {
            Grinder.DashboardImport.cancelImport();
        });
    },

    cancelImport: function () {
        $("#dashboardContainer").show();
        $("#importFormContainer").hide();
    }
};
//create the area's namespace or get it if it already exists
Grinder.Index = Grinder.Index || {};
Grinder.Index = {

    initializePage: function () {
        Grinder.Index.showRecentActivity();
    },

    showRecentActivity: function () {
        $("#divRecentlyAddedMarketsTabArea").hide();
        $("#divRecentAddedTab").attr("class", "DefaultActivityInactiveTab");
        $("#divRecentActivityTabArea").show();
        $("#divRecentActivityTab").attr("class", "DefaultActivityActiveTab");
        $("#divMyMarketResponseTabArea").hide();
        $("#divMyMarketResponseTab").attr("class", "DefaultActivityInactiveTab");
    },

    showRecentlyAddedMarkets: function () {
        $("#divRecentlyAddedMarketsTabArea").show();
        $("#divRecentAddedTab").attr("class", "DefaultActivityActiveTab");
        $("#divRecentActivityTabArea").hide();
        $("#divRecentActivityTab").attr("class", "DefaultActivityInactiveTab");
        $("#divMyMarketResponseTabArea").hide();
        $("#divMyMarketResponseTab").attr("class", "DefaultActivityInactiveTab");
    },
    
    showMyMarketResponse: function () {
        $("#divRecentlyAddedMarketsTabArea").hide();
        $("#divRecentAddedTab").attr("class", "DefaultActivityInactiveTab");
        $("#divRecentActivityTabArea").hide();
        $("#divRecentActivityTab").attr("class", "DefaultActivityInactiveTab");
        $("#divMyMarketResponseTabArea").show();
        $("#divMyMarketResponseTab").attr("class", "DefaultActivityActiveTab");
    }
};
//create the area's namespace or get it if it already exists
Grinder.Market = Grinder.Market || {};
Grinder.Market = {
    initializePage: function () {
        var _$submissionsDataSource;

        //if ($("#IsLoggedIn").val() != null && $("#IsLoggedIn").val() == "True") {
        //    $("#DateSent").kendoDatePicker();
        //    $("#DateAcknowledged").kendoDatePicker();
        //    $("#DateReceived").kendoDatePicker();
        //}

        $("#suggestCorrectionWindow").kendoWindow({
            height: "330px",
            modal: true,
            resizable: false,
            title: "Suggest Market Correction",
            width: "770px",
            visible: false,
            draggable: false
        });

        $("#recentResponsesWindow").kendoWindow({
            height: "750px",
            modal: true,
            resizable: false,
            title: "Recent Responses for " + $("#MarketName").val(),
            width: "770px",
            visible: false,
            draggable: false
        });

        $("#submissionWindow").kendoWindow({
            height: "350px",
            modal: true,
            resizable: false,
            title: "New Submission for " + $("#MarketName").val(),
            width: "570px",
            visible: false,
            draggable: false
        });

        var ajaxDataRenderer = function(url, plot, options) {
            var ret = null;
            $.ajax({
                async: false,
                url: url,
                type: "GET",
                dataType: "json",
                success: function(data) {
                    ret = data;
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    alert('There was a problem fetching the chart data.');
                }
            });
            return ret;
        };

        var marketTurnAroundData = ajaxDataRenderer(_$marketRejectionsForChartURL + "?_='" + new Date().getTime());
        var marketRecencyData = ajaxDataRenderer(_$marketRecencyForChartURL + "?_='" + new Date().getTime());
        var marketSubRecencyData = ajaxDataRenderer(_$marketSubRecencyForChartURL + "?_='" + new Date().getTime());

        var pendingDaysXYPair = new Array();

         for(var i = 0; i < marketTurnAroundData.pendingDays.length; i++)
        {
            pendingDaysXYPair.push([marketTurnAroundData.pendingDays[i], 1]);
        }

        var rejectionDaysXYPair = [];
        var acceptanceDaysXYPair = [];
        var maxcount = 0;
        if (marketTurnAroundData.rejectionCount.length >= marketTurnAroundData.acceptanceCount.length)
        {
            maxcount = marketTurnAroundData.rejectionCount.length;
        }
        else
        {
            maxcount = marketTurnAroundData.acceptanceCount.length;
        }

        for (var i = 0; i < maxcount; i++)
        {
            rejectionDaysXYPair.push([i, marketTurnAroundData.rejectionCount[i]]);
            acceptanceDaysXYPair.push([i, marketTurnAroundData.acceptanceCount[i]]);
        }


        if (marketTurnAroundData.pendingDays[marketTurnAroundData.pendingDays.length-1] > maxcount)
            maxcount = marketTurnAroundData.pendingDays[marketTurnAroundData.pendingDays.length - 1];

        var myBarWidth = 573 / maxcount;
        if (myBarWidth < 3)
            myBarWidth = 3;

        $.jqplot('turnAroundChart', [acceptanceDaysXYPair, rejectionDaysXYPair, pendingDaysXYPair], {
            stackSeries: true,
            title: "Response Times for " + $("#MarketName").val(),
            series: [
                {
                    renderer: $.jqplot.BarRenderer,
                    rendererOptions:
                    {
                        fillToZero: true,
                        barWidth: myBarWidth //chosen by rough image size of that divided by max number
                    },
                    label: 'Acceptances',
                    color: $("#ColorAcceptance").val(),//'green',//'rgb(64,255,0)',
                    shadow: false
                },
                {
                    renderer: $.jqplot.BarRenderer,
                    rendererOptions:
                    {
                        fillToZero: true,
                        barWidth: myBarWidth //chosen by rough image size of that divided by max number
                    },
                    label: 'Rejections',
                    color: $("#ColorRejection").val(),//'red',//'rgb(179, 0, 0)',
                    shadow: false
                },
                {
                    label: 'My Pending',
                    color: $("#ColorPending").val(),//'purple',
                    
                    showLine: false,
                    disableStack: true,
                    shadow: false
                }
            ],
            legend: {
                show: true,
                placement: 'outsideGrid',
                location: 'ne'
            },
                axes: {
                xaxis: {
                    tickRenderer: $.jqplot.CanvasAxisTickRenderer,
                    tickOptions: {
                        showGridline: false
                    },
                    label: 'Response Time (Days)',
                    min: 0,
                    //max: maxcount+1
                },
                yaxis: {
                    tickRenderer: $.jqplot.CanvasAxisTickRenderer,
                    labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
                    min: 0,
                    label: '# of Submissions'
                }
            },
            cursor: {
                show: true,
                zoom: true,
                showTooltip: false
            }
        });

        //this is how the reverse chronological axis was handled
        //some people preferred this to chronological with zoom
        //so leaving this commented for now
        /*var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

        var ticks = new Array();
        var curMonth = new Date().getMonth();
        var curYear = new Date().getFullYear();
        var month = curMonth;

        ticks[0] = "Today";

        for (var i = 1; i < 363; i++) {
            var d = new Date();
            d.setDate(d.getDate() - i);

            if (month != d.getMonth()) {
                month = d.getMonth();

                if (month == curMonth && d.getFullYear() == curYear) {
                    ticks[i] = '';
                } else {
                    if (i > 10) {
                        ticks[i] = months[month] + ' ' + d.getFullYear();
                    }
                }
            } else {
                ticks[i] = '';
            }
        }*/

        var recencyRejectionDaysXYPair = [];
        var recencyAcceptanceDaysXYPair = [];

        var subRecencyRejectionDaysXYPair = [];
        var subRecencyAcceptanceDaysXYPair = [];
        var subRecencyPendingDaysXYPair = [];
        var subRecencyMyPendingDaysXYPair = [];


        var maxcount = 0;
        if (marketRecencyData.rejectionData.length >= marketRecencyData.acceptanceData.length) {
            maxcount = marketRecencyData.rejectionData.length;
        }
        else {
            maxcount = marketRecencyData.acceptanceData.length;
        }

        if (marketSubRecencyData.pendingData.length > maxcount)
            maxcount = marketSubRecencyData.pendingData.length;

        var TodayDate = new Date();
        TodayDate.setHours(0, 0, 0, 0);

        var myPendingIndex = marketTurnAroundData.pendingDays.length-1;

        for (var i = -1; i < 365; i++) {
            var DaysAgo = new Date(TodayDate.getFullYear(), TodayDate.getMonth(), TodayDate.getDate() - i, 0, 0, 0, 0);

            var thisRejectValue = 0;
            var thisAcceptValue = 0;

            var thisSubRejectValue = 0;
            var thisSubAcceptValue = 0;
            var thisSubPendingValue = 0;

            var iplus = i + 1; //the first value represents day -1, but we can't index on -1, so have to adjust when indexing

            if (i < maxcount)
            {
                thisRejectValue = marketRecencyData.rejectionData[iplus];
                thisAcceptValue = marketRecencyData.acceptanceData[iplus];

                thisSubRejectValue = marketSubRecencyData.rejectionData[iplus];
                thisSubAcceptValue = marketSubRecencyData.acceptanceData[iplus];;
                thisSubPendingValue = marketSubRecencyData.pendingData[iplus];;
            }
            recencyRejectionDaysXYPair.push([DaysAgo.toDateString(), thisRejectValue]);
            recencyAcceptanceDaysXYPair.push([DaysAgo.toDateString(), thisAcceptValue]);

            subRecencyRejectionDaysXYPair.push([DaysAgo.toDateString(), thisSubRejectValue]);
            subRecencyAcceptanceDaysXYPair.push([DaysAgo.toDateString(), thisSubAcceptValue]);
            subRecencyPendingDaysXYPair.push([DaysAgo.toDateString(), thisSubPendingValue]);

            if (myPendingIndex >= 0 && marketTurnAroundData.pendingDays[myPendingIndex] == i)
            {
                subRecencyMyPendingDaysXYPair.push([DaysAgo.toDateString(), 1]);
                myPendingIndex--;
            }
            
        }
        if (marketRecencyData.rejectionData.length > 0 || marketRecencyData.acceptanceData.length > 0) {
            $.jqplot('responseRecencyChart', [recencyAcceptanceDaysXYPair,recencyRejectionDaysXYPair], {
                stackSeries: true,
                title: "Response Timeline for " + $("#MarketName").val(),
                seriesDefaults: {
                    renderer: $.jqplot.BarRenderer,
                    rendererOptions:
                    {
                        fillToZero: true,
                        barWidth: 3
                    }
                },

                series: [
                    {
                        label: 'Acceptances',
                        color: $("#ColorAcceptance").val(),//'green',//'rgb(64,255,0)',
                        shadow: false
                    },
                    {
                        label: 'Rejections',
                        color: $("#ColorRejection").val(),//'red',//'rgb(179, 0, 0)',//'red',
                        shadow: false
                    }
                ],
                legend: {
                    show: true,
                    placement: 'outsideGrid',
                    location: 'ne'
                },
                axes: {
                    xaxis: {
                        //this is Turnaround Time
                        //tickRenderer: $.jqplot.CanvasAxisTickRenderer, //including this makes the x axis labels messy and unreadable, zoom broken
                        //min: 0,  //including this makes no discernible difference


                        //this is shared
                        tickOptions: {
                            showGridline: false
                        },

                        //renderer: $.jqplot.CategoryAxisRenderer, 
                        renderer: $.jqplot.DateAxisRenderer,
                        label: 'Response Timeline',
                        pad: 0,
                        max: new Date().toDateString()
                        //ticks: ticks 

                    },
                    yaxis: {
                        tickRenderer: $.jqplot.CanvasAxisTickRenderer,
                        labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
                        pad: 0,
                        min: 0,
                        label: '# of Reports (Past Year)'
                    }
                },
                cursor:
                {
                    show: true,
                    zoom: true,
                    showTooltip: false
                }
            });
        }


        //submission timeline

        if (marketSubRecencyData.rejectionData.length > 0 || marketSubRecencyData.acceptanceData.length > 0 || marketSubRecencyData.pendingData.length > 0) {
            $.jqplot('subRecencyChart', [subRecencyAcceptanceDaysXYPair, subRecencyPendingDaysXYPair, subRecencyRejectionDaysXYPair, subRecencyMyPendingDaysXYPair], {
                stackSeries: true,
                title: "Submission Timeline for " + $("#MarketName").val(),
    

                series: [
                    {
                        renderer: $.jqplot.BarRenderer,
                        rendererOptions:
                        {
                            fillToZero: true,
                            barWidth: 3
                        },
                        label: 'Acceptances',
                        color: $("#ColorAcceptance").val(),//'green',//'rgb(64,255,0)',//green
                        shadow: false
                    },
                    {
                        renderer: $.jqplot.BarRenderer,
                        rendererOptions:
                        {
                            fillToZero: true,
                            barWidth: 3
                        },
                        label: 'Pending',
                        color: $("#ColorPending").val(),//'purple',
                        shadow: false
                    },
                    {
                        renderer: $.jqplot.BarRenderer,
                        rendererOptions:
                        {
                            fillToZero: true,
                            barWidth: 3
                        },
                        label: 'Rejections',
                        color: $("#ColorRejection").val(),//'red',//'rgb(179, 0, 0)',//'red',
                        shadow: false
                    },
                    {
                        label: 'My Pending',
                        color: 'black',
                        showLine: false,
                        shadow: false,
                        disableStack: true
                    }
                ],
                legend: {
                    show: true,
                    placement: 'outsideGrid',
                    location: 'ne'
                },
                axes: {
                    xaxis: {

                        tickOptions: {
                            showGridline: false
                        },

                        //renderer: $.jqplot.CategoryAxisRenderer, 
                        renderer: $.jqplot.DateAxisRenderer,
                        label: 'Submission Timeline',
                        pad: 0,
                        max: new Date().toDateString()
                        //ticks: ticks 

                    },
                    yaxis: {
                        tickRenderer: $.jqplot.CanvasAxisTickRenderer,
                        labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
                        pad: 0,
                        min: 0,
                        label: '# of Reports (Past Year)'
                    }
                },
                cursor:
                {
                    show: true,
                    zoom: true,
                    showTooltip: false
                }
            });
        }

        _$submissionsDataSource = new kendo.data.DataSource({
            schema: {
                model: {
                    id: "SubmissionID",
                    fields: {
                        SubmissionID: {},
                        Title: {},
                        DateSent: { type: "date" },
                        DateReceived: { type: "date" },
                        DateHeldForConsideration: {type: "date"},
                        ResponseStatus: {},
                        DaysOut: {},
                        AverageReturnDays: {},
                        EstimatedReturn: {},
                        AverageReturnDifference: {},
                        EstimatedReturnDifference: {}
                    }
                }
            },
            sort: { field: "DateSent", dir: "desc" },
            transport: {
                read: function(options) {
                    $.ajax({
                        //data: { id: $("#MarketID").val() },
                        url: _$marketSubmissionForUser,
                        dataType: "json",
                    success: function(result) {
                        options.success(result);

                        if (result.length == 0)
                            $("#yourSubmissionsSection").hide();
                        }
                    });
                }
            }
        });

        $("#yourSubmissionsGrid").kendoGrid({
            columns: [
                {
                    field: "Title",
                    title: "Piece",
                    width: 230
                },
                {
                    field: "DateSent",
                    title: "Date Sent",
                    template: '#= kendo.toString(Grinder.Market.CheckNull(new Date(DateSent.getTime()+(DateSent.getTimezoneOffset()*60*1000))), "MMM d, yyyy" ) #',
                    width: 100
                },
                {
                    field: "DateHeldForConsideration",
                    title: "Date Held",
                    template: '#= kendo.toString(DateHeldForConsideration == null ? \'\' : (new Date(DateHeldForConsideration.getTime()+(DateHeldForConsideration.getTimezoneOffset()*60*1000))), "MMM d, yyyy" ) #',
                    width: 100
                },
                {
                    field: "DateReceived",
                    title: "Date Res'd",
                    template: '#= kendo.toString(DateReceived == null ? \'\' : (new Date(DateReceived.getTime()+(DateReceived.getTimezoneOffset()*60*1000))), "MMM d, yyyy" ) #',
                    width: 100
                },
                {
                    field: "ResponseStatus",
                    title: "Response",
                    template: "<span class='#= Grinder.SubmissionList.getCssClassBySubmissionStatus(DaysOut, AverageReturnDays, EstimatedReturn, StatusID) #'>#= ResponseStatus #</span>",

                },
                {
                    field: "DaysOut",
                    template: "<center>#= DaysOut #/#if(AverageReturnDays===null){#<span>?</span>#}else{##: AverageReturnDays ##}#/#if(EstimatedReturn===null){#<span>?</span>#}else{##: EstimatedReturn ##}#</center>",
                    title: "Days/Avg/Est",
                    width: 75
                },
                {
                    template: '<div style="text-align: center;"><a href="/Account/Submissions?id=#= SubmissionID #">Update</a></div>',
                    width: 70
                },
                {
                    template: '<img src="#= Grinder.SubmissionList.getNotesURL(Notes) #" title="#= Grinder.SubmissionList.getNotesText(Notes) #" alt="#= Grinder.SubmissionList.getNotesText(Notes) #" />',
                    width: 20
                }
            ],
            dataSource: _$submissionsDataSource,
            sortable: false,
            scrollable: false //always must be scrollable false or it breaks it into 2 tables
            //scrollable: true,
            //height: 210
        });

        if ($("DNQ").val() == "True") {
            $("#stuffToHideForDNQ").hide();
        }

        Grinder.Market.showSubRecencyChart();
    },
 
    showMarketCorrectionWindow: function() {
        _$kendoSuggestCorrectionWindow = _$suggestCorrectionWindow.getKendoWindow();
        _$kendoSuggestCorrectionWindow.center();
        _$kendoSuggestCorrectionWindow.open();
    },

  

    showRecencyChart: function() {
        _$responseRecencyChart.show();
        _$recencyChartTab.attr("class", "DefaultActivityActiveTab");
        _$turnAroundChart.hide();
        _$turnaroundChartTab.attr("class", "DefaultActivityInactiveTab");
        _$subRecencyChart.hide();
        _$subRecencyChartTab.attr("class", "DefaultActivityInactiveTab");

    },

    showTurnaroundChart: function() {
        _$turnAroundChart.show();
        _$turnaroundChartTab.attr("class", "DefaultActivityActiveTab");
        _$responseRecencyChart.hide();
        _$recencyChartTab.attr("class", "DefaultActivityInactiveTab");
        _$subRecencyChart.hide();
        _$subRecencyChartTab.attr("class", "DefaultActivityInactiveTab");

    },

    showSubRecencyChart: function () {
        _$subRecencyChart.show();
        _$subRecencyChartTab.attr("class", "DefaultActivityActiveTab");
        _$turnAroundChart.hide();
        _$turnaroundChartTab.attr("class", "DefaultActivityInactiveTab");
        _$responseRecencyChart.hide();
        _$recencyChartTab.attr("class", "DefaultActivityInactiveTab");

    },


    favoriteMarket: function () {
        $.ajax({
            async: false,
            type: "POST",
            dataType: "json",
            //data: { marketId: $("#MarketID").val() },
            url: _$marketFavoriteURL,
            error: function(xhr, ajaxOptions, thrownError) {
                alert('There was a problem. Please try again.');
            },
            success: function(msg) {
                if ($("#lbFavorite").html() == "Add to Favorites") {
                    $("#lbFavorite").html("Remove from Favorites");
                } else {
                    $("#lbFavorite").html("Add to Favorites");
                }
            }
        });
    },

    ignoreMarket: function () {
        $.ajax({
            async: false,
            type: "POST",
            dataType: "json",
            //data: { marketId: $("#MarketID").val() },
            url: _$marketIgnoreURL,
            error: function (xhr, ajaxOptions, thrownError) {
                alert('There was a problem. Please try again.');
            },
            success: function (msg) {
                if ($("#lbIgnore").html() == "Ignore Market") {
                    $("#lbIgnore").html("Unignore Market");
                } else {
                    $("#lbIgnore").html("Ignore Market");
                }
            }
        });
    },

    followMarket: function() {
        $.ajax({
            async: false,
            type: "POST",
            dataType: "json",
            //data: { marketId: $("#MarketID").val() },
            url: _$marketFollowURL,
            error: function (xhr, ajaxOptions, thrownError) {
                alert('There was a problem. Please try again.');
            },
            success: function (msg) {
                if ($("#lbFollow").html() == "Follow Market") {
                    $("#lbFollow").html("Unfollow Market");
                } else {
                    $("#lbFollow").html("Follow Market");
                }
            }
        });
    },

    suggestUpdate: function () {
        $.ajax({
            type: "POST",
            async: false,
            dataType: 'html',
            url: _$marketSuggestionURL,
            contentType: "application/json; charset=utf-8",
            success: function (data, status, jqXHR) {
                $("#marketProfileContainer").hide();
                $("#suggestCorrectionContainer").show();
                $("#suggestCorrectionContainer").html(data);
                $.validator.unobtrusive.parse($("#updateForm"));
            }
        });
    },

    cancelUpdate: function() {
        $("#marketProfileContainer").show();
        $("#suggestCorrectionContainer").html('');
        $("#suggestCorrectionContainer").hide();
    },

    CheckNull: function(val) {
        if (val == null)
            return '';
        else
            return val;
    }
};;
//create the area's namespace or get it if it already exists
Grinder.PaymentList = Grinder.PaymentList || {};
Grinder.PaymentList = {
    initializePage: function () {
        var _$busyIndicator = $("#busyIndicator");

        _$busyIndicator.kendoWindow({
            actions: {},
            height: "50px",
            modal: true,
            resizable: false,
            width: "170px",
            visible: false,
            title: $("#loadingText").val()//"Reticulating splines"
        });

        //Grinder.PaymentList.showPayments();

    },

    hideBusyIndicator: function () {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.close();
    },

    showBusyIndicator: function (message) {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.title(message);
        kendoWindow.center();
        kendoWindow.open();
    },

    showPayments: function () {
        Grinder.PaymentList.showBusyIndicator();

        var _$searchDataSource;
        _$searchDataSource = new kendo.data.DataSource({
            schema: {
                model: {
                    id: "PaymentID",
                    fields: {
                        PaymentID: {},
                        PieceID: {},
                        UserID: {},
                        MarketID: {},
                        SubmissionID: {},
                        PaymentDate: { type: "date" },
                        SubmissionDate: { type: "date"},
                        Note: {},
                        MarketName: {},
                        PieceTitle: {},

                    }
                }
            },
            sort: { field: "PaymentDate", dir: "desc" },
            transport: {
                read: function (options) {
                    var searchModel = {
                        PieceID: $("#PieceID").val(),
                        MarketID: $("#MarketID").val(),
                        StartDate: $("#StartDate").val(),
                        EndDate: $("#EndDate").val(),
                        Keyword: $("#Keyword").val()
                    };
                    $.ajax({
                        url: "Payments/SearchPayments",
                        data: searchModel,
                        dataType: "json",
                        success: function (result) {
                            options.success(result);
                            Grinder.PieceList.hideBusyIndicator();

                            let incomecount = 0;
                            let expensecount = 0;
                            let incomesum = 0;
                            let expensesum = 0;

                            if (result.length > 0) {

                                incomecount = result.map(o => o.IsExpense ? 0 : 1).reduce((a, c) => a + c);
                                expensecount = result.map(o => o.IsExpense ? 1 : 0).reduce((a, c) => a + c);

                                incomesum = result.map(o => o.IsExpense ? 0 : o.PaymentAmount).reduce((a, c) => a + c);
                                expensesum = result.map(o => o.IsExpense ? o.PaymentAmount : 0).reduce((a, c) => a + c);
                            }

                            $("#incomeLabel").html(incomecount + " income payment(s), total:  " + incomesum.toFixed(2));
                            $("#expenseLabel").html(expensecount + " expense payment(s), total: " + expensesum.toFixed(2));
                            $("#netLabel").html((incomecount + expensecount) + " overall payment(s), net total: " + (incomesum - expensesum).toFixed(2));
                        }
                    });
                }
            }  
        });

        UpdateTemplate = '<a href="javascript:Grinder.PieceList.editPaymentByID(#= PaymentID #)">Update</button>';

        $("#paymentsGrid").kendoGrid({
            columns: [
                {
                    field: "PaymentDate",
                    title: "Pay Date",
                    template: '#= kendo.toString(new Date(PaymentDate.getTime()+(PaymentDate.getTimezoneOffset()*60*1000)), "MMM d, yyyy" ) #',
                    width: 100
                },
                {
                    field: "MarketName",
                    title: "Market",
                    width: 100
                },
                {
                    field: "PieceTitle",
                    title: "Piece",
                    width: 100
                },
                {
                    field: "SubmissionDate",
                    title: "Sub Date",
                    template: '#= kendo.toString(new Date(SubmissionDate.getTime()+(SubmissionDate.getTimezoneOffset()*60*1000)), "MMM d, yyyy" ) #',
                    width: 100
                },
                {
                    field: "PaymentAmount",
                    title: "Amount",
                    template: '#if (IsExpense) {# #=((-PaymentAmount).toFixed(2))# #} else {# #=(PaymentAmount.toFixed(2))# #}  #',
                    width: 100
                },
                {
                    field: "Note",
                    title: "Note",
                    template: '#= Grinder.SubmissionList.getNoteDisplay(Note) #',
                    width: 100
                },
                {
                    template: "<a href='javascript:Grinder.PaymentList.editPaymentByID(#= PaymentID #)'>Update</a>",
                    width: 100
                }
            ],            dataSource: _$searchDataSource,
            sortable: true,
            scrollable: false
        });
    },

    editPaymentByID: function (id) {
        Grinder.PaymentList.editPayment(id);
    },

    editPayment: function (id) {
        $.ajax({
            type: "POST",
            async: false,
            dataType: 'html',
            url: ('/Account/Payments/Payment_Edit?id=' + id),
            contentType: "application/json; charset=utf-8",
            success: function (data, status, jqXHR) {
                $("#ListDiv").hide();
                $("#EditDiv").hide();
                $("#EditPayDiv").show();
                $("#EditPayDiv").html(data);
                $.validator.unobtrusive.parse($("#editPaymentForm"));

            }
        });
    },

    addPaymentBySubmissionId: function (id) {
        $.ajax({
            type: "POST",
            async: false,
            dataType: 'html',
            url: ('/Account/Payments/Payment_Edit?submissionId=' + id),
            contentType: "application/json; charset=utf-8",
            success: function (data, status, jqXHR) {
                $("#ListDiv").hide();
                $("#EditDiv").hide();
                $("#EditPayDiv").show();
                $("#EditPayDiv").html(data);
                $.validator.unobtrusive.parse($("#editPaymentForm"));

            }
        });
    }
};

Grinder.PaymentEdit = Grinder.PaymentEdit || {};
Grinder.PaymentEdit = {
    initializePage: function() {

        _$paymentsDataSource = new kendo.data.DataSource({
            schema: {
                model: {
                    id: "PaymentID",
                    fields: {
                        PaymentID: {},
                        UserID: {},
                        SubmissionID: {},
                        MarketID: {},
                        PaymentTableAmount: {},
                        OtherCurrencyCode: {},
                        OtherPaymentTableAmount: {},
                        IsExpense: {},
                        PaymentDate: { type: "date" },
                        Note: {}
                    }
                }
            },
            sort: { field: "PaymentDate", dir: "desc" },
            transport: {
                read: function (options) {
                    $.ajax({
                        url: _$submissionPaymentForUser,
                        dataType: "json",
                        success: function (result) {
                            options.success(result);
                        }
                    });
                }
            }
        });


        if ($("#PaymentID").val() == 0) $("#deletePayment").hide();

        $("#deleteConfirmPayment").kendoWindow({
            actions: {},
            height: "100px",
            modal: true,
            resizable: false,
            width: "370px",
            visible: false,
            title: "Confirm deletion"
        });

        $('#savePayment').on('click', function (e) {
            Grinder.Core.cancelEvent(e);
            var clientvalidate = true;

            var $theForm = $("#editPaymentForm");

            var TodayPlusOne = new Date();
            TodayPlusOne.setDate(TodayPlusOne.getDate() + 1);


            var dt = $("#PaymentDate").val();

            var timestamp = Date.parse(dt);
            if (isNaN(timestamp) === true) {
                clientvalidate = false;
            }

            var datepayment = new Date(dt);
            if (dt && dt.match(/\//g) && dt.match(/\//g).length == 1) {
                datepayment.setFullYear(new Date().getFullYear());
            }
            else if (dt && dt.match(/-/g) && dt.match(/-/g).length == 1) {
                datepayment.setFullYear(new Date().getFullYear());
            }

            if (!datepayment || datepayment.getFullYear() < 1969) {
                alert("Invalid Payment Date");
                clientvalidate = false;
            }

            if (datepayment > TodayPlusOne) {
                clientvalidate = false;
                alert("Dates cannot be more than one day in the future.");
            }

            
            $theForm.validate().settings.ignore = "";
            if (clientvalidate && $theForm.valid()) {
                Grinder.PaymentEdit.savePayment();
            }
        });
    },

    savePayment: function () {
        var data = {};

        data.PaymentID = $("#PaymentID").val();
        data.UserID = $("#UserID").val();
        data.SubmissionID = $("#SubmissionID").val();
        data.MarketID = $("#MarketID").val();
        data.PaymentTableAmount = $("#PaymentTableAmount").val();
        data.OtherCurrencyCode = $("#OtherCurrencyCode").val();
        data.OtherPayentAmount = $("#OtherPayentAmount").val();
        data.PaymentDate = $("#PaymentDate").val();
        data.Note = $("#Note").val();
        data.PaymentType = $("#PaymentType").val();
        //data.IsExpense = $("#IsExpense").is(":checked");

        

        $.ajax({
            type: "POST",
            async: false,
            data: JSON.stringify(data),
            dataType: 'html',
            url: ('/Account/Payments/SavePayment' ),
            contentType: "application/json; charset=utf-8",
            success: function (msg) {


                //$("#EditDiv").show();
                $("#EditPayDiv").html('');
                if (window.location.href.indexOf("/Account/Payments") > -1) {
                    Grinder.PaymentList.showPayments();
                    $("#ListDiv").show();

                }
                else {
                    Grinder.SubmissionList.editSubmissionByID(data.SubmissionID);
                }

            }
        });
    },

    confirmDeletePayment: function() {
        var kendoWindow = $("#deleteConfirmPayment").getKendoWindow();
        kendoWindow.center();
        kendoWindow.open();
    },

    deletePayment: function() {
        var paymentId = $("#PaymentID").val();
        var submissionId = $("#SubmissionID").val();
        $.ajax({
            type: "POST",
            url: "/Account/Payments/DeletePayment",
            data: { paymentId: paymentId },
            success: function () {
                var kendoWindow = $("#deleteConfirmPayment").getKendoWindow();
                kendoWindow.close();

                //$("#EditDiv").show();
                $("#EditPayDiv").html('');
                if (window.location.href.indexOf("/Account/Payments") > -1) {
                    Grinder.PaymentList.showPayments();
                    $("#ListDiv").show();
                }
                else {
                    Grinder.SubmissionList.editSubmissionByID(submissionId);
                }



            }
        });
    },

    cancelDelete: function() {
        var kendoWindow = $("#deleteConfirmPayment").getKendoWindow();
        kendoWindow.close();
    }
};;
//create the area's namespace or get it if it already exists
Grinder.PaymentList = Grinder.PaymentList || {};
Grinder.PaymentList = {
    initializePage: function () {
        var _$busyIndicator = $("#busyIndicator");

        _$busyIndicator.kendoWindow({
            actions: {},
            height: "50px",
            modal: true,
            resizable: false,
            width: "170px",
            visible: false,
            title: $("#loadingText").val()//"Reticulating splines"
        });

        //Grinder.PaymentList.showPayments();

    },

    hideBusyIndicator: function () {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.close();
    },

    showBusyIndicator: function (message) {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.title(message);
        kendoWindow.center();
        kendoWindow.open();
    },

    showPayments: function () {
        Grinder.PaymentList.showBusyIndicator();

        var _$searchDataSource;
        _$searchDataSource = new kendo.data.DataSource({
            schema: {
                model: {
                    id: "PaymentID",
                    fields: {
                        PaymentID: {},
                        PieceID: {},
                        UserID: {},
                        MarketID: {},
                        SubmissionID: {},
                        PaymentDate: { type: "date" },
                        SubmissionDate: { type: "date"},
                        Note: {},
                        MarketName: {},
                        PieceTitle: {},

                    }
                }
            },
            sort: { field: "PaymentDate", dir: "desc" },
            transport: {
                read: function (options) {
                    var searchModel = {
                        PieceIDFilter: $("#PieceIDFilter").val(),
                        OtherPartyNameFilter: $("#OtherPartyNameFilter").val(),
                        StartDate: $("#StartDate").val(),
                        EndDate: $("#EndDate").val(),
                        Keyword: $("#Keyword").val()
                    };
                    $.ajax({
                        url: "Payments/SearchPayments",
                        data: searchModel,
                        dataType: "json",
                        success: function (result) {
                            options.success(result);
                            Grinder.PieceList.hideBusyIndicator();

                            let incomecount = 0;
                            let expensecount = 0;
                            let incomesum = 0;
                            let expensesum = 0;

                            if (result.length > 0) {

                                incomecount = result.map(o => o.IsExpense ? 0 : 1).reduce((a, c) => a + c);
                                expensecount = result.map(o => o.IsExpense ? 1 : 0).reduce((a, c) => a + c);

                                incomesum = result.map(o => o.IsExpense ? 0 : o.PaymentAmount).reduce((a, c) => a + c);
                                expensesum = result.map(o => o.IsExpense ? o.PaymentAmount : 0).reduce((a, c) => a + c);
                            }

                            $("#incomeLabel").html(incomecount + " income payment(s), total:  " + incomesum.toFixed(2));
                            $("#expenseLabel").html(expensecount + " expense payment(s), total: " + expensesum.toFixed(2));
                            $("#netLabel").html((incomecount + expensecount) + " overall payment(s), net total: " + (incomesum - expensesum).toFixed(2));
                        }
                    });
                }
            }  
        });

        UpdateTemplate = '<a href="javascript:Grinder.PieceList.editPaymentByID(#= PaymentID #)">Update</button>';

        $("#paymentsGrid").kendoGrid({
            columns: [
                {
                    field: "PaymentDate",
                    title: "Pay Date",
                    template: '#= kendo.toString(new Date(PaymentDate.getTime()+(PaymentDate.getTimezoneOffset()*60*1000)), "MMM d, yyyy" ) #',
                    width: 100
                },
                {
                    field: "MarketName",
                    title: "Market",
                    width: 100
                },
                {
                    field: "PieceTitle",
                    title: "Piece",
                    width: 100
                },
                {
                    field: "SubmissionDate",
                    title: "Sub Date",
                    template: '#= kendo.toString(SubmissionDate == null ? \'\' : (new Date(SubmissionDate.getTime()+(SubmissionDate.getTimezoneOffset()*60*1000))), "MMM d, yyyy" ) #',
                    width: 100
                },
                {
                    field: "PaymentAmount",
                    title: "Amount",
                    template: '#if (IsExpense) {# #=((-PaymentAmount).toFixed(2))# #} else {# #=(PaymentAmount.toFixed(2))# #}  #',
                    width: 100
                },
                {
                    field: "Note",
                    title: "Note",
                    template: '#= Grinder.SubmissionList.getNoteDisplay(Note) #',
                    width: 100
                },
                {
                    template: "<a href='javascript:Grinder.PaymentList.editPaymentByID(#= PaymentID #)'>Update</a>",
                    width: 100
                }
            ],            dataSource: _$searchDataSource,
            sortable: true,
            scrollable: false
        });
    },

    editPaymentByID: function (id) {
        Grinder.PaymentList.editPayment(id);
    },

    editPayment: function (id) {
        $.ajax({
            type: "POST",
            async: false,
            dataType: 'html',
            url: ('/Account/Payments/Payment_Edit?id=' + id),
            contentType: "application/json; charset=utf-8",
            success: function (data, status, jqXHR) {
                $("#ListDiv").hide();
                $("#EditDiv").hide();
                $("#EditPayDiv").show();
                $("#EditPayDiv").html(data);
                $.validator.unobtrusive.parse($("#editPaymentForm"));

            }
        });
    },

    addPaymentBySubmissionId: function (id) {
        $.ajax({
            type: "POST",
            async: false,
            dataType: 'html',
            url: ('/Account/Payments/Payment_Edit?submissionId=' + id),
            contentType: "application/json; charset=utf-8",
            success: function (data, status, jqXHR) {
                $("#ListDiv").hide();
                $("#EditDiv").hide();
                $("#EditPayDiv").show();
                $("#EditPayDiv").html(data);
                $.validator.unobtrusive.parse($("#editPaymentForm"));

            }
        });
    },
    addPaymentWithoutSubmissionId: function () {
        $.ajax({
            type: "POST",
            async: false,
            dataType: 'html',
            url: ('/Account/Payments/Payment_Edit'),
            contentType: "application/json; charset=utf-8",
            success: function (data, status, jqXHR) {
                $("#ListDiv").hide();
                $("#EditDiv").hide();
                $("#EditPayDiv").show();
                $("#EditPayDiv").html(data);
                $.validator.unobtrusive.parse($("#editPaymentForm"));

            }
        });
    },

};

Grinder.PaymentEdit = Grinder.PaymentEdit || {};
Grinder.PaymentEdit = {
    initializePage: function() {

        _$paymentsDataSource = new kendo.data.DataSource({
            schema: {
                model: {
                    id: "PaymentID",
                    fields: {
                        PaymentID: {},
                        UserID: {},
                        SubmissionID: {},
                        MarketID: {},
                        PieceID: {},
                        PaymentTableAmount: {},
                        OtherCurrencyCode: {},
                        OtherPaymentTableAmount: {},
                        OtherPartyAltName: {},
                        IsExpense: {},
                        PaymentDate: { type: "date" },
                        Note: {}
                    }
                }
            },
            sort: { field: "PaymentDate", dir: "desc" },
            transport: {
                read: function (options) {
                    $.ajax({
                        url: _$submissionPaymentForUser,
                        dataType: "json",
                        success: function (result) {
                            options.success(result);
                        }
                    });
                }
            }
        });


        if ($("#PaymentID").val() == 0) $("#deletePayment").hide();

        $("#deleteConfirmPayment").kendoWindow({
            actions: {},
            height: "100px",
            modal: true,
            resizable: false,
            width: "370px",
            visible: false,
            title: "Confirm deletion"
        });

        $('#savePayment').on('click', function (e) {
            Grinder.Core.cancelEvent(e);
            var clientvalidate = true;

            var $theForm = $("#editPaymentForm");

            var TodayPlusOne = new Date();
            TodayPlusOne.setDate(TodayPlusOne.getDate() + 1);


            var dt = $("#PaymentDate").val();

            var timestamp = Date.parse(dt);
            if (isNaN(timestamp) === true) {
                clientvalidate = false;
            }

            var datepayment = new Date(dt);
            if (dt && dt.match(/\//g) && dt.match(/\//g).length == 1) {
                datepayment.setFullYear(new Date().getFullYear());
            }
            else if (dt && dt.match(/-/g) && dt.match(/-/g).length == 1) {
                datepayment.setFullYear(new Date().getFullYear());
            }

            if (!datepayment || datepayment.getFullYear() < 1969) {
                alert("Invalid Payment Date");
                clientvalidate = false;
            }

            if (datepayment > TodayPlusOne) {
                clientvalidate = false;
                alert("Dates cannot be more than one day in the future.");
            }

            var pubform = document.getElementById("notapublisherform");

            if (pubform != null) {

                var mid = $("#MarketID").val();
                var othername = $("#OtherPartyAltName").val();
                var ismarket = pubform.classList.contains("hidden");

                if (ismarket) {
                    if (mid === null || mid=== 0|| mid === "0") {
                        clientvalidate = false;
                        alert("You must select an other entity for the payment.");
                    }

                    document.getElementById("OtherPartyAltName").value = "";
                }

                if (!ismarket) {
                    if (othername === null || othername === "") {
                        clientvalidate = false;
                        alert("You must select an other entity for the payment.")
                    }

                    document.getElementById("MarketID").value = 0;

                }
            }

            
            $theForm.validate().settings.ignore = "";
            if (clientvalidate && $theForm.valid()) {
                Grinder.PaymentEdit.savePayment();
            }
        });
    },

    savePayment: function () {
        var data = {};

        data.PaymentID = $("#PaymentID").val();
        data.UserID = $("#UserID").val();
        data.SubmissionID = $("#SubmissionID").val();
        data.MarketID = $("#MarketID").val();
        data.PieceID = $("#PieceID").val();
        data.PaymentTableAmount = $("#PaymentTableAmount").val();
        data.OtherCurrencyCode = $("#OtherCurrencyCode").val();
        data.OtherPayentAmount = $("#OtherPayentAmount").val();
        data.PaymentDate = $("#PaymentDate").val();
        data.Note = $("#Note").val();
        data.PaymentType = $("#PaymentType").val();
        data.OtherPartyAltName = $("#OtherPartyAltName").val();
        //data.IsExpense = $("#IsExpense").is(":checked");

        

        $.ajax({
            type: "POST",
            async: false,
            data: JSON.stringify(data),
            dataType: 'html',
            url: ('/Account/Payments/SavePayment' ),
            contentType: "application/json; charset=utf-8",
            success: function (msg) {
                if (window.location.href.indexOf("LogPayment") > -1) {
                    window.location = "/Account/Payments";
                }
                else {
                    $("#EditPayDiv").html('');
                    if (window.location.href.indexOf("/Account/Payments") > -1) {
                        Grinder.PaymentList.showPayments();
                        $("#ListDiv").show();

                    }
                    else {
                        Grinder.SubmissionList.editSubmissionByID(data.SubmissionID);
                    }
                }



            }
        });
    },

    confirmDeletePayment: function() {
        var kendoWindow = $("#deleteConfirmPayment").getKendoWindow();
        kendoWindow.center();
        kendoWindow.open();
    },

    deletePayment: function() {
        var paymentId = $("#PaymentID").val();
        var submissionId = $("#SubmissionID").val();
        $.ajax({
            type: "POST",
            url: "/Account/Payments/DeletePayment",
            data: { paymentId: paymentId },
            success: function () {
                var kendoWindow = $("#deleteConfirmPayment").getKendoWindow();
                kendoWindow.close();

                //$("#EditDiv").show();
                $("#EditPayDiv").html('');
                if (window.location.href.indexOf("/Account/Payments") > -1) {
                    Grinder.PaymentList.showPayments();
                    $("#ListDiv").show();
                }
                else {
                    Grinder.SubmissionList.editSubmissionByID(submissionId);
                }



            }
        });
    },

    cancelDelete: function() {
        var kendoWindow = $("#deleteConfirmPayment").getKendoWindow();
        kendoWindow.close();
    },

    clickIsMarket: function () {
        $("#notapublisherform").addClass("hidden");
        $("#publisherform").removeClass("hidden");
    },

    clickIsNotMarket: function () {
        $("#notapublisherform").removeClass("hidden");
        $("#publisherform").addClass("hidden");
    }
};;
/// <reference path="C:\Users\DSteffen\Documents\tfs\Grinder\Websites\DiabolicalPlots.TheGrinder\DiabolicalPlots.TheGrinder.Web\Areas/Account/Views/Profile/Alerts.cshtml" />
//create the area's namespace or get it if it already exists
Grinder.PieceList = Grinder.PieceList || {};
Grinder.PieceList = {
    initializePage: function () {
        var _$busyIndicator = $("#busyIndicator");

        _$busyIndicator.kendoWindow({
            actions: {},
            height: "50px",
            modal: true,
            resizable: false,
            width: "170px",
            visible: false,
            title: $("#loadingText").val()//"Reticulating splines"
        });

        Grinder.PieceList.showPieces();

        $("#excludeRetired").on("click", function () {
            Grinder.PieceList.showPieces();
        });

        $("#excludePublished").on("click", function () {
            Grinder.PieceList.showPieces();
        });

        $("#excludePending").on("click", function () {
            Grinder.PieceList.showPieces();
        });


        $("#excludeToBePublished").on("click", function () {
            Grinder.PieceList.showPieces();
        });



        $("#excludeInExclusivity").on("click", function () {
            Grinder.PieceList.showPieces();
        });

        $("#excludeFiction").on("click", function () {
            Grinder.PieceList.showPieces();
        });

        $("#excludePoetry").on("click", function () {
            Grinder.PieceList.showPieces();
        });

    },

    hideBusyIndicator: function () {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.close();
    },

    showBusyIndicator: function (message) {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.title(message);
        kendoWindow.center();
        kendoWindow.open();
    },
    
    showPieces: function () {
        Grinder.PieceList.showBusyIndicator();

        var _$searchDataSource;

        _$searchDataSource = new kendo.data.DataSource({
            schema: {
                model: {
                    id: "PieceID",
                    fields: {
                        PieceID: {},
                        UserID: {},
                        Title: {},
                        StoryTypeID: {},
                        StoryType: {},
                        LengthTypeID: {},
                        LengthType: {},
                        GenreID: {},
                        Genre: {},
                        SubGenreID: {},
                        SubGenre: {},
                        StoryStyleID: {},
                        StoryStyle: {},
                        SubjectTypeID: {},
                        SubjectType: {},
                        Notes: {},
                        DateCompleted: {},
                        Published: {},
                        Submitted: {},
                        Retired: {},
                        Translation: {},
                        WordCount: {},
                        LineCount: {},
                        CurrentSubmissionCount: {},
                        AllTimeSubmissionCount: {},
                        TwelveMonthSubmissionCount: {}
                    }
                }
            },
            transport: {
                read: function (options) {
                    $.ajax({
                        url: "Pieces/SearchPieces",
                        data: {mid: $("#MarketID").val(),
                            excludePublished: $("#excludePublished").is(":checked"),
                            excludeRetired: $("#excludeRetired").is(":checked"),
                            excludePending: $("#excludePending").is(":checked"),
                            excludeToBePublished: $("#excludeToBePublished").is(":checked"),
                            excludeInExclusivity: $("#excludeInExclusivity").is(":checked"),
                            excludeFiction: $("#excludeFiction").is(":checked"),
                            excludePoetry: $("#excludePoetry").is(":checked")
                        },
                        dataType: "json",
                        success: function (result) {
                            console.log($("#MarketID").val());
                            options.success(result);
                            Grinder.PieceList.hideBusyIndicator();
                            $("#resultCountLabel").html(result.length + " piece(s) shown");
                        }
                    });
                }
            }
        });


        RunSearchTemplate = '<a href="/Search/ByFilter?id=#= PieceID #">Run Search</button>';
        UpdateTemplate = '<a href="javascript:Grinder.PieceList.editPieceByID(#= PieceID #)">Update</button>';
        if ($("#MarketID").val() != 0) {
            RunSearchTemplate = '<a href="/Account/Submissions/LogSubmission?id=' + $("#MarketID").val() + '&pid=#= PieceID #">Log Submission</button>';
            //UpdateTemplate = '';
        }

        $("#piecesGrid").kendoGrid({
            columns: [
                {
                    field: "Title",
                    title: "Title",
                    //template: '# if(IncompleteInfo){<span>#= Title #**</span>}else{<span>#= Title #</span>} #',
                    width: 200
                },
                {
                    field: "StoryType",
                    title: "Type",
                    width: 120
                },
                {
                    field: "WordCount",
                    title: "Word Count",
                    width: 120
                },
                {
                    field: "LineCount",
                    title: "Line Count",
                    width: 120
                },
                {
                    title: "Submissions*",
                    template: '[#= CurrentSubmissionCount #/#= TwelveMonthSubmissionCount #/#= AllTimeSubmissionCount #]',
                    widht: 100
                },
                {
                    template: RunSearchTemplate,
                    width: 100
                },
                {
                    template: UpdateTemplate,
                    width: 20
                }
            ],
            dataSource: _$searchDataSource,
            sortable: true,
            scrollable: false
        });
    },
    
    addPiece: function () {
        var piece = {
            PieceID: 0
        };

        Grinder.PieceList.editPiece(piece);
    },

    showReadyToSubmit: function (data) {
        $("#excludeRetired").prop("checked", true);
        $("#excludePublished").prop("checked", false);
        $("#excludePending").prop("checked", true);
        $("#excludeToBePublished").prop("checked", true);
        $("#excludeInExclusivity").prop("checked", true);
        Grinder.PieceList.showPieces();
    },

    showReadyToSubmitNoReprint: function (data) {
        $("#excludeRetired").prop("checked", true);
        $("#excludePublished").prop("checked", true);
        $("#excludePending").prop("checked", true);
        $("#excludeToBePublished").prop("checked", true);
        $("#excludeInExclusivity").prop("checked", true);
        Grinder.PieceList.showPieces();
    },



    editPieceByID: function (id) {
        _$searchDataSource = $("#piecesGrid").data("kendoGrid").dataSource;

        var piece = _$searchDataSource.get(id);
        Grinder.PieceList.editPiece(piece);
    },

    editPiece: function (piece) {
        $.ajax({
            type: "POST",
            async: false,
            dataType: 'html',
            url: ('/Account/Pieces/Piece_Edit?id=' + piece.PieceID),
            contentType: "application/json; charset=utf-8",
            success: function (data, status, jqXHR) {
                $("#ListDiv").hide();
                $("#EditDiv").show();
                $("#EditDiv").html(data);
                $.validator.unobtrusive.parse($("#editPieceForm"));

             }
        });
    }
};

Grinder.PieceEdit = Grinder.PieceEdit || {};
Grinder.PieceEdit = {
    initializePage: function() {

        _$submissionsDataSource = new kendo.data.DataSource({
            schema: {
                model: {
                    id: "SubmissionID",
                    fields: {
                        SubmissionID: {},
                        Title: {},
                        DateSent: { type: "date" },
                        DateReceived: { type: "date" },
                        DateHeldForConsideration: { type: "date" },
                        ResponseStatus: {},
                        DaysOut: {},
                        AverageReturnDays: {},
                        EstimatedReturn: {},
                        AverageReturnDifference: {},
                        EstimatedReturnDifference: {}
                    }
                }
            },
            sort: { field: "DateSent", dir: "desc" },
            transport: {
                read: function (options) {
                    $.ajax({
                        //data: { id: $("#MarketID").val() },
                        url: _$marketSubmissionForUser,
                        dataType: "json",
                        success: function (result) {
                            options.success(result);

                            if (result.length == 0)
                                $("#yourSubmissionsSection").hide();
                        }
                    });
                }
            }
        });

        $("#yourSubmissionsGrid").kendoGrid({
            columns: [
                {
                    field: "MarketName",
                    title: "Market",
                    width: 230
                },
                {
                    field: "DateSent",
                    title: "Date Sent",
                    template: '#= kendo.toString(Grinder.Market.CheckNull(new Date(DateSent.getTime()+(DateSent.getTimezoneOffset()*60*1000))), "MMM d, yyyy" ) #',
                    width: 100
                },
                {
                    field: "DateHeldForConsideration",
                    title: "Date Held",
                    template: '#= kendo.toString(DateHeldForConsideration == null ? \'\' : (new Date(DateHeldForConsideration.getTime()+(DateHeldForConsideration.getTimezoneOffset()*60*1000))), "MMM d, yyyy" ) #',
                    width: 100
                },
                {
                    field: "DateReceived",
                    title: "Date Res'd",
                    template: '#= kendo.toString(DateReceived == null ? \'\' : (new Date(DateReceived.getTime()+(DateReceived.getTimezoneOffset()*60*1000))), "MMM d, yyyy" ) #',
                    width: 100
                },
                {
                    field: "ResponseStatus",
                    title: "Response",
                    template: "<span class='#= Grinder.SubmissionList.getCssClassBySubmissionStatus(DaysOut, AverageReturnDays, EstimatedReturn, StatusID) #'>#= ResponseStatus #</span>",

                },
                {
                    field: "DaysOut",
                    template: "<center>#= DaysOut #/#if(AverageReturnDays===null){#<span>?</span>#}else{##: AverageReturnDays ##}#/#if(EstimatedReturn===null){#<span>?</span>#}else{##: EstimatedReturn ##}#</center>",
                    title: "Days/Avg/Est",
                    width: 75
                },
                {
                    template: '<div style="text-align: center;"><a href="/Account/Submissions?id=#= SubmissionID #">Update</a></div>',
                    width: 70
                },
                {
                    template: '<img src="#= Grinder.SubmissionList.getNotesURL(Notes) #" title="#= Grinder.SubmissionList.getNotesText(Notes) #" alt="#= Grinder.SubmissionList.getNotesText(Notes) #" />',
                    width: 20
                }
            ],
            dataSource: _$submissionsDataSource,
            sortable: false,
            scrollable: false //always must be scrollable false or it breaks it into 2 tables
            //scrollable: true,
            //height: 210
        });

        if ($("#PieceID").val() == 0) $("#deletePiece").hide();

        $("#deleteConfirm").kendoWindow({
            actions: {},
            height: "100px",
            modal: true,
            resizable: false,
            width: "370px",
            visible: false,
            title: "Confirm deletion"
        });

        $('#savePiece').on('click', function (e) {
            Grinder.Core.cancelEvent(e);

            var $theForm = $("#editPieceForm");
            
            $theForm.validate().settings.ignore = "";
            if ($theForm.valid()) {
                Grinder.PieceEdit.savePiece();
            }
        });
    },

    savePiece: function () {
        var data = {};

        data.PieceID = $("#PieceID").val();
        data.Title = $("#Title").val();
        data.StoryTypeID = $("#StoryTypeID").val();
        data.LengthTypeID = $("#LengthTypeID").val();
        data.SelectedGenres= $("#SelectedGenres option").map(function () { return this.selected ? this.value : null; }).get(),
        data.Notes = $("#Notes").val();
        data.Keywords = $("#Keywords").val();
        data.DateCompleted = $("#DateCompleted").val();
        data.Published = $("#Published").is(":checked");
        data.Submitted = $("#Submitted").is(":checked");
        data.Retired = $("#Retired").is(":checked");
        data.Translation = $("#Translation").is(":checked");
        data.WordCount = $("#WordCount").val();
        data.LineCount = $("#LineCount").val();
        

        $.ajax({
            type: "POST",
            async: false,
            data: JSON.stringify(data),
            dataType: 'html',
            url: ('/Account/Pieces/SavePiece'),
            contentType: "application/json; charset=utf-8",
            success: function (msg) {

                $("#EditDiv").show();
                $("#EditDiv").html('');

                if (window.location.href.indexOf("/Account/Pieces") > -1) {
                    Grinder.PieceList.showPieces();
                }
                else {
                    option = document.createElement('option');
                    msgobject = JSON.parse(msg);
                    option.text = msgobject.title;
                    option.value = msgobject.rowAffected;
                    dropdown = document.getElementById("PieceID");
                    dropdown.options.add(option);
                    dropdown.value = msgobject.rowAffected;
                }

                $("#ListDiv").show();

            }
        });
    },

    confirmDeletePiece: function() {
        var kendoWindow = $("#deleteConfirm").getKendoWindow();
        //kendoWindow.title(message);
        kendoWindow.center();
        kendoWindow.open();
    },

    deletePiece: function() {
        var pieceId = $("#PieceID").val();
        $.ajax({
            type: "POST",
            url: "/Account/Pieces/DeletePiece",
            data: { pieceId: pieceId },
            success: function () {
                var kendoWindow = $("#deleteConfirm").getKendoWindow();
                kendoWindow.close();

                $("#ListDiv").show();
                $("#EditDiv").show();
                $("#EditDiv").html('');
                Grinder.PieceList.showPieces();
            }
        });
    },

    cancelDelete: function() {
        var kendoWindow = $("#deleteConfirm").getKendoWindow();
        kendoWindow.close();
    }
};;
//create the area's namespace or get it if it already exists
Grinder.ProfileEdit = Grinder.ProfileEdit || {};
Grinder.ProfileEdit = {
    initializePage: function () {

        $('#saveProfile').on('click', function (e) {
            Grinder.Core.cancelEvent(e);

            var $theForm = $("#editProfileForm");

            $theForm.validate().settings.ignore = "";
            if ($theForm.valid()) {
                Grinder.ProfileEdit.saveProfile();
            }
        });
    },

    saveProfile: function () {
        var data = {};

        data.CurrentPassword = $("#CurrentPassword").val();
        data.NewPassword = $("#NewPassword").val();
        data.ConfirmNewPassword = $("#ConfirmNewPassword").val();
        data.FirstName = $("#FirstName").val();
        data.LastName = $("#LastName").val();
        data.Pseudonym = $("#Pseudonym").val();
        data.Newsletter = $("#Newsletter").is(":checked");
        data.Brag = $("#Brag").is(":checked");
        //data.MultiCurrency = $("#MultiCurrency").is(":checked");
        data.PrimaryCurrencyCode = $("#PrimaryCurrencyCode").val();
        data.ColorRejection = $("#ColorRejection").val();
        data.ColorAcceptance = $("#ColorAcceptance").val();
        data.ColorPending = $("#ColorPending").val();
        data.EmailAddress = $("#EmailAddress").val();
        data.DefaultLanguage = $("#DefaultLanguage").val();
        data.FuzzyMaxLimit = $("#FuzzyMaxLimit").val()

        $.ajax({
            type: "POST",
            async: false,
            data: JSON.stringify(data),
            url: ('/Account/Profile/SaveProfile'),
            contentType: "application/json; charset=utf-8",
            success: function (msg) {
                if (msg.success) {
                    var kendoWindow = $("#siteMessageWindow").getKendoWindow();
                    $("#siteMessageBody").html("Profile saved!");
                    kendoWindow.center();
                    kendoWindow.open();
                } else {
                    var kendoWindow = $("#siteMessageWindow").getKendoWindow();
                    $("#siteMessageBody").html(msg.errorMessage);
                    kendoWindow.center();
                    kendoWindow.open();
                }
            }
        });
    }
};
//create the area's namespace or get it if it already exists
Grinder.ReminderList = Grinder.ReminderList || {};
Grinder.ReminderList = {
    initializePage: function () {
        var _$busyIndicator = $("#busyIndicator");

        _$busyIndicator.kendoWindow({
            actions: {},
            height: "50px",
            modal: true,
            resizable: false,
            width: "170px",
            visible: false,
            title: $("#loadingText").val()//"Reticulating splines"
        });

        Grinder.ReminderList.showReminders();

    },

    hideBusyIndicator: function () {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.close();
    },

    showBusyIndicator: function (message) {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.title(message);
        kendoWindow.center();
        kendoWindow.open();
    },

    showReminders: function () {
        Grinder.ReminderList.showBusyIndicator();

        var _$searchDataSource;
        _$searchDataSource = new kendo.data.DataSource({
            schema: {
                model: {
                    id: "ReminderID",
                    fields: {
                        ReminderID: {},
                        ReminderText: {},
                        Descriptor: {},
                        IntervalName: {}
                    }
                }
            },
            sort: { field: "ReminderID" },
            transport: {
                read: function (options) {
                    $.ajax({
                        url: "Reminders/SearchReminders",
                        success: function (result) {
                            options.success(result);
                            Grinder.ReminderList.hideBusyIndicator();

                            
                        }
                    });
                }
            }  
        });

        $("#remindersGrid").kendoGrid({
            columns: [
                {
                    field: "IntervalName",
                    title: "Type",
                    width: 10
                },
                {
                    field: "Descriptor",
                    title: "Detail",
                    width: 100
                },
                {
                    field: "ReminderText",
                    title: "Reminder Text",
                    width: 100
                },
                {
                    template: "<a href='/Account/Reminders/DeleteReminder?reminderId=#= ReminderID #' onclick='return confirm(\"Are you sure you want to delete this item?\");'>Delete</a>",
                    width: 10
                }
            ],
            dataSource: _$searchDataSource,
            sortable: true,
            scrollable: false
        });
    }

};
;
//create the area's namespace or get it if it already exists
Grinder.SearchByName = Grinder.SearchByName || {};
Grinder.SearchByName = {
    initializePage: function() {
        $("#searchCriteria").keypress(function(e) {
            var code = e.keyCode || e.which;
            if (code == 13) {
                Grinder.SearchByName.doSearch();
            }
        });

        _$busyIndicator.kendoWindow({
            actions: {},
            height: "50px",
            modal: true,
            resizable: false,
            width: "170px",
            visible: false,
            title: $("#loadingText").val()
        });

        _$noResults.kendoWindow({
            height: "50px",
            modal: true,
            resizable: false,
            width: "500px",
            visible: false,
            title: "Search Error"
        });

        _$minLength.kendoWindow({
            height: "50px",
            modal: true,
            resizable: false,
            width: "500px",
            visible: false,
            title: "Search Error"
        });

        _$tooManyResults.kendoWindow({
            height: "50px",
            modal: true,
            resizable: false,
            width: "500px",
            visible: false,
            title: "Search Error"
        });

    },

    hideBusyIndicator: function() {
        var kendoWindow = _$busyIndicator.getKendoWindow();
        kendoWindow.close();
    },

    showBusyIndicator: function(message) {
        var kendoWindow = _$busyIndicator.getKendoWindow();
        kendoWindow.title(message);
        kendoWindow.center();
        kendoWindow.open();
    },

    doSearch: function() {
        if ($("#searchCriteria").val().length > 1) {
            Grinder.SearchByName.showBusyIndicator();

            _$searchDataSource = new kendo.data.DataSource({
                schema: {
                    model: {
                        id: "MarketID",
                        fields: {
                            MarketID: {},
                            Name: {},
                            Genre: {},
                            LengthType: {},
                            PayScale: {},
                            PayScaleNumeric: {},
                            DNQ: {},
                            TempClosed: {},
                            PermClosed: {},
                            AverageReturnDays: {}
                        }
                    }
                },
                transport: {
                    read: function (options) {
                        $.ajax({
                            data: { queryString: $("#searchCriteria").val() },
                            url: _$searchByNameUrl,
                            dataType: "json",
                            success: function(result) {
                                options.success(result);
                                Grinder.SearchByName.hideBusyIndicator();

                                if (result.length == 0) {
                                    _$gridSearchResults.hide();
                                    var kendoWindow = _$noResults.getKendoWindow();
                                    kendoWindow.center();
                                    kendoWindow.open();
                                } else {
                                    _$gridSearchResults.show();
                                }
                            }
                        });
                    }
                }
            });


            _$gridSearchResults.kendoGrid({
                sortable: true,
                columns: [
                    {
                        field: "Name",
                        title: "Market Name",
                        template: "<a href='#= Grinder.SearchByName.getMarketLink(MarketID) #'>#= Name #</a>" + (!$("#adminPath").val() ? "" : " <a href='" + $("#adminPath").val() + "?id=#=MarketID#'><img height='18px' src='/Images/actionadventure.png'></a>")
                    },
                    {
                        template: "<center><img src='/Images/#= Grinder.SearchByName.showMarketStatusIcon(TempClosed, PermClosed, DNQ) #' height='18px' alt='#= Grinder.SearchByName.showMarketStatusText(TempClosed, PermClosed, DNQ) #' title='#= Grinder.SearchByName.showMarketStatusText(TempClosed, PermClosed, DNQ) #'/></center>",
                        width: '18px'
                    },
                    {
                        field: "Genre",
                        title: "Genres",
                        template: "#= Grinder.SearchByName.showIcons(Genre) #",
                        sortable: false
                    },
                    {
                        field: "LengthType",
                        title: "Lengths",
                        template: "#= Grinder.SearchByName.showIcons(LengthType) #",
                        sortable: false
                    },
                    {
                        field: "AverageReturnDays",
                        title: "Avg Response Days",
                        template: "#= Grinder.SearchByName.showResponseTime(AverageReturnDays) #"
                    }
                ],
                dataSource: _$searchDataSource,
                sortable: true,
                scrollable: false
            });
        } else {
            var kendoWindow = _$minLength.getKendoWindow();
            kendoWindow.center();
            kendoWindow.open();
        }
    },
    
    getMarketLink: function (marketId) {
        var autoLog = $("#autoLog").val() == "True";

        if (autoLog) {
            return '../Account/Submissions/LogSubmission?id=' + marketId;
        } else {
            return '../Market/Index?id=' + marketId;
        }
    },

    showMarketStatusIcon: function(temp, perm, dnq) {
        if (dnq)
            return "DNQIcon.png";
        else if (perm)
            return "PermIcon.png";
        else if (temp)
            return "TempIcon.png";
        else {
            return "OpenIcon.png";
        }
    },

    showMarketStatusText: function(temp, perm, dnq) {
        if (dnq)
            return "Does Not Qualify";
        else if (perm)
            return "Permanently Closed";
        else if (temp)
            return "Temporarily Closed";
        else {
            return "Open";
        }
    },


    showPayText: function (data) {
        if (data == -2) {
            return "?";
        }
        else if (data == -1) {
            return "0";
        }
        else if (data == 0) {
            return "<1";
        }
        else {
            return data;
        }
    },

    showIcons: function(data) {
        var items = data.split(',');
        var result = '';

        for (var i = 0; i < items.length; i++) {
            if (items[i] != undefined && items[i].length > 0)
                result = result + '<img class="MarketSearchIcon" alt="' + items[i] + '" title="' + items[i] + '" src="/Images/' + items[i].replace(' ', '').replace('/', '') + '.png" style="border-width:0px;"/>';
        }

        return result;
    },

    showResponseTime: function(data) {
        if (data != "9999") {
            return data + " days";
        } else {
            return "No Data";
        }
    },
};

Grinder.SearchByFilter = Grinder.SearchByFilter || {};
Grinder.SearchByFilter = {    
    initializePage: function () {
        $("#busyIndicator").kendoWindow({
            actions: {},
            height: "50px",
            modal: true,
            resizable: false,
            width: "170px",
            visible: false,
            title: $("#loadingText").val()
        });

        $("#insufficientSearchCritieria").kendoWindow({
            height: "50px",
            modal: true,
            resizable: false,
            width: "500px",
            visible: false,
            title: "Search Error"
        });

        $("#tooManyResults").kendoWindow({
            height: "50px",
            modal: true,
            resizable: false,
            width: "500px",
            visible: false,
            title: "Search Error"
        });

        $("#helpDiv").kendoWindow({
            height: "500px",
            modal: true,
            resizable: false,
            width: "800px",
            visible: false,
            title: "Advanced Search Help"
        });

        if ($("#IsLoggedIn").val() == "True") {
            $("#ExcludeIgnored").removeAttr("disabled");
            $("#ExcludeNonFavorites").removeAttr("disabled");
            $("#ExcludeWherePending").removeAttr("disabled");
            $("#ExcludeWhereSubmittedPieceID").removeAttr("disabled");
        }

    },
    
    hideBusyIndicator: function() {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.close();
    },

    showBusyIndicator: function(message) {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.title(message);
        kendoWindow.center();
        kendoWindow.open();
    },

    showHideHelp: function() {
        var kendoWindow = $("#helpDiv").getKendoWindow();
        kendoWindow.center();
        kendoWindow.open();
    },

    doSearch: function() { 
        var $searchDataSource;


        Grinder.SearchByFilter.showBusyIndicator();

        var queryModel =
        {
            SelectedGenres: $("#SelectedGenres option").map(function () { return this.selected ? this.value : null; }).get(),
            StyleID: $("#StyleID").val(),
            PoetrySearch: $("#PoetrySearch").val(),
            Paying: $("#Paying")[0] ? $("#Paying")[0].checked : false,
            SubjectID: $("#SubjectID").val(),
            WordCount: $("#WordCount").val(),
            LineCount: $("#LineCount").val(),
            PayScaleID: $("#PayScaleID").val(),
            PayScaleNumeric: $("#PayScaleNumeric").val(),
            PayScaleNumericReprint: $("#PayScaleNumericReprint").val(),
            SubmissionTypeID: $("#SubmissionTypeID").val(),
            MaxAvgResponseDays: $("#MaxAvgResponseDays").val(),
            MarketQualificationID: $("#MarketQualificationID").val(),
            ReprintType: $("#ReprintType").val(),
            AcceptsTranslations: $("#AcceptsTranslations")[0] ? $("#AcceptsTranslations")[0].checked : false,
            AcceptsSimultaneous: $("#AcceptsSimultaneous")[0] ? $("#AcceptsSimultaneous")[0].checked : false,
            AcceptsMultiple: $("#AcceptsMultiple")[0] ?  $("#AcceptsMultiple")[0].checked : false,
            ShowOnlyAnthologies: $("#ShowOnlyAnthologies")[0] ?  $("#ShowOnlyAnthologies")[0].checked : false,
            ShowOnlyContests: $("#ShowOnlyContests")[0] ?  $("#ShowOnlyContests")[0].checked : false,
            ExcludeIgnored: $("#ExcludeIgnored")[0] ? $("#ExcludeIgnored")[0].checked: null,
            ExcludeNonFavorites: $("#ExcludeNonFavorites")[0] ? $("#ExcludeNonFavorites")[0].checked : null,
            ExcludeTempClosed: $("#ExcludeTempClosed")[0].checked,
            ExcludePermClosed: $("#ExcludePermClosed")[0].checked,
            ExcludeFeeBased: $("#ExcludeFeeBased")[0].checked,
            ExcludeMandatoryNewsletter: $("#ExcludeMandatoryNewsletter")[0].checked,
            ExcludeBadContract: $("#ExcludeBadContract")[0].checked,
            ExcludeAIAllowed: $("#ExcludeAIAllowed")[0].checked,
            ExcludeWherePending: $("#ExcludeWherePending")[0]?$("#ExcludeWherePending")[0].checked:null,
            ExcludeWhereSubmittedPieceID: $("#ExcludeWhereSubmittedPieceID") ? $("#ExcludeWhereSubmittedPieceID").val() : null,
            FuzzyMaxLimit: $("#FuzzyMaxLimit").val(),
            Keywords: $("#Keywords") ? $("#Keywords").val() : null,
            RememberAdvancedSearchSettings: $("#RememberAdvancedSearchSettings")[0] ? $("#RememberAdvancedSearchSettings")[0].checked : null,
            SortBy: $("#SortBy").val()
        };


        $searchDataSource = new kendo.data.DataSource({
                schema: {
                        model: {
                                id: "MarketID",
                                fields: {
                                        MarketID: {},
                                        Name: {},
                                        Genre: {},
                                        LengthType: {},
                                        PayScale: {},
                                        PayScaleNumeric: {},
                                        DNQ: {},
                                        TempClosed: {},
                                        PermClosed: {},
                                        AverageReturnDays: {},
                                        LimitedDemographic: {},
                                        MarketUserNote: {},
                                        SearchByPieceID: {},
                                        RelationshipTypeID: {}
                        }
                }
        },
                transport: {
                    read: function (options) {
                        //C# has issues receiving empty list, just put a dummy value in
                        if (queryModel.SelectedGenres.length == 0)
                        {
                            queryModel.SelectedGenres = [-1];
                        }
                        $.ajax({
                            type: "POST",
                            data: JSON.stringify(queryModel),
                            url: "/Search/Byfilter/Search",
                            dataType: "json",
                            contentType: "application/json; charset=utf-8",
                            success: function(result) {
                            options.success(result);
                            Grinder.SearchByFilter.hideBusyIndicator();


                            $("#advancedResultCountLabel").html(result.length + " result(s) shown");

                    }
                    });
                }
        }
        });

        $("#gridSearchResults").kendoGrid({
            sortable: true,
            columns: [
                {
                    title: "Piece Priority",
                    template: "#if (Grinder.SearchByFilter.IsLoggedIn() & SearchByPieceID != 0 ) {#<button type='button' aria-pressed='#= (RelationshipTypeID == -1) #' alt='Mark Unsuitable' title='Mark Unsuitable' id='thumbdown_#= MarketID #' onclick='Grinder.SearchByFilter.clickPiecePriority(#= MarketID #, \"Unsuitable\")' style='border:none;background:none;' ><img style='width:25px;' id='img_thumbdown_#= MarketID #' src='#= Grinder.SearchByFilter.getInitialButtonImgName(\"Unsuitable\", MarketID, RelationshipTypeID ) #' /></button><button type='button' aria-pressed='#= (RelationshipTypeID == 1) #' alt='Mark Preferred' title='Mark Preferred' id='thumbup_#= MarketID #' onclick='Grinder.SearchByFilter.clickPiecePriority(#= MarketID #, \"Preferred\")' style='width:25px;border:none;background:none;'><img style='width:25px;' id='img_thumbup_#= MarketID #' src='#= Grinder.SearchByFilter.getInitialButtonImgName(\"Preferred\", MarketID, RelationshipTypeID ) #' /></button> <div style='display:none;'><input tabindex='-1' type='radio' id='unsuitable_#= MarketID #' name='piecepriority_#= MarketID #' value='unsuitable_#= MarketID #' onclick='Grinder.SearchByFilter.updatePiecePriority(#= MarketID #, #= SearchByPieceID #, \"Unsuitable\")' #= Grinder.SearchByFilter.getradiochecked(RelationshipTypeID, 'Unsuitable') # ><input tabindex='-1' type='radio' id='neutral_#= MarketID #' name='piecepriority_#= MarketID #' value='neutral_#= MarketID #'onclick='Grinder.SearchByFilter.updatePiecePriority(#= MarketID #, #= SearchByPieceID #, \"Neutral\")' #= Grinder.SearchByFilter.getradiochecked(RelationshipTypeID, 'Neutral') # ><input tabindex='-1' type='radio' id='preferred_#= MarketID #' name='piecepriority_#= MarketID #' value='preferred_#= MarketID #' onclick='Grinder.SearchByFilter.updatePiecePriority(#= MarketID #, #= SearchByPieceID #, \"Preferred\")' #= Grinder.SearchByFilter.getradiochecked(RelationshipTypeID, 'Preferred') # ></div>  #} #"
                },
                {
                    field: "Name",
                    title: "Market Name",
                    template: "<a href='/Market/Index?id=#= MarketID #" + ($("#ExcludeWhereSubmittedPieceID").val() == "0" ? "" : ("&pid=" + $("#ExcludeWhereSubmittedPieceID").val())) + "' target='_blank'>#= Name # </a>#if ( RelationshipTypeID == 1 ){# <img style='width:15px;' src='/Images/thumbupblack.png' alt='Preferred' title='Preferred' > #} ##if ( IsKeywordMatch ){# <img style='width:15px;' src='/Images/KeywordMatch.png' alt='Keyword Match' title='Keyword Match' > #} #"
                },
                {
                    template: "<center><img src='/Images/#= Grinder.SearchByFilter.showMarketStatusIcon(TempClosed, PermClosed, DNQ) #' height='18px' alt='#= Grinder.SearchByFilter.showMarketStatusText(TempClosed, PermClosed, DNQ) #' title='#= Grinder.SearchByFilter.showMarketStatusText(TempClosed, PermClosed, DNQ) #'/></center>",
                    width: '18px'
                },
                {
                    field: "Genre",
                    title: "Genres",
                    template: "#= Grinder.SearchByFilter.showIcons(Genre) #",
                    sortable: false
                },
                {
                    field: "LengthType",
                    title: "Lengths",
                    template: "#= Grinder.SearchByFilter.showIcons(LengthType) #",
                    sortable: false
                },
                {
                    field: "PayScaleNumeric",
                    title: $("#PoetrySearch").val() == "True" ? "Pay/poem" : "Pay(¢/word)",
                    template: "#= DisplayPayFromPayScale #",
                    sortable:
                        {
                            compare: function (a, b, descending) {


                                var aNum = a.PayScaleNumeric;
                                var bNum = b.PayScaleNumeric;

                                if (aNum > bNum) {
                                    return -1;
                                }
                                else if (aNum < bNum) {
                                    return 1;
                                }
                                else {
                                    return 0;
                                }
                            }
                        }
                },
                {
                    field: "AverageReturnDays",
                    title: "Avg Response",
                    template: "#= Grinder.SearchByFilter.showResponseTime(AverageReturnDays) #"
                },
                {
                    template: '<img src="#= Grinder.SearchByFilter.getLimitedDemographicURL(LimitedDemographic) #" title="#= Grinder.SearchByFilter.getLimitedDemographicText(LimitedDemographic) #" alt="#= Grinder.SearchByFilter.getLimitedDemographicText(LimitedDemographic) #" />',
                    width: 20
                },
                {
                    template: '<img src="#= Grinder.SearchByFilter.getNotesURL(MarketUserNote) #" title="#= Grinder.SearchByFilter.getNotesText(MarketUserNote) #" alt="#= Grinder.SearchByFilter.getNotesText(MarketUserNote) #" />',
                    width: 20
                },
                {
                    template: '#if (Grinder.SearchByFilter.IsLoggedIn()) {# <button class="imagebutton" style="padding:0;border:none;background:none;" alt="Ignore this market in all future searches" title="Ignore this market in all future searches" id="ignorebutton_#= MarketID #" onclick="Grinder.SearchByFilter.ignoreMarket(#= MarketID #)"><img src="/Images/Ignore.png" /></button> #} #'
                }
            ],
            dataSource: $searchDataSource,
            sortable: true,
            scrollable: false
        });
    },
    getInitialButtonImgName(priority, marketId, relationshipTypeId) {
        switch (relationshipTypeId) {
            case -1:
                return Grinder.SearchByFilter.getButtonImgName(priority, marketId, "unsuitable");
            case 0:
                return Grinder.SearchByFilter.getButtonImgName(priority, marketId, "neutral");
            case 1:
                return Grinder.SearchByFilter.getButtonImgName(priority, marketId, "preferred");
        }
    },
    getButtonImgName(priority, marketId, currentpriority) {
        if (currentpriority == null) {
            currentpriority = this.getradioValueByName("piecepriority_" + marketId);
        }

        switch (priority) {
            case "Unsuitable":
                if (currentpriority.startsWith("unsuitable")){
                    return "/Images/thumbdownblack.png"
                }
                return "/Images/thumbdowngray.png";
            case "Preferred":
                if (currentpriority.startsWith("preferred")){
                    return "/Images/thumbupblack.png"
                }
                return "/Images/thumbupgray.png";
        }

    },

    clickPiecePriority: function (marketId, priority) {
        currentpriority = this.getradioValueByName("piecepriority_" + marketId).substring(0,7);

        switch (currentpriority) {
            case "unsuita":
                switch (priority) {
                    case "Unsuitable":
                        document.getElementById("neutral_" + marketId).click();
                        break;
                    case "Preferred":
                        document.getElementById("preferred_" + marketId).click();
                        break;
                }
                break;
            case "neutral":
                switch (priority) {
                    case "Unsuitable":
                        document.getElementById("unsuitable_" + marketId).click();
                        break;
                    case "Preferred":
                        document.getElementById("preferred_" + marketId).click();
                        break;
                }
                break;
            case "preferr":
                switch (priority) {
                    case "Unsuitable":
                        document.getElementById("unsuitable_" + marketId).click();
                        break;
                    case "Preferred":
                        document.getElementById("neutral_" + marketId).click();
                        break;

                }
                break;
        }

        //update image and pressed status of Unsuitable button
        var buttonname = Grinder.SearchByFilter.getButtonImgName("Unsuitable", marketId);
        document.getElementById("img_thumbdown_" + marketId).src = buttonname
        if (buttonname.includes("black")) {
            document.getElementById("thumbdown_" + marketId).setAttribute("aria-pressed", "true");
        }
        else {
            document.getElementById("thumbdown_" + marketId).setAttribute("aria-pressed", "false");
        }

        buttonname = Grinder.SearchByFilter.getButtonImgName("Preferred", marketId);
        if (buttonname.includes("black")) {
            document.getElementById("thumbup_" + marketId).setAttribute("aria-pressed", "true");
        }
        else {
            document.getElementById("thumbup_" + marketId).setAttribute("aria-pressed", "false");
        }

        document.getElementById("img_thumbup_" + marketId).src = Grinder.SearchByFilter.getButtonImgName("Preferred", marketId);


    },

    getradioValueByName: function (name) {
        var radios = document.getElementsByName(name);

        for (var i = 0, length = radios.length; i < length; i++) {
            if (radios[i].checked) {
                return radios[i].value;
            }
        }
        return "";
    },

    getradiochecked: function (relationshipTypeId, priority) {
        switch (relationshipTypeId) {
            case -1:
                if (priority == "Unsuitable") {
                    return "checked";
                }
                break;
            case 0:
                if (priority == "Neutral") {
                    return "checked";
                }
                break;
            case 1:
                if (priority == "Preferred") {
                    return "checked";
                }
                break;
        }
        return "";

    },

    IsLoggedIn: function () {
        if ($("#IsLoggedIn").val() == "True") {
            return true;
        }
        else {
            return false;
        }
    },

    //call this with any piece priority radio button press
    updatePiecePriority: function (marketId, pieceId, priority) {

        $.ajax({
            async: false,
            type: "POST",
            dataType: "json",
            data: { marketId: marketId, pieceId:pieceId, priority:priority },
            url: "/Market/UpdatePiecePriority",
            error: function (xhr, ajaxOptions, thrownError) {
                alert('There was a problem. Please try again.');
            },
            success: function (msg) {
                //some success indicator?
            }
        });

    },

    ignoreMarket: function (marketId) {
        if (confirm("Are you sure you want to ignore this market in all future searches?")) {
            $.ajax({
                async: false,
                type: "POST",
                dataType: "json",
                data: { marketId: marketId },
                url: "/Market/Ignore",
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('There was a problem. Please try again.');
                },
                success: function (msg) {
                    document.getElementById("ignorebutton_" + marketId).style.visibility = "hidden";
                }
            });
        }
    },


    getNotesURL: function (notes) {
        if (notes == "" || notes == null)
            return "/Images/NoNotes.png";
        else
            return "/Images/Notes.png";
    },

    getNotesText: function (notes) {
        if (notes == "" || notes == null) {
            if ($("#IsLoggedIn").val() == "True")
            {
                return "You have made no private notes about this market.";
            }
            else {
                return "You must log in to make private notes about a market.";
            }
        }
        else
            return "Your private note: " + notes;
    },

    getLimitedDemographicURL: function (notes) {
        if (notes == "" || notes == null)
            return "/Images/NoLimitedDemographic.png";
        else
            return "/Images/LimitedDemographic.png";
    },

    getLimitedDemographicText: function (notes) {
        if (notes == "" || notes == null)
            return "No Limited Demographic (anyone may submit)";
        else
            return "Limited Demographic: " + notes;
    },

    showMarketStatusIcon: function(temp, perm, dnq) {
        if (dnq)
            return "DNQIcon.png";
        else if (perm)
            return "PermIcon.png";
        else if (temp)
            return "TempIcon.png";
        else {
            return "OpenIcon.png";
        }
    },

    showMarketStatusText: function(temp, perm, dnq) {
        if (dnq)
            return "Does Not Qualify";
        else if (perm)
            return "Permanently Closed";
        else if (temp)
            return "Temporarily Closed";
        else {
            return "Open";
        }
    },

    showPayText: function (data) {
        
        if ($("#PoetrySearch").val() == "True")
        {
            return data;

        }

        if (data === -2) {
            return "?";
        }
        else if (data == -1) {
            return "0";
        }
        else if (data == 0) {
            return "<1";
        }
        else {
            return data;
        }
    },
    showIcons: function(data) {
        var items = data.split(',');
        var result = '';

        for (var i = 0; i < items.length; i++) {
            if (items[i] != undefined && items[i].length > 0)
                result = result + '<img class="MarketSearchIcon" alt="' + items[i] + '" title="' + items[i] + '" src="/Images/' + items[i].replace(' ', '').replace('/', '') + '.png" style="border-width:0px;"/>';
        }

        return result;
    },

    showResponseTime: function(data) {
        if (data != "9999") {
            return data + " days";
        } else {
            return "No Data";
        }
    }
};

Grinder.SearchByAlpha = Grinder.SearchByAlpha || {};
Grinder.SearchByAlpha = {
    initializePage: function () {
        $("#busyIndicator").kendoWindow({
            actions: {},
            height: "50px",
            modal: true,
            resizable: false,
            width: "170px",
            visible: false,
            title: $("#loadingText").val()
        });

        $("#noResults").kendoWindow({
            height: "50px",
            modal: true,
            resizable: false,
            width: "500px",
            visible: false,
            title: "Search Error"
        });
    },
    
    hideBusyIndicator: function() {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.close();
    },

    showBusyIndicator: function(message) {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.title(message);
        kendoWindow.center();
        kendoWindow.open();
    },

    showMarkets: function (page) {
        var $searchDataSource;
        Grinder.SearchByAlpha.showBusyIndicator();

        $searchDataSource = new kendo.data.DataSource({
            schema: {
                model: {
                    id: "MarketID",
                    fields: {
                        MarketID: {},
                        Name: {},
                        Genre: {},
                        LengthType: {},
                        PayScale: {},
                        PayScaleNumeric: {},
                        DNQ: {},
                        TempClosed: {},
                        PermClosed: {},
                        AverageReturnDays: {}
                    }
                }
            },
            transport: {
                read: function(options) {
                    $.ajax({
                            data: { page: page },
                            url: "/Search/ByAlpha/Search",
                            dataType: "json",
                    success: function(result) {
                            options.success(result);
                            Grinder.SearchByAlpha.hideBusyIndicator();

                            if (result.length == 0) {
                                $("#gridSearchResults").hide();
                                var kendoWindow = $("#noResults").getKendoWindow();
                                kendoWindow.center();
                                kendoWindow.open();
                            } else {
                                $("#gridSearchResults").show();
                            }
                        }
                    });
                }
            }
        });

        $("#gridSearchResults").kendoGrid({
            sortable: true,
            columns: [
                {
                    field: "Name",
                    title: "Market Name",
                    template: "<a href='/Market/Index?id=#= MarketID #'>#= Name #</a>"
            },
                {
                    template: "<center><img src='/Images/#= Grinder.SearchByAlpha.showMarketStatusIcon(TempClosed, PermClosed, DNQ) #' height='18px' alt='#= Grinder.SearchByAlpha.showMarketStatusText(TempClosed, PermClosed, DNQ) #' title='#= Grinder.SearchByAlpha.showMarketStatusText(TempClosed, PermClosed, DNQ) #'/></center>",
                    width: '18px'
                },
                {
                    field: "Genre",
                    title: "Genres",
                    template: "#= Grinder.SearchByAlpha.showIcons(Genre) #",
                    sortable: false
                },
                {
                    field: "LengthType",
                    title: "Lengths",
                    template: "#= Grinder.SearchByAlpha.showIcons(LengthType) #",
                    sortable: false
                },
                {
                    field: "AverageReturnDays",
                    title: "Avg Response Days",
                    template: "#= Grinder.SearchByAlpha.showResponseTime(AverageReturnDays) #"
                }
            ],
            dataSource: $searchDataSource,
            sortable: true,
            scrollable: false
        });
    },

    showMarketStatusIcon: function(temp, perm, dnq) {
        if (dnq)
            return "DNQIcon.png";
        else if (perm)
            return "PermIcon.png";
        else if (temp)
            return "TempIcon.png";
        else {
            return "OpenIcon.png";
        }
    },

    showMarketStatusText: function(temp, perm, dnq) {
        if (dnq)
            return "Does Not Qualify";
        else if (perm)
            return "Permanently Closed";
        else if (temp)
            return "Temporarily Closed";
        else {
            return "Open";
        }
    },


    showPayText: function (data) {
        if (data == -2) {
            return "?";
        }
        else if (data == -1) {
            return "0";
        }
        else if (data == 0) {
            return "<1";
        }
        else {
            return data;
        }
    },
    showIcons: function(data) {
        var items = data.split(',');
        var result = '';

        for (var i = 0; i < items.length; i++) {
            if (items[i] != undefined && items[i].length > 0)
                result = result + '<img class="MarketSearchIcon" alt="' + items[i] + '" title="' + items[i] + '" src="/Images/' + items[i].replace(' ', '').replace('/', '') + '.png" style="border-width:0px;"/>';
        }

        return result;
    },

    showResponseTime: function (data) {
        if (data != "9999") {
            return data + " days";
        } else {
            return "No Data";
        }
    }
};;
//create the area's namespace or get it if it already exists
Grinder.SubmissionList = Grinder.SubmissionList || {};
Grinder.SubmissionList = {
    initializePage: function () {
        var _$busyIndicator = $("#busyIndicator");

        _$busyIndicator.kendoWindow({
            actions: {},
            height: "50px",
            modal: true,
            resizable: false,
            width: "170px",
            visible: false,
            title: $("#loadingText").val()
        });

        var $HasSavedSearch = $("#SavedSearch_HasSavedSearch").val() == "True";
        var $PendingResponse = $("#SavedSearch_PendingResponse") == "True";
        var $PendingQuery = $("#SavedSearch_PendingQuery") == "True";
        //var $PendingShortListed = $("#SavedSearch_PendingShortListed") == "True";
        var $Accepted = $("#SavedSearch_Accepted") == "True";
        var $RewriteRequest = $("#SavedSearch_RewriteRequest") == "True";
        var $RejectionForm = $("#SavedSearch_RejectionForm") == "True";
        var $RejectionPersonal = $("#SavedSearch_RejectionPersonal") == "True";
        var $Withdrawal = $("#SavedSearch_Withdrawal") == "True";
        var $LostReturned = $("#SavedSearch_LostReturned") == "True";
        var $NeverResponded = $("#SavedSearch_NeverResponded") == "True";
        var $PieceID = $("#SavedSearch_PieceID").val();
        var $MarketID = $("#SavedSearch_MarketID").val();

        var $ViewSubmissionId = $("#ViewSubmissionId").val();

        if ($PendingResponse != null && $PendingResponse == "True") {
            $('#StatusPendingResponse').prop('checked', true);
        }

        if ($PendingQuery != null && $PendingQuery == "True") {
            $('#StatusPendingQuery').prop('checked', true);
        }

        //if ($PendingShortListed != null && $PendingShortListed == "True") {
        //    $('#StatusPendingShortlisted').prop('checked', true);
        //}

        if ($Accepted != null && $Accepted == "True") {
            $('#StatusAccepted').prop('checked', true);
        }

        if ($RewriteRequest != null && $RewriteRequest == "True") {
            $('#StatusRewriteRequested').prop('checked', true);
        }

        if ($RejectionForm != null && $RejectionForm == "True") {
            $('#StatusRejectionForm').prop('checked', true);
        }

        if ($RejectionPersonal != null && $RejectionPersonal == "True") {
            $('#StatusRejectionPersonal').prop('checked', true);
        }

        if ($Withdrawal != null && $Withdrawal == "True") {
            $('#StatusWithdrawal').prop('checked', true);
        }

        if ($LostReturned != null && $LostReturned == "True") {
            $('#StatusLostReturned').prop('checked', true);
        }

        if ($NeverResponded != null && $NeverResponded == "True") {
            $('#StatusNeverResponded').prop('checked', true);
        }

        if ($PieceID != null) {
            $('#PieceID').val(" + $PieceID + ");
        }

        if ($MarketID != null) {
            $('#MarketID').val(" + $MarketID + ");
        }

        var formCheckBoxes = $.find('input');
        $.uniform.update(formCheckBoxes);

        if ($HasSavedSearch) {
            Grinder.SubmissionList.showSubmissions();
        }

        $("#EditDiv").hide();
        $("#MarketSearchDiv").hide();

        if ($ViewSubmissionId != "0") {
            // We've got a bad ass over here.

            var sub = { SubmissionID: $ViewSubmissionId };
            Grinder.SubmissionList.editSubmission(sub);
        }
    },

    hideBusyIndicator: function () {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.close();
    },

    showBusyIndicator: function (message) {
        var kendoWindow = $("#busyIndicator").getKendoWindow();
        kendoWindow.title(message);
        kendoWindow.center();
        kendoWindow.open();
    },

    validateSubmissionForm: function (isNewSubmission) {
        var valid = true;
        var dateSent = new Date($("#DateSent").val());
        var dateAcknowledged = new Date($("#DateAcknowledged").val());
        var dateReceived = new Date($("#DateReceived").val());

        if (dateSent == "Invalid Date") valid = false;
        if (dateSent > addDays(today(), 2)) valid = false;
        if (dateAcknowledged != "Invalid Date" && dateAcknowledged < dateSent) valid = false;
        if (dateReceived != "Invalid Date" && dateAcknowledged != "Invalid Date" && dateReceived < dateAcknowledged) valid = false;
        if (dateReceived != "Invalid Date" && dateReceived < dateSent) valid = false;

        return valid;
    },

    closeLogSubmission: function (result) {
        $("#submissionWindowStatus").val(result);

        _$kendoSubmissionPopup.close();
    },

    addSubmission: function () {
        $.ajax({
            type: "POST",
            async: false,
            dataType: 'html',
            url: ('../Account/Submissions/Submission_Add_MarketSearch'),
            contentType: "application/json; charset=utf-8",
            success: function (data, status, jqXHR) {
                $("#EditDiv").hide();
                $("#ListDiv").hide();
                $("#MarketSearchDiv").show();
                $("#MarketSearchDiv").html(data);
                $.validator.unobtrusive.parse($("#editSubmissionForm"));
            }
        });
    },

    editSubmissionByID: function (id) {
        _$searchDataSource = $("#submissionsGrid").data("kendoGrid").dataSource;

        var submission = _$searchDataSource.get(id);
        Grinder.SubmissionList.editSubmission(submission);
    },

    editSubmission: function (submission) {
        $.ajax({
            type: "POST",
            async: false,
            dataType: 'html',
            url: ('/Account/Submissions/Submission_Edit?id=' + submission.SubmissionID),
            contentType: "application/json; charset=utf-8",
            success: function (data, status, jqXHR) {
                $("#ListDiv").hide();
                $("#EditDiv").show();
                $("#EditDiv").html(data);
                $.validator.unobtrusive.parse($("#editSubmissionForm"));
            }
        });
    },

    showSubmissions: function () {
        var $searchDataSource;

        Grinder.SubmissionList.showBusyIndicator();

        var model = {
            StatusPendingResponse: $("#StatusPendingResponse")[0].checked,
            StatusPendingQuery: $("#StatusPendingQuery")[0].checked,
            //StatusPendingShortlisted: $("#StatusPendingShortlisted")[0].checked,
            StatusAccepted: $("#StatusAccepted")[0].checked,
            StatusRewriteRequested: $("#StatusRewriteRequested")[0].checked,
            StatusRejectionForm: $("#StatusRejectionForm")[0].checked,
            StatusRejectionPersonal: $("#StatusRejectionPersonal")[0].checked,
            StatusWithdrawal: $("#StatusWithdrawal")[0].checked,
            StatusLostReturned: $("#StatusLostReturned")[0].checked,
            StatusNeverResponded: $("#StatusNeverResponded")[0].checked,
            StatusAcceptedNotPublished: $("#StatusAcceptedNotPublished")[0].checked,
            StatusAcceptedPublishedNotPaid: $("#StatusAcceptedPublishedNotPaid")[0].checked,
            RememberSettings: $("#RememberSettings")[0].checked,
            PieceID: $("#FilterPieceID").val(),
            MarketID: $("#FilterMarketID").val(),
            DateType: $("#FilterDateType").val(),
            StartDate: $("#FilterStartDate").val(),
            PublishedLanguage: $("#PublishedLanguage").val(),
            EndDate: $("#FilterEndDate").val()
        };

        $searchDataSource = new kendo.data.DataSource({
            schema: {
                total: "total",
                model: {
                    id: "SubmissionID",
                    fields: {
                        SubmissionID: {},
                        PieceID: {},
                        MarketID: {},
                        Title: {},
                        DateAcknowledged: { type: "date" },
                        DateSent: { type: "date" },
                        DateReceived: { type: "date" },
                        DateHeldForConsideration: {type: "date"},
                        DaysOut: {},
                        AverageReturnDays: {},
                        EstimatedReturn: {},
                        StatusID: {},
                        ResponseStatus: {},
                        AverageReturnDifference: {},
                        EstimatedReturnDifference: {},
                        PaymentAmount: {},
                        FeeAmount: {},
                        DateOfPayment: { type: "date" },
                        DateOfPublication: { type: "date" },
                        Notes: {}
                    }
                }
            },
            transport: {
                read: function (options) {
                    $.ajax({
                        data: model,
                        url: "Submissions/SearchSubmissions",
                        dataType: "json",
                        success: function (result) {
                            options.success(result.submissions);
                            Grinder.SubmissionList.hideBusyIndicator();
                            $("#resultCount").text(result.total + " results found");
                        }
                    });
                }
            },
            //serverPaging: true,
            //pageSize: 10
        });

        $("#submissionsGrid").kendoGrid({
            columns: [
                {
                    field: "Title",
                    title: "Piece",
                    width: 110
                },
                {
                    field: "MarketName",
                    title: "Market",
                    template: "<a href='/Market/Index?id=#= MarketID #'>#= MarketName #</a>",
                    width: 200
                },
                {
                    field: "DateSent",
                    title: "Date Sent",
                    template: '#= kendo.toString(Grinder.Market.CheckNull(new Date(DateSent.getTime()+(DateSent.getTimezoneOffset()*60*1000))), "MMM d, yyyy" ) #',
                    width: 100
                },
                {
                    field: "DateHeldForConsideration",
                    title: "Date Held",
                    template: '#= kendo.toString(DateHeldForConsideration == null ? \'\' : (new Date(DateHeldForConsideration.getTime()+(DateHeldForConsideration.getTimezoneOffset()*60*1000))), "MMM d, yyyy" ) #',
                    width: 100
                },
                {
                    field: "DateReceived",
                    title: "Date Res'd",
                    template: '#= kendo.toString(DateReceived == null ? \'\' : (new Date(DateReceived.getTime()+(DateReceived.getTimezoneOffset()*60*1000))), "MMM d, yyyy" ) #',
                    width: 100
                },
                {
                    field: "ResponseStatus",
                    title: "Response*",
                    template: "<span class='#= Grinder.SubmissionList.getCssClassBySubmissionStatus(DaysOut, AverageReturnDays, EstimatedReturn, StatusID) #'>#= ResponseStatus #</span>",
                    width: 130
                },
                {
                    field: "DaysOut",
                    template: "<center>#= DaysOut #/#if(AverageReturnDays===null){#<span>?</span>#}else{##: AverageReturnDays ##}#/#if(EstimatedReturn===null){#<span>?</span>#}else{##: EstimatedReturn ##}#</center>",
                    title: "Days/Avg/Est",
                    width: 75
                },
                {
                    template: "#= PaidString #",
                    title: "Paid?",
                    width: 40
                },
                {
                    template: "#= Grinder.SubmissionList.getPubString(ResponseStatus, DateOfPublication, Released) #",
                    title: "Pub'd?",
                    width: 40
                },
                {
                    template: "<a href='javascript:Grinder.SubmissionList.editSubmissionByID(#= SubmissionID #)'>Update</a>"
                },
                {
                    template: '<img src="#= Grinder.SubmissionList.getNotesURL(Notes) #" title="#= Grinder.SubmissionList.getNotesText(Notes) #" alt="#= Grinder.SubmissionList.getNotesText(Notes) #" />',
                    width: 20
                }
            ],
            dataSource: $searchDataSource,
            //pageable: true,
            sortable: true,
            scrollable: false
        });
    },

    checkAll: function (data) {
        var checkAllButtonTop = $("#checkAllButtonTop");
        var checkAllButtonBottom = $("#checkAllButtonBottom");

        if (data == 0) {
            if (checkAllButtonTop.text() == "[Check All]") {
                $("#StatusPendingResponse").prop("checked", true);
                $("#StatusPendingQuery").prop("checked", true);
                //$("#StatusPendingShortlisted").prop("checked", true);
                $("#StatusAccepted").prop("checked", true);
                $("#StatusRewriteRequested").prop("checked", true);
                checkAllButtonTop.text("[Uncheck All]");
            } else {
                $("#StatusPendingResponse").prop("checked", false);
                $("#StatusPendingQuery").prop("checked", false);
                //$("#StatusPendingShortlisted").prop("checked", false);
                $("#StatusAccepted").prop("checked", false);
                $("#StatusRewriteRequested").prop("checked", false);
                checkAllButtonTop.text("[Check All]");
            }
        }

        if (data == 1) {
            if (checkAllButtonBottom.text() == "[Check All]") {
                $("#StatusRejectionForm").prop("checked", true);
                $("#StatusRejectionPersonal").prop("checked", true);
                $("#StatusWithdrawal").prop("checked", true);
                $("#StatusLostReturned").prop("checked", true);
                $("#StatusNeverResponded").prop("checked", true);
                checkAllButtonBottom.text("[Uncheck All]");
            } else {
                $("#StatusRejectionForm").prop("checked", false);
                $("#StatusRejectionPersonal").prop("checked", false);
                $("#StatusWithdrawal").prop("checked", false);
                $("#StatusLostReturned").prop("checked", false);
                $("#StatusNeverResponded").prop("checked", false);
                checkAllButtonBottom.text("[Check All]");
            }
        }
    },

    getNotesURL: function (notes) {
        if (notes == "" || notes == null)
            return "/Images/NoNotes.png";
        else
            return "/Images/Notes.png";
    },

    getNoteDisplay: function (note) {
        if (note === "" || note === null) {
            return "";
        }
        else {
            if (note.length <= 25) {
                return note;
            }
            else {
                return note.substring(0, 25) +  '... <img src="/Images/Notes.png" title="' + note + '" alt="' + note + '">';
            }

        }
    },

    getNotesText: function (notes) {
        if (notes == "" || notes == null)
            return "No Notes";
        else
            return notes;
    },

    getPaidString: function (status, paymentString, datePaidString) {
        //if it's not an Acceptance, payment not expected, so N/A
        //if there's a payment date but no payment amount, that's the best way to indicate non-paying sale, so N/A
        if (status != "Acceptance" || (paymentString == "" && datePaidString != "")) return "N/A";

        if (Grinder.SubmissionList.CheckNull(datePaidString) == '')
            return "No";
        else
            return "Yes";
    },

    getPubString: function (status, datePubString, released) {
        //if it's not an Acceptance, publication not expected, so N/A
        if (status != "Acceptance" || released) return "N/A";

        if (Grinder.SubmissionList.CheckNull(datePubString) == '')
            return "No";
        else
            return "Yes";
    },

    getCssClassBySubmissionStatus: function (daysOut, averageReturn, estimatedReturn, statusID) {
        var cssClass = "SubmissionResultStatus";

        if (statusID == 73 || statusID == 74 || statusID == 75) {
            if (averageReturn !== null && daysOut >= averageReturn ) cssClass = "SubmissionResultStatusExceedsAverage";
            if (estimatedReturn !== null && daysOut >= estimatedReturn ) cssClass = "SubmissionResultStatusExceedsEstimated";
        }

        return cssClass;
    },

    CheckNull: function (val) {
        if (val == null)
            return '';
        else
            return val;
    },

    exportResults: function () {
        var model = {
            StatusPendingResponse: $("#StatusPendingResponse")[0].checked,
            StatusPendingQuery: $("#StatusPendingQuery")[0].checked,
            //StatusPendingShortlisted: $("#StatusPendingShortlisted")[0].checked,
            StatusAccepted: $("#StatusAccepted")[0].checked,
            StatusRewriteRequested: $("#StatusRewriteRequested")[0].checked,
            StatusRejectionForm: $("#StatusRejectionForm")[0].checked,
            StatusRejectionPersonal: $("#StatusRejectionPersonal")[0].checked,
            StatusWithdrawal: $("#StatusWithdrawal")[0].checked,
            StatusLostReturned: $("#StatusLostReturned")[0].checked,
            StatusNeverResponded: $("#StatusNeverResponded")[0].checked,
            RememberSettings: $("#RememberSettings")[0].checked,
            PieceID: $("#FilterPieceID").val(),
            MarketID: $("#FilterMarketID").val()
        };

        $.ajax({
            type: "POST",
            url: "/Account/Submissions/GenerateExportFile",
            data: model,
            success: function (response, status, request) {
                var disp = request.getResponseHeader('Content-Disposition');
                if (disp && disp.search('attachment') != -1) {
                    var form = $('<form method="POST" action="/Account/Submissions/GenerateExportFile">');
                    $.each(model, function (k, v) {
                        form.append($('<input type="hidden" name="' + k +
                                '" value="' + v + '">'));
                    });
                    $('body').append(form);
                    form.submit();
                }
            }
        });
    },
};

Grinder.SubmissionEdit = Grinder.SubmissionEdit || {};
Grinder.SubmissionEdit = {

    initializePage: function () {

        _$paymentsDataSource = new kendo.data.DataSource({
            schema: {
                model: {
                    id: "PaymentID",
                    fields: {
                        PaymentID: {},
                        UserID: {},
                        SubmissionID: {},
                        MarketID: {},
                        PaymentAmount: {},
                        OtherCurrencyCode: {},
                        OtherPaymentAmount: {},
                        IsExpense: {},
                        PaymentDate: { type: "date" },
                        Note: {}
                    }
                }
            },
            sort: { field: "PaymentDate", dir: "desc" },
            transport: {
                read: function (options) {
                    $.ajax({
                        url: _$submissionPaymentForUser,
                        dataType: "json",
                        success: function (result) {
                            options.success(result);

                        }
                    });
                }
            }
        });

        var _$postAcceptanceFields = $("#postAcceptanceFields");

        //only hide the post-acceptance if there is no data in them
        if (($("#HasPostAcceptanceData").val()) === "False") {
            _$postAcceptanceFields.hide();
        }
        if ($("#SubmissionID").val() == 0) $("#deleteSubmissionbutton").hide();

        $("#deleteConfirm").kendoWindow({
            actions: {},
            height: "100px",
            modal: true,
            resizable: false,
            width: "370px",
            visible: false,
            title: "Confirm deletion"
        });


        $("#yourPaymentsGrid").kendoGrid({
            columns: [
                {
                    field: "PaymentDate",
                    title: "Date",
                    template: '#= kendo.toString(new Date(PaymentDate.getTime()+(PaymentDate.getTimezoneOffset()*60*1000)), "MMM d, yyyy" ) #',
                    width: 100
                },
                {
                    field: "PaymentAmount",
                    title: "Amount",
                    template: '#if (IsExpense) {# #=((-PaymentAmount).toFixed(2))# #} else {# #=(PaymentAmount.toFixed(2))# #}  #',
                    width: 100
                },
                {
                    field: "Note",
                    title: "Note",
                    template: '#= Grinder.SubmissionList.getNoteDisplay(Note) #',
                    width: 100
                },
                {
                    template: "<a href='javascript:Grinder.PaymentList.editPaymentByID(#= PaymentID #)'>Update</a>",
                    width: 100
                }
            ],
            dataSource: _$paymentsDataSource,
            sortable: false,
            scrollable: false //always must be scrollable false or it breaks it into 2 tables
            //scrollable: true,
            //height: 210
        });

        $('#saveSubmission').on('click', function (e) {
            Grinder.Core.cancelEvent(e);

            var $theForm = $("#editSubmissionForm");
            var clientvalidate = true;

            $theForm.validate().settings.ignore = "";

            var dt = $("#DateSent").val();
            var datesent = new Date(dt);
            if (dt && dt.match(/\//g) && dt.match(/\//g).length == 1)
            {
                datesent.setFullYear(new Date().getFullYear());
            }
            else if (dt && dt.match(/-/g) && dt.match(/-/g).length == 1)
            {
                datesent.setFullYear(new Date().getFullYear());
            }

            var dateheldforconsideration = null;
            if ($("#DateHeldForConsideration").val()) {
                dt = $("#DateHeldForConsideration").val();
                dateheldforconsideration = new Date(dt);
                if (dt && dt.match(/\//g) && dt.match(/\//g).length == 1) {
                    dateheldforconsideration.setFullYear(new Date().getFullYear());
                }
                else if (dt && dt.match(/-/g) && dt.match(/-/g).length == 1) {
                    dateheldforconsideration.setFullYear(new Date().getFullYear());
                }
            }

            var datereceived = null;
            if ($("#DateReceived").val()) {
                dt = $("#DateReceived").val();
                datereceived = new Date(dt);
                if (dt && dt.match(/\//g) && dt.match(/\//g).length == 1) {
                    datereceived.setFullYear(new Date().getFullYear());
                }
                else if (dt && dt.match(/-/g) && dt.match(/-/g).length == 1) {
                    datereceived.setFullYear(new Date().getFullYear());
                }
            }

            var dateacknowledged = null;
            if ($("#DateAcknowledged").val()) {
                dt = $("#DateAcknowledged").val();
                dateacknowledged = new Date(dt);
                if (dt && dt.match(/\//g) && dt.match(/\//g).length == 1)
                {
                    dateacknowledged.setFullYear(new Date().getFullYear());
                }
                else if (dt && dt.match(/-/g) && dt.match(/-/g).length == 1) {
                    dateacknowledged.setFullYear(new Date().getFullYear());
                }

            }

            var dateofcontract = null;
            if ($("#DateOfContract").val()) {
                dt = $("#DateOfContract").val();
                dateofcontract = new Date(dt);
                if (dt && dt.match(/\//g) && dt.match(/\//g).length == 1) {
                    dateofcontract.setFullYear(new Date().getFullYear());
                }
                else if (dt && dt.match(/-/g) && dt.match(/-/g).length == 1) {
                    dateofcontract.setFullYear(new Date().getFullYear());
                }

            }


            var dateofpublication = null;
            if ($("#DateOfPublication").val() != null) {
                dt = $("#DateOfPublication").val();
                dateofpublication = new Date(dt);
                if (dt && dt.match(/\//g) && dt.match(/\//g).length == 1) {
                    dateofpublication.setFullYear(new Date().getFullYear());
                }
                else if (dt && dt.match(/-/g) && dt.match(/-/g).length == 1) {
                    dateofpublication.setFullYear(new Date().getFullYear());
                }

            }

            var TodayPlusOne = new Date();
            TodayPlusOne.setDate(TodayPlusOne.getDate() + 1);

            var statusid = $("#StatusID").val();



            if (!datesent || datesent.getFullYear() < 1969) {
                alert("Invalid Date Sent");
                clientvalidate = false;
            }
            else if (datereceived && (statusid == 73 || statusid == 74 || statusid == 75)) {
                clientvalidate = false;
                alert("Pending submissions should not have a date resolved.");
            }
            else if (!datereceived && (statusid == 76 || statusid == 78 || statusid == 79 || statusid == 82 || statusid == 83)) {
                alert("Resolved submissions should have a date resolved.");
                clientvalidate = false;
            }
                //this is working okay
            else if ((datereceived !== null && datereceived < datesent)
                    || (dateacknowledged !== null && dateacknowledged < datesent)
                    || (dateofcontract !== null && dateofcontract < datesent)
                    || (dateofpublication !== null && dateofpublication < datesent)
                    || (dateheldforconsideration !== null && dateheldforconsideration < datesent)) {
                alert("No date should be before Date sent.");
                clientvalidate = false;
            }
                //this one is working okay
            else if (datesent > TodayPlusOne
                    || (datereceived !== null && datereceived > TodayPlusOne)
                    || (dateacknowledged !== null && dateacknowledged > TodayPlusOne)
                    || (dateofcontract !== null && dateofcontract > TodayPlusOne)
                    || (dateofpublication !== null && dateofpublication > TodayPlusOne)
                    ||(dateheldforconsideration !== null && dateheldforconsideration > TodayPlusOne)) {
                clientvalidate = false;
                alert("Dates cannot be more than one day in the future.");
            }

            //no dates before date sent

            if (clientvalidate && $theForm.valid()) {
                Grinder.SubmissionEdit.saveSubmission();
            }
        });
    },

    showHidePostAcceptance: function () {
        var _$postAcceptanceFields = $("#postAcceptanceFields");
        var _$showHidePostAcceptanceAnchor = $("#showHidePostAcceptanceAnchor");

        // if hidden, show, else hide.
        if (_$postAcceptanceFields.is(":visible")) {
            _$postAcceptanceFields.hide();
            _$showHidePostAcceptanceAnchor.html("[ + ]");
        } else {
            _$postAcceptanceFields.show();
            _$showHidePostAcceptanceAnchor.html("[ - ]");
        }
    },

    saveSubmission: function () {
        var data = {};

        data.MarketID = $("#MarketID").val();
        data.SubmissionID = $("#SubmissionID").val();
        data.PieceID = $("#PieceID").val();
        data.MethodID = $("#MethodID").val();
        data.DateSent = $("#DateSent").val();
        data.DateAcknowledged = $("#DateAcknowledged").val();
        data.DateReceived = $("#DateReceived").val();
        data.StatusID = $("#StatusID").val();
        data.Notes = $("#Notes").val();
        data.DateOfContract = $("#DateOfContract").val();
        data.DateHeldForConsideration = $("#DateHeldForConsideration").val();
        data.DateOfPayment = $("#DateOfPayment").val();
        data.PaymentAmount = $("#PaymentAmount").val();
        data.FeeAmount = $("#FeeAmount").val();
        data.DateOfPublication = $("#DateOfPublication").val();
        data.DateOfExclusivityExpiration = $("#DateOfExclusivityExpiration").val();
        data.PeriodOfExclusivity = $("#PeriodOfExclusivity").val();
        data.PublishedLanguages = $("#PublishedLanguages").val();
        data.Released = $("#Released").is(":checked");
        data.NonPaying = $("#NonPaying").is(":checked");


        $.ajax({
            type: "POST",
            async: false,
            data: JSON.stringify(data),
            dataType: 'html',
            url: ('/Account/Submissions/SaveSubmission'),
            contentType: "application/json; charset=utf-8",
            success: function (msg) {
                if ($("#SubmissionID").val() != "0") {
                    window.location = "/Account/Submissions/ConfirmSubmission?id=" + data.SubmissionID
                } else {
                    window.location = "/Account/Submissions/ConfirmSubmission";
                }
            }
        });
    },

    confirmDeleteSubmission: function () {

        var kendoWindow = $("#deleteConfirm").getKendoWindow();
        kendoWindow.center();
        kendoWindow.open();
    },

    deleteSubmission: function () {
        var submissionId = $("#SubmissionID").val();
        $.ajax({
            type: "POST",
            url: "/Account/Submissions/DeleteSubmission",
            data: { submissionId: submissionId },
            success: function () {
                var kendoWindow = $("#deleteConfirm").getKendoWindow();
                kendoWindow.close();


                $("#ListDiv").show();
                $("#EditDiv").show();
                $("#EditDiv").html('');
                Grinder.SubmissionList.showSubmissions();
            }
        });
    },

    getNotesURL: function (notes) {
        if (notes == "" || notes == null)
            return "/Images/NoNotes.png";
        else
            return "/Images/Notes.png";
    },

    getNotesText: function (notes) {
        if (notes == "" || notes == null) {
           return "You have made no note about this payment.";


        }
        else
            return notes;
    },

    cancelDelete: function () {
        var kendoWindow = $("#deleteConfirm").getKendoWindow();
        kendoWindow.close();
    }
};;
