﻿/*
* Queued Ajax requests.
* A new Ajax request won't be started until the previous queued 
* request has finished.
* Taken from http://plugins.jquery.com/files/jquery-ajax-queue_1.0.js.txt on 15 June 2010
*/
jQuery.ajaxQueue = function (o) {
    var body = jQuery(document.body);
    var startQueue = body.queue("ajax").length == 0;
    var _old = o.complete;
    o.complete = function () {
        if (_old) _old.apply(this, arguments);
        body.dequeue("ajax");
    };

    body.queue("ajax", function () {
        jQuery.ajax(o);
    });

    if (startQueue) body.dequeue("ajax");
};

jQuery.fn.ajaxRenderAction = function (url, values, onload, reloadable) {
    return this.each(function () {
        var _this = $(this);
        jQuery.ajaxQueue({
            url: url,
            type: "POST",
            dataType: 'html',
            data: values,
            success: function (data) {
                if (reloadable === true) {
                    _this.data('url', url)
                        .data('values', values)
                        .data("onload", onload)
                        .html(data);
                }
                else {
                    _this.replaceWith(data);
                }
                if (jQuery.isFunction(onload)) onload();
            }
        });
    });
};

jQuery.fn.reload = function () {
    return this.each(function () {
        var _this = $(this);
        var url = _this.data('url');
        if (!url) return;

        jQuery.ajaxQueue({
            url: url,
            data: _this.data('values'),
            dataType: 'html',
            success: function (data) {
                _this.html(data);
                var onload = _this.data('onload');
                if (jQuery.isFunction(onload))
                    onload();
            } 
        });
    });
};
