/*
 * InputSelect.js
 * by Phill Sparks
 *
 * This attaches a function to labels to focus the mentionned input.
 *
 * Copyright (c) Phill Sparks, 2006.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Common Public License v1.0
 * (CPL) which accompanies this distribution, and is available at
 * http://www.opensource.org/licenses/cpl.php
 */

if (typeof _EventManager_ == 'undefined')
	alert('InputSelect: The EventManager has not been loaded!');

var _InputSelect_ = true;

function getInputForLabel(label)
{
	var input = false;

	if (label.getAttribute('for'))
	{
		input = GetObject(label.getAttribute('for'));
	}

	if (!input)
	{
		// Search the children of this label for an input
		if (label.getElementsByTagName)
		{
			childInputs = label.getElementsByTagName('input');
			if (childInputs.length > 0)
				input = childInputs[0];

		}
		else
		{
			var childNodes = (label.childNodes) ? label.childNodes : label.children;
			for (var i = 0; i < childNodes.length; ++i)
			{
				if (childNodes[i].tagName.toLowerCase() == 'input')
				{
					input = childNodes[i];
					break;
				}
			}
		}
	}
	return input;
}

function InputSelect(e)
{	
	var e = (e) ? e : ((event) ? event : null);
	var input = false;
	
	if (!e) return;
	var label = (e.target) ? e.target : e.srcElement;
	var srcType = label && label.getAttribute('type') ? label.getAttribute('type').toLowerCase() : '';
	
	if (srcType == 'radio' || srcType == 'checkbox')
		return;

	while (label && label.tagName.toLowerCase() != 'label')
		label = label.parentNode;
	
	input = getInputForLabel(label);
	
	if (input)
	{
		if (input.getAttribute('type') && 
			(input.getAttribute('type').toLowerCase() == 'checkbox' || input.getAttribute('type').toLowerCase() == 'radio'))
				input.checked = !input.checked || srcType == 'text' || input.getAttribute('type') == 'radio';

		if (input.checked && label.className.match(/\bother\b/))
		{
			var inputs = label.getElementsByTagName('input');
			input = inputs[inputs.length - 1];
		}
		
		if (input.tagName.toLowerCase() == 'textarea' || input.tagName.toLowerCase() == 'select' || input.getAttribute('type').toLowerCase() == 'text') {
			input.focus();
		}
	}

	// Stop browsers from undoing what we've done
	if (e.preventDefault)	e.preventDefault();
	e.returnValue = false;
}

EventManager.Add(window, 'load', function ()
{
	// Find all of the labels on this page and attach the select function to them;
	var labels = document.getElementsByTagName('label');

	if (labels.length > 0)
	{
		// Attach the event to all the labels
		for (var i = 0; i < labels.length; ++i)
		{
			EventManager.Add(labels[i], 'click', InputSelect);
		}

		// Select the first input
		var input = false;
		if ((input = getInputForLabel(labels[0])) && 
			(input.tagName.toLowerCase() == 'textarea' || input.getAttribute('type').toLowerCase() == 'text'))
		{
			input.focus();
		}
	}
});