// =====================
// = Site5 Javascript =
// =====================

var site5 = {
	init: function() {
		var instance = this;

		instance._document = jQuery(document);
		instance._window = jQuery(window);
		instance._body = jQuery(document.body);

		instance._tooltips();

	},

	_closeOutsideOf: function(el, onClose) {
		var instance = this;

		var obj = jQuery(el);
		var test = function(target) {
			if (el.constructor === String) {
				test = function(target) {
					return (target.is(el) || target.parents(el).length);
				};
			}
			else {
				test = function(target) {
					return (obj.find('*').andSelf().index(target[0]) > -1);
				};
			}

			return test(target);
		};

		var click = function(event) {
			if (test(jQuery(event.target))) {
				event.stopPropagation();
				return;
			}
			else {
				obj.fadeOut('fast',
					function() {
						if (onClose) {
							onClose.call(this, event);
						}

						instance._document.unbind('click.site5', click);
					}
				);
			}
		};

		instance._document.bind('click.site5', click);
	},

	_tooltips: function() {
		var instance = this;

		var allTerms = jQuery('.tooltips dl');
		var docHeight = instance._document.height();
		var win = instance._window;

		var showTooltip = function(event) {
			var href = this.href;
			var id = href.slice(href.lastIndexOf('#'), href.length);

			var link = jQuery(this);
			var term = jQuery(id);

			if (term.length) {
				var termTitle = term.find('dt');
				var termDef = term.find('dd');
				var arrow = termDef.find('strong.direction-indicator');
				var closeBtn = termTitle.find('.close');

				instance._closeOutsideOf(term[0]);

				if (!closeBtn.length) {
					closeBtn = jQuery('<strong class="close">x</strong>');
					termTitle.append(closeBtn);
				}

				if (!arrow.length) {
					termDef.append('<strong class="direction-indicator"></strong>');
				}

				allTerms.hide();

				closeBtn.unbind('click.site5');
				closeBtn.click(
					function(event) {
						term.fadeOut();
					}
				);

				instance._document.bind(
					'keyup.site5',
					function(event) {
						if (event.which != 27) {
							return;
						}

						closeBtn.trigger('click');
						instance._document.unbind('keyup.site5', arguments.callee);
					}
				);

				var offset = link.offset();
				var height = term.outerHeight();
				var top = height + offset.top;
				var windowHeight = win.height() + win.scrollTop();
				var className = 'below';

				if (top > windowHeight && !((offset.top - height) < 0)) {
					offset.top -= height;
					className = 'above';

					if (win.scrollTop() > offset.top) {
						win.scrollTop(offset.top);
					}
				}

				term.css(
					{
						left: offset.left,
						top: offset.top
					}
				);

				term.attr('class', className);

				term.fadeIn();
			}

			return false;
		};

		jQuery('.term-definition').click(showTooltip);
	},



}

jQuery(
	function() {
		site5.init();
	}
);


