﻿/**
* jQuery dotNet Plugin - http://code.google.com/p/jquerydotnetplugin/
* Copyright (c) 2008 Walter Poch (http://wpoch.com.ar || http://wpoch.wordpress.com)
* Licensed under the GPL (http://www.gnu.org/copyleft/gpl.html) license.
*
* $Date: 2008-09-05
*
* $Date: 2009-03-13 by bigsan.chen@gmail.com
*	(^) remove evalJSON helper method, because jQuery will return json object itself.
*	(+) add serialize function detection. Now we can call service like this: $.callDotNet(urlMethod, jsonData, onSuccess);
*
* $Date: 2009-03-26 by bigsan.chen@gmail.com
*	(^) data parameter becomes a must, so the function signature is now function(url, data, onSuccess, onFailure, userContext).
*		and the signatures of onSuccess, onFailure becomes function(result, userContext, methodName)
*/
// Plugin definition
(function($) {
	$.extend({
		debug: function(msg) {
			if (window.Debug)
				Debug.writeln(msg);
			else if (window.console && window.console.log) {
				window.console.log(msg);
			}
		}
	});
})(jQuery);


(function($) {
	// Plugin implementation
	$.callDotNet = function(url, data, onSuccess, onFailure, userContext) {
		// Helper method
		var serialize = function(object) {
			if (typeof (object) == "string" || object == null) return object;

			var f = (window["Sys"] && Sys.Serialization && Sys.Serialization.JavaScriptSerializer.serialize) || (window["JSON"] && JSON.stringify);
			if ($.isFunction(f)) {
				return f(object);
			}
			else {
				var msg = "Cannot find serializer function, try the following solution:\n\n";
				msg += " 1. Make sure there is a ScriptManger server control on your page, or\n";
				msg += " 2. get JSON javascript from http://www.json.org/js.html, or\n";
				msg += " 3. pass in manually serialized string type data parameter.\n";
				throw new Error(-1, msg);
			}
		}

		data = serialize(data);
		//var methodName = /[^/]+$/.exec(url)[0];
		var methodName = new RegExp("[^/]+$").exec(url)[0];

		return $.ajax({
			type: "POST",
			url: url,
			data: data,
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(msg) {
				return onSuccess(msg.d, userContext, methodName);
			},
			error: function(error) {
				var f = onFailure || $.callDotNet.onError;
				f(error, userContext, methodName);
			}
		});
	}

	// Default implementation of the error function
	$.callDotNet.onError = function(error) {
		alert("There was an error processing your request.\n"
                    + "[" + error.status + "]"
                    + " [" + error.statusText + "]");
	}
})(jQuery);
