/*global jQuery, Calendar, editAreaLoader */
/*jslint browser: true */
(function ($) {
	
	$("<style type='text/css'>div.emr div.feedback { display: none }</style>").appendTo($("head").get(0));
	
	$.emr = {};
	
	function concat(pieces) {
		return pieces.join('');
	}
	
	function log() {
		if (!$.browser.msie && window.console) {
			window.console.log.apply(window, arguments);
		} else {
			$.each(arguments, function () {
				alert(this);
			});
		}
	}
	
	$.fn.logMatches = function (label) {
		this.each(function () {
			log(label, this);
		});
		return this;
	};

	function ajaxGraphic(elem) {
		var img,
			dialog = $(elem).parents(".ui-dialog"),
			hasDialog = dialog.size() > 0,
			$this = $(elem),
			height = hasDialog ? dialog.height() : $this.height(),
			width = hasDialog ? dialog.width() : $this.width(),
			offset = hasDialog ? {top: 0, left: 0} : $this.offset(),
			markup = [
				"<div class='loadingGraphicDiv'>",
				"<div class='obscured' style='",
				"background-color: white; ",
				"z-index: 1100; ",
				"height: ", height, "px; ",
				"width: ", width, "px; ",
				"left: ", offset.left, "px; ",
				"position: absolute; ",
				"top: ", offset.top, "px;",
				"'>&nbsp;</div>",
				"<img class='loadingImage' style='",
				"display: block; ",
				"margin: auto; ",
				"position: absolute; ",
				"z-index: 1500; ",
				"' src='", $.emr.staticContextPath, "/images/bigrotation2.gif'>", 
				"</div>"
			].join('');
		$this.append(markup);
		img = $('img.loadingImage', $this.get(0));
		img.css("top", (offset.top + (height / 2) - (img.height() / 2)));
		img.css("left", (offset.left + (width / 2) - (img.width() / 2)));
	}
	
	function removeAjaxGraphic(elem) {
		$(".loadingGraphicDiv", elem).remove();
	}
	
	function transformTimeInput(input) {
		if(input.disabled || $(input).data("__transformedTimeInput")) {
			return;
		}
		var name = $(input).attr("name");
		var html = "<select name=\"" + name + "\">";
		var mins = ["00", "05", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55"];
		for(var i = 6; i <= 23; i++) {
	          for (var n = 0; n < mins.length; n++) {
	            html += "<option value=\"";
	            var hrs = (i % 12);
	            if(hrs == 0) {hrs = 12}
	            var ampm = (i <= 11) ? " AM" : " PM";
	            var str = hrs + ":" + mins[n] + ampm;
	            html += str + "\"";
	            html += (str == $(input).val() ? " selected>" : ">") 
	                  + str + "</option>";
	          }
		}
	    html += "</select>";
	    var parent = $(input).parent();
        $(input).replaceWith(html);
        parent.children("select[name=\"" + name + "\"]").bind("click", 
          function() {
        	$(this).change();
        });
		$(input).data("__transformedTimeInput", true);
	}
	
	function transformDateInput(input) {
		if ($(input).data("__transformedDateInput")) {
			return;
		}
		var $link = $([
			'<a href="#" title="Click here to choose a date from a pop-up calendar.">',
			'<img src="', $.emr.staticContextPath, '/images/icon_calendar.gif" ', 
			'alt="Calendar Icon" align="absmiddle"></a>'
		].join('')).insertAfter(input);
		Calendar.setup({
			inputField : input,
			ifFormat : "%m/%d/%Y",
			button: $link.get(0),
			align: "Lr",
			singleClick: true,
			weekNumbers: false,
			onSelect : function (cal) {
				var p = cal.params,
					update = (cal.dateClicked || p.electric);
				if (update && p.inputField) {
					p.inputField.value = cal.date.print(p.ifFormat);
					$(p.inputField).change();
				}
				if (update && p.displayArea) {
					p.displayArea.innerHTML = cal.date.print(p.daFormat);
				}
				if (update && typeof p.onUpdate === "function") {
					p.onUpdate(cal);
				}
				if (update && p.flat) {
					if (typeof p.flatCallback === "function") {
						p.flatCallback(cal);
					}
				}
				if (update && p.singleClick && cal.dateClicked) {
					cal.callCloseHandler();
				}
				$(input).change();
			}
		});
		$(input).data("__transformedDateInput", true);
	}
	
	function processCustomFieldValues(select) {
		var options = $(select).children('option');
		options.each(function() {
			$(select).after("<input type='hidden' name='" + $(select).attr('name') + "' value='" + $(this).val() + "'>");
		});
	}
		
	function addDropShadow(elem) {
//		var $elem = $(elem); //, 
			//margins = {}, 
			//prop, 
//			$div;
//		$.each(['top', 'bottom', 'left', 'right'], function () {
//			prop = "margin-" + this;
//			margins[prop] = $elem.css(prop);
//		});
		$(elem).wrap([
			"<div class='shadow-container'>",
			"<div class='shadow1'>",
			"<div class='shadow2'>",
			"<div class='shadow3'>",
			"<div class='container'>", 
			"</div></div></div></div></div>"
		].join(''));
	}
	
	function submitHandler(event) {
		var form = event.target;
		try {
			form.bypass(true);
			if (form.e1b_inv_skipValidation) {
				form.e1b_inv_skipValidation = false;
				return true;
			} else if (form.isValid(true)) {
				return true;
			} else {
				return false;
			}
		} catch (ex) {
			log("form submit error", ex);
			return false;
		}
	}
	
	function addValidationMessages(form, data, refocus) {
		$(".validationError", form).remove();
		var success = true,
			firstInput = null,
			elements = [],
			globalMessages = null;
		
		
		$.each(data, function (i, list) {
			var input, id, holder;
			holder = $('.negative[id$=' + i + '_feedback]', form);
			if (holder.size() === 0) {
				input = $("input, select, textarea", form).filter("[name='" + i + "']:first");
				if (firstInput === null) {
					firstInput = input.get(0);
				}
				if (input.size() > 0) {
					elements.push(input.get(0));
					holder = $('#' + input.attr("id") + '_feedback');
					if (holder.size() === 0) {
						holder = input.parents(":first");
					}
				} else {
					holder = null;
				}
			}
			if (holder.size() > 0) {
				elements.push(holder.get(0));
			}
			$.each(list, function (i, val) {
				if (holder !== null) {
					$("<span class='negative validationError' />").text(val).appendTo(holder);
				}
			});
			success = false;		
		});
		if (refocus && elements.length > 0) {
			var minoffset = null, offset;
			for (var j in elements) {
				offset = $(elements[j]).offset().top;
				if (offset != null && (minoffset == null || (offset < minoffset))) {
					minoffset = offset;
				}
			}
			if (minoffset != null) {
				$("html,body").animate({scrollTop: minoffset}, 500);				
			}
		}
		if (firstInput !== null && refocus) {
			$(firstInput).focus().select();
		}
		return success;
	}
	
	var forms = [],
		afterTableLoaded = function () {};
	
	function enhanceForm(form) {
	
		$(form).each(function () {
				
			var form = this, title, timeOut;
			form.e1b_inv_changed = $(this).hasClass('changed');
			form.e1b_inv_bypass = false;
			form.e1b_inv_skipValidation = false;
			form.e1b_inv_needsRevalidation = false;
			
			title = form.getAttribute("title");
			if (title) {
				form.e1b_inv_title = title;
				form.setAttribute("title", "");
			}
			
			form.isValid = function (refocus, throttleBack) {
				if (timeOut) {
					clearTimeout(timeOut);
				}
				if (throttleBack) {
					timeOut = setTimeout(function () {
						form.isValid(refocus, false);
					}, 2000);
					return;
				}
				var options = $(this).metadata(),
					data = $(this).serialize(),
					success = false;
				if (options.action !== null && options.namespace !== null) {
					$.ajax({
						url : $.emr.contextPath + $.emr.servletPathPrefix + 
								"/validate/" + options.namespace + "/" + options.action,
						type : 'POST',
						async : false,
						dataType : 'json',
						data : data,
						success : function (data) {
							success = addValidationMessages(form, data, refocus);
						},
						error : function (data) {
							success = true;
						}
					});
					this.setShouldRevalidate(!success);
					return success;
				}
			};
			
			form.hasChanged = function () {
				return this.e1b_inv_changed;
			};
			
			form.fireChanged = function (b) {
				var old = this.e1b_inv_changed;
				this.e1b_inv_changed = (b !== false);
				if(!old && this.hasChanged()) {
					$(this).prepend("<input type='hidden' name='changed' value='true'>");
				}				
				if (this.hasChanged() && this.shouldRevalidate()) {
					this.isValid(false, true);
				}
			};
			
			form.shouldBypass = function () {
				return this.e1b_inv_bypass;
			};
			
			form.bypass = function (b) {
				this.e1b_inv_bypass = b;
			};
			
			form.skipValidation = function (b) {
				this.e1b_inv_skipValidation = b;
			};

			form.setShouldRevalidate = function (b) {
				this.e1b_inv_needsRevalidation = b;
			};
			
			form.shouldRevalidate = function () {
				return this.e1b_inv_needsRevalidation;
			};
	
			forms.push(form);
			
		}).
		submit(submitHandler).
		find('.confirmCancel').
			click(function () {
				var form = $(this).parents("form:first").get(0), sure;
				if (form.hasChanged()) {
					sure = confirm("Are you sure that you would like to cancel your changes?");
					if (sure) {
						form.skipValidation(true);
					}
					return sure;
				}
				form.skipValidation(true);
			}).
		end().
		find('input, textarea, select').
			change(
				function () {
					if (!$(this).hasClass("nochange")) {
						var form = $(this).parents("form:first").get(0);
						form.fireChanged();
					}
				}
			).
		end().
//		find("input[type=submit], input[type=image]").logMatches().click(
//			function () {
//				var $this = $(this),
//					form = $(this).parents("form:first").get(0);
//				if (!$this.hasClass("noBypass")) {
//					form.bypass(true);			
//				}
//			}
//		).end().
		find('.immediate').
			click(
				function () {
					$(this).parents("form:first").get(0).skipValidation(true);
				}
			).
		end();
	}
	
	function beforeUnloadFunction() {
		for (var i = 0, l = forms.length, form, bypass; i < l; i += 1) {
			form = forms[i];
			bypass = form.shouldBypass();
			form.bypass(false);
			if (!bypass && form.hasChanged()) {
				return "You have unsaved changes.";
			}
		}
	}
	
	window.onbeforeunload = beforeUnloadFunction;
	
	function destroyDialog(elem) {
		var $elem = $(elem).dialog("destroy");
		if ($elem.hasClass("emrDialog")) {
			$elem.remove();
		} else {
			$elem.parents(".emrDialog").remove();
		}
	}
		
	function alertDialog(content) {
		content = $("<div class='eBOCESWebApp emr' title='Alert'></div>")
						.css("font-size", "0.7em")
						.append(content)
						.get(0);
		$(content).appendTo("body").dialog({
			modal: true, 
			close : function (type, data) {
				destroyDialog(content);
			},
			show: 'puff'
		});
		return this;
	}
	
	function ajaxUrl(file, params, element) {
		var data = $.extend({'e1b_namespace' : $(element).parents("form:first").metadata().namespace}, params || {});
		return concat([$.emr.contextPath, $.emr.servletPathPrefix, "/ajax/", file, '?', $.param(data)]);
	}
	
	function ajaxGet(file, params, element, successFunction) {
		$.ajax({
			url: ajaxUrl(file, params, element),
			type: 'GET',
			cache: false,
			success: successFunction,
			error: function (xhr, textStatus, errorThrown) {
				if (textStatus) {
					alert("There was an error communicating with the server: " + textStatus);
				}
			}
		});
	}
	
	function ajaxDialog(title, file, button, okayFunction, params, width, height) {
		ajaxGet(file, params, button, function (data) {
			var div = $('<div class="eBOCESWebApp emr emrDialog" />"').attr("title", title).get(0);			
			$(div).
				dialog({
					modal: true, 
					height: height || 300,
					width: width || 550,
					close : function (type, data) {
						destroyDialog(div);
					},
					show: 'puff',
					resizable: false
				}).
				append(data).
				find("input[value=Cancel]").click(function () {
					destroyDialog(div);
					$(button).parents("form.emrForm:first").each(
						function () {
							this.bypass(false);
						}
					);
					return false;
				}).end().
				find("input[value=Okay]").click(okayFunction).end();
		});
	}
	
	function makeAutocomplete(select) {
		var splitter = (/\|/),
			options = [],
			alot = 100,
			selectedVal = '',
			$input, width,
			anything = new RegExp('.'),
			grepFunction = function (val) {
				return anything.test(val);
			},
			refocus,
			$select, $button, $autocomplete;
		function formatAutocompleteItem(row, sep) {
			var parts = row[0].split(splitter);
			parts.pop();
			return $.grep(parts, grepFunction).join(sep);
		}
		function formatAutocompleteRow(row, i, max, term) {
			return formatAutocompleteItem(row, ", ");
		}
		$(select).hide().find("option").each(function (i, item) {
			var thisvalue = this.value, val;
			if (thisvalue) {
				val = $(this).text() + "|" + thisvalue;
				options.push(val);
				if (!selectedVal && (i === select.selectedIndex)) {
					selectedVal = formatAutocompleteRow([val]);
				}
			}
		}).end().after(concat([
			"<input id='", select.id, "_autocomplete' class='autocompleteText' style='width: 215px;' />", 
			"<img class='autocompleteIcon' id='", select.id, "_button' src='", 
			$.emr.staticContextPath, "/images/selectTriangle.gif' />",
		]));
		$input = $("#" + select.id + "_autocomplete");
		width = $input.width();
		if (options.length >= alot) {
			$input.width(width + 18);
		}
		width += 21 + ($.browser.msie ? 2 : 0);
		$input.val(selectedVal).autocomplete(options, {
			mustMatch: true,
			max: alot,
			minChars: options.length < alot ? 0 : 1,
			multipleSeparator: String.fromCharCode(27),
			width: width,
			formatItem : function (row, i, max, term) {
				return formatAutocompleteItem(row, "<br>");
			},
			formatResult : formatAutocompleteRow,
			formatMatch : formatAutocompleteRow
		}).bind('result', function (event, data, formatted) { 
			var val = data[0].split(splitter).pop();
			$(select).val(val);
		}).change(function () {
			if (!this.value) {
				$(select).val("");
			}
		}).focus(function () {
			$(this).select();
		});
		$select = $(select).attr("size", 10);
		$button = $('#' + select.id + '_button');
		$autocomplete = $($button).add($input);
		refocus = function() {
			$select.blur();
			$input.focus();
		};
		$select.keypress(function (event) {
			if (event.keyCode == 13) {
				refocus();
				return false;
			}
		}).blur(function () {
			$(this).fadeOut('fast');
			var selectedOption = this.options[this.selectedIndex];
			if (selectedOption.value) {
				$input.val($(selectedOption).text());
			} else {
				$input.val("");
			}
		});
		$select.click(refocus);
		$button.click(function () {
			var offset = $input.offset(),
				height = $input.height(),
				css = {
					position: 'absolute', 
					zIndex: '100',
					top: offset['top'] + height + 3,
					left: offset['left']
				};
			$select.css(css).fadeIn('fast').focus();
			return false;
		});
	}
	
	function enhanceJCaptcha(img) {
		var captchaDiv = $(img).parents("div.captcha:first");
		$("<a href='javascript:;'>Can't read the word? Click here for a new one.</a>")
			.click(function () {	
				$.ajax({
					url: img.src + '&new=true',
					type: 'GET',
					cache: false,
					success: function (data) {
						captchaDiv.html(data);
						enhanceJCaptcha($('img.jcaptchaImage', captchaDiv).get(0));
					},
					error: function (xhr, textStatus, errorThrown) {
						if (textStatus) {
							alert("There was an error communicating with the server: " + textStatus);
						}
					}
				});
			})
			.appendTo(captchaDiv);
		$(img).parents("form:first").each(function () {
			var form = this,
				button = $("input[value=submit]", this);
			button.click(function () {
				var input = $("input.jcaptcha_field", this);
				if (!input.val()) {
					alert("Please enter a response to verification challenge.");
					input.focus();
					return false;
				}
			});
		});
	}
	
	$(function () {
		
		$('div.emr div.feedback').fadeIn("slow");
			
		// This applies validation function automatically to emr forms
		$('div.emr form.emrForm').each(function () {
			enhanceForm(this);
		});

		$('div.emr input.dateInput').each(function () {
			transformDateInput(this);
		});
		
		$('div.emr input.timeInput').each(function () { 
			transformTimeInput(this); 
		});
		
		$('div.emr .tooltip').each(function() {
			$(this).cluetip({splitTitle : "|", cluetipClass: 'e1b'});
		});
		
		$('div.emr [name=openApproval]').eq(0).each(function() {
			var URL = $('div.emr [name=approvalFormButton]').attr('href');
			var newWindow = window.open(URL);
			newWindow.print();
		});
		
		$('div.emr .approvalContinue').each(function() {
			$(this).addClass('obscured');
			$(this).attr('disabled', 'disabled');
		});
		
		$('div.emr .approvalCheckbox').bind('click', function() {
			var checked = $(this).attr('checked');
			$('div.emr .approvalContinue').each(function() {
				if(checked) {
					$(this).removeClass('obscured');
					$(this).attr('disabled', '');
				} else {
					$(this).addClass('obscured');
					$(this).attr('disabled', 'disabled');					
				}
			})
		});
		
		$('div.emr .inputTypeSelector').each(function() {
			$(this).bind('change', function() {
				if($(this).val() == 'TEXT') {
					$(this).parents('table').find('.disableOnText').attr('disabled', 'disabled');
					$(this).parents('table').find('.addCustomFieldValue').addClass('obscured');
					$(this).parents('table').find('.deleteCustomFieldValue').addClass('obscured');
				} else {
					$(this).parents('table').find('.disableOnText').attr('disabled', '');
					$(this).parents('table').find('.addCustomFieldValue').removeClass('obscured');
					$(this).parents('table').find('.deleteCustomFieldValue').removeClass('obscured');
				}
			});
		})
		
		$('div.emr fieldset.expandable').each(function() {
			var fieldset = $(this);
			var legend = fieldset.children('legend').eq(0);
			var html = "<span class='expander_opened'><img src='" + $.emr.staticContextPath + 
				"/images/bullet_toggle_minus.gif' title='Expand/Collapse'></span>";
			legend.prepend(html);
			var expander = $(fieldset.find('.expander_opened').eq(0));
			expander.bind('click', function() { 
				var exp = $(this);
				var fs = exp.parents('fieldset').eq(0);				
				if(exp.hasClass('expander_opened')) {
					fs.children(':not(legend, select)').hide();
					exp.removeClass('expander_opened');
					exp.addClass('expander_closed');
					exp.children('img').attr('src', $.emr.staticContextPath + "/images/bullet_toggle_plus.gif");
				} else {
					fs.children(':not(legend, select)').show();
					exp.children('img').attr('src', $.emr.staticContextPath + "/images/bullet_toggle_minus.gif");
					exp.removeClass('expander_closed');
					exp.addClass('expander_opened');
				}
			});
			
		});
		
		$('div.emr fieldset.selectAll').each(function() {						
			var fieldset = $(this);
			var html = "<span><input type='checkbox' class='checkbox selectAllCB'>" +
					"<label class='deEmph inline";
			if (fieldset.attr('disabled') == 'disabled') {
				html += " obscured";
			}
			html += "'>Select/Deselect All</label></span>"
			var legend = $(fieldset.children('legend').eq(0));
			legend.append(html);
			var clicker = legend.find('.selectAllCB').eq(0);
			clicker.bind('click', function() {
				var cb = $(this);
				var fs = $(cb.parents('legend').eq(0).parents('fieldset').eq(0));
				var children = fs.find('input[type=checkbox]');
				children.each(function() {
					if (!$(this).hasClass('selectAllCB') && $(this).attr('disabled') == '') {
						$(this).attr('checked', cb.attr('checked'));
					}
				});
			});
		});
		
		$('div.emr .generateFlyer').each(function () {
			$(this).bind('click', function() {
				var id = $('input[name=flyerId]:checked').val();
				if(!id) {
					alertDialog("<span class='negative'>Please select a flyer type first.</span>");
					return false;
				} else {					
					$(this).parents("form:first").get(0).bypass(true);
					this.href += ("&flyer=" + id);
					return true;
				}
			});
		});
			
		$('div.emr input.cancelCheckbox').live('click', function() { 
				if($(this).attr('checked')) {
					$(this).parents('tr').eq(0).find('.disableOnCancel').attr('disabled', 'disabled');
				} else { 
					$(this).parents('tr').eq(0).find('.disableOnCancel').not('.disableAttended').attr('disabled', '');
				}
			});
		
		$('div.emr input.attendedCheckbox').live('click', function() { 
				if($(this).attr('checked')) {
					$(this).parents('tr').eq(0).find('.disableOnAttended').attr('disabled', 'disabled');
				} else { 
					$(this).parents('tr').eq(0).find('.disableOnAttended').attr('disabled', '');
				}
			});
		$('div.emr select.sessionSelect').each(function() {
			$(this).bind("change", function() {
				$(this).after('<input type="hidden" name="e1b_formAction.selectSessionACTIONNAME" value="true">');
				var form = $(this).parents('form');
				form.submit();
			});
		});	
		
		$('div.emr select.schedulingSelect').each(function() {
			$(this).bind("change", function() {
				$(this).after('<input type="hidden" name="e1b_formAction.switchModeACTIONNAME" value="true">');
				var form = $(this).parents('form');
				form.submit();
			});
		});
		$('div.emr .previewCustomFields').each(function() {
			$(this).bind('click', function() {
				ajaxDialog('Preview Custom Fields', 'customFieldsPreview', this);
				return false;
			});
		});
		
		$('div.emr .previewConfirmation').each(function() {
			$(this).bind('click', function() {
				ajaxDialog('Preview Confirmation E-Mail', 'emailPreview', this, null, 
					{ 
						'type' : 'C',
						'confirmationNames' : $('input[name=confirmationNames]').val(),
						'confirmationPhoneNums' : $('input[name=confirmationPhoneNums]').val()  
					}
				);
				return false;
			});
		});
		
		$('div.emr .previewReminder').each(function() {
			$(this).bind('click', function() {
				ajaxDialog('Preview Reminder E-Mail', 'emailPreview', this, null, 
					{ 
						'type' : 'R', 
						'reminder' : $('textarea[name=reminder]').val(),
						'confirmationNames' : $('input[name=confirmationNames]').val(),
						'confirmationPhoneNums' : $('input[name=confirmationPhoneNums]').val() 
					}
				);
					
				return false;
			});
		});
		
		$('div.emr input.confirmDelete').click(function () {
			return confirm("Are you sure that you would like to delete this item?");
		});
		
		$('div.emr select.cfAllowedValues').each(function () {
			processCustomFieldValues(this);
		});
		
		$('div.emr .addCustomFieldValue').each(function () { 
			$(this).bind('click', function() {
				if(!$(this).parents('table').eq(0).find('.cfAllowedValues').attr('disabled')) {
					var field = $(this).siblings('.newAllowedValue');
					var val = field.val();
					if(val && val.length > 0) {
						var select = $(this).parents('table').eq(0).find('.cfAllowedValues');
						select.append('<option value="' + val + '">' + val + "</option>");
						select.after('<input type="hidden" value="' + val + '" name="' + select.attr('name') + '">');
					}
					field.val('');
					return false;
				} else {
					return false;
				}
			});
		});
		
		$('div.emr .deleteCustomFieldValue').each(function () {
			$(this).bind('click', function() { 
				if (!$(this).parents('table').find('.cfAllowedValues').attr('disabled')) {
					var select = $(this).siblings('select');
					var options = select.attr('options');
					var index = select.attr('selectedIndex');
					if (index >= 0 && index < options.length) {
						var option = $(options[index]);
						option.remove();
						select.siblings('input').each(function(){
							if ($(this).val() == option.val()) 
								$(this).remove();
						});
					}
					return false;
				} else {
					return false;
				}
			});
		});
		
		$('div.emr input.unitQuantityRadio').each(function () { 
			$(this).bind('click', function() { 
				var val = $(this).val();
				$('input.unitQuantityField').each(function() { 
					$(this).attr('disabled', $(this).attr('id').indexOf(val) < 0 ? 'disabled' : '');
				});
			});
		});
		
		$('div.emr input.allowRegistration').each(function () {
			$(this).bind('click', function() {
				if($(this).val() == "true") {
					$('.registerableOnly').attr('disabled', '');
					$('.registerableOnly:submit, .registerableOnly:image').removeClass('obscured');
				} else {
					$('.registerableOnly').attr('disabled', 'disabled');
					$('.registerableOnly:text').val('0');
					$('.registerableOnly:submit, .registerableOnly:image').addClass('obscured');
				}
			});
		});
		
		// Adds the drop shadow to data tables... just fluff, no stuff
		$('div.ebocesTable table.dataTable').each(function () { 
			addDropShadow(this); 
		});
		
		$('div.emr a[rel=external]').click(function () {
			window.open(this.href);
			return false;
		});

		$('div.emr select.autocomplete').each(function () {
			makeAutocomplete(this);
		});

		$('div.emr select.confirmChange').each(function () {
			var $this = $(this);
			$this.data("lastValue", $this.val());
			$this.change(function () {
				var lastValue = $this.data("lastValue");
				if (lastValue && !confirm($this.metadata().confirmMessage)) {
					$this.val(lastValue);
				}
				$this.data("lastValue", $this.val());
			});
		});
		
		if ($.fn.listBuilder) {
			$('div.emr select.orderableAddRemove').listBuilder({
				imagePath: $.emr.staticContextPath + "/images/listBuilder/", 
				orderable: true
			});
			$('div.emr select.addRemove').listBuilder({
				imagePath: $.emr.staticContextPath + "/images/listBuilder/", 
				orderable: false
			});
		}
		
		$('div.emr img.jcaptchaImage').each(function () {
			enhanceJCaptcha(this);
		});
	});

	function paramString(id) {
		var retVal = $.jmesa.createParameterStringForLimit(id),
			form = $('#' + id).parents("div.emr form:first"),
			ns;
		if (form.size() === 0) {
			form = $('#' + id).parents("form.emrDialogForm:first");
		}
		if (form.size() > 0) {
			ns = form.metadata().namespace;
			if (ns) {
				retVal = concat(['e1b_namespace=', encodeURIComponent(ns), '&', retVal]);
			}
		}
		return retVal;
	}
	
	// These are the JMesa callback functions for table actions and exports	
	window.emrTableAction = function (id, action) {
		var tableDiv = $("#" + id).parents(".tableDiv");
		ajaxGraphic(tableDiv.get(0));
		$.jmesa.setExportToLimit(id, '');
		$.ajax({
			url: $.emr.contextPath + $.emr.servletPathPrefix + '/table/' + id + '?' + paramString(id),
			type: 'GET',
			cache: false,
			success: function (data) {
				tableDiv.html(data);
				afterTableLoaded();
				tableDiv.find("table.dataTable").each(function () { 
					addDropShadow(this); 
				});
				$('input.dateInput', tableDiv).each(function () {
					transformDateInput(this);
				});
			},
			error: function (xhr, textStatus, errorThrown) {
				if (textStatus) {
					alert("There was an error communicating with the server: " + textStatus);
				}
				window.location.reload();
			}
		});
	};
	
	window.emrTableExportAction = function (id, action) {
		location.href = $.emr.contextPath + $.emr.servletPathPrefix + '/table/' + id + '?' + paramString(id);
	};
	
}(jQuery));