﻿var ajaxHelper = {};

ajaxHelper.call = function (args)
{
    var _data = args.data == undefined ? null : args.data;
    var _type = args.type == undefined ? "POST" : args.type;
    var _dataType = args.dataType == undefined ? "JSON" : args.dataType;
    var _cache = args.cache == undefined ? false : args.cache;
    var _this = this;

    $.ajax(
    {
        url: args.url, type: _type, data: _data, dataType: _dataType, cache: _cache,
        success: function (dataText)
        {
            var _args = ajaxHelper.getCallbackParams(dataText, args.params);
            if ($.isFunction(args.success))
            {
                args.success.apply(args.context, _args);
            }
            else if (args.context && $.isFunction(args.context.onSuccess))
            {
                args.context.onSuccess.apply(args.context, _args);
            }
            else
            {
                _this.success(_args);
            }
        },
        error: function (error)
        {
            var _args = ajaxHelper.getCallbackParams(error.responseText, args.params);
            if ($.isFunction(args.error))
            {
                args.error.apply(args.context, _args);
            }
            else if (args.context && $.isFunction(args.context.onError))
            {
                args.context.onError.apply(args.context, _args);
            }
            else
            {
                _this.error(_args);
            }
        }
    });
};

ajaxHelper.createDelegate = function (instance, method)
{
    return function ()
    {
        return method.apply(instance, arguments);
    }
}

ajaxHelper.getCallbackParams = function (dataText, params) {
    var _result = [];

    if (dataText) {
        try {
            _result.push($.parseJSON(dataText));
        }
        catch (e) {
            _result.push({ "message": dataText });
        }
    }
    else {
        _result.push(null);
    }

    if (params != undefined) {
        $.each(params, function (index, param) { _result.push(param) });
    }

    return _result;
};

ajaxHelper.success = function (data)
{
};

ajaxHelper.error = function (errorData)
{
};

