/************** GLOBAL VARIABLES **************/

/**
 * Used by the "coverThis" JQuery extension (see below)
 */
var coverCount = 0;

/**
 * Standard options for a JQuery dialog.
 */
var dialogOpts = {
		resizable: false,
		draggable: true,
		modal: true,
		autoOpen: false,
		position: [40, 40]	};

/** 
 * This global variable stores the site's "full BASE url" - e.g. "http://www.foo.com"
 * It is used when injecting CSS files with an absolute URL to prevent problems in IE6 & IE7.
 * (see "orbisApp.components" below) 
 *
 * FIXME: this variable should be a member of the orbisApp object itself.
 */
var fullBaseURL = window.location.protocol + "//" + window.location.hostname;


/************** GLOBAL JQUERY DOC-READY BLOCK **************
 * This is a global "document ready" block that applies 
 * various global behaviours to the entire site.
 */
$(document).ready(function() {	
	orbisApp.hideSuccessMsg();
	orbisApp.hideWarningMsg();
	orbisApp.renderNotePopups();
	orbisApp.renderButtons();
	orbisApp.setTextareaLimit();
	orbisApp.renderBlinkTags();
	
	$(".altStripe tr:even").css("background-color", "#E0E0E0");
	$(".altStripe tr:odd").css("background-color", "#EAEAEA");
	
	//Firefox fix for radio button cycling issue
    if($.browser.mozilla)
	{
    	$("form").attr("autocomplete", "off");
	}
  
    if($.browser.msie && $.browser.version == "6.0")
	{
    	orbisApp.defaultDialogOpts.modal = false;
	}
});


/************** GLOBAL OBJECT: orbisApp **************
 * "orbisApp" is a global object that holds various 
 * utility methods that are used throughout the site.
 */
var orbisApp = {

	/**
	 * "addComponent" function is called by the JSP to dynamically 
	 * inject a component from "this.components" in the the <head>
	 */
	addComponent : function(component) {
		var c = this.components[component];
		
		if (c)
		{
			if (c.loaded === false)
			{
				if(c.dependencies)
				{
					for(var i = 0; i < c.dependencies.length; i++)
					{
						this.addComponent(c.dependencies[i]);				
					}
				}			
	
				$("head").append(c.tag);			
				c.loaded = true;
			}
		}
		else
		{
			this.alertDialog("Error -> orbisApp.addComponent() -> Component '" + component + "' is undefined.", true, 300);
		}				
	},

	/**
	 * This is the global map of all the available "components" that a JSP can choose from. 
	 */
	components : {
		
		alphanumeric : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery-alphanumeric-0.1.1/jquery.alphanumeric.pack.js'></script>",
			loaded : false
		},
		
		jqueryAutocomplete : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery.autocomplete-1.0.2/jquery.autocomplete.pack.js'></script>",
			dependencies : ["jqueryAutocomplete_css"],
			loaded : false
		},
		
		jqueryAutocomplete_css : {
			tag : "<link type='text/css' rel='Stylesheet' href='" + fullBaseURL + "/core/scripts/jquery/jquery.autocomplete-1.0.2/jquery.autocomplete.css' />",
			loaded : false
		},
		
		jqGrid : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery.jqGrid-3.8.2/js/jquery.jqGrid.min.js'></script>",
			dependencies : ["jqGrid_css", "jqGrid_locale", "multiselect", "json", "OrbisGrid"],
			loaded : false
		},
		
		jqGrid_css : {
			tag : "<link type='text/css' rel='stylesheet' href='" + fullBaseURL + "/core/scripts/jquery/jquery.jqGrid-3.8.2/css/ui.jqgrid.css' />",
			loaded : false
		},

		jqGrid_locale : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery.jqGrid-3.8.2/js/i18n/grid.locale-"+orbisLocale+".js'></script>",
			loaded : false
		},
		
		multiselect : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery.multiselect-1.8/js/ui.multiselect.js'></script>",
			dependencies : ["multiselect_css"],
			loaded : false
		},
		
		multiselect_css : {
			tag : "<link type='text/css' rel='stylesheet' href='" + fullBaseURL + "/core/scripts/jquery/jquery.multiselect-1.8/css/ui.multiselect.css' />",
			loaded : false
		},
		
		json : {
			tag : "<script type='text/javascript' src='/core/scripts/json/json2.js'></script>",
			loaded : false
		},

		OrbisGrid : {
			tag : "<script type='text/javascript' src='/core/scripts/orbis/orbisGrid/OrbisGrid.js'></script>",
			loaded : false
		},
		
		blockUI : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery.blockUI-2.31/jquery.blockUI.js'></script>",
			loaded : false
		},
		
		form : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery.form-2.43/jquery.form.js'></script>",
			loaded : false
		},
		
		calendar : {
			tag : "<script type='text/javascript' src='/core/scripts/calendar/calendar-setup.js'></script>",
			dependencies : ["calendar_css", "calendar_js", "calendar_en"],
			loaded : false
		},
		
		calendar_js : {
			tag : "<script type='text/javascript' src='/core/scripts/calendar/calendar.js'></script>",
			loaded : false
		},

		calendar_css : {
			tag : "<link type='text/css' rel='stylesheet' href='" + fullBaseURL + "/core/scripts/calendar/calendar-blue.css' />",
			loaded : false
		},
		
		calendar_en : {
			tag : "<script type='text/javascript' src='/core/scripts/calendar/lang/calendar-en.js'></script>",
			loaded : false
		},
		
		/**
		 * Note: JQuery Validate must be imported before the additional methods.
		 */
		jqueryValidate : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery-validation-1.8.1/additional-methods.min.js'></script>",
			dependencies : ["jqueryValidate_css", "jqueryValidateJS"],
			loaded : false
		},
		
		jqueryValidateJS : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery-validation-1.8.1/jquery.validate.min.js'></script>",
			loaded : false
		},
		
		jqueryValidate_css : {
			tag : "<link type='text/css' rel='stylesheet' href='" + fullBaseURL + "/core/css/jquery-validate.css' />",
			loaded : false
		},
		
		jqueryTooltip : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery-tooltip-1.3/jquery.tooltip.min.js'></script>",
			dependencies : ["bgiFrame", "delegate", "dimentions"],
			loaded : false
		},
		
		bgiFrame : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery-tooltip-1.3/lib/jquery.bgiframe.js'></script>",
			loaded : false
		},
		
		delegate : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery-tooltip-1.3/lib/jquery.delegate.js'></script>",
			loaded : false
		},
		
		dimentions : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery-tooltip-1.3/lib/jquery.dimensions.js'></script>",
			loaded : false
		},
		
		tooltip : {
			tag : "<script type='text/javascript' src='/core/scripts/tooltip/form-field-tooltip.js'></script>",
			loaded : false
		},
		
		tooltipCorners : {
			tag : "<script type='text/javascript' src='/core/scripts/tooltip/rounded-corners.js'></script>",
			loaded : false
		},
		
		tooltip_css : {
			tag : "<link type='text/css' rel='stylesheet' href='" + fullBaseURL + "/core/css/tooltip/form-field-tooltip.css' />",
			loaded : false
		},
		
		md5 : {
			tag : "<script type='text/javascript' src='/core/scripts/md5.js'></script>",
			loaded : false
		},
		
		FusionCharts : {
			tag : "<script type='text/javascript' src='/core/scripts/FusionCharts.js'></script>",
			loaded : false
		},
		
		keepAlive : {
			tag : "<script type='text/javascript' src='/core/scripts/orbis/keepAlive.js'></script>",
			loaded : false
		},
		
		zrssfeed : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/zrssfeed-101/jquery.zrssfeed.min.js'></script>",
			loaded : false
		},	
		
		tree : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery-wdTree/src/Plugins/jquery.tree.js'></script>",
			dependencies : ["tree_css", "treeTools"],
			loaded : false
		},
		
		tree_css : {
			tag : "<link type='text/css' rel='stylesheet' href='" + fullBaseURL + "/core/scripts/jquery/jquery-wdTree/css/tree.css' />",
			loaded : false
		},
		
		treeTools : {
			tag : "<script type='text/javascript' src='/core/scripts/orbis/treeTools/treeTools.js'></script>",
			loaded : false
		},
		
		dragscrollable : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery.dragscrollable-1.0/dragscrollable.js'></script>",
			loaded : false 
		},
		
		myideaTools : {
			tag : "<script type='text/javascript' src='/core/scripts/orbis/myidea/myidea_tools.js'></script>",
			loaded : false
		},
		
		colorPicker : {
			tag : "<script type='text/javascript'src='/core/scripts/jquery/jquery-colorpicker-1.4/colorpicker.js'></script>",
			dependencies : ["colorPicker_css", "colorPicker_layoutCss"],
			loaded : false
		},
		
		colorPicker_css : {
			tag : "<link rel='stylesheet' href='" + fullBaseURL + "/core/scripts/jquery/jquery-colorpicker-1.4/css/colorpicker.css' type='text/css' />",			
			loaded : false
		},
		
		colorPicker_layoutCss : {
			tag : "<link rel='stylesheet' media='screen' type='text/css' href='" + fullBaseURL + "/core/scripts/jquery/jquery-colorpicker-1.4/css/layout.css' />",
			loaded : false
		},
		
		hoverIntent : {
			tag : "<script type='text/javascript' src='/core/scripts/jquery/jquery.hoverIntent-r5/jquery.hoverIntent.minified.js'></script>",
			loaded : false
		},
		
		lightbox : {
			tag : '<script type="text/javascript" src="/core/scripts/jquery/jquery-lightbox-0.5/js/jquery.lightbox-0.5.pack.js"></script>',
			dependencies : ["lightbox_css"],
			loaded : false
		},
		
		lightbox_css : {
			tag : '<link rel="stylesheet" type="text/css" href="' + fullBaseURL + '/core/scripts/jquery/jquery-lightbox-0.5/css/jquery.lightbox-0.5.css" media="screen" />',
			loaded : false
		},
		
		uploadify : {
			tag : '<script type="text/javascript" src="/core/scripts/jquery/jquery.uploadify-2.0.3/jquery.uploadify.v2.0.3.ForOch.min.js"></script>',
			dependencies : ["uploadify_css", "swfobject"],
			loaded : false
		},
		
		uploadify_css : {
			tag : '<link href="' + fullBaseURL + '/core/scripts/jquery/jquery.uploadify-2.0.3/css/style.css" rel="stylesheet" type="text/css" />',
			loaded : false
		},
		
		swfobject : {
			tag : '<script type="text/javascript" src="/core/scripts/swfobject_2_2.js"></script>',
			loaded : false
		},
		
		fckEditor : {
			tag : '<script type="text/javascript" src="/fckeditor.js"></script>',
			loaded : false
		},
		
		youtubin : {
			tag : '<script type="text/javascript" src="/core/scripts/jquery/jquery.youtubin-1.2/jquery.youtubin.js"></script>',
			dependencies : ["swfobject"],
			loaded : false
		},

		simpleviewer : {
			tag : '<script type="text/javascript" src="/core/scripts/simpleviewer_pro_210/js/simpleviewer.js"></script>',
			dependencies : ["swfobject"],
			loaded : false
		},
		
		orbisSlideshow : {
			tag : '<script type="text/javascript" src="/core/scripts/orbis/orbisSlideshow/orbisSlideshow-2.js"></script>',
			dependencies : ["orbisSlideshow_css"],
			loaded : false
		},
		
		orbisSlideshow_css : {
			tag : '<link href="' + fullBaseURL + '/core/scripts/orbis/orbisSlideshow/orbisSlideshow.css" rel="stylesheet" type="text/css" />',
			loaded : false
		},
		
		clockPick : {
			tag : '<script type="text/javascript" src="/core/scripts/jquery/jquery-clockpick-1.2.5/jquery.clockpick.1.2.5.min.js"></script>',
			dependencies : ["clockPick_css"],
			loaded : false
		},
		
		clockPick_css : {
			tag : '<link href="' + fullBaseURL + '/core/scripts/jquery/jquery-clockpick-1.2.5/clockpick.1.2.5.css" rel="stylesheet" type="text/css" />',
			loaded : false
		},

		orbisChat : {
			tag : '<script type="text/javascript" src="/core/scripts/orbis/orbisChat/orbisChat.js"></script>',
			dependencies : ["orbisChat_css"],
			loaded : false
		},
		
		orbisChat_css : {
			tag : '<link href="' + fullBaseURL + '/core/scripts/orbis/orbisChat/orbisChat.css" rel="stylesheet" type="text/css" />',
			loaded : false
		},
		
		scrollTo : {
			tag : '<script type="text/javascript" src="/core/scripts/jquery/jquery.scrollTo-1.4.2/jquery.scrollTo-min.js"></script>',
			loaded : false
		},
		
		printElement : {
			tag : '<script type="text/javascript" src="/core/scripts/jquery/jquery.printElement-1.2/jquery.printElement.min.js"></script>',
			loaded : false
		},
		
		orbisDropdownMenu : {
			tag : '<script type="text/javascript" src="/core/scripts/orbis/orbisDropdownMenu/orbisDropdownMenu.js"></script>',
			dependencies : ["orbisDropdownMenu_css"],
			loaded : false
		},
		
		orbisDropdownMenu_css : {
			tag : '<link href="' + fullBaseURL + '/core/scripts/orbis/orbisDropdownMenu/orbisDropdownMenu.css" rel="stylesheet" type="text/css" />',
			loaded : false
		},
		
		jqueryTools : {
			tag : '<script type="text/javascript" src="/core/scripts/jquery/jquery-tools-1.2.5/jquery.tools.min.js"></script>',
			loaded : false
		},

		highCharts : {
			tag : '<script type="text/javascript" src="/core/scripts/jquery/jquery.highcharts-2.1.6/js/highcharts.js"></script>',
			loaded : false
		}
	},
	
	/** 
	 * "hideSuccessMsg" automatically hides "successMsgFadeout" div's after 5 seconds
	 */
	hideSuccessMsg : function() {
		$(".successMsgFadeout:visible").stepDelay(5000, function() {$(this).fadeOut("slow")});
	},
	
	/** 
	 * "hideWarningMsg" automatically hides "warningMsgFadeout" div's after 5 seconds
	 */
	hideWarningMsg : function() {
		$(".warningMsgFadeout:visible").stepDelay(5000, function() {$(this).fadeOut("slow");});
	},

	/** 
	 * Note system
	 * Create a span with class="notePopup" around the note text where you want the link to be
	 * set the span style="display:none;" <- This fixes a minor glitch where the popup text would display before being replaced by 'Note'
	 * To edit the link style use the class ".noteLink"
	 */
	renderNotePopups : function() {
		var noteDialogNum = 0;
		$("span.notePopup").each(function(){
			var noteText = $(this).html();
			var dialogId = "note"+noteDialogNum;
			var thisDialog = "div[aria-labelledby='ui-dialog-title-" + dialogId + "']";
			var setTitle = "<img src=\"/core/images/iconHelp.gif\" alt=\"Click here for more information\" style=\"width: 14px; height: 14px; margin-top: 3px; margin-left: 5px;\" /> " + $(this).attr("noteTitle"); 
			$("body").prepend("<div title='"+setTitle+"' class='notePopupClass' id='"+dialogId+"' style='display:none; width: 100%; height: 100%;' title=' '><div class='noteText'>"+noteText+"</div></div>");		
			orbisApp.setUpRegularDialog("#"+dialogId, {}, {width: 400});
			//$(thisDialog).find('div.ui-widget-header').css({'background':'#B90101'});
			$(this).html("<a href='#' class='noteLink' onClick=\"$('#"+dialogId+"').dialog('open'); return false;\"><img src='/core/images/iconHelp.gif' alt='Click here for more information' style='width: 14px; height: 14px; margin-top: 3px; margin-left: 5px;' /></a>");
			$(this).css({display:"inline"});
			$(".noteText").css({"font-size":11, "line-height":1});

			noteDialogNum++;
		});		
	},
	
	/** 
	 * Button system
	 *
	 * Create a div with a class of "largeTestButton", "mediumTestButton" or "smallTestButton" with a form followed by text
	 * The form does not require the method or the Id attributes, they will be set within this function.
	 * 
	 * For buttons to execute local functions, add the attributes callback(function name OR inline function)
	 * Note: args MUST be a delimited string sepparated by commas(,) and the function will receive a String[]
	 *
	 * To make buttons go to some URL, do something like this...
	 * <div class="mediumTestButton"><a href="http://www.website.com?foo=bar">Click Me</a></div>
	 *
	 * Button Note: to override any of the css styles, apply the style to the button div with the !important attribute
	 * eg: <div class="largeTestButton" style="width: 100px !important"><form><input ...></form>Button Text</div>
	 */
	renderButtons : function() {		

		$(".largeTestButton[buttonRendered!='true']").each(function(){
			var style = new Object();
			style.width = "98%";
			style.margin = "1px";
			style.fontWeight = "bold";
			style.fontSize = "16px";
			orbisApp.setupButtons(this, style);
		});
		$(".mediumTestButton[buttonRendered!='true']").each(function(){
			var style = new Object();
			style.width = "98%";
			style.margin = "1px";
			style.fontWeight = "bold";
			style.fontSize = "12px";
			orbisApp.setupButtons(this, style);
		});
		$(".smallTestButton[buttonRendered!='true']").each(function(){
			var style = new Object();
			style.width = "98%";
			style.margin = "1px";
			style.fontWeight = "bold";
			style.fontSize = "9px";
			orbisApp.setupButtons(this, style);
		});
		$(".orbisLink[buttonRendered!='true']").each(function(){
			var style = new Object();
			style.width = "98%";
			style.margin = "1px";
			orbisApp.setupButtons(this, style);
		});
	},

	/**
	 * "orbisApp.checkAjaxResponse" is a utility method that can be used for 
	 * checking an ajax response for error conditions.  If such a 
	 * condition is detected then this method will perform the 
	 * appropriate UI behaviour, and also return FALSE which the 
	 * caller can use to stop normal application flow.
	 *
	 * @param xmlHttpRequest<XmlHttpRequest> - the ajax-object used to perform the ajax request.
	 * @return <boolean> - FALSE if there was a problem, otherwise TRUE
	 */
	checkAjaxResponse : function (xmlHttpRequest)
	{
		var happy = true;
		
		if (this.isEmpty(xmlHttpRequest))
		{
			happy = false;
			this.alertDialog("There has been a communication error with the server(1).  Please try again.", true, 300);			
		}
		else
		{
			if (!this.isEmpty(xmlHttpRequest.getResponseHeader("notLoggedIn")))
			{
				happy = false;
			    window.parent.location = "/notLoggedIn.htm";
			}
			else if (!this.isEmpty(xmlHttpRequest.getResponseHeader("portalError")))
			{
				happy = false;
			    window.parent.location = "/portalError.htm";
			}
			else if (this.isEmpty(xmlHttpRequest.status))
			{
				happy = false;
				this.alertDialog("There has been a communication error with the server(2).  Please try again.", true, 300);			
			}
			else if (xmlHttpRequest.status != 200)
			{
				happy = false;
				this.alertDialog("There has been a communication error with the server(3).  Please try again.", true, 300);			
			}
		}
		
		return happy;
	},
	
	/**
	 * Returns TRUE if s is a "valid email address", otherwise returns FALSE
	 */
	isValidEmail : function (s)
	{
	   return !this.isEmpty(s) && s.indexOf(" ") < 0 && (s.indexOf(".") > 2) && (s.indexOf("@") > 0);
	},
	
	isArray : function (obj)
	{
		return !this.isEmpty(obj) && !this.isEmpty(obj.length);
	},
	
	/**
	 * Returns TRUE if obj is "empty", otherwise returns FALSE
	 */
	isEmpty : function (obj)
	{
		var empty = false;
		
		if (typeof obj == "undefined" || obj == null || obj == "")
		{
			empty = true;
		}
		
		return empty;
	},
	
	/**
	 * Returns the specified "str" without the left or right
	 * "chars".
	 */
	trim : function (str, chars) {
		return this.ltrim(this.rtrim(str, chars), chars);
	},
	 
	/**
	 * Returns the specified "str" without the left "chars".
	 */
	ltrim : function (str, chars) {
		chars = chars || "\\s";
		return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
	},
	 
	/**
	 * Returns the specified "str" without the right "chars".
	 */
	rtrim : function (str, chars) {
		chars = chars || "\\s";
		return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
	},
	
	
	/*********** DATEPICKER STUFF **************/
	
	/**
	 * "defaultDatePickerOpts" is used to set the standard options
	 * for a JQuery datepicker. 
	 *
	 * example: $("#fooInput").datepicker(orbisApp.defaultDatePickerOpts);
	 */
	defaultDatePickerOpts : {
		buttonImage: "/core/images/icons/calendar-16x16.png",
		buttonImageOnly: true,
		buttonText: "",
		changeMonth: true, 
		changeYear: true,
		dateFormat: "mm/dd/yy",
		yearRange:"-100:+15",
		showAnim: "fadeIn",
		showOn: "both"},
	
	/*********** DIALOG STUFF **************/
	
	numOfDialogs : 0,
	
	defaultDialogOpts : {
		resizable: false,
		draggable: true,
		modal: true,
		autoOpen: false,
		dialogClass: "orbisDialog",
		width: 600
		},
			
	/**
	 * A "private" function use for supporting dialog functionality.
	 */
	resetDialog : function (dialogDiv, options)
	{
		var dName;
		if (dialogDiv.substr(0, 1) == "#")
		{
			dName = $(dialogDiv).attr("id");
		}
		else if (dialogDiv.substr(0, 1) == ".")
		{
			dName = $(dialogDiv).attr("class");
		}
		else 
		{
			dName = dialogDiv;
		}
	
		var showTitle = $(dialogDiv).attr("title") != undefined && $(dialogDiv).attr("title") != null && $(dialogDiv).attr("title") != "";
	
		if (options)
		{
			$(dialogDiv).dialog(options);
		}
		else
		{
			$(dialogDiv).dialog(this.defaultDialogOpts);
		}	
		
		var thisDialog = $("div[aria-labelledby='ui-dialog-title-" + dName + "']");
	
		if (!showTitle)
		{		
			$(thisDialog).find(".ui-dialog-titlebar").css({"display" : "none"});
		}
		else
		{
			$(thisDialog).find(".ui-dialog-titlebar").css({"display" : "block"});
		}
	
		$(dialogDiv).dialog('option', 'open', function() { 
			$(this).css({'max-height': ($(window).height()-160), 'overflow-y':'auto'}); 
			$('.orbisDialog').css({position:"fixed", "top" : "40px", left : "40px"});
			if (options && options.open)
			{
				options.open();
			}
		});
		
		$(dialogDiv).dialog('option', 'buttons', {"Close": function(){ $(dialogDiv).dialog("close");}});		
		$(dialogDiv).dialog('option', 'closeOnEscape', true );			
	},
	
	/**
	 * A utiltiy for turning any <div> into a standard dialog.  Once 
	 * this method is called, the target div will be turned into a dialog
	 * but you are still required to call $(divClassOrId).dialog("open");
	 * and $(divClassOrId).dialog("close"); to open and close the dialog
	 * respectively.
	 * 
	 * @param divClassOrId - a JQuery selector to your target div
	 * @param buttons - a JQuery dialog button object (for custom buttons)
	 * @param opts - a JQuery dialog options object (for custom dialog behaviour)
	 */
	setUpRegularDialog : function (divClassOrId, buttons, opts)
	{
		if($(divClassOrId).is(':data(dialog)'))
		{
			$(divClassOrId).dialog("destroy");
		}

		this.resetDialog(divClassOrId, this.extendOptions(opts));			 	
		
		if(buttons && buttons != null)
		{
			$(divClassOrId).dialog('option', 'buttons', buttons);
		}	
	},
	
	/**
	 * A "private" function use for supporting dialog functionality.
	 */
	extendOptions : function (options)
	{
		var extendableOpts = new Object();
		$.extend(extendableOpts, this.defaultDialogOpts);
		if (options)
		{
			return $.extend(extendableOpts, options);
		}
		return extendableOpts;
	},
	
	/**
	 * A utility for showing a standard "confirmation dialog"
	 * 
	 * @param message<string> - the text to be displayed in the dialog
	 * @param okCallback<function> - the callback to be fired when "Ok" gets clicked.
	 * @param cancelCallback<function> - the callback to be fired when "Cancel" gets clicked.
	 */
	confirmDialog : function (message, okCallback, cancelCallback, width)
	{	
		var dName = this.createDialogDiv();
		$("#" + dName).attr("title", "Confirmation");
		var opts = {"close": function() {if($("#" + dName).is(':data(dialog)')){$("#" + dName).dialog("destroy");}}};	
		this.resetDialog("#" + dName, this.extendOptions(opts));
		var thisDialog = $("div[aria-labelledby='ui-dialog-title-" + dName + "']");
		
		var r;
		
		if(width)
		{
			$("#" + dName).dialog('option', 'width', width);
		}
		else
		{
			$("#" + dName).dialog('option', 'width', '');
		}
		
		$("#" + dName).dialog('option', 'buttons', '');
		$("#" + dName).dialog('option', 'buttons', {
										"OK": function(){ 
											$("#" + dName).dialog("close"); 									
											if (okCallback)
											{
												okCallback();
											}
										},
										"Cancel": function(){
											$("#" + dName).dialog("close"); 
											if (cancelCallback)
											{
												cancelCallback();
											}
										}																
									});
		
		$("#" + dName).html("<div id='centerThis'>" + message + "</div>");		
		$("#" + dName).dialog("open");					
		$(thisDialog).find(".ui-dialog-buttonpane button").css({"float":"none"}); //these 3 lines will hack the default UI settings and make the buttons center
		$(thisDialog).find(".ui-dialog-buttonpane").css({"text-align":"center"});
		$(thisDialog).find(".ui-dialog-buttonpane").css({"padding":"0px"});	
		$(thisDialog).find(".ui-dialog-title").css({"width":"100%", "text-align":"center"});	
			
		this.centerDiv("#" + dName, "#centerThis");		
		
		return "#" + dName;
	},
	
	/**
	 * A utility for showing a standard "alert dialog"
	 * 
	 * @param message<string> - the text to be displayed in the dialog
	 * @param error<boolean> - when TRUE, the dialog will be styled as an "error alert".
	 * @param width<number>[optional] - the pixel-width of the dialog.
	 */
	alertDialog : function (message, error, width)
	{	
		var dName = this.createDialogDiv();
		$("#" + dName).attr("title", "Alert");
		var opts = {"close": function() {if($("#" + dName).is(':data(dialog)')){$("#" + dName).dialog("destroy");}}};	
		this.resetDialog("#" + dName, this.extendOptions(opts));
		var thisDialog = $("div[aria-labelledby='ui-dialog-title-" + dName + "']");
		
		var r;

		if (width)
		{
			width = width + "px";
		}
		else
		{
			width = '';
		}
					
		$("#" + dName).dialog('option', 'width', width);
		$("#" + dName).dialog('option', 'buttons', '');
		$("#" + dName).dialog('option', 'buttons', {
									"OK": function(){ 
										$("#" + dName).dialog("close"); 									
										}															
									});
		$("#" + dName).html("<div id='centerThis'>" + message + "</div>");		
		$("#" + dName).dialog("open");
		
		if(error)
		{
			$("#" + dName).addClass("ui-state-error");
			$(thisDialog).find(".ui-dialog-title").css({"color":"#FFFFFF"});		
			$(thisDialog).find(".ui-dialog-titlebar").css({"background":"#B90101"});
		}
									
		$(thisDialog).find(".ui-dialog-title").css({"width":"100%", "text-align":"center"});
		$(thisDialog).find(".ui-dialog-title").css({"display" : "block", "padding-left":"0px", "padding-right":"0px"});//display title bar	
		$(thisDialog).find(".ui-dialog-buttonpane button").css({"float":"none"}); //these 2 lines will hack the default UI settings and make the buttons center
		$(thisDialog).find(".ui-dialog-buttonpane").css({"text-align":"center", "padding":"0px"});
		
		this.centerDiv("#" + dName, "#centerThis");
		
		return "#" + dName;		
	},
	
	/**
	 * A utility for showing a standard "message dialog"
	 * NOTE: you must call "closeTempMessageDialog" to close it
	 * 
	 * @param text<string> - the message to display in the pop-up
	 * @param waitBar<boolean> - will show a "loading graphic" when TRUE
	 * @returns <string> - the JQuery selector of the pop-up (to be passed in the "closeTempMessageDialog" call)  
	 */
	openTempMessageDialog : function (text, waitBar)
	{		
		var dName = this.createDialogDiv();
		var opts = {"close": function() {if($("#" + dName).is(':data(dialog)')){$("#" + dName).dialog("destroy");}}};	
		this.resetDialog("#" + dName, this.extendOptions(opts));
		
		if (waitBar)
		{
			 text += " <br /> <img src='/core/images/loading2.gif' />";
		}
		
		$("#" + dName).html("<div class='textToCenter-" + dName + "'>" + text + "</div>");
		$("#" + dName).dialog("option", "buttons", "");
		$("#" + dName).dialog('option', 'width', "300");	
		$("#" + dName).dialog('option', 'closeOnEscape', false );	
		$("#" + dName).dialog("open");
		this.centerDiv("#" + dName, ".textToCenter-" + dName);
		
		return "#" + dName;
	},
	
	/**
	 * A utility for closing a standard "message dialog"
	 *
	 * @param dName<string> - the JQuery selector that should be used for closing the "tempMessageDialog"
	 */
	closeTempMessageDialog : function (dName)
	{
		$(dName).dialog("close");	
	},
	
	/**
	 * A utility for showing a standard "message dialog" which will
	 * automatically close after the specified "mili" seconds.
	 * 
	 * @param text<string> - the message to display in the pop-up
	 * @param mili<int> - this lengh of time (in miliseconds) before the pop-up closes
	 * @param callback<function> - the callback that will be fired after the pop-up closes
	 */
	timedMessageDialog : function (text, mili, callback)
	{
		var toClose = this.openTempMessageDialog(text);
		$(toClose).stepDelay(mili, function() {orbisApp.closeTempMessageDialog(toClose);});
		if (callback) { 
			$("html").stepDelay(mili, function() {callback();}); 
		}	
	},
	
	/**
	 * A "private" function use for supporting dialog functionality.
	 */
	centerDiv : function (nameOfContainer, nameOfChild)
	{
		cHeight = $(nameOfContainer).height();
		cWidth = $(nameOfContainer).width();
		
		tHeight = $(nameOfContainer + " " + nameOfChild).height();
		tWidth = $(nameOfContainer + " " + nameOfChild).width();
		
		$(nameOfContainer + " " + nameOfChild).css({"text-align" : "center"});	
		$(nameOfContainer + " " + nameOfChild).css({"margin-top" : ((cHeight/2) - (tHeight/2))});
		$(nameOfContainer + " " + nameOfChild).css({"margin-left" : ((cWidth/2) - (tWidth/2))});
	},
	
	/**
	 * A "private" function use for supporting dialog functionality.
	 */
	createDialogDiv : function ()
	{
		this.numOfDialogs++;
		var dName = "dialog_" + this.numOfDialogs;
		$("body").append("<div id='" + dName + "'></div>");
		return dName;
	},
	
	/**
	* function used within orbisApp.renderButtons()	
	*/
	setupButtons : function (entity, style)
	{
		var callback;
		var buttonText;
		var uniqueId = Math.floor(Math.random()*100000);				
		var icons = new Object();
		
		if($(entity).attr("primaryIcon"))
		{
			icons.primary = $(entity).attr("primaryIcon"); 
		}
		if($(entity).attr("secondaryIcon"))
		{
			icons.secondary = $(entity).attr("secondaryIcon"); 
		}
		
		style.icons = icons;
		
		if($(entity).attr("width"))
		{
			if ($(entity).attr("width") == "auto") {
				style.width = "";
			} else {
				style.width = $(entity).attr("width");
			}
		}
		
		orbisApp.addComponent("json");
				
		if($(entity).attr("style"))
		{
			var styleArray = $(entity).attr("style").split(";");			
			for(var i = 0; i < styleArray.length; i++)
			{
				var styleElement = styleArray[i].split(":");
				if(styleElement.length == 2)
				{					
					style[orbisApp.trim(styleElement[0], " ")] = orbisApp.trim(styleElement[1], " ");
				}
			}
		}
		
		if($(entity).find("form").length != 0)
		{
			$(entity).find("form").attr("method", "post");
			$(entity).find("form").attr("id", uniqueId);
			$("body").append($(entity).find("form"));
			$(entity).find("form").remove();
	
			callback = function(){
				if($(entity).hasClass("confirm"))
				{
					orbisApp.confirmDialog("Are you sure?", function(){
						$("form#" + uniqueId).submit();
					});
				}
				else
				{
					$("form#" + uniqueId).submit();
				}
				
			};
			buttonText = $(entity).html();				
		}
		
		else if($(entity).find("a").length != 0)
		{
			var target = $(entity).find("a").attr("target");
			var href = $(entity).find("a").attr("href");
	
			if((target.toLowerCase() == "_blank") || (target.toLowerCase() == "blank"))
			{
				callback = function(){
					window.open(href);
				};
			}
			else
			{
				callback = function(){
					window.location = href;						
				};					
			}
			buttonText = $(entity).find("a").html();
		}		
		
		else
		{
			if($(entity).attr("callback"))	
			{
				var callbackText = $(entity).attr("callback");
				if(callbackText.match("^function\(\)"))
				{
					callback = new Function (callbackText.substr(11,callbackText.length - 12));
				}
				else
				{
					callback = function(){eval(callbackText)(entity)};
				}
			}
			
			else
			{
				callback = function(){};
				style.fontWeight = "";
			}
			
			buttonText = $(entity).html();
		}
		
		
		if($(entity).hasClass("orbisLink"))
		{
			var linkNumber = "link" + Math.floor(Math.random()*100000);
			$(entity).html('<a href="#" id="' + linkNumber + '">' + buttonText + '</a>');
			$("#" + linkNumber).click(function(){callback(); return false;});
		}
		else
		{
			$(entity).html(buttonText);
			$(entity).setUpButton(callback, style);
		}
		$(entity).attr("buttonRendered", "true");
	},
	
	/**
	 * function used within $.fn.tableHilight
	 */
	highlightHelper : function (entity, color)
	{	
		var col = $(entity).parent().children().index($(entity));
		$(entity).parent().parent().children().each(function(){
			$(this).find("td:eq("+col+")").css({background:color});
		});
		
		$(entity).parent().children().css({background:color});
	},
	
	/**
	* When this function is assigned to an anchor "onClick" event,
	* displayHome within the controller will be executed
	*/
	
	displayHome : function()
	{
		$("body").append("<form id='orbisAppDisplayHomeForm' method='post'><input type='hidden' name='action' value='displayHome' /></form>");
		$("form#orbisAppDisplayHomeForm").submit();
		return false;
	},
	
	setTextareaLimit : function()
	{
		var i = 0;
		$("textarea.maxlength, input[type='text'].maxlength").each(function(){
			var maxLength = 255;
			if($(this).attr("maxlength") && $(this).attr("maxlength") != -1)
			{
				maxLength = $(this).attr("maxlength");
			}
			var initialLength = maxLength - $(this).val().length;
			var counterId = "counter" + i;
			var counter = "<br />Characters Remaining: <span id='"+counterId+"'>"+initialLength+"</span>";
			$(this).attr("counterId", counterId);
			$(counter).insertAfter(this);
			
			$(this).bind("keydown keyup paste", function(){
				var entity = this;
				setTimeout(function(){
					var textEntered = $(entity).val();
					var count = $("span#" + $(entity).attr("counterId"));
					var finalValue = textEntered;
					if(textEntered.length > maxLength)
					{
						finalValue = textEntered.substr(0, maxLength);
						$(entity).val(finalValue);
					}
					count.html(maxLength - finalValue.length);
				}, 1);
			});
				
			i++;
		});
	},
	
	renderBlinkTags : function(){
		$("blink").each(function(){
			var entity = this;
			setInterval(function(){orbisApp.blink(entity);}, $(entity).attr("freq") ? $(entity).attr("freq") : 700);
		});
	},
	
	blink: function(entity){
		$(entity).css("visibility", $(entity).css("visibility") == "visible" ? "hidden" : "visible");
	}
};

/************** GLOBAL JQUERY EXTENSIONS **************/

$.fn.stepDelay = function(time, callback){
	$.fx.step.delay = function(){};
	return this.animate({delay:1}, time, callback); //the callback is the function that will wait for the delay to run before it executes
};

$.fn.coverThis = function(){
	if($(this).find("#" + $(this).attr("coverId")).length == 0)
	{
		$(this).attr("coverId", "cover" + coverCount);
		if($(this).css("position") == "static")
		{		
			$(this).css({"position":"relative"});
		}
		$(this).prepend("<div class='coverStyles' id='cover" + coverCount + "' style='margin-left: -"+$(this).css("padding-left")+"; margin-top: -"+$(this).css("padding-top")+";'></div>");		
		coverCount++;
	}
};

$.fn.uncoverThis = function(){	
	$(this).find("#" + $(this).attr("coverId")).remove();
	$(this).removeAttr("coverId");
};

$.fn.groupCheckboxes = function(selectAll){
		
	var checkAll = false;
	var groupOfChkBxs = this.selector;
	var lastChecked = null;	
	checkAll = $(groupOfChkBxs + ":checked").length == $(groupOfChkBxs).not(":disabled").length;		
	$(selectAll).attr('checked', checkAll);
	
	if(selectAll)
	{			
		$(selectAll).click(function() {			
			checkAll = $(selectAll).attr("checked");			
			$(groupOfChkBxs).not(":disabled").attr("checked", checkAll);			
		});
	}	
			
	$(groupOfChkBxs).click(function(event) {											
		if(!lastChecked) 
		{					
        	lastChecked = this;	              
        }

        if(event.shiftKey) 
        {        	
            var start = $(groupOfChkBxs).index(this);
            var end = $(groupOfChkBxs).index(lastChecked);                                                        
            $(groupOfChkBxs).slice(Math.min(start,end), Math.max(start,end) + 1).not(":disabled").attr("checked", lastChecked.checked);
        }
              
        lastChecked = this;
        
		checkAll = $(groupOfChkBxs + ":checked").length == $(groupOfChkBxs).not(":disabled").length;		
		$(selectAll).attr('checked', checkAll);		
	});
};

$.fn.checkboxWidget = function(opts){
	var methods = {
		update: function(){
			var randNum;
			var classes = $(this).find("input[type='checkbox']").attr("class").split(" ");
			for(var i = 0; i < classes.length; i++)
			{
				if(classes[i].indexOf("check") != -1)
				{
					randNum = classes[i].substr(5); 
				}
			}
			
			if(randNum)
			{
				if($(this).find("input[type='checkbox']:checked").length == $(this).find("input[type='checkbox']").length)
				{
					$("#widgetSelectAll" + randNum).attr("checked", "checked");
				}
				else
				{
					$("#widgetSelectAll" + randNum).attr("checked", "");
				}
			}
		}
	};
	
	if(methods[opts])
	{
		return methods[ opts ].apply( this, Array.prototype.slice.call( arguments, 1 ));
	}
	else if(typeof opts === 'object' || ! opts)
	{
		var cssProperties = new Object();
		var randNum = Math.floor(Math.random()*100000);
		var selectAllId = "widgetSelectAll" + randNum;
		var selectAllSelector = "#widgetSelectAll" + randNum;	
		var centerStyle = "";
		
		//***The following set of variables contains default values***//	
		var height = "100px";
		var width = "200px";
		var selectAll = true;	
		
		if(opts)
		{
			if(opts.height)
			{
				height = opts.height;		
			}				
			
			if(opts.width)
			{		
				width = opts.width;
			} 
			
			if(!opts.selectAll && opts.selectAll != null)
			{		
				selectAll = false;
				selectAllSelector = "";
			}
			if(opts.center)
			{
				centerStyle = "margin-left: auto; margin-right: auto;";
				cssProperties.marginLeft = "auto";
				cssProperties.marginRight = "auto";
			}
		}
	
		cssProperties.width = width;
		cssProperties.height = height;
		cssProperties.overflow = "auto";
		cssProperties.border = "1px solid black";
		cssProperties.background = "#FFFFFF";
		
		if(selectAll || selectAll == null)
		{		
			var prepend = '<div style="'+centerStyle+' text-align: left; border: 1px solid black; border-bottom: 0px; padding-bottom: 5px; width: '+width+'; height: 15px; background-color: #e5e5e5;"><input style="width: auto;" id="'+selectAllId+'" type="checkbox" id="widgetSelectAll" />SELECT ALL</div>';
			cssProperties.borderTop = 0;
			$(prepend).insertBefore($(this));						
		}
	
		$(this).find("input").each(function(){$(this).addClass("check" + randNum);});
		$("input.check" + randNum).groupCheckboxes(selectAllSelector);
		$(this).css(cssProperties);
	}
	else
	{
		$.error("You have inputed incorrect parameters within the checkboxWidget plugin.");
	}
};

$.fn.tableHighlight = function(color){
	var prevColor;
	var table = this;	
	
	$(this).find("td").not(".untouchable").hover(function(){	
		prevColor = $(this).css("background-color");		
		orbisApp.highlightHelper(this, color);
	},
	function(){		
		orbisApp.highlightHelper(this, prevColor);
	});
};

/**
* A utility that will take an element and transform it into a JQueryUI 
* button. The content of that element will be the one used to be the
* content within the button.
* @param callback<function> - This function will be executed when the button is clicked.
* @param opts<Object[]> - This can contain extra button opts along with any CSS properties that
* are to be applied to the button. 
*/	

$.fn.setUpButton = function (callback, opts) {		
	$(this).button(opts);		
	
	if(callback)
		$(this).click(function(){
			if($(this).button("option", "disabled") != true && $(this).button("option", "disabled") != "disabled")
			{
				callback();
			}
		});

	if(opts)		
		$(this).css(opts);
};

/**
 * RSS Widget: 
 *      loads rss feeds into a target container.
 *
 * USAGE EXAMPLES:
 * 		$("#containerDiv").rssWidget({urls: ["http://www.reddit.com/.rss", "http://feeds.digg.com/digg/popular.rss"]});
 * 		$("#containerDiv").rssWidget({limit:10, urls: ["http://www.reddit.com/.rss", "http://feeds.digg.com/digg/popular.rss"]});
 * 		$("#containerDiv").rssWidget({dateSort: "asc", limit:10, urls: ["http://www.reddit.com/.rss", "http://feeds.digg.com/digg/popular.rss"]});
 * 		$("#containerDiv").rssWidget({dateFormat: "hide", limit:10, urls: ["http://www.reddit.com/.rss", "http://feeds.digg.com/digg/popular.rss"]});
 * 		$("#containerDiv").rssWidget({dateFormat: "MM dd, yyyy", limit:10, urls: ["http://www.reddit.com/.rss", "http://feeds.digg.com/digg/popular.rss"]});
 *
 * OPTIONS:
 *      urls  (optional): An array of rss urls.
 *      limit (optional): An integer to specify a maximum limit of feed-items.
 *      dateSort   (optional): Specify "asc" or "desc" to indicate which direction you want feed-items sorted by date.  Default is "desc" (newest on top). 
 *		dateFormat (optional): The format-string (ala: SimpleDateFormat) of the date.  Specify "hide" to hide the date altogether. Default value is "MMM dd, yyyy @ h:mm a z"
 */
$.fn.rssWidget = function (opts) {
	if (!orbisApp.isEmpty(opts) && orbisApp.isArray(opts.urls))
	{
		orbisApp.addComponent("json");
		
		var request = new Object();
		request.action = "loadRssFeeds";
		request.opts = JSON.stringify(opts);
		request.rnd = Math.random() * 10000;
		
		$(this).html("<center><B style='color:blue;'>Fetching news feed....</B></center>");
		
		$(this).load("/rss.htm", request, function(response, status, xhr) 
		{
			if (!orbisApp.checkAjaxResponse(xhr))
			{
				$(this).html("<center><B style='color:red;'>News feed unavailable!</B></center>");
			}
		});
	}
	else
	{	
		$(this).html("<center><B style='color:red;'>News feed unavailable!</B></center>");
	}
};

/************** GLOBAL "ROLL-OVER" FUNCTIONS **************/

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_nbGroup(event, grpName) { //v6.0
  var i,img,nbArr,args=MM_nbGroup.arguments;
  if (event == "init" && args.length > 2) {
    if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
      img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src;
      if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
      nbArr[nbArr.length] = img;
      for (i=4; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
        if (!img.MM_up) img.MM_up = img.src;
        img.src = img.MM_dn = args[i+1];
        nbArr[nbArr.length] = img;
    } }
  } else if (event == "over") {
    document.MM_nbOver = nbArr = new Array();
    for (i=1; i < args.length-1; i+=3) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = (img.MM_dn && args[i+2]) ? args[i+2] : ((args[i+1])? args[i+1] : img.MM_up);
      nbArr[nbArr.length] = img;
    }
  } else if (event == "out" ) {
    for (i=0; i < document.MM_nbOver.length; i++) {
      img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up; }
  } else if (event == "down") {
    nbArr = document[grpName];
    if (nbArr)
      for (i=0; i < nbArr.length; i++) { img=nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; }
    document[grpName] = nbArr = new Array();
    for (i=2; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = img.MM_dn = (args[i+1])? args[i+1] : img.MM_up;
      nbArr[nbArr.length] = img;
  } }
}
