/**
 *
 * File: 		conduit.js
 *
 * Abstract:	AJAX communications wrapper.
 *
 * Notes:		Depends on jQuery UI for pretty messages.
 *
 *
**/
var conduit = {
	
	/**
	 * Exchange JSON
	 */
	exchangeJSON: function (map) {
		var url = 'conduit/' + map.url + ".json";
		var params = map.params;
	
		for (var n in params) {
			if (typeof params[n] == 'object' && !(params[n] instanceof Array)) {
				params[n] = $.toJSON(params[n]);
			}
		}
		
		$.ajax({
			type: 'POST',
			url: url,
			dataType: 'json',
			data: params,
			error: conduit.postErrorHandler(map),
			success: conduit.makeCatchFunction(map.success, map.error)
		});
	},
	
	/**
	 *
	 */
	postErrorHandler: function (map) {
		return function (request, textStatus, errorThrown) {
			var msg;
			var url = 'conduit/' + map.url + ".json";
			
			msg = 	'COMMUNICATION ERROR \n' +
					'------------------------------------------------------------------------------------ \n\n' +
					'Conduit call: \t\t' + url + '\n\n';
			
			if (textStatus == 'parsererror') {
				msg += 	'Problem: Parse Error on Server Response';
			} else {
				msg +=	'textStatus: \t\t' + textStatus + '\n' +
						'errorThrown: \t' + errorThrown + '\n\n ';
			}
			
			alert(msg);
		}
	},
	
	/**
	 *
	 */
	makeCatchFunction: function (goodFunc, badFunc) {
		return function (data, textStatus) {
			if (data && data.header && data.header.success) {
				if (goodFunc) {
					goodFunc(data);
				}
			} else {
				if (data && data.header ) {
					if (data.header.exception) {
						notify(
							'<table cellspacing="10">' +
								'<tr>' +
									'<td valign="top" width="60"><b>Class</b></td>' + 
									'<td>' + data.header.exception.xClass + '</td>' +
								'</tr>' +
								'<tr>' +
									'<td valign="top"><b>Message</b></td>' + 
									'<td>' + data.header.exception.message + '</td>' +
								'</tr>' +
							'</table>',
							{
								title: 'EXCEPTION',
								width:	400,
								height: 300,
								autosize: true
							}
						);
					} else if (data.header.reason && data.header.reason.code == 'EXPIRED-SESSION') {
						notify(
							'<table cellspacing="10">' +
								'<tr>' +
									'<td valign="top"><b>Message</b></td>' + 
									'<td>' + data.header.reason.msg + '</td>' +
								'</tr>' +
							'</table>',
							{
								title: 'SESSION EXPIRED',
								width:	400,
								height: 200,
								autosize: true
							}
						);
						
						return; // we don't want to call the badFunc in this case.
					}
				}
				
				if (badFunc) {
					badFunc(data);
				}
			}
		}
	}
};

