var conduit = {
	version : '1.0.0'
};

conduit.exchangeHTML= function( map )
{
	var url = 'conduit/' + map.url + ".html.php";
	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 : 'html'
	,   data     : params
	,   error    : conduit.postErrorHandler
	,   success  : map.success
	});
}

conduit.exchangeJSON = function( map )
{
	var url = 'conduit/' + map.url + ".json.php";
	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,
		success   : conduit.makeCatchFunction(map.success, map.error)
	});
}

conduit.postErrorHandler = function(request, textStatus, errorThrown)
{
	alert('CONDUIT COMMUNICATIONS ERROR');

	if( textStatus == 'parsererror' ) 
	{
		alert('Parse Error on Server Response');
	}
	else 
	{
		alert('request: '     + request);
		alert('textStatus: '  + textStatus);
		alert('errorThrown: ' + errorThrown);
	}
}

conduit.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') 
				{
					PI.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);
			}
		}
	}
}
