/**
 * Library of javascript functions to support form objects within WebBuzz
 */

/**
 * Function wbGetElement() gets an object by a string name.
 * First, the function attempts to locate element by id using getElementById()
 * If that fails, the function attempts to get element by name using getElementsByName()
 * @return The object, if any, found
 * @type Object
 */
function wbGetElement( element )
{
	try { 
		var foundObj=document.getElementById( element );
		if( foundObj==null ) throw 'ID Not Found';
	}
	catch(e) {
		var foundElements=document.getElementsByName( element );
		var foundObj=foundElements[0];
	}
	return foundObj;
}

/**
 * Function wbMoveFromList() will move items selected in list fromList to list toList
 * @param string fromList the name/id of the list currently containing the selected items
 * @param string toList the name/id of the target list to which the selected items are to be transferred
 */
function wbMoveFromList( fromlist, tolist )
{
	var fromObj=wbGetElement(fromlist);
	var toObj=wbGetElement(tolist);
	if( fromObj.options.length > 0 )
	{
		for( count=0; count<fromObj.options.length; count++ )
		{
			// if the current option is selected, add a copy of the option to the target list
			if( fromObj.options[count].selected )
			{
				var newOption=document.createElement('option');
				newOption.text=fromObj.options[count].text;
				newOption.value=fromObj.options[count].value;
				try { toObj.add(newOption,null); }
				catch(err) { toObj.add(newOption); }
			}
		}
		
		// Remove the options from the original list in a separate pass. Must be separate because the option indices change when an option is removed.
		while( fromObj.selectedIndex!=-1 ) fromObj.options[fromObj.selectedIndex]=null;
	}
}

/**
 * Function wbEmptyList removes all option items from an html list
 * @param {object} listObj The parent list object
 */
function wbEmptyList( listObj ) {
	if( listObj != null && listObj.options != null && listObj.options.length > 0 ) {
		var total = listObj.options.length;
		for( count=0; count<total; count++ ) listObj.remove(0);
	}
}

/**
 * function GetSeletedItems() determines what items are selected in list myList
 * @param string myList The name/id of the list to be examined
 * @return array of option objects that are currently selected in myList.
 */
function wbGetSelItems( myList )
{
	var listObj=wbGetElement(myList);
	if( listObj.options.length > 0 )
	{
		var selectedItems=new Array();
		for( count=0; count<listObj.options.length; count++ )
		{
			// if the current option is selected, add a copy of the option to the target list
			if( listObj.options[count].selected )
			{
				var tmpItem=document.createElement('option');
				tmpItem.value=listObj.options[count].value;
				tmpItem.text=listObj.options[count].text;
				selectedItems.push(tmpItem);
			}
		}
	} else return false;
	if( selectedItems.length>0 ) return selectedItems;
	else return false;
}

/**
 * Function wbAddSelectOption() Adds an option to an existing select item
 * @param {string} selectName The id of the existing select item
 * @param {string} optValue The value of the option
 * @param {string} optLabel The display value of the option
 * @param {string} optID The id value for the option
 * @param {boolean} True: the option is currently selected
 */
function wbAddSelectOption( selectName, optValue, optLabel, optID, isSelected ) {
	var myOpt = null;
	if( optID != null ) {
		// If an option id is passed, check to see if the option already exists
		myOpt = wbGetElement( optID );
	}
	
	if( myOpt == null || myOpt == '' ) {
		// The option doesn't exist.  Create a new option and set the optID accordingly
		myOpt = document.createElement('option');
		myOpt.setAttribute('id', optID ); // set the id for option
		myOpt.setAttribute('name', optID ); // set the id for option
	}
	myOpt.value = optValue;
	myOpt.innerHTML = optLabel;
	
	if( isSelected ) myOpt.selected = true;
	else myOpt.selected = false;
	
	var selObj = wbGetElement( selectName );
	selObj.appendChild( myOpt );
	return myOpt;
}

/**
 * Function wbAddSelectOption() Adds an option to an existing select item
 * @param {string} selectName The id of the existing select item
 * @param {string} optValue The value of the option
 * @param {string} optLabel The display value of the option
 * @param {string} optID The id value for the option
 * @param {boolean} True: the option is currently selected
 */
function wbAddListItem( listName, itemContents, itemID ) {
	var myItem = null;
	if( itemID != null ) {
		// If an item id is passed, check to see if the item already exists
		myItem = wbGetElement( itemID );
	}
	
	if( myItem == null || myItem == '' ) {
		// The item doesn't exist.  Create a new item and set the optID accordingly
		myItem = document.createElement('li');
		myItem.setAttribute('id', itemID ); // set the id for option
		myItem.setAttribute('name', itemID ); // set the name for option
	}
	myItem.innerHTML = itemContents;
	
	var listObj = wbGetElement( listName );
	listObj.appendChild( myItem );
	return myItem;
}

/**
 * function wbGetSelectedIndex() returns the (1st) selected index in list myList
 * @param string myList The name/id of the list to be examined
 * @return integer The index of the first selected item.
 */
function wbGetSelIndex( myList )
{
	var listObj=wbGetElement(myList);
	return listObj.selectedIndex;
}

/**
 * function wbGetSelValue() Returns the value of the first selected item in list myList
 * @param string myList The name/id of the list to be examined
 * @return mixed The value of the first selected item in list myList
 */
function wbGetSelValue( myList )
{
	var listObj=wbGetElement(myList);
	var index=listObj.selectedIndex;
	if( index >= 0 ) return listObj.options[index].value;
	else return null;
}

/**
 * Function wbMoveUpInList() moves an item up in a list by reducing its index value in the parent select object via the function wbSwapListItemPos().
 * @see wbSwapListItemPos()
 * @param string myList The name/id of the list to be modified
 */
function wbMoveUpInList( myList )
{
	var listObj=wbGetElement(myList);
	if( listObj )
	{
		// To move the selected item earlier in a list, simply swap the current item with the item in the preceding index
		var currentIndex=listObj.selectedIndex;
		var targetIndex=listObj.selectedIndex - 1;
		wbSwapListItemPos( myList, currentIndex, targetIndex );
	}
}

/**
 * Function wbMoveDownInList() moves an item up in a list by increasing its index value in the parent select object via the function wbSwapListItemPos().
 * @see wbSwapListItemPos()
 * @param string myList The name/id of the list to be modified
 */
function wbMoveDownInList( myList )
{
	var listObj=wbGetElement(myList);
	if( listObj )
	{
		// To move the selected item earlier in a list, simply swap the current item with the item in the preceding index
		var currentIndex=listObj.selectedIndex;
		var targetIndex=listObj.selectedIndex + 1;
		wbSwapListItemPos( myList, currentIndex, targetIndex );
	}
}

/**
 * Function wbSwapListItemPos() swaps the positions of two option objects in a select list by interchanging their index values in the parent select object named myList.
 * Generates alert messages for various invalid input.
 * @param string myList The name/id of the select object to be modified
 * @param integer index1 The index of the first option object to be moved
 * @param integer index2 The index of the second option object to be moved
 * @return True if the operation is successful
 * @type boolean
 */
function wbSwapListItemPos( myList, index1, index2 )
{
	var listObj=wbGetElement(myList);
	if( listObj && listObj.options.length > 0 )
	{
		if( index1==null || index1<0 )
		{
			alert( 'You must select an item first' );
			return false;
		}
		
		var testMultiple = wbGetSelItems( myList );
		if( testMultiple && testMultiple.length > 1 )
		{
			alert( 'You can only have one item selected when moving positions' );
			return false;
		}
		
		var lastIndex=listObj.options.length-1;
		
		if( index1<listObj.options.length ) // the first index must be valid.  If it is less than the length, it should be a valid index
		{
			if( index1==0 && index2<=0 )
			{
				alert( 'The item is already at the top of the list' );
				return false;
			}
			
			if( index1>=lastIndex && index2>=lastIndex )
			{
				alert( 'The item is already at the bottom of the list' );
				return false;
			}
			
			// Duplicate the option currently located at index1
			var item1=document.createElement('option');
			item1.text=listObj.options[index1].text;
			item1.value=listObj.options[index1].value;
			
			// Duplicate the option located at index2
			var item2=document.createElement('option');
			item2.text=listObj.options[index2].text;
			item2.value=listObj.options[index2].value;
			
			// Replace the item at index1 with the duplicate of item2
			listObj.options[index1] = item2;
			
			// Replace the item at index2 with the duplicate of item1
			listObj.options[index2] = item1;
			
			// Set the currenly selected index to index2 (signify that the first item was moved to the second item's location)
			listObj.selectedIndex=index2;
			return true;
		} else {
			alert( 'The items could not be moved as requested.' );
			return false;
		}
	} else {
		alert( 'There are no items in the list.' );
		return false;
	}
}

/**
 * Function wbMakeHiddenField() creates and assigns a hidden field object with name fieldName and value fieldValue for form formName on-the-fly
 * @param string fieldName The name to use for the new hidden field object
 * @param string fieldValue The value to be assigned to the new hidden field object
 * @param string formName The name/id of the form to be modified
 */
function wbMakeHiddenField( fieldName, fieldValue, formName )
{
	var hidden=document.createElement('input');
	hidden.type='hidden';
	hidden.value=fieldValue;
	hidden.name=fieldName;
	formObj=wbGetElement(formName);
	formObj.appendChild(hidden);
}

/**
 * Function wbPostAllListItems() generates hidden fields with values matching all option items contained in select object myList
 * The name of each hidden field is the select object name myList plus and underscore and a count.  When the form is submitted, you can extract all values by looking for request keys matching myform_count.
 * @param string myForm The name/id of the form to be modified
 * @param string myList The name/id of the select object to be examined.
 */
function wbPostAllListItems( myForm, myList )
{
	var listObj=wbGetElement(myList);
	if( listObj.options.length > 0 )
	{
		for( count=0; count<listObj.options.length; count++ )
		{
			// if the current option is selected, add a copy of the option to the target list
			wbMakeHiddenField( myList+'_'+count, listObj.options[count].value, myForm );
		}
	} else return false;
}

/**
 * Function wbDisableButton() Sets the disabled value to true for button object named myButton
 * @param string myButton The name/id of the button object to be modified.
 */
function wbDisableButton( myButton )
{
	var buttonObj = wbGetElement( myButton );
	if( buttonObj != null ) buttonObj.disabled=true;
}

/**
 * Function wbEnableButton() Sets the disabled value to false for button object named myButton
 * @param string myButton The name/id of the button object to be modified.
 */
function wbEnableButton( myButton )
{
	var buttonObj = wbGetElement( myButton );
	if( buttonObj != null ) buttonObj.disabled=false;
}

/**
 * Function wbAjaxObj creates an Ajax connection
 * @return object The Ajax connection object
 */
function wbAjaxObj() {
	var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
		return xmlHttp;
	}
	catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			return xmlHttp;
		}
		catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
				return xmlHttp;
			}
			catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
}

/**
 * Function wbHTMLEntities encodes a string with HTML entities (example '&' is converted to '&amp;')
 * @param string s The string to be converted
 * @return string The encoded string
 */
function wbHTMLEntities(s){
	var div=document.createElement('DIV');
	var text=document.createTextNode(s);
	div.appendChild(text);
	return div.innerHTML;
}

/**
 * Function wbClearContainer removes all child nodes from an object
 * @param object object
 */
wbClearContainer=function(object){
	if(object!=null&&object.childNodes.length>0){
		var total =  object.childNodes.length;
		for( count=0; count<total; count++ ) object.removeChild[0];
		object.innerHTML='';
		return true;
	} else return false;
}

/**
 * Object wbPropObj() emulates a keyed array (array with text labels for each element, instead of numbered indexes.
 */
function wbPropObj() {
	this.setProp= Set_Property;
}

function Set_Property ( propName, propValue ) {
	this[propName] = propValue;
}

/**
 * Function wbHookEvent adds an event listener to an element
 * @param {string} element The element name
 * @param {string} eventName The event to listen
 * @param {string} callback The callback function when the event occurs
 */
function wbHookEvent(element, eventName, callback){
	if(typeof(element) == "string") element = document.getElementById(element);
	if(element == null) return;
	if(element.addEventListener) element.addEventListener(eventName, callback, false);
	else if(element.attachEvent) element.attachEvent("on" + eventName, callback);
}

function wbUnhookEvent(element, eventName, callback){
	if(typeof(element) == "string") element = document.getElementById(element);
	if(element == null) return;
	if(element.removeEventListener) element.removeEventListener(eventName, callback, false);
	else if(element.detachEvent) element.detachEvent("on" + eventName, callback);
}

function wbCancelEvent(e)
{
	e=e?e:window.event;
	if(e.stopPropagation) e.stopPropagation();
	if(e.preventDefault) e.preventDefault();
	e.cancelBubble = true;
	e.cancel = true;
	e.returnValue = false;
	return false;
}

/**
 * Function wbGetMousePosition() gets the current x,y coordinates of the mouse pointer
 * @param {event} eventObj is the triggering event
 */
function wbGetMousePosition(eventObj){
	// get the current position of the mouse
	var m=new Object();
	m.posx = 0;
	m.posy = 0;
	if (!eventObj) var eventObj = window.event;
	if (eventObj.pageX || eventObj.pageY) 	{
		m.posx = eventObj.pageX;
		m.posy = eventObj.pageY;
	}
	else if (eventObj.clientX || eventObj.clientY) 	{
		m.posx = eventObj.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		m.posy = eventObj.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	return m;
}