﻿// http://encosia.com/2009/07/21/simplify-calling-asp-net-ajax-services-from-jquery/
// http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
// http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/
// http://www.sogeti-phoenix.com/Blogs/post/2009/05/MVC-ndash3b-Using-AntiForgeryToken-over-AJAX.aspx

var isDotNet = true;  // (document.location.href.match(/^http:\/\/localhost/m) != undefined);

/*
$.ajaxSetup({
	type: isDotNet ? "POST" : "GET",
	//contentType: "application/json; charset=utf-8", // MVC fails to pass function parameters if this is set
	data: "{}",
	dataType: "json", // must disable in jQuery 1.3.2, else, it will cause primitive return values like string and int to return an error
	// In 1.4, it doesn't matter because even if dataType is not set, it knows it's json by looking at the content type returned from the server. And when MVC returns Json(<string>), the jQuery json parser fails. So the server must return rich object rather than primitive one whenever it wants to return a string.
	dataFilter: function(data) {
		var msg;

		// not JSON at all
		if (data.indexOf('{') != 0)
			return data;

		if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function')
			msg = JSON.parse(data);
		else
			msg = eval('(' + data + ')');

		if (msg.hasOwnProperty('d'))
			return msg.d;
		else
			return msg;
	}
})
*/

$.service = function(serviceName, /* method, */jsonInput, successCallback, failureCallback) {
	jsonSetup();
	var token = $('input[name=__RequestVerificationToken]').val();
	$.ajax({
		type: isDotNet ? "POST" : "GET",
		dataType: "json",
		dataFilter: function(data) {
			var msg;

			if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function')
				msg = JSON.parse(data);
			else
				msg = eval('(' + data + ')');

			if (msg.hasOwnProperty('d'))
				return msg.d;
			else
				return msg;
		},
		url: (isDotNet ? "/AJAX/" + serviceName : serviceName + ".htm"),
		// type: method || "POST",
		data: $.extend(jsonInput, { "__RequestVerificationToken": token }),
		success: successCallback,
		error: failureCallback
	});
}

$.htmlEncode = function(s) {
	// TODO: Debug. It has not been unit-tested yet.
	return s.replace("<", "&lt;").replace(">", "$gt;").replace("\"", "&quot;");
}

function jsonSetup() {
}


$.fn.serializeObject = function() {
	var o = {};
	var a = this.serializeArray();
	$.each(a, function() {
		if (o[this.name]) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
}; 
