﻿function GAjax() {
    this.successFunctions = new Array();
    this.globalUrl = "";
}
GAjax.prototype.registerSuccessFunction = function(op, url, func, blockElement, failfunc) {
    var obj = { url: url, operation: op.toLowerCase(), func: func, failfunc: failfunc, blockElement: blockElement };
    this.successFunctions.push(obj);
}

GAjax.prototype.findOperation = function(sOperation) {
    var i = 0;
    sOperation = sOperation.toLowerCase();
    for (i = 0; i < this.successFunctions.length; i++) {
        if (this.successFunctions[i].operation == sOperation)
            return i;
    }
}

GAjax.prototype.DoFormAjax = function(sOperation, data, param) {
    var iIndex = this.findOperation(sOperation);
    blockUI(this.successFunctions[iIndex].blockElement);
    //convert param to JSON string
    if (typeof (param) == 'undefined')
        param = {};
    var o = "";
    for (sProperty in param) {
        o += sProperty;
        o += ":'";
        o += param[sProperty];
        o += "',";
    }

    o += "operation:" + iIndex;
    $$('resultback').value = o;
    document.forms[0].action = this.globalUrl + this.successFunctions[iIndex].url;
    document.forms[0].submit();
}

GAjax.prototype.doAjax = function(sOperation, data, param) {
    var iIndex = this.findOperation(sOperation);
    var $this = this;
    if (this.successFunctions[iIndex].blockElement != null)
        blockUI(this.successFunctions[iIndex].blockElement);

    if (typeof (param) == 'undefined')
        param = {};
    if (typeof (data) == 'undefined')
        data = '{}';
    param.operation = iIndex;
    $.ajax({
        type: 'POST',
        url: this.globalUrl + this.successFunctions[iIndex].url,
        data: data,
        dataType: 'json',
        success: function(result) {
            gAjax.callSuccessFunction(result, param);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("Ajax Error");
            if ($this.successFunctions[iIndex].blockElement != null)
                unblockUI();
        }
    });
}

GAjax.prototype.callSuccessFunction = function(result, o) {
    var iIndex = o.operation;
    if (result.d.ErrorCode != 0) {
        var sErrMsg = result.d.ErrorMessage.replace(new RegExp('<br>', 'g'), "\n"); ;
        alert(sErrMsg + "\r\n" + result.d.InternalErrorMessage);
        if (this.successFunctions[iIndex].failfunc != null)
            this.successFunctions[iIndex].failfunc();
        if (this.successFunctions[iIndex].blockElement != null)
            unblockUI();
        return;
    }
    var iIndex = o.operation;
    var successFunction = this.successFunctions[iIndex].func;
    successFunction(result, o);
    if (this.successFunctions[iIndex].blockElement != null)
        unblockUI();
}

var gAjax = new GAjax();
