$(function()
{
	/*
	 * This section replaces pop-up-date.js
	 * Popup for date fields.
	 */

	$('input[id$=_date]').datepicker({dateFormat: 'yy-mm-dd'});

	/*
	 * This section replaces pop-up-time.js
	 * Popup for time fields.
	 */

	var options = [];

	for (var hour = 0; hour < 24; hour++)
	{
		for (var minute = 0; minute < 60; minute += 15)
		{
			options.push(
				(hour < 10 ? '0' : '') + hour +
				(minute < 10 ? ':0' : ':') + minute + ':00');
		}
	}

	$('input[id$=_time]').autocomplete(options, {width: '8em'});

	/*
	 * This section replaces form-action.js
	 * Activation of form anchors.
	 */

	$.fn.buttonSubmit = function(pageName)
	{
		var actionName = this.text().toLowerCase().replace(' ', '-');

		return this
			.parent()
			.html('<img src="' + image + '" border="0"></img>')
			.performSubmit(pageName, actionName);
	};

	var image = '/images/jquery/indicator.gif';
	new Image().src = image;

	$('form a[href^=#page-]').one(
		'click',
		function(event)
		{
			var anchor = $(this);
			var href = anchor.attr('href');

			if (href.substring(0, 6) == '#page-')
			{
				var pageName = href.substring(6);
				anchor.buttonSubmit(pageName);
				return false;
			}
			else
			{
				return true;
			}
		});

	/*
	 * Client-side validation of fields.
	 */

	$('input[type=text]').each(function()
	{
		var thisElement = $(this);
		var id = thisElement.attr('id');

		if (page[id])
		{
			thisElement.validate(page[id]);
		}
	});

	/*
	 * This section replaces on-change.js
	 */

	$.fn.changeSubmit = function(pageName, actionName)
	{
		var type = this.attr('type');

		if (type == 'checkbox' || type == 'radio')
		{
			return this.click(function()
			{
				var thisElement = $(this);
				thisElement.performSubmit(pageName, actionName);
				return false;
			});
		}
		else
		{
			return this.change(function()
			{
				var thisElement = $(this);
				thisElement.performSubmit(pageName, actionName);
				return false;
			});
		}
	};

	$.fn.performSubmit = function(pageName, actionName)
	{
		var formElement = this.parents().filter('form');
		var formAction = pageName + '-' + actionName;

		formElement
			.attr('method', 'post')
			.find('input[name=form_action]')
			.val(formAction)
			.end()
			.css({cursor: 'wait'})
			.submit();

		return this;
	};
});
