// **********************************************************************
// * Functions list:
// * ar(module_instance, command, params, extraParam)   - query some 'module'. Define 'command' and 'params'.
// *
// **********************************************************************
// * Event processing functions (optional):
// * ajax.onShowWait() - Wait state switch on (called after sending request to server with given delay 'ajax.showWaitDelay')
// *
// **********************************************************************
var ajax = {
    showWaitDelay : 1000,
    waitTimerId : false,
    msgWaitDelay : 5000,
    msgTimerId : {},

    doRequest : function(q) {
        if (!jQuery || !jQuery.ajaxSettings.url) return;
        if (q.length > 1) {
            query = '';
            for ( var i = 0; i < q.length; i++) {
                query += '&c[]=' + encodeURIComponent(q[i]['p'] + '&t=' + q[i]['t'] + '&c=' + q[i]['c']);
            }
        } else {
            query = q[0]['p'] + '&t=' + q[0]['t'] + '&c=' + q[0]['c'];
        }
        if (typeof(arguments[1]) == 'function') {
            afterResponse=arguments[1];
        } else {
            afterResponse=function(){};
        }
        if (this.onShowWait) {
            if (this.waitTimerId)
                window.clearTimeout(this.waitTimerId);
            this.waitTimerId=window.setTimeout(this.onShowWait, this.showWaitDelay);
        }
        if (typeof(arguments[1]) == 'boolean') {
            document.location.href=jQuery.ajaxSettings.url + (jQuery.ajaxSettings.url.indexOf('?')!=-1?'&':'?') + query;
        } else {
            if (this.onRequestBegin) this.onRequestBegin(q);
            $.ajax({data:query, success:function(resp){ ajax.processResponse(resp); afterResponse(resp); ajax.store(q, resp)}});
        }
    },

    processResponse : function(resp) {

        if (ajax.waitTimerId) {window.clearTimeout(ajax.waitTimerId);ajax.waitTimerId=0;}

        for(action in resp) {
            switch(action) {
                case 'h':
                    for (query in resp[action]) {
                        $(query).html(resp[action][query]);
                    }
                    break;
                case 'jsb':
                case 'jsa':
                    try {
                        eval('response_js = function() {'+resp[action]+'}');
                        response_js(resp);
                    } catch(e) { if (console) console.error(e);}
                    break;
                case 'mc':
                    try {
                        this.onShowMessage(resp[action][0], resp[action][1], resp[action][2]);
                    } catch(e) { if (console) console.error(e);}
                    break;
                case 'jump':
                    document.location.href=resp.jump;
                    break;
            }
        }
    },

    coverArea : function(which) {
        this._attachCover();
        if (which && $('.'+which).length && $('#cover').length) {
            w = $('.'+which).width();
            h = $('.'+which).height();
            $('#cover').css({
                left:$('.'+which).offset().left,
                top:$('.'+which).offset().top,
                width:w,
                height:h
            });
            $('#cover').removeClass('wait_state').show();
        }
    },

    onRequestBegin : function(q) {
        receiver = q[0].t;
        this.coverArea(receiver.split('/')[receiver.split('/').length-1]+'_area');
    },
    onShowWait : function() { $('#cover').addClass('wait_state'); },
    store : function (req, resp) {},
    onShowMessage : function (code, widget_id, p) {
        var selector = '.'+widget_id+'_msg_'+code;
        $(selector + '.__active').remove();
        var source = $(selector), target = source.clone();
        target.html(source.tmpl($.isFunction(source.tmpl) && $.isPlainObject(p) ? p : {})).addClass('__active').fadeIn();
        source.each(function(i) { target.eq(i).insertAfter(source.eq(i)) });
        target.fadeIn();
        if (ajax.msgTimerId[selector]) window.clearTimeout(ajax.msgTimerId[selector]);
        ajax.msgTimerId[selector] = window.setTimeout(function() {
            target.fadeOut(undefined, function() { target.remove(); delete target; })
        }, ajax.msgWaitDelay);
    },
    _attachCover : function() {
        if (!$('#cover').length) {
            $('body').append('<div id="cover"><img src="/r/i/progressbar.gif"><span><img src="/r/i/0.gif" width="1"></span></div>');
        }
    }
}

function ar(target, command, params) {
    ajax.doRequest([{'t':target,'c':command,'p':params}], arguments[3]);
}
