﻿
(function() {

    $.webMethod = function(page, webMethod, data, success, error) {

    ///     1) $.webMethod(page, webMethod, data)
    ///     2) $.webMethod(page, webMethod, data, success)
    ///     3) $.webMethod(page, webMethod, data, success, error)
    ///     4) $.webMethod(page, webMethod, success, error)
    ///     5) $.webMethod(page, webMethod, success)
    
        // function(page, webMethod, data, success, error)
        // Argument overloading for: (page, webMethod, success, error)
    
        if (
            typeof data    === "function" && 
            typeof success === "function" &&
            typeof error   === "undefined"
        ){
            error = success;
            success = data;
            data = null;
        }
        
        // Argument overloading for (page, webMethod, success)
        
        else if (
            typeof data    === "function"  &&
            typeof success === "undefined" &&
            typeof error   === "undefined"
        ){
            success = data;
            data = null;
        }
        
        function dateFix(obj) {
        
            if (obj == null) {
                return obj;
            }
            
            // ASP.NET JSON date?
            
            if (typeof obj === "string") {
	            if (obj.toString().indexOf("Date(") < 0) return obj;
                var idate = obj.toString().replace("\/Date(","").replace(")\/","");
                return new Date(parseInt(idate));
            }
            
            // string or number
            
            if (typeof obj !== "object") {
                return obj;
            }
            
            // array or object
            
            jQuery.each(obj, function(key, val) {
                obj[key] = dateFix(val);
            });
            
            return obj;
        }
    
        // Automatically unwrap the return value from the service
    
        function successWrapper(data, textStatus) {
            if (success) {
                success(dateFix(data.d), textStatus);
            }
        };
    
        // Send request 
        
        return $.ajax({
            type: "POST",
            data: (!data ? "{}" : JSON.stringify(data)),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: page + "/" + webMethod,
            success: successWrapper,
            error: error
        });
    };
})();
