﻿function ajax_getHtml(url, container, callback, source) {
    $(container).hide(250);
    $(container).html("<img src='/Content/images/throbber.gif'></img>");
    $(container).show(250);
    $.get(url, null, function (data, textStatus) { $(container).html(data); if (callback) callback(source, data); }, "html");

}

function ajax_postHtml(action, post, container, callback, source, completeMsg) {
    $(container).html("<img src='/Content/images/throbber.gif'></img>");
    
    $.post(
        action, 
        post,
        function (data, textStatus) {
            $(container).html(data);
            $(container).prepend("<span class='info ajax_PostHtmlFlasher'>" + (completeMsg === undefined ? "Changes saved" : completeMsg) + "</span>");
            if (callback) callback(source, data);
            $(container).children(".ajax_PostHtmlFlasher").hide(1500, function () { $(container).remove(".ajax_PostHtmlFlasher"); });
        }, 
        "html");
}

$(document).ready(function () {
    jQuery.ajaxSettings.traditional = true;

    $("form.async").live('submit', function (evt) {
        evt.preventDefault();
        if ($(this).validate().form()) {
            var cb = $(this).data("callback");
            var container = $(this).data("container");
            var completeMsg = $(this).data("completeMessage");

            if (!container)
                container = $(this).parent();

            ajax_postHtml($(this).attr("action"), $(this).serialize(), $(container), cb, $(this), completeMsg);
        }
    });

    $("a.async").live('click', function (evt) {

        evt.preventDefault();
        if ($(this).data("cancelled") != true) {
            var cb = $(this).data("callback");
            var container = $(this).data("container");
            ajax_getHtml($(this).attr("href"), container, cb, $(this));
        }
    });

    $("select.async").live('change', function (evt) {
        if ($(this).data("cancelled") != true) {
            var cb = $(this).data("callback");
            var container = $(this).data("container");
            var url = $(this).data("href").replace("{value}", $(this).val());

            ajax_getHtml(url, container, cb, $(this));
        }
    });

    $("a.asyncExpando").live("click", function (evt) {
        evt.preventDefault();
        var container = $(this).data("container");

        if ($(this).hasClass("expando_open")) {
            $(this).removeClass("expando_open");

            $(container).hide(250);
        }
        else {
            var cb = $(this).data("callback");
            ajax_getHtml($(this).attr("href"), container, cb, $(this));
            $(this).addClass("expando_open");

        }

    });
});
