var KS = KS || {};
KS.ajax = function(ajaxCommand, o)
{
    this._options =
    {
        debug: false,
        baseURL: null,
        type: 'post',
        url: "/ajax/"  + ajaxCommand,
        ajaxPrefix: '',
        command: ajaxCommand,
        csrfEnabled: true,
        csrfToken: $("input[name='csrfmiddlewaretoken']").val(),
        jQ: { cache: false },
        // handlers
        beforeSend: function(jqXHR, settings) {},
        dataFilter: null,
        error: function(jqXHR, textStatus, errorThrown) {},
        failed: function(data, jqXHR, textStatus) {},
        success: function(data, jqXHR, textStatus) {},
        complete: function(jqXHR, textStatus) {} 
    };
    $.extend(this._options, o);
    // urls
    if (this._options.baseURL != null)
        this._options.url = this._options.baseURL + '/' + ajaxCommand;

};

KS.ajax.prototype =
{
    log: function(str)
    {
        if (this._options.debug && window.console) console.log('[ks-ajax] ' + str);        
    },

    beforeSend: function(jqXHR, settings)
    {
        // add the csrf token to the request, if needed
        if (this._options.csrfEnabled)
            jqXHR.setRequestHeader("X-CSRFToken", this._options.csrfToken);
        this._options.beforeSend(jqXHR, settings);
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        this.log("error fulfilling request: " + textStatus);
        this._options.error(jqXHR, textStatus, errorThrown);
    },
    success: function(data, textStatus, jqXHR)
    {
        if (data._meta && data._meta.success)
        {
            this.log("success fulfilling request: " + textStatus);
            this._options.success(data, textStatus, jqXHR);
        }
        else
        {
            // server flagged an error in the JSON response
            this.log("server signaled error:");
            this.log(data._meta.localizedError);
            this._options.failed(data, data._meta.localizedError, jqXHR);
        } 
    },
    complete: function(jqXHR, textStatus)
    {
        this._options.complete(jqXHR, textStatus);
    },
    prepData: function(data)
    {
        ajaxData = this.ajaxData || {};
        for (key in data)
            ajaxData[this._options.ajaxPrefix + key] = data[key];
        ajaxData[this._options.ajaxPrefix + '_command'] = this._options.command;
        return ajaxData;
    },
 
    send: function(data)
    {
        self = this;
        jQ = self._options.jQ;
        jQ.type = this._options.type;
        jQ.url = this._options.url;
        jQ.beforeSend = this.beforeSend;
        if (this._options.dataFilter)
            jQ.dataFilter = this._options.dataFilter;
        jQ.error = this.error;
        jQ.success = this.success;
        jQ.complete = this.complete;
        jQ.dataType = "json";
        jQ.data = this.prepData(data);
        jQ.context = self;
        this.log(jQ.data);
        $.ajax(jQ);
    },
};

