/*
 *	Wed Jun 22 11:47:50 EST 2011
 *
 * 	This file contains some of the functions that were in the original default.js file for the Intranet.
 *
 * 	As all three sites - web, provider portal and intranet - start using the same versions of functions from default.js
 * 	we'll move those functions here to common.js.  This one file is shared amongst all three sites.
 *
 * 	We'll have a symbolic link between the Intranet and PP sites and a hard link (where possible) for the web site
 * 	(since that may not run on the same web server in production).
 */

/*
 *	Return an (ID) string which is suitable to use as a jQuery selector.
 */
function id_to_jq_selector(id) {
	var res = null;
	if (id == null) {
		console.log("null value in call to id_to_jq_selector(id)");
	} else {
		res = '#' + id.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1');
	}
	return res;
}


/*
 * 	Exactly the same thing as id_to_jq_selector(), only return a jQuery selector for a NAME.
 */
function name_to_jq_selector (name) {
	return '[name="' + name.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1') + '"]';
}


/*
 *	Given the $errors array from PHP's validate() we process the errors and
 *	set up the form's fields to reflect them.
 *
 *	BJR 27/4/11	Modified to move on to a '-VISIBLE' ID if the field it finds is a HIDDEN field.
 */
function _processfielderrors(errorfields, display_qtips) {
	if (typeof(display_qtips) == 'undefined')
		display_qtips = true;

	$('.qtip').remove();
	$('.errorinput').removeClass('errorinput');

	if (errorfields == null)
		return;

	for (var i in errorfields) {
		//
		//	We try and find the field by ID.  If that doesn't work we'll look it up by name.
		//
		var widget = $(id_to_jq_selector(errorfields[i].name));

		if (widget.length == 0)
			widget = $(name_to_jq_selector(errorfields[i].name));

		//	If we couldn't find a field OR if it's hidden then try for a related '-VISIBLE' field instead; a field with
		//	'-VISIBLE' appended to the end of the ID.

		if (widget.length == 0  ||  widget.is('input[type="hidden"]'))
			widget = $(id_to_jq_selector(errorfields[i].name + '-VISIBLE'));

		widget.addClass('errorinput');

		//	14/7/11	Mark the label of any enclosing tab with the 'errorinput' class also.

		widget.parents('div.ui-tabs-panel').each(function () {
			var panel_id = $(this).attr('id');

			if (panel_id)
				$(this).siblings('ul.ui-tabs-nav').find('li > a[href="#' + panel_id + '"]').addClass('errorinput');
		});

		//	Mark any table-list style collapser bar.

		widget.parents('tr.table-collapser-client').prev('tr.table-collapser-bar').addClass('errorinput');

		//	Mark any Display collapser bar.

		widget.parents('div.collapser-client').prev('div.collapser-bar').addClass('errorinput');

		//	Mark any in-core row that's associated with the in-core div that houses the error.

		widget.parents('div.AP2_in_core').each(function () {
			var in_core_id = $(this).attr('id');

			$('table.ap_library_table tr.AP2_in_core_row_' + in_core_id).addClass('errorinput');
		});

		//	Now handled Qtips.
	
		if (! display_qtips)
			continue;

		if (errorfields[i].required) {
			widget.qtip( {
				content : 'Required',
				show : {
					ready : true
				},
				hide : {
					fixed : true,
					delay : 3
				},
				position : {
					corner : {
						target : 'rightMiddle',
						tooltip : 'leftMiddle'
					}
				},
				style : {
					name : 'red',
					tip : 'leftMiddle'
				}
			});
		}

		var type = errorfields[i].type;

		if (errorfields[i].type != undefined) {
			widget.qtip( {
				content : 'Error: ' + errorfields[i].message,
				show : {
					ready : true
				},
				hide : {
					fixed : true,
					delay : 3
				},
				position : {
					corner : {
						target : (type == 'top' ? 'topMiddle' : 'rightTop'),
						tooltip : (type == 'top' ? 'bottomMiddle'
								: 'leftBottom')
					}
				},
				style : {
					name : 'red',
					tip : (type == 'top' ? 'bottomMiddle' : 'leftBottom')
				}
			});
		}
	}
}


/*
 * 	deliver_form() is a variant of submitform() which handles a couple more options:
 *
 * 	-	returning content_div/content_html will cause the div's content to be replaced
 * 		with the new content in content_html;
 *
 * 	-	returning popup_html will cause a jQuery dialog (popup) to be created and populated
 * 		with the HTML.
 *
 * 		(A popup_parms object can also be supplied with jQuery parameters to supercede the
 * 		defaults used here.)
 *
 * 	The routine does a POST to a web URL and expects a JSON data structure back.  The structure
 * 	may have any of the following properties:
 *
 * 		error		MUST be set to 0/1
 *
 * 		message		message displayed; MUST be set if error is set to 1.
 *
 * 		errors		An array of errors returned from the Intranet validate().
 *
 * 		newlocation		A web url which the browser is to load;
 *
 * 		updatediv		The ID of a <div> into which the HTML output of a web page will be loaded;
 * 		divurl			The URL of the web page whose content we load into 'updatediv'
 *
 * 		contentdiv_id		The ID of a <div> into which the HTML of the 'content' property will be loaded
 * 		contentdiv_html		A string with the HTML content for 'contentdiv'
 *
 * 		popup_html			HTML to load into a jQuery dialog (popup).
 * 		popup_parms			Optional parameters for the jQuery dialog (to supercede the defaults).
 *
 * 		eval_js				javascript to eval()
 *
 * 	Parameters:
 *
 * 		formid		The ID of the HTML form we're submitting.
 * 		submitUrl	The URL which is receiving the POST data.
 * 		statusMsg	The message put up while the saving is taking place. (Optional)
 */
function deliver_form (formid, submitUrl, statusMsg) {
	//
	//	Setup default parameters for the jQuery popup.
	//
	var script_content;
	var dialog_content;

	var dialog_parms = {
		height:		'auto',
		width:		'auto',
		modal:		true,

		buttons:	{
			'Close':	function () {
				$(this).dialog('close');
			}
		},

		close:		function() {
			if (script_content.length > 0)
				script_content.remove();

			$(this).dialog('destroy');
			$(this).remove();
		}
	};

	//	Now on with the show.
	
	var formData = $("#" + formid).serialize();

	statusmessage(statusMsg ? statusMsg : "SAVING", false);

	$.ajax({
		type : "POST",
		url : submitUrl,
		data : formData,
		dataType : "json",

		success : function(json) {
			if (json.error == 1) {
				statusmessage(json.message, true);

				if (json.errors)
					_processfielderrors(json.errors.fields, json.display_qtips);
			} else {
				//
				//	Success; various things to do depending on what we get back.
				//
				_processfielderrors(null);						//	blank any field errors

				if (json.message)
					statusmessage(json.message, false);		//	optional status message

				//	Now load content.

				if (json.newlocation)
					document.location.href = json.newlocation;		//	load a full web page
				else {
					//
					//	We load any/all of the following content if they are provided.
					//
					//	First of all, loading the content of a web page into a div.
					//
					if (json.updatediv) 
						loadcontent(json.updatediv, json.divurl);

					//	Now see if there is actual HTML returned to load into a div.
				
					if (json.contentdiv_id)
						$(id_to_jq_selector(json.contentdiv_id)).html(json.contentdiv_html);

					//	Now see if there is HTML to load into a jQuery dialog (popup)

					if (json.popup_html) {
						var content = $('<div>' + json.popup_html + '</div>');

						script_content = content.filter('script');
						dialog_content = content.not('script');

						//	Supercede any supplied parameters

						if (json.popup_parms)
							for (var i in json.popup_parms)
								dialog_parms[i] = json.popup_parms[i];

						//	Kick off the dialog

						dialog_content.dialog(dialog_parms);
						
						if (script_content.length > 0)
							script_content.appendTo('body');
					}

					//	Now see if we're supposed to blank out form fields.

					if (json.reset_form) {
						//	Actually, just do a form reset().
						//$('form#' + formid + ' input').val('');

						$('form#' + formid).get(0).reset();
					}

					//	See if there's any javascript to eval

					if (json.eval_js)
						eval(json.eval_js);
				}
			}
		},

		error : function(XMLHttprequest, textStatus, errorThrown) {
			statusmessage('Server communication error!', true);
		}
	});
}

