//
// Util.js
//
// General purpose client-side functions.
//

//
// Constants
//
var ELEMENT_NODE = 1;

function o(id) { return document.getElementById(id); }
function IsIE() { return navigator.userAgent.indexOf("MSIE") != -1; }

function GetSelectedItems( listId )
{
    var arr = new Array();
    var list = o(listId);
    
    var j=0;
    for( var i=0; i<list.options.length; i++ )
    {
        if( list.options[i].selected )
            arr[j++] = list.options[i];
    }
    
    return arr;
}

function IndexOf( obj, objArr )
{
    for( var i=0; i<objArr.length; i++ )
        if( obj == objArr[i] )
            return i;
            
    return -1;
}

//
// EnableElementAndDescendents()
//
// Enables or disables an element and all its descendents.
//
// Parameters:
//
//		oElement: Element to enable or disable.
//
//		bEnable: true to enable, false to disable.
//
function EnableElementAndDescendents(oElement, bEnable)
{
	EnableElement(oElement, bEnable);

	// Loop through the child nodes, some of which may be elements.

	for (var i = 0; i < oElement.childNodes.length; i++)
	{
		var oChildNode = oElement.childNodes[i];

		if (oChildNode.nodeType == ELEMENT_NODE)
		{
			EnableElementAndDescendents(oChildNode, bEnable);
		}
	}
}

//
// EnableElement()
//
// Enables or disables an element.
//
// Parameters:
//
//     oElement: Element to enable or disable.
//
//     bEnable: true to enable, false to disable.
//
function EnableElement(oElement, bEnable)
{
	var sTagName = oElement.tagName.toLowerCase();

	if (sTagName == "input" || sTagName == "select")
	{
		// Use the disabled property.
		//
		// (Note: Don't check for the existence of a disabled property instead
		// of checking the tag name.  In IE, all elements have a disabled
		// property, including divs and spans.  Disabling a div would disable
		// its children, which would bypass the test for validation controls
		// in the next block.)

		oElement.disabled = !bEnable;
	}
	else
	{
		// The element has no disabled property.  Use the style instead.

		var oStyle = oElement.style;

		// Don't change the color of validation controls.  TODO: This is not
		// at all robust.  What is a better way?  (Not expando properties,
		// which are IE-only.)

		if ( !(sTagName == "span" && oStyle.color.toLowerCase() == "red") )
		{
			oElement.style.color = (bEnable ? "" : "graytext");
		}
	}
}

//
// SetFocusToElement()
//
// Sets focus to an element.  If possible, the element's text is selected.
//
// Parameters:
//
//		sElementID: ID of the element to set focus to.  Element must support
//			the focus() method.
//
function SetFocusToElement(sElementID)
{
	var oElement = o(sElementID);

    if( oElement == null )
        return;
    
	oElement.focus();

	if (oElement.select != null)
	{
		oElement.select();
	}
}


