/**
 * Resolve Key for autocomplete
 * Make it global to reuse in callbacks
 */
 (function ($) {
	$.resolveKey = function(dataset, name) {
			var keys = name.split('.'),
				current = keys.shift(),
				valueStack = dataset;

			while (current) {
				if (valueStack[current] === undefined) {
					return '';
				}
				valueStack = valueStack[current];
				current = keys.shift();
			}
			return valueStack;
	};
})(jQuery);


/**
 * Foreign Key autocomplete
 * Allows for foriegn Key autocompletion.
 *
 * Options
 *  - idValue - the json key to your ID value ie. 'Team.id'
 *  - nameValue - the json key to your name value ie. 'Team.name'
 *  - hiddenField - Selector to hidden field.
 *  - handlerFunction - replaces the function called when a row is selected
 *
 * You may also replace parse, and formatItem callbacks by specifying them in the options.
 */

(function ($) {
	$.fn.foreignKeyAutocomplete = function(url, options) {
		var undef;

		options = $.extend({}, $.fn.foreignKeyAutocomplete.defaults, options);

		if (options.hiddenField == null || options.nameValue == null || options.idValue == null) {
			alert('Missing required options, [hiddenField, nameValue, idValue]');
			return;
		}

		function handleResult (event, data) {
			$(options.hiddenField).val($.resolveKey(data, options.idValue));
		}

		if (options.formatItem === undef) {
			options.formatItem = function (data, i, max, value, term) {
				return $.resolveKey(data, options.nameValue);
			};
		}

		if (options.parse === undef) {
			options.parse = function (response) {
				var parsed = [];
				var rows = response.data;
				for (var i in rows) {
					var curRow = rows[i];
					parsed[i] = {
						data : curRow,
						value : $.resolveKey(curRow, options.nameValue),
						result : $.resolveKey(curRow, options.nameValue)
					};
				}
				return parsed;
			};
		}

		return this.each(function() {
			var $this = $(this);
			if (options.handlerFunction == null) {
				$this.autocomplete(url, options).result(handleResult);
			} else {
				$this.autocomplete(url, options).result(options.handlerFunction);
			}
		});
	};

	$.fn.foreignKeyAutocomplete.defaults = {
		hiddenField : null,
		dataType : 'json',
		idValue : null,
		nameValue : null
	};
})(jQuery);


/**
 * Clear input jquery plugin.
 * binds a click event to an element, allowing it to clear
 * an adjacent input element.
 *
 */
 (function ($) {
	$.fn.clearField = function (options) {

		var doClear = function (event) {
			$(this).siblings('input').val('');
			return false;
		};

		return this.each(function () {
			$(this).bind('click', doClear);
		});
	};

	$.fn.clearField.defaults = {

	};
})(jQuery);

/**
 * disableInputs()
 * enableInputs()
 * toggleInputs()
 *
 * Disable all the inputs inside an element. and hide the form.
 * Enable all inputs inside an element and show the form
 * Toggle the inputs / element from hidden to shown.
 */
(function ($) {
	$.fn.toggleInputs = function(options) {
		var state = bool ? fn : $(this).is(":hidden");

		return this.each(function () {
			$(this).form[ state ? "enableInputs" : "disableInputs" ]();
		});
	};

	$.fn.disableInputs = function (options) {
		options = jQuery.extend({}, $.fn.disableInputs.defaults, options);

		return this.each(function () {
			if (options.hide) {
				$(this).hide();
			}
			$(options.selector, this).attr('disabled', 'disabled');
		});
	};

	$.fn.enableInputs = function (options) {
		options = jQuery.extend({}, $.fn.disableInputs.defaults, options);

		return this.each(function () {
			if (options.hide) {
				$(this).show();
			}
			$(options.selector, this).removeAttr('disabled');
		});
	};

	$.fn.disableInputs.defaults = {
		hide : true,
		selector : 'input[type!=submit]'
	};
})(jQuery);

// Simple add and remove of disabled attribute and
// Disabled classname.
(function ($) {
	$.fn.disable = function (className) {
		className = className || 'disabled';
		this.addClass(className);
		this.attr('disabled', 'disabled');
		return this;
	};

	$.fn.enable = function (className) {
		className = className || 'disabled';
		this.removeClass(className);
		this.removeAttr('disabled');
		return this;
	};
})(jQuery);


// Add table sorter widgets
if ($.tablesorter) {
	(function ($) {
		var headerCache = {},
			uuid = 0,
			ident = 'tableSorter' +(+ new Date());
		//
		// keepStyle widget
		//
		// Maintains style info when table rows are resorted
		// used on competition tables to ensure tables stay coloured properly.
		$.tablesorter.addWidget({
			id: 'keepStyle',
			format: function (table) {
				var id = table[ident];
				if (!id) {
					id = table[ident] = ++uuid;
				}

				if (!headerCache[id]) {
					headerCache[id] = [];
					$('tbody tr', table).each(function () {
						headerCache[id].push($(this).attr('style') || '');
					});
				}
				for (var i = 0, len = headerCache[id].length; i < len; i++) {
					if (!table.tBodies[0].rows[i]) {
						continue;
					}
					$(table.tBodies[0].rows[i]).attr('style', headerCache[id][i]);
				}
			}
		});
	})(jQuery);
}
