﻿

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(serviceLocation, serviceName) {

    var _this = this;
    var _serviceLocation = serviceLocation;
    var _serviceName = serviceName;
    var _executingMethod = '';
    var _eventCache = new Object();
    
    
    function _getAjaxUrl() {

        return _serviceLocation + _serviceName + ".asmx/" + _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.AddEventHandler = function(type, fn, multicast)
    {
        if (multicast != null && !multicast)
        {
            $(_eventCache).unbind(type);
        }

        switch (type)
        {
            case "OnResponse":
                $(_eventCache).bind(type, { sender: _this, handler: fn }, function(event, eventArgs)
                {
                    event.data.handler(event.data.sender, eventArgs);
                });
                break;
            default:
                throw (type + " is not an event of the AjaxService");
        }
    }

}
