﻿

var Json = 
{
    serialize: function(data)
    {
        return Sys.Serialization.JavaScriptSerializer.serialize(data);
    },
    deserialize: function(string)
    {
        return Sys.Serialization.JavaScriptSerializer.deserialize(string);
    }
}
    
function AjaxResponse(result)
{
   this.status = '';
   this.result = '';
   this.statusText = ''; 
   
   if (result)
   {
        this.result = result.d;
        this.status = result.status;
        this.statusText = result.statusText;
   }
}

function AjaxService(servicePath) {

    var _this = this;
    var _servicePath = servicePath;
    var _executingMethod = '';
    var _eventCache = new Object();
    
    
    function _getAjaxUrl() {

        return _servicePath + "/" + _executingMethod;
    }

    this.execute = function(method, data, callback) {

        _executingMethod = method;

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: _getAjaxUrl(),
            data: !data ? "{}" : Json.serialize(data),
            dataType: "json",
            success: function(result) {

                $(_eventCache).trigger("OnResponse", new AjaxResponse(result));
                if (callback) { callback(new AjaxResponse(result)); }
            }
        });
    }
    
    this.add_response = function(fn, multicast)
    {
        if (multicast != null && !multicast)
        {
            $(_eventCache).unbind('OnResponse');
        }

        $(_eventCache).bind('OnResponse', { sender: _this, handler: fn }, function(event, eventArgs)
        {
            event.data.handler(event.data.sender, eventArgs);
        });
    }

}

