/**
 * Used for wrapping jQuery's .ajax function. It adds some much-needed standardization for our system's millions of AJAX calls.
 * Usage:
		jQuery.go({
			url: '/panel/ajax/thing.php',
			mode: 'prompt',
			type: 'create,
			get: 'var=val&var2=val2',
			post: 'var=val&var2=val2',
			handle: {
				200: function() {  },
				300: function() {  },
				def: function() {  }
			}
		});
 *
 *
 * ==> IF the response isn't a JSON object, the result will simply be printed to the body via jQuery("body").append() <==
 * 
 * @author Torgie - 03/04/09
 */

jQuery.extend({
	// Define our function "go" with 
	go: function(s) {
		// We can't do much of anything without a URL!
		if(typeof s.url == "undefined" || s.url == "")
			return false;

		// Build up our GET variables
		var gets = new Array;
		if(typeof s.mode != "undefined" && s.mode != "")
			gets.push("mode=" + s.mode);
		if(typeof s.type != "undefined" && s.type != "")
			gets.push("type=" + s.type);
		if(typeof s.get != "undefined" && s.get != "")
			gets.push(s.get);

		// Define the GET string
		var getString = (gets.length > 0) ? "?" + gets.join("&") : "";

		// Run the AJAX
		jQuery.ajax({
			type: "POST",
			dataType: "html",
			url: s.url + getString,
			data: s.post,
			success: function(data) {
				// If the data is empty, or if we have no handlers, just return
				if(data == "")
					return;

				// Extract our JSON object
				var json = eval("(" + data + ")");

				// Write non-JSON responses to the body
				if(typeof json.code != "number")
				{
					jQuery("body").append(data);
					return;
				}

				// Execute the appropriate callback
				var callbackExecuted = false;
				for(handledCode in s.handle)
				{
					if(handledCode == json.code)
					{
						// Run the callback
						s.handle[handledCode](json);
						callbackExecuted = true;
					}//if
				}//for

				// Execute the default if necessary, and one exists
				if(!callbackExecuted && typeof s.handle.def != "undefined")
					s.handle.def(json);
			}//success
		});//jQuery.ajax
	}//end function go
});//end extend