/**
* AjaxFeedback 1.0 - jQuery Plugin
* http://plugins.jquery.com/project/AjaxFeedback
* http://code.google.com/p/jqueryAjaxFeedback
*
* This is a mini plugin that extend jQuery ajax function by adding "delay" that
* will be called few seconds after the request if the server is not responding...
* This version does not implement xhr stack, therefore it will work for the last xhr.
*
* Copyright (c) 2009 Gal Dubitski - http://dubitski.blogspot.com
*
* Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
* I take no responsability at all for this software.
*
*/
(function ($) {

    $.feedback = {};

    var feedbackOnDelay = function (xhr) {
        $.feedback.last_ajax_call = xhr;
        $.feedback.last_ajax_call.timeCalled = new Date().getTime();
        if (!$.isFunction($.feedback.delay.callback)) return;
        setTimeout(function () {
            // invoke callback if last ajax call is not finished yet...
            var xhr = $.feedback.last_ajax_call;
            var now = new Date().getTime();
            if (xhr.readyState == 1 && (now - xhr.timeCalled >= $.feedback.delay.time))
                $.feedback.delay.callback();
        }, $.feedback.delay.time);
    };

    var jQuery_ajax_function = $.ajax;

    $.ajax = function (options) {
        $.feedback.delay = options.delay;
        var caller_function;
        if (options.delay) {
            caller_function = options.beforeSend;
            options.beforeSend = function (xhr) {
                if ($.isFunction(caller_function)) caller_function(xhr);
                feedbackOnDelay(xhr);
            };
        }
        return jQuery_ajax_function(options);
    };

})(jQuery);
