(function ($) {
	
	$(function () {
		
		if (typeof(BOCES_LOCATOR) !== 'object') {
			BOCES_LOCATOR = {};
		}
		
		var contextPath = BOCES_LOCATOR.contextPath,
			ns = BOCES_LOCATOR.namespace,
			dataset = BOCES_LOCATOR.dataset;
		
		function paramString(id) {
			var retVal = $.jmesa.createParameterStringForLimit(id);
			return 'e1b_namespace=' + encodeURIComponent(ns) + '&' + 
					'dataset=' + dataset + '&' + retVal;
		}
		
		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='", contextPath, "/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)));
		}
		
		// These are the JMesa callback functions for table actions and exports	
		window.boceslocatorTableAction = function (id, action) {
			var tableDiv = $("#" + id).parents(".tableDiv");
			ajaxGraphic(tableDiv.get(0));
			$.jmesa.setExportToLimit(id, '');
			$.ajax({
				url: contextPath + '/table/' + id + '?' + paramString(id),
				type: 'GET',
				cache: false,
				success: function (data) {
					tableDiv.html(data);
				},
				error: function (xhr, textStatus, errorThrown) {
					if (textStatus) {
						alert("There was an error communicating with the server: " + textStatus);
					}
					window.location.reload();
				}
			});
		};
		
		window.boceslocatorTableExportAction = function (id, action) {
			location.href = contextPath + '/table/' + id + '?' + paramString(id);
		};
		
		function concat(pieces) {
			return pieces.join('');
		}
	
		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' />", 
				"<img class='autocompleteIcon' id='", select.id, "_button' src='" + 
				BOCES_LOCATOR.contextPath + "/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;
			});
		}
	
		$(".bocesSearch select.autocomplete")
			.each(function () { 
				makeAutocomplete(this); 
			})
			.parents("form:first")
			.find("input[name=searchTerm]").hide();
		
		$('#' + ns + 'changeDataset').hide();
		
		$('#' + ns + '_datasets_select').change(function () {
			$('#' + ns + 'changeDataset').click();
		});
		
		if ($.fn.cluetip) {
			$('.bocesSearchPin').cluetip({
				local:true, 
				sticky: true,
				cursor: 'pointer', 
				attribute: "rel",
				arrows: true,
				closePosition: 'title',
				closeText: '',
				dropShadow: false,
				mouseOutClose: true,
				cluetipClass: 'bocesSearch',
				arrows: false
			});
		}
	});
	
}(jQuery));