﻿var NOTIFY = 1;
var NOTIFYERROR = 2;
var UPDATEFORM = 3;
var RELOAD = 4;
var REDIRECT = 5;
var EXECUTE = 6
var currentForm;

function BeforeSend(request, settings, formID)
{
    currentForm = formID;
    $('input[type=submit]').attr('disabled', 'disabled');
    $("#indicator")
    .show("slide", { direction: "right" }, "fast");
}

function Complete(response, status)
{
    $("#indicator")
    .hide("slide", { direction: "right" }, "fast");
    $('input[type="submit"]').removeAttr('disabled');
}

function AfterUpdate(response, status)
{
    notify(response.Message, "messages-success", "messages-error");
    $('input[type="submit"]').removeAttr('disabled');
    HandleCommand(response, currentForm);
}

function Error(response, status, error)
{
    data = ParseResponse(response);
    notify(data.Message, "messages-error", "messages-success");
    $('input[type="submit"]').removeAttr('disabled');
    HandleCommand(data, currentForm);
}

function notify(text, addClass, removeClass)
{
    $("#defaultNotificationPane").removeClass(removeClass)
    .addClass(addClass);

    $("#defaultNotificationPane-message").html(text);

    $("#defaultNotificationPane")
    .slideDown("fast")
    .animate({ opacity: 1.0 }, 3000)
    .slideUp("fast");
}

function ParseResponse(response)
{
    return $.parseJSON(response.responseText);
}

function Notify(message)
{
    notify(message, "messages-success", "messages-error");
}

function NotifyError(message)
{
    notify(message, "messages-error", "messages-success");
}

function HandleCommand(json, formID)
{
    if (json.Command == NOTIFY)
    {
        Notify(json.CommandArguement);
        return true;
    }
    else if (json.Command == RELOAD)
    {
        window.location.reload(true);
        return true;
    }
    else if (json.Command == NOTIFYERROR)
    {
        NotifyError(json.CommandArguement);
        return true;
    }
    else if (json.Command == UPDATEFORM)
    {
        $("#" + formID).html(json.CommandArguement);
        $.validator.unobtrusive.parse("#" + formID);
        return true;
    }
    else if (json.Command == REDIRECT)
    {
        window.location.href = json.CommandArguement;
        return true;
    }
    else if (json.Command == EXECUTE)
    {
        eval(json.CommandArguement);
        return true;
    }

    return false;
}

$.fn.clearForm = function ()
{
    return this.each(function ()
    {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form')
            return $(':input', this).clearForm();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};
