﻿jQuery.ajaxDotNet = function(url, options) {
	/// <returns type="jQuery"></returns>
	/// <param name="url" type="String">
	///		The URL of the PageMethod or WebService.
	/// </param>
	/// <param name="options" optional="true" type="Object">
	///		[verb: String, Optional, Default = 'POST'], 
	///		[data: Object, Optional, Default = new Object()], 
	///		[success: Function, Optional, Default = function() {}], 
	///		[other: Function, Optional, Default = function() {}]
	/// </param>
	options = jQuery.extend({
		verb: 'POST',
		data: new Object(),
		success: function() {},
		other: function() {}
	}, options);
	
	var xhr = null;
	if (typeof XMLHttpRequest != 'undefined')
		xhr = new XMLHttpRequest();
	else if (typeof ActiveXObject != 'undefined') {
		try {
			xhr = new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch(err) {
			try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
		}
	}
	
	var data = '';
	if (options.verb == 'GET') {
		for (var i in options.data) {
			if (data != '')
				data += '&';
			data += i + '=' + JSON.stringify(options.data[i]);
		}
		url += '?' + data;
		data = null;
	}
	else if (options.verb == 'POST') {
		data = JSON.stringify(options.data);
	}
	
	xhr.open(options.verb, url, true); //true = async
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			var response;
			try {
				response = JSON.parse(xhr.responseText);
			}
			catch (err) {
				response = err;
			}
			
			if (xhr.status == 200 && typeof options.success != 'undefined')
				options.success(response, xhr.status, xhr.statusText);
			else if (typeof options.other != 'undefined')
				options.other(response, xhr.status, xhr.statusText);
		}
	}
	xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
	xhr.send(data);
};
