/*	FUNCTION jit_send([array of jit events],[asynchronous=true/false flag])

	Requires jquery.toJSON.js - if you get an object error when calling this.
	
	INPUT
	
	OUTPUT
		Both success and failure of ajax data transmission are processed by jit_process.  Success and failure can happen at different levels of the event - in communications with the server itself, or in the server's processing of the data.

*/
function jit_send(myEventArray,async,root) { 
	//Default to asynchronous; some events need to be synchronous though, i.e. async=false
	if (async === "undefined") async = true;

	//Ensure beamed contents are an array
	if (!$.isArray(myEventArray)) myEventArray=[myEventArray];
	
	var rootprefix = "/";
	if (root) rootprefix += root;
	
	//"json" parameter involkes parsing of returned data as JSON data, so "parsererror" can stem from that.
	//Like $.post("jit_process.php?uid="+Math.random(),{jit_events:$.toJSON([event])},jit_process,"json");
	$.ajax({ 
        type: "POST", 
        url: rootprefix+"jit_process.php?uid="+Math.random(), //jitfob& 
        data: {jit_events:$.toJSON(myEventArray)}, 
        dataType: "json", 
		//complete: jit_process //(xmlhttprequest,statusText,errorCode)
        //In this function you will get the XMLHttpRquest Object. By using the xmlHttp.getResponseHeader("<<Header name>>"), you will get all the response headers details. 
        error: jit_process, //(xmlhttprequest,statusText,errorCode)
        success: jit_process // (data,statusText)
	}); 
}	

//GOOD NOTES AT: http://www.javascriptkit.com/jsref/ajax.shtml
//if this is called as error, data will be XMLHttpRequest; otherwise it will be parsed data received by call.
function jit_process(data,textStatus,errorCode) {
	
	/*	 Data could be xmlDoc, jsonObj, html, text, etc...
	"this": the options for this ajax request
	 this. object dump:
		.type = [POST|GET]
		.url = "jit_process.php?[randomid]
		.data has JSON data sent
		.success ---> function jit_process
		.error -->function jit_process
		.dataType = "json"
		.timeout
		.contentType="application/x-www-form-urlencoded"
		.processData=true
		.async=true
		.username=
		.password=
		.accepts=various contentTypes.
		.cache=false
*/
	//alert(textStatus+":"+errorCode);
	//$.dump(this);//dumps jquery object not original "this" object!!!!!!
	var jit_events = [{type:"",error:"0"}];

	switch (textStatus) {
		//Error occured when parsing according to given dataType:
		case "parsererror": jit_events[0].error=1;
			jit_events[0].message="Unable to parse "+this.dataType;
			jQuery.dump(this.data, true, true);
			if (this.data && this.data.getAllResponseHeaders) 
				alert(this.data.getAllResponseHeaders());
			break;

		//Error occured in AJAX fetch for some other reason (404, authentication?):
		//FUTURE: In this situation, the single error would apply to each original event notice/request on the list.
		case "error": //jQuery.dump(data, true, true);	
			//alert(data.getAllResponseHeaders());
			//alert(data.responseText); RAW content of received file
			jit_events[0].error=data.status;//XMLHttpRequest.status code. 301,...
			jit_events[0].message=data.statusText;
			if (data.status== 404) 
				jitclient_alert("Unable to access URL:" + this.url + " from " + document.location.href,"Server or Software error");

			break;
		case "success": 

			//There are different levels of success.  Request may contain error state recorded on server.
			jit_events=data.jit_events;
			
			var jit_errors=0;
			for (var ptr in jit_events) {
			
				jit_event = jit_events[ptr];
				//PROBLEM: WHEN WE DEFINE PROTOTYPE EXTENSIONS TO ARRAY, THEY GET INCLUDED IN ptr key of "ptr in jit_events" iteration.  Must filter them out.
				if (typeof jit_event =="function") {}

				else if (jit_event.error > 0) {
					if (jit_event.domID) {
						if (jQuery.fn.buttonAct) $("#"+jit_event.domID).buttonAct("failed");
						else alert("Software notice: can't do buttonAct() because module isn't loaded");
					}
					//Recognize if an jit_[event type]_error() function exists, if so, run it
					if (jit_event.type && jit_event.type.length && window["jit_"+jit_event.type+"_error"]) {
						if (jit_event.domID) jit_event.domID = $("#"+jit_event.domID);
						window["jit_"+jit_event.type+"_error"](jit_event);
					}
					else jit_errors=1;
				}

				/*	Recognize if an jit_[event type]() function exists. e.g.
						userProfileLoad, accountLoadDefaults accountSaveDefaults, memberListLoad, memberImport, surveyCreate, projectCreate, projectTreeLoad
				*/
				else if (jit_event.type && window["jit_"+jit_event.type]) {
					//Since there is no error, convert dom identifier back to reference to Jquery object, before proceeding.
					//alert(jit_event.domID);
					if (jit_event.domID) jit_event.domID = $("#"+jit_event.domID);
					window["jit_"+jit_event.type](jit_event);
				}
				else {
					jQuery.dump(jit_events);
					alert("Jit event not recognized on client:" +jit_event.type);
					//jit_errors=1;
				}
			} 
			if (jit_errors!=1) return;
			break;
		case "timeout": jit_events[0].error=2;
			break;
		case "notmodified": jit_events[0].error=3;
			break;					
		default: 
	}
	//Reached when there is an error:
	if (jit_errors) jQuery.dump(jit_events, true, true);
}

function jitclient_getFolder(jit_event) {}

(function ($) {
    m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
	},
	$.toJSON = function (value, whitelist) {
		
		var a,          // The array holding the partial texts.
			i,          // The loop counter.
			k,          // The member key.
			l,          // Length.
			r = /["\\\x00-\x1f\x7f-\x9f]/g,
			v;          // The member value.

		switch (typeof value) {
		case 'string':
			return r.test(value) ?
				'"' + value.replace(r, function (a) {
					var c = m[a];
					if (c) {
						return c;
					}
					c = a.charCodeAt();
					return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
				}) + '"' :
				'"' + value + '"';

		case 'number':
			return isFinite(value) ? String(value) : 'null';

		case 'boolean':
		case 'null':
			return String(value);

		case 'object':
			if (!value || value=="undefined") {
				return 'null';
			}

			if (typeof value.toJSON === 'function') {
				return $.toJSON(value.toJSON());
				//return 'null';
			}
			a = [];
			if (typeof value.length === 'number' &&
					!(value.propertyIsEnumerable('length'))) {
				l = value.length;
				for (i = 0; i < l; i += 1) {
					a.push($.toJSON(value[i], whitelist) || 'null');
				}
				return '[' + a.join(',') + ']';
			}
			if (whitelist) {
				l = whitelist.length;
				for (i = 0; i < l; i += 1) {
					k = whitelist[i];
					if (typeof k === 'string') {
						v = $.toJSON(value[k], whitelist);
						if (v) {
							a.push($.toJSON(k) + ':' + v);
						}
					}
				}
			} else {
				for (k in value) {
					if (typeof k === 'string') {
						v = $.toJSON(value[k], whitelist);
						if (v) {
							a.push($.toJSON(k) + ':' + v);
						}
					}
				}
			}

			return '{' + a.join(',') + '}';
		}

	};
	
})(jQuery);


function td(text,attributes) {return  '<td '+attributes+'>' + (text=="" ? '&nbsp;' : text ) + '</td>'}

function jitclient_alert(message, title,options) {
	if (!title) {title="";}
	if (!options) {options = {};}
	options.modal = true;
	options.width = 550;
	//options.position ='bottom';
	//options.draggable=false;//BAD BAD WINDOW RESIZING/SCROLLING OCCURS IF DIALOG IS DRAGGABLE
	try {
		$('<div title="'+title +'" style="overflow:auto;" >' +message+'</div>').dialog(options).dialog("open");
	}
	catch (err) {alert('Error in jitclient_alert(): "message" parameter has malformed HTML: ' + message);}
}










