
// define the namespace if necessary
if ( Lutz == undefined )
	var Lutz = { };

Lutz.DomUtil = { 
	// methods in this namespace
	
	isArray: function(testObject) {   
		return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
	},

	getControl: function(control) {
		var retval = control;
		if ( typeof control == 'string' )
			retval = document.getElementById(control);
		return retval;
	},

	getFormFieldValue: function(control) {
		var field = Lutz.DomUtil.getControl(control);
		if ( field == null ) 
			return null;
		
		if ( (field.tagName == 'INPUT' && (field.type == 'text' || field.type == 'password' || field.type == 'hidden')) 
		   || field.tagName == 'TEXTAREA' )
		{
			return field.value;
		}
		else if ( field.tagName == 'SELECT' )
		{
			if ( field.options.length == 0 || field.selectedIndex == -1 )
				return null;
			var value = field.options[field.selectedIndex].value;
			if ( value == null )
				field.options[field.selectedIndex].text;
			return value;
		}
		else if ( field.tagName == 'INPUT' && field.type == 'checkbox' )
		{
			return field.checked;
		}
		else if ( field.tagName == 'INPUT' && field.type == 'radio' )
		{
			var controls = Lutz.DomUtil.findRadioButtonsByName(field.form, field.name);
			for ( var  i = 0; i < controls.length; i++ )
			{
				if ( controls[i].checked )
					return controls[i].value;
			}
			return null;
		}
		else if ( field.tagName == 'INPUT' && field.type == 'file' )
		{
			return field.value;
		}
		
		return null;
	},
	
	getRadioValue: function(ctls, defaultValue)
	{
		if ( !Lutz.DomUtil.isArray(ctls) )
			return null;

		if ( typeof defaultValue == "undefined" )
			defaultValue = null;
		
		for ( var i = 0; i < ctls.length; i++ )
		{
			var ctl = Lutz.DomUtil.getControl( ctls[i] );
			if ( ctl == null )
				continue;
			if ( ctl.checked )
				return ctl.value;
		}
		
		return defaultValue;
	},
	
	findRadioButtonsByName: function(parent, name) {
		var controls = [];

		if ( parent.nodeName == "INPUT" && parent.type == "radio" && parent.name == name )
			controls.push( parent );
			
		for ( var i = 0; i < parent.childNodes.length; i++ )
		{
			var childControls = Lutz.DomUtil.findRadioButtonsByName( parent.childNodes[i], name );
			for ( var j = 0; j < childControls.length; j++ )
				controls.push( childControls[j] );
		}
		
		return controls;
	},

	findSubmitButtons: function(parent) {
		var buttons = [];
		if ( parent.nodeName == "INPUT" && parent.type == "submit" )
			buttons.push( parent );
		
		for ( var i = 0; i < parent.childNodes.length; i++ )
		{
			var childButtons = Lutz.DomUtil.findSubmitButtons( parent.childNodes[i] );
			for ( var j = 0; j < childButtons.length; j++ )
				buttons.push( childButtons[j] );
		}
		return buttons;
	}
	
}
