var sendEmailInterval = null;
var emailSendCount = 0;
$(function () {

    clearAllStatus();

    $("#btnSend").click(function () {
        clearAllStatus();

        if (checkRequired('divEmailSend', 'errorMessage') == false) {
            return;
        }
        

        $.ajax({
            url: "/Overview/BeginSendEmail",
            type: 'POST',
            data: { Content: $("#Content").val(), Subject: $("#Subject").val(), type:$("input[name='RecieverType']:checked").val() },
            success: function (result) {
            },
            error: function (e) {
            }
        });

        $("#divProgress").show();
        $("#logs").val("");
        $("#divReport").hide();
        $("#progress").attr("value", "0");

        disableUI();

        sendEmailInterval = setInterval("RefreshProgress()", 3000);
    });

    $("#btnAbort").click(function () {
        $.ajax({
            url: "/Overview/AbortSendEmail",
            type: 'GET',
            cache: false,
            success: function (result) {
            },
            error: function (e) {
            }
        });
    });
});


function RefreshProgress() {
    $.ajax({
        url: "/Overview/SendEmailProgress/",
        type: 'GET',
        cache: false,
        success: function (result) {
            for (var i = 0; i < result.message.length; i++) {
                emailSendCount = emailSendCount + 1;
                if (emailSendCount % 1000 == 0) {
                    $('#logs').val("");
                }
                $('#logs').val($('#logs').val() + result.message[i] + " \r\n");
            }

            if ((result.progress == 100 || result.progress == -1) && result.message.length == 0) {
                if (sendEmailInterval != null) {
                    clearInterval(sendEmailInterval);

                }
                enableUI();
            }
            $("#progress").attr("value", result.progress);
        },

        error: function (e) {
            if (sendEmailInterval != null) {
                clearInterval(sendEmailInterval);
                $("#divReport").show();
            }
            enableUI();
        }
    });
}

function disableUI() {
    $('#btnSend').attr('disabled', "true");
    $('#btnAbort').removeAttr("disabled");
}

function enableUI() {  
    $('#btnSend').removeAttr("disabled");
    $('#btnAbort').attr('disabled', "true");   
}

function clearAllStatus() {
    $("#divErrorMessage").html("");
    $('#logs').html('');
    $('#btnAbort').attr('disabled', "true");
    emailSendCount = 0;
}