<!--
////////////////////////////////////////////////////////////////////////////////
// Table of Contents
////////////////////////////////////////////////////////////////////////////////
// 1. General JS Scripts
// 2. Main Menu
// 3. Dynamic Element and Content Creation
// 4. Custom JQuery UI Layout
// 5. Custom JQuery Widgets
// 6. Custom Namespaced Plugins
////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////// 1. General JS Scripts
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////// Scheduled Tasks
// Queues ajax requests for the taskbar clock, main greeting and session expiry check
/*
$(document).ready(function() {
	updateScheduledTasks();
	setInterval('updateScheduledTasks()', 60000);
});
// Updates the taskbar clock, greeting message and checks session if proper conditions exist
function updateScheduledTasks() {
	$.ajax({
		type: 'GET',
		url: frameworkIndexPage,
		data: frameworkRouteIndex + '=scheduled_tasks',
		dataType: 'json',
		error: function (XMLHttpRequest) {
			showModal('service', '', '', '', 'Scheduled tasks service failed.');
		},
		success: function (json) {
			// Update the greeting message
			if ($('#greeting_taskbar_tab').length) {
				$('#greeting_taskbar_tab span.ui-button-text').text(json.greeting);
			}
			
			// Update the taskbar clock
			if ($('#clock_taskbar_tab').length) {
				$('#clock_taskbar_tab span.ui-button-text').html(json.clock.date + ' &#8226; ' + json.clock.hour + ':' + json.clock.minute + ' ' + json.clock.meridiem);
			}
			
			// Check the session
			if (($('#clock_taskbar_tab').length) && ($('#greeting_taskbar_tab').length)) {
				var time_remain = parseInt(json.session.time_remain);
				var session_expiration_notice = parseInt(json.session.session_expiration_notice);
				
				if (time_remain <= 0) {
					// Logout the user, session has expired
					window.location.search = '?' + frameworkRouteIndex + '=logout&fr=400';
				} else if (time_remain <= session_expiration_notice) {
					// Display the warning modal dialog
					showExpirationPrompt();
				} else {
					// Hide the warning modal dialog
					hideExpirationPrompt();
				}
			}
		}
	});
}
*/
//////////////////////////////////////////////////////////////////////////////// External Links
// Convert hyperlinks with rel="open_window" to target="_blank"
$(document).ready(function() {
	if (!document.getElementsByTagName) {
		return;
	}
	var anchors = document.getElementsByTagName('a');
	for (var i = 0; i < anchors.length; i++) {
		var anchorElement = anchors[i];
		if (anchorElement.getAttribute('href') && anchorElement.getAttribute('rel') == 'open_window') {
			anchorElement.target = '_blank';
		}
	}
});

//////////////////////////////////////////////////////////////////////////////// JQuery AJAX Bug Fix for IE
$(document).ready(function() {
	$.ajaxSetup({
		xhr: function() {
			if ($.browser.msie) {
				return new ActiveXObject('Microsoft.XMLHTTP');
			} else {
				return new XMLHttpRequest();
			}
		}
	})
});

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////// 2. Main Menu
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////// Main Menu Functionality
/*
						// Submenu animation
						$(document).ready(function() {
							// Main Menu: slides the sub menu into or out of view
							$('#mainmenu li.mainmenu-maintab').hover(
								function() {
									var mainTabWidth = $(this).width() - 1;
									var subTabWidth = $('ul.mainmenu-submenu', this).width() + 2;
									var offsetValue = (mainTabWidth - subTabWidth) / 2;
									$('ul.mainmenu-submenu', this).css('left', offsetValue + 'px');
									$('ul.mainmenu-submenu', this).stop(true, true);
									$('ul.mainmenu-submenu', this).slideDown('normal');
								},
								function() {
									$('ul.mainmenu-submenu', this).slideUp('normal');
								}
							);
						});
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////// 3. Dynamic Element and Content Creation
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////// Modal XHTML Creation
// Create all of the modal xhtml
$(document).ready(function() {
	$('body').append('<div id="dialogAjaxError" title="System Error"><table border="0" cellpadding="5" cellspacing="0" class="fullWidth fullHeight"><tbody><tr><td align="center" valign="middle" class="modal-dialog-icon"><span class="ui-icon ui-icon-alert"></span></td><td align="left" valign="middle" class="modal-dialog-title">AJAX Request Failed.</td></tr><tr><td align="left" valign="middle" colspan="2" class="modal-dialog-description">There was an error processing a requested service and it could not be completed.</td></tr><tr><td align="left" valign="middle" colspan="2" class="modal-dialog-service">Service: </td></tr></tbody></table></div>');
	$('body').append('<div id="dialogFailedPrompt" title="Request Failed"><table border="0" cellpadding="5" cellspacing="0" class="fullWidth fullHeight"><tbody><tr><td align="center" valign="middle" class="modal-dialog-icon"><span class="ui-icon ui-icon-alert"></span></td><td align="left" valign="middle" class="modal-dialog-title">Request Failed.</td></tr><tr><td align="left" valign="middle" colspan="2" class="modal-dialog-description">The request has failed and it could not be completed.</td></tr></tbody></table></div>');
	$('body').append('<div id="dialogSuccessPrompt" title="Request Completed"><table border="0" cellpadding="5" cellspacing="0" class="fullWidth fullHeight"><tbody><tr><td align="center" valign="middle" class="modal-dialog-icon"><span class="ui-icon ui-icon-check"></span></td><td align="left" valign="middle" class="modal-dialog-title">Request Completed.</td></tr><tr><td align="left" valign="middle" colspan="2" class="modal-dialog-description">The request has been completed successfully.</td></tr></tbody></table></div>');
	$('body').append('<div id="dialogExpirationPrompt" title="Session Expiration Notice"><table border="0" cellpadding="5" cellspacing="0" class="fullWidth fullHeight"><tbody><tr><td align="center" valign="middle" class="modal-dialog-icon"><span class="ui-icon ui-icon-key"></span></td><td align="left" valign="middle" class="modal-dialog-title">Your Session will Expire Soon!</td></tr><tr><td align="left" valign="middle" colspan="2" class="modal-dialog-description">Due to a lack of activity, your session will automatically log you out if you do nothing. To remain connected, please extend your session or log out now.</td></tr></tbody></table></div>');
	$('#dialogAjaxError, #dialogFailedPrompt, #dialogSuccessPrompt, #dialogExpirationPrompt').hide();
	$('#dialogAjaxError').dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		buttons: {
			'Dismiss': function() {
				$(this).dialog('close');
			}
		}
	});
	$('#dialogFailedPrompt, #dialogSuccessPrompt').dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		buttons: {
			'Ok': function() {
				$(this).dialog('close');
			}
		}
	});
	$('#dialogExpirationPrompt').dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		buttons: {
			'Extend Session': function() {
				$(this).dialog('close');
				$.ajax({
					type: 'POST',
					url: frameworkIndexPage,
					data: frameworkRouteIndex + '=extend_session',
					dataType: 'json',
					error: function (XMLHttpRequest) {
						showModal('service', '', '', '', 'Session extension service failed.');
					},
					success: function (json) {
						if (json.error_msg != 'OK') {
							window.location.search = '?' + frameworkRouteIndex + '=logout&fr=400';
						}
					}
				});
			},
			'Log Out': function() {
				window.location.search = '?' + frameworkRouteIndex + '=logout';
			}
		}
	});
});

//////////////////////////////////////////////////////////////////////////////// Modal Access Functions
// Shows a specific modal prompt
// type: service | fail | success
function showModal(type, title, subject, errorMessage, errorService) {
	if (type == 'service') {
		if (title != '') {
			$('#ui-dialog-title-dialogAjaxError').text(title);
		} else {
			$('#ui-dialog-title-dialogAjaxError').text('System Error');
		}
		if (subject != '') {
			$('#dialogAjaxError td.modal-dialog-title').text(subject);
		} else {
			$('#dialogAjaxError td.modal-dialog-title').text('AJAX Request Failed.');
		}
		if (errorMessage != '') {
			$('#dialogAjaxError td.modal-dialog-description').text(errorMessage);
		} else {
			$('#dialogAjaxError td.modal-dialog-description').text('There was an error processing a requested service and it could not be completed.');
		}
		if (errorService != '') {
			$('#dialogAjaxError td.modal-dialog-service').text('Service: ' + errorService);
		} else {
			$('#dialogAjaxError td.modal-dialog-service').text('General service failure.');
		}
		$('#dialogAjaxError').dialog('open');
	} else if (type == 'fail') {
		if (title != '') {
			$('#ui-dialog-title-dialogFailedPrompt').text(title);
		} else {
			$('#ui-dialog-title-dialogFailedPrompt').text('Request Failed');
		}
		if (subject != '') {
			$('#dialogFailedPrompt td.modal-dialog-title').text(subject);
		} else {
			$('#dialogFailedPrompt td.modal-dialog-title').text('Request Failed.');
		}
		if (errorMessage != '') {
			$('#dialogFailedPrompt td.modal-dialog-description').text(errorMessage);
		} else {
			$('#dialogFailedPrompt td.modal-dialog-description').text('The request has failed and it could not be completed.');
		}
		$('#dialogFailedPrompt').dialog('open');
	} else if (type == 'success') {
		if (title != '') {
			$('#ui-dialog-title-dialogSuccessPrompt').text(title);
		} else {
			$('#ui-dialog-title-dialogSuccessPrompt').text('Request Completed');
		}
		if (subject != '') {
			$('#dialogSuccessPrompt td.modal-dialog-title').text(subject);
		} else {
			$('#dialogSuccessPrompt td.modal-dialog-title').text('Request Completed.');
		}
		if (errorMessage != '') {
			$('#dialogSuccessPrompt td.modal-dialog-description').text(errorMessage);
		} else {
			$('#dialogSuccessPrompt td.modal-dialog-description').text('The request has been completed successfully.');
		}
		$('#dialogSuccessPrompt').dialog('open');
	}
}
// Call this method to display the session expiration notice
function showExpirationPrompt() {
	$('#dialogExpirationPrompt').dialog('open');
}
// Call this method to close the session expiration notice
function hideExpirationPrompt() {
	$('#dialogExpirationPrompt').dialog('close');
}

//////////////////////////////////////////////////////////////////////////////// Loading Spinner
$(document).ready(function() {
	// Create the ajax loading dialog
	$('body').append('<div id="dialogAjaxLoader" class="pngAlphaFix"><div class="pngAlphaFix"></div></div>');
	plugin.centerElement($('#dialogAjaxLoader'));
	hideAjaxLoader();
});
function showAjaxLoader() {
	plugin.centerElement($('#dialogAjaxLoader')).show();
}
function hideAjaxLoader() {
	$('#dialogAjaxLoader').hide();
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////// 4. Custom JQuery UI Layout
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////// Layout Components
/*
<div class="uic-component-heading remove_border_bottom ui-corner-top">
	Heading
</div>
<div class="uic-component-box ui-corner-bottom">
	Content
</div>

<div>
	<div class="uic-component-panel-heading">
		<span class="ui-icon ui-icon-triangle-1-s"></span><span>Heading</span>
	</div>
	<div class="uic-component-panel-content">
		Content
	</div>
</div>

<table border="0" cellpadding="0" cellspacing="0" class="fullWidth uic-component-table">
	<thead class="table_corner">
		<tr>
			<td colspan="2">Header</td>
		</tr>
	</thead>
	<tfoot class="table_corner">
		<tr>
			<td>Footer</td>
			<td>Footer</td>
		</tr>
	</tfoot>
	<tbody class="table_corner table_highlight">
		<tr>
			<td align="right">Content</td>
			<td align="left">Content</td>
		</tr>
	</tbody>
</table>
*/
$(document).ready(function() {
	// Clear floats on layout components
	$('.uic-divider-main-left, .uic-divider-main-right, .uic-divider-equal').addClass('clear-floats');
	
	// Creates a single heading box
	$('.uic-component-heading').addClass('ui-state-hover uic-component-style-part-heading');
	// Creates a single content box
	$('.uic-component-box').addClass('ui-widget-content uic-component-style-part-box');
	
	// Creates a panel with heading and content
	$('.uic-component-panel-heading').addClass('ui-state-hover ui-corner-top uic-component-style-heading');
	$('.uic-component-panel-heading span.ui-icon').addClass('uic-component-style-heading-icon');
	$('.uic-component-panel-heading span:last').addClass('uic-component-style-heading-title');
	$('.uic-component-panel-content').addClass('ui-widget-content ui-corner-bottom uic-component-style-content remove_border_top');
	
	// Data tables styling
	$('table.uic-component-table > thead > tr > td').addClass('ui-state-hover uic-component-style-part-cell-heading');
	$('table.uic-component-table > tfoot > tr > td, table.uic-component-table > tbody > tr > td').addClass('ui-widget-content uic-component-style-part-cell remove_border_top');
	// Correct the borders
	$('table.uic-component-table > thead > tr:not(:first-child) > td').addClass('remove_border_top');
	$('table.uic-component-table > thead > tr > td:not(:last-child), table.uic-component-table > tfoot > tr > td:not(:last-child), table.uic-component-table > tbody > tr > td:not(:last-child)').addClass('uic-component-style-part-cell-side-fix');
	// Apply corners if needed
	$('table.uic-component-table > thead.table_corner > tr:first-child > td:first-child').addClass('ui-corner-tl');
	$('table.uic-component-table > thead.table_corner > tr:first-child > td:last-child').addClass('ui-corner-tr');
	$('table.uic-component-table > tfoot.table_corner > tr:last-child > td:first-child, table.uic-component-table > tbody.table_corner > tr:last-child > td:first-child').addClass('ui-corner-bl');
	$('table.uic-component-table > tfoot.table_corner > tr:last-child > td:last-child, table.uic-component-table > tbody.table_corner > tr:last-child > td:last-child').addClass('ui-corner-br');
	// Apply highlight if needed
	$('table.uic-component-table > tbody.table_highlight > tr').hover(
		function() {
			$('> td', this).addClass('uic-component-style-part-highlight');
		},
		function() {
			$('> td', this).removeClass('uic-component-style-part-highlight');
		}
	);
});

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////// 5. Custom JQuery Widgets
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

/* DEPRECATED
// Centers an element on the screen
jQuery.fn.centerElement = function() {
	$(this).css('position', 'absolute');
	$(this).css('top', (($(window).height() - $(this).height()) / 2) + $(window).scrollTop() + 'px');
	$(this).css('left', (($(window).width() - $(this).width()) / 2) + $(window).scrollLeft() + 'px');
	return this;
}
*/

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////// 6. Custom JQuery Plugins
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////// Namespace
// Configure a namespace called: plugin
if (typeof plugin == 'undefined') {
	var plugin = {};
}

//////////////////////////////////////////////////////////////////////////////// Form: Accessibility
// Put focus on first enabled input form element
plugin.formFocus = function() {
	$('input:text:visible:enabled:first').focus();
}

// Prevent specified form from being submitted
plugin.formPreventSubmit = function(selector) {
	selector.submit(function() {
		return false;
	});
}

// Form submit loading spinner
plugin.formSubmitSpinner = function() {
	showAjaxLoader();
}

//////////////////////////////////////////////////////////////////////////////// Form: Dropbox
// Remove all selector options
plugin.dropboxRemoveOptions = function(selector) {
	selector.children().remove();
}

// Append selector options with specified dual keys and values array
plugin.dropboxAddOptions = function(selector, keys, values) {
	for (i = 0; i < keys.length; i++) {
		selector.append($('<option></option>').val(keys[i]).html(values[i]));
	}
}

//////////////////////////////////////////////////////////////////////////////// Form: Hidden Data Elements
// Returns a hidden input form field with supplied parameters
// Returns: <input type='hidden'> element with value
plugin.createDataElement = function(id, value) {
	if ((id == '') || (typeof id == 'undefined')) {
		id = 'cache';
	}
	return $('<input type="hidden"></input>')
		.attr('id', id)
		.attr('name', id)
		.val(value);
}

//////////////////////////////////////////////////////////////////////////////// Layout: Element Centering
plugin.centerElement = function(my_selector, of_selector) {
	if ((of_selector == '') || (typeof of_selector == 'undefined')) {
		of_selector = $(window);
	}
	my_selector.position({
		my: 'center',
		at: 'center',
		of: of_selector,
		offset: '0',
		collision: 'none'
	});
}

//////////////////////////////////////////////////////////////////////////////// Layout: Error Animations
// Shows error style
plugin.rowErrorShow = function(selector) {
	selector.addClass('form-style-error');
}

// Hides error style
plugin.rowErrorHide = function(selector) {
	selector.removeClass('form-style-error');
}

//////////////////////////////////////////////////////////////////////////////// Logic: Regex Validators
// Accepts only: ^([a-zA-Z0-9_- &.]+)$
// Returns: true | false
plugin.regexNames = function(value) {
	var regexPattern = /^([a-zA-Z0-9_\-\s\&\.]+)$/;
	if (regexPattern.test(value)) {
		return true;
	} else {
		return false;
	}
}

//////////////////////////////////////////////////////////////////////////////// JQueryUI: Autocomplete Dropdowns
						/*
						// Lists all funds
						plugin.autocompleteAllFunds = function(selector, fiscalPackage) {
							selector.autocomplete({
								delay: 300,
								minLength: 1,
								source: function(request, response) {
									$.ajax({
										type: 'GET',
										url: frameworkIndexPage,
										data: frameworkRouteIndex + '=ajax_get_all_funds'
											+ '&fiscalPackage=' + encodeURIComponent(fiscalPackage)
											+ '&queryString=' + encodeURIComponent(request.term),
										dataType: 'xml',
										async: true,
										error: function (XMLHttpRequest) {
											showModal('service', '', '', '', 'There was an error while attempting to retrieve the funds list.');
										},
										success: function(xml) {
											response(
												$('item', xml).map(function() {
													return {
														value: $('fund_tag', this).text(),
														label: $('fund_name', this).text()
													};
												})
											);
										}
									})
								}
							}).data('autocomplete')._renderItem = function(ul, item) {
								return $('<li></li>')
									.data('item.autocomplete', item)
									.addClass('text-align-left')
									.append('<a><strong>' + item.label + '</strong><br />' + item.value + '</a>')
									.appendTo(ul);
							};
						}
						*/

						/*
						// Lists fundable funds only
						plugin.autocompleteFundables = function(selector, fiscalPackage) {
							selector.autocomplete({
								delay: 300,
								minLength: 1,
								source: function(request, response) {
									$.ajax({
										type: 'GET',
										url: frameworkIndexPage,
										data: frameworkRouteIndex + '=ajax_get_fundables'
											+ '&fiscalPackage=' + encodeURIComponent(fiscalPackage)
											+ '&queryString=' + encodeURIComponent(request.term),
										dataType: 'xml',
										async: true,
										error: function (XMLHttpRequest) {
											showModal('service', '', '', '', 'There was an error while attempting to retrieve the funds list.');
										},
										success: function(xml) {
											response(
												$('item', xml).map(function() {
													return {
														value: $('fund_tag', this).text(),
														label: $('fund_name', this).text()
													};
												})
											);
										}
									})
								}
							}).data('autocomplete')._renderItem = function(ul, item) {
								return $('<li></li>')
									.data('item.autocomplete', item)
									.addClass('text-align-left')
									.append('<a><strong>' + item.label + '</strong><br />' + item.value + '</a>')
									.appendTo(ul);
							};
						}
						*/

//////////////////////////////////////////////////////////////////////////////// JQueryUI: Datepicker
						/*
						// Display a single date panel
						plugin.datepicker = function(selector) {
							selector.datepicker({
								beforeShow: function(element) {
									$.datepicker._gotoToday = function(id) {
										selector.val('31/12/9999');
										this._hideDatepicker();
									}
								},
								changeMonth: true,
								changeYear: true,
								numberOfMonths: 1,
								dateFormat: 'dd/mm/yy',
								currentText: 'Indefinite',
								showButtonPanel: true
							});
						}
						*/
-->
