/*
* UCB Form functions
*/

//Sets anchor for new item on event form
function goToAnchor(anchorname)
{
		  location.replace(location.href+anchorname);
}

//Sets the value of a selector
function setSelector(selectorID, targetValue)
{
	selector = document.getElementById(selectorID);

	if(!selector)
	{
		alert('setSelector could not find ' + selectorID);
		return false;
	}

	for(var i = 0; i < selector.length; ++i)
	{
		if (selector[i].value == targetValue)
		{
			selector.selectedIndex = i;
			return true;
		}
	}
	return false;
}

/* 
* Alter CSS Style on an element
*/

//{{{ 
function alterStyle(elementID, styleName, value) 
{
	obj = document.getElementById(elementID);
	obj.style[styleName] = value;
}

/* 
* Alter CSS Class
*/

//{{{ 
function alterClass(className, element, value) 
{

//DEBUG
//alert(className+" "+element+" "+value);
	 var cssRules;
	 if (document.all) 
	 {
	 	cssRules = 'rules';
	 }
	 else if (document.getElementById) 
	 {
	 	cssRules = 'cssRules';
	 }
	 for (var i = 0; i < document.styleSheets.length; i++)
	 {
	 	for (var e = 0; e < document.styleSheets[i][cssRules].length; e++) 
	 	{
	   		iClassName = new RegExp(className, "i");
	   		if (document.styleSheets[i][cssRules][e].selectorText.match(iClassName)) 
	   		{
	    		document.styleSheets[i][cssRules][e].style[element] = value;
	   		}
	  	}
	}	
}

function isFieldChecked(field, value)
{
	var found = false;
	for (var i = 0; i < document.forms[0].elements.length; i++)
	{
		q = document.forms[0].elements[i];		
		if(q.name == field && q.value == value && q.checked == true)
		{
			found = true;
		}
	}
	//alert(found);
	return found;
}

function toggleClass(className)
{
	if(isClassElementValue(className, "display", "block"))
	{
		alterClass(className, "display", "none");
	}
	else
	{
		alterClass(className, "display", "block");
	}
}

function isClassElementValue(className, element, value)
{
	var found = false;
	var cssRules;
	if (document.all) 
	{
		cssRules = 'rules';
	}
	else if (document.getElementById) 
	{
	 	cssRules = 'cssRules';
	}
	for (var i = 0; i < document.styleSheets.length; i++)
	{
		for (var e = 0; e < document.styleSheets[i][cssRules].length; e++) 
	 	{
	   		iClassName = new RegExp(className, "i");
	   		if (document.styleSheets[i][cssRules][e].selectorText.match(iClassName) && document.styleSheets[i][cssRules][e].style[element] == value) 
	   		{
	    		found = true;
	   		}
	  	}
	}
	return found;
}

function showSection(section)
{
	 switch (section)
	{
		case "performer":
		
			alterClass('groupPerformer','display','block');
			alterClass('groupPerformerShow','display','none');
			
			// Count the performers
			performerCount = 0;
			for (var i = 0; i < document.forms[0].elements.length; i++)
			{
				searchTerm = new RegExp('Performer(.*)Type');
				
				q = document.forms[0].elements[i];		
				if(q.name.match(searchTerm) && q.value == 'Individual')
				{
					performerCount++;
				}
			}
			
			//loop and hide or show
			for (var i = 0; i < performerCount; i++)
			{
				if(isFieldChecked('Performer['+i+'][Type]','Group'))
				{
					alterClass('groupPerformerGroup'+i,'display','block');
  					alterClass('groupPerformerIndividual'+i,'display','none');
				}
				else
				{
					alterClass('groupPerformerIndividual'+i,'display','block');
  					alterClass('groupPerformerGroup'+i,'display','none');
				}			
			}
			  			  			
  		break
  		case "admission":
  			//alert("admission");
  			var admissionTypes = new Array('tickets','registration','enrollment','reservation','rsvp');
  			
  			alterClass('.groupAdmission','display','block');
			alterClass('.groupAdmissionShow','display','none');
			
			for (var i = 0; i < admissionTypes.length; i++)
			{
				if(isFieldChecked('AdmissionTypes[]', admissionTypes[i]))
				{
					//alert(admissionTypes[i] + ' checked!');
					alterClass('groupAdm_' + admissionTypes[i],'display','block');
				}
			}
  		break
	}
}

function hideSection(section)

{
	 switch (section)
	{
		case "performer":
			alterClass('groupPerformer','display','none');
			alterClass('groupPerformerShow','display','block');
	
  		break
  		case "admission":
  			var admissionTypes = new Array('tickets','registration','enrollment','reservation','rsvp');
  			
  			alterClass('.groupAdmission','display','none');
			alterClass('.groupAdmissionShow','display','block');
			
			for (var i = 0; i < admissionTypes.length; i++)
			{
				alterClass('groupAdm_' + admissionTypes[i],'display','none');
			}

  		break

	}
}
//}}}

function toggleFreeHelp(buttonID, DivID)
{
	button = document.getElementById(buttonID);
	div = document.getElementById(DivID);
	
	if(button && div && (div.style.display == 'none'))
	{
		button.value = 'hide help';
		div.style.display = 'block';
	}
	else if(button && div && (div.style.display == 'block'))
	{
		button.value = 'show help';
		div.style.display = 'none';
	}
}

/*
* Color Picker
*/

function selectColor(field,color)
{
	toggleId('pick'+field+'Box');
	document.getElementById('pick'+field).style.backgroundColor = '#'+color;
	document.getElementById('pick'+field+'PreviewBG').style.backgroundColor = '#'+color;
	document.getElementById('pick'+field+'PreviewText').style.color = '#'+color;
	document.getElementById('pick'+field).style.backgroundColor = '#'+color;
	document.getElementById('pick'+field+'field').value = '#'+color;
}

function changePreview(field,color)
{
	var previewBG = document.getElementById('pick'+field+'PreviewBG');
	var previewText = document.getElementById('pick'+field+'PreviewText');
	var defaultColor = document.getElementById('pick'+field+'field').value;
	
	if(color == null)
	{
		color = defaultColor;	
	}
	
	previewBG.style.backgroundColor = color;
	previewText.style.color = color;
	
/*

document.getElementById('pick".$this->name."PreviewBG').style.backgroundColor =  document.getElementById('pick".$this->name."field').value; 
document.getElementById('pick".$this->name."PreviewText').style.color =  document.getElementById('pick".$this->name."field').value;\" ".
				

*/
	
}

function togglePicker(field)
{
	var elementID = 'pick'+field+'Box';
	var element = document.getElementById(elementID);
	var defaultColor = document.getElementById('pick'+field+'field').value;
	
	if(element.style.display == 'block')
	{
		element.style.display = 'none';
	}
	else
	{
		if(element.innerHTML == '')
		{
			var websafeColorCodes = new Array('0','3','6','9','C','F');
			var pickerHTML = '';
			
			// Write in the Preview box
			pickerHTML += '<span style="background-color:'+defaultColor+';" id="pick'+field+'PreviewBG">'+
				'<span style="color:black;">&nbsp;Sample&nbsp;</span>'+
				'<span style="color:white;">&nbsp;Sample&nbsp;</span>'+
				'</span>'+
				'<span style="color:'+defaultColor+';" id="pick'+field+'PreviewText">'+
				'<span style="background-color:black;">&nbsp;Sample&nbsp;</span>'+
				'<span style="background-color:white;">&nbsp;Sample&nbsp;</span>'+
				'</span> '+
				'<br />';	
			
			for (var ai = 0; ai < websafeColorCodes.length; ai++)
			{
				var a = websafeColorCodes[ai];
				for (var bi = 0; bi < websafeColorCodes.length; bi++)
				{
					var b = websafeColorCodes[bi];
					for (var ci = 0; ci < websafeColorCodes.length; ci++)
					{
						var c = websafeColorCodes[ci];			
						var currentColor = a+a+b+b+c+c;
						pickerHTML += "<a href=\"javascript:selectColor('"+field+"','"+currentColor+"');\" "+
								"onmouseover=\"changePreview('"+field+"', '"+currentColor+"');\" "+
								"onmouseout=\"changePreview('"+field+"', null);\" "+
								"style=\"background-color:#"+currentColor+"; color:#"+currentColor+";\">#</a>";
					}
				}
				pickerHTML += "<br />";
			}
			
			element.innerHTML = pickerHTML;
		}
		
		element.style.display = 'block';
	}
}

function toggleId(id)
{
	var element = document.getElementById(id);
	if(element.style.display == 'block')
	{
		element.style.display = 'none';
	}
	else
	{
		element.style.display = 'block';
	}
}

/*
 * Menu functions
 */
//{{{ 
var menuStore; //global scope registry
function getMenuStore() { //singleton factory
	if(typeof(menuStore)=='undefined') {
		menuStore = new MenuStore();
		menuStore.setObserver();
	}
	return menuStore;
}



function MenuStore() { //registry with click observer callback
	var menus = new Array();
	var mindex = new Object();
	var observer_set = false;
	var self = this;
	var du = new DomUtils();
	var block_next_hideAll = false;
	this.setObserver = function() {
		if(!observer_set) {
			var o = getClickObserver();
			o.addObserver(self,'hideAll');
			observer_set = true;
		}
	}
	this.getIndex = function(menuid) {
		if(typeof(mindex[menuid])=='undefined') return null;
		else return mindex[menuid];
	}
	this.registerMenu = function(menu) {
		var r = new Object();
		r.idx = menus.length;
		r.state = null;
		r.subm = false; //is a submenu
		r.submp = null; //parent ID
		menus[r.idx] = menu;
		mindex[menu.id] = r;
		return r;
	}
	this.showAtIndex = function(oIdx) {
		//alert(menus[oIdx.idx].id);
		menus[oIdx.idx].style.display = 'inline';
		oIdx.state = 'on';
	}
	this.hideAtIndex = function(oIdx) {
		menus[oIdx.idx].style.display = 'none';
		oIdx.state = 'off';
	}
	this.showMenu = function(menu) {
		//alert(menu.id);
		self.showMenuID(menu.id);
	}
	this.showMenuID = function() { //for submenu-specific handler use f(sMenuID,sParentMenuID)
		var menuid = arguments[0];
		//alert(menuid);
		var r = this.getIndex(menuid);
		if(!r) {
			var menu = du.findElement(menuid);
			r = this.registerMenu(menu);
			if(arguments.length>1 && arguments[1]) r.subm = true;
		}
		if(r.subm) this.hideSubs(); //hide other submenus before displaying this submenu
		self.showAtIndex(r);
	}
	this.hideMenu = function(menu) {
		self.hideMenuID(menu.id);
	}
	this.hideMenuID = function(menuid) {
		//alert('hide'+menuid);
		var r = this.getIndex(menuid);
		if(r) self.hideAtIndex(r); //do not hide if menu was not registered/opened through this registry
	}
	this.hideSubs = function() {
		var r;
		for(r in mindex) {
			if(mindex[r].subm && mindex[r].state == 'on') {
				self.hideAtIndex(mindex[r]);
			}
		}
		return true; 
	}
	this.hideAll = function() {
		if(self.block_next_hideAll) { //set by showMenu
			self.block_next_hideAll = false; //reset
			return true;
		}
		var r;
		for(r in mindex) {
			if(mindex[r].state == 'on') {
				self.hideAtIndex(mindex[r]);
			}
		}
		return true;
	}
}

function toggleMenu() {
	//alert('toggle');
	var containername = arguments[0];
	var is_submenu = (arguments.length>1) ? arguments[1] : false;
	var m;
	var du = new DomUtils();
	var ms = getMenuStore();
	if(m = du.findElement(containername)) {
		if(m.style.display=='none'||m.style.display=='') {
			 //hide other menus if this is a root level context popup menu
			if(!is_submenu) {ms.hideAll();}
			ms.showMenu(m);
			ms.block_next_hideAll = true; //kludge to offset bubbling to document.onclick event handler which calls hide function
		}
		else ms.hideMenu(m);
	}
	return true;
}

/*
 * document click observer
 * add callbacks to this object to execute on generic click events
 */
var clickObserver;
function getClickObserver() {
	if(typeof(clickObserver) == 'undefined') clickObserver = new ClickObserver();
	return clickObserver;
}
function ClickObserver() {
	var observers = new Array();
	this.addObserver = function(oObs,sFuncName) {
		observers[observers.length] = oObs[sFuncName];
	}
	this.handleClick = function() {
		var l;
		if(l=observers.length) {
			for(i=0;i<l;i++) {
				observers[i].call();
			}
		}
		return true;
	}
}
 //bind the observer to the document onClick handler
var documentClickObserver = getClickObserver();
document.onclick = documentClickObserver.handleClick;

/*
 * DomUtils
 * exposes simple methods for dealing with document objects
 */
function DomUtils() {

	 // Browser compatible element getter
	this.findElement = function(id) {
		if (document.getElementById(id))
			return document.getElementById(id);
		if (document.all)
			return document.all[id];
		return null;
	}
	
	 // field finder (Requires field to be part of a <form>)
	this.findField = function(fldnm) {
		var i,j;
		for(i=0;i<document.forms.length;i++) {
			for(j=0;j<document.forms[i].length;j++) {
				if(document.forms[i].elements[j].name == fldnm) {
					return document.forms[i].elements[j];
				}
			}
		}
		return false;
	}

}
/*
 * StyleUtils
 */
function StyleUtils() {
	 //
	//this.getClassRegistry
	
	this.getClassOf = function(itemkey) {
		
	}
}


/*
 * BucketSelector
 * manages 2 display <select> fields 
 *  + 1 hidden field containing csv data for submission
 * HTML page code must instantiate one BucketSelector for each group
 *  and bind the add/remove buttons of each group to the 
 *  addOption/removeOption methods of the appropriate named instance
 */

function BucketSelector(avail_field,picked_field,value_field) {
	this.avail = 0;
	this.picked = 0;
	this.bucketValue = 0;
	this.utils = new DomUtils();
	
	this.findField = this.utils.findField;
	
	this.moveOption = function(direction) {
		var fr = (direction == 'add') ? this.avail : this.picked;
		var to = (direction == 'add') ? this.picked : this.avail;
		var fi = fr.selectedIndex;
		if(fi==-1) {
			alert(this.emptyMessage);
			fr.focus();
			return false;
		}
		var tl = to.options.length;
		if(navigator.userAgent.indexOf('MSIE')==-1) {
			var mover = fr.options[fi];
			to.options[tl] = mover;
		} else { //this is kludgy, but seemingly necessary
			o=new Option(fr.options[fi].text,fr.options[fi].value);
			to.options[tl]=o;
			fr.options[fi]=null;
		}
		return true;
	}

	this.setBucketValue = function() {
		var pl = this.picked.options.length;
		var v = new Array();
		for(vi=0;vi<pl;vi++) {
			v[vi]=this.picked.options[vi].value;
		}
		this.bucketValue.value = v.join(',');
		return true;
	}

	this.addOption = function() {
		if(this.moveOption('add')) {
			return this.setBucketValue();
		} else return false;
	}

	this.removeOption = function() {
		if(this.moveOption('remove')) {
			return this.setBucketValue();
		} else return false;
	}
 //construct
	this.emptyMessage = "Please highlight the item you would like to move";
	
	if(!(
				(this.avail = this.findField(avail_field))
		&&	(this.picked = this.findField(picked_field))
		&&	(this.bucketValue = this.findField(value_field))
	)) { 
		alert('The Add/Remove List Selector is misconfigured.  Your data may not be properly saved.');
	}
} //END BucketSelector

/*
 * ChainedSelector
 * requires provision of a data array with format:
 *	chainDataArray = [
			['primary_selector_value_1','sub_selector_value_1','sub selector text 1'],
			['primary_selector_value_1','sub_selector_value_2','sub selector text 2'],
			['primary_selector_value_1','sub_selector_value_n','sub selector text n'],
			['primary_selector_value_2','sub_selector_value_a','sub selector text a'],
			['primary_selector_value_2','sub_selector_value_b','sub selector text b'],
			['primary_selector_value_n','sub_selector_value_x','sub selector text x'],
		];
 */

function ChainedSelector(sel_name,sub_name,data_array) {
	this.msel = null; //master selector
	this.ssel = null; //slave selector
	this.chdata = new Array(); //data array

	this.findField = function(fnm) {
		var i,j;
		for(i=0;i<document.forms.length;i++) {
			for(j=0;j<document.forms[i].length;j++) {
				if(document.forms[i].elements[j].name == fnm) {
					return document.forms[i].elements[j];
				} continue;
			} continue;
		}
		return false;
	}
	
	this.change = function() {
		this.ssel.options.length = 0; //this works faster, so why not?
		//var sl = this.ssel.options.length; //take initial size of the options array before we modify it
		var v = this.msel.options[this.msel.selectedIndex].value;
		var cdl = this.chdata.length;
		var o,i,j=0;
		for(i=0;i<cdl;i++) {
			o = this.chdata[i];
			if(o[0] != v) continue;
			this.ssel.options[j++] = new Option(o[2],o[1]);
		}
		//modify this to reflect length of array changing as we delete items from it...
		/*while(j<sl) {
			alert(j+','+sl);
			this.ssel.options[j] = null;
			j++;
		}*/
		//alert(this.ssel.selectedIndex);
		return true;
	}
	
//bootstrap
	if(!(
				(this.msel = this.findField(sel_name))
		&& 	(this.ssel = this.findField(sub_name))
		&&	(this.chdata = data_array)	))
	{
		alert("The chained selector on this page is misconfigured. \n Any data you submit may not be correct.");
	}
	 //preset the initial subselector if it has not already been given options
	
	/*if((this.ssel.length==0) && (this.msel.value)) {
		this.change();
	}*/
	
} //END ChainedSelector


// -------------------------------------------------------------------
// hasOptions(obj)
//  Utility function to determine if a select object has an options array
// -------------------------------------------------------------------
function hasOptions(obj) {
	if (obj!=null && obj.options!=null) { return true; }
	return false;
	}

// -------------------------------------------------------------------
// selectUnselectMatchingOptions(select_object,regex,select/unselect,true/false)
//  This is a general function used by the select functions below, to
//  avoid code duplication
// -------------------------------------------------------------------
function selectUnselectMatchingOptions(obj,regex,which,only) {
	if (window.RegExp) {
		if (which == "select") {
			var selected1=true;
			var selected2=false;
			}
		else if (which == "unselect") {
			var selected1=false;
			var selected2=true;
			}
		else {
			return;
			}
		var re = new RegExp(regex);
		if (!hasOptions(obj)) { return; }
		for (var i=0; i<obj.options.length; i++) {
			if (re.test(obj.options[i].text)) {
				obj.options[i].selected = selected1;
				}
			else {
				if (only == true) {
					obj.options[i].selected = selected2;
					}
				}
			}
		}
	}
		
// -------------------------------------------------------------------
// selectMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Currently-selected options will not be changed.
// -------------------------------------------------------------------
function selectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"select",false);
	}
// -------------------------------------------------------------------
// selectOnlyMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Selected options that don't match will be un-selected.
// -------------------------------------------------------------------
function selectOnlyMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"select",true);
	}
// -------------------------------------------------------------------
// unSelectMatchingOptions(select_object,regex)
//  This function Unselects all options that match the regular expression
//  passed in. 
// -------------------------------------------------------------------
function unSelectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"unselect",false);
	}
	
// -------------------------------------------------------------------
// sortSelect(select_object)
//   Pass this function a SELECT object and the options will be sorted
//   by their text (display) values
// -------------------------------------------------------------------
function sortSelect(obj) {
	var o = new Array();
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
		}
	if (o.length==0) { return; }
	o = o.sort( 
		function(a,b) { 
			if ((a.text+"") < (b.text+"")) { return -1; }
			if ((a.text+"") > (b.text+"")) { return 1; }
			return 0;
			} 
		);

	for (var i=0; i<o.length; i++) {
		obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
		}
	}

// -------------------------------------------------------------------
// selectAllOptions(select_object)
//  This function takes a select box and selects all options (in a 
//  multiple select object). This is used when passing values between
//  two select boxes. Select all options in the right box before 
//  submitting the form so the values will be sent to the server.
// -------------------------------------------------------------------
function selectAllOptions(obj) {
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		obj.options[i].selected = true;
		}
	}
	
// -------------------------------------------------------------------
// moveSelectedOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  This function moves options between select boxes. Works best with
//  multi-select boxes to create the common Windows control effect.
//  Passes all selected values from the first object to the second
//  object and re-sorts each box.
//  If a third argument of 'false' is passed, then the lists are not
//  sorted after the move.
//  If a fourth string argument is passed, this will function as a
//  Regular Expression to match against the TEXT or the options. If 
//  the text of an option matches the pattern, it will NOT be moved.
//  It will be treated as an unmoveable option.
//  You can also put this into the <SELECT> object as follows:
//    onDblClick="moveSelectedOptions(this,this.form.target)
//  This way, when the user double-clicks on a value in one box, it
//  will be transferred to the other (in browsers that support the 
//  onDblClick() event handler).
// -------------------------------------------------------------------
function moveSelectedOptions(from,to) {
	// Unselect matching options, if required
	if (arguments.length>3) {
		var regex = arguments[3];
		if (regex != "") {
			unSelectMatchingOptions(from,regex);
			}
		}
	// Move them over
	if (!hasOptions(from)) { return; }
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
			to.options[index] = new Option( o.text, o.value, false, false);
			
			// Update hidden variables 
			//alert(from.name+'_'+o.value);
			
			var s = new String(from.name);
			
			// Check direction
			if(s != s.replace(/_source/,"")) {
				
				//enable
				s = s.replace(/_source/,"");
				var n = s + '_' + o.value;
				document.getElementById(n).name = s+'[]';	
				
				} else {
				
				//disable
				s = s.replace(/_destination/,"");
				var n = s + '_' + o.value;
				document.getElementById(n).name = "disabled"+s+'[]';
				
				}			
			}
		}
	// Delete them from original
	for (var i=(from.options.length-1); i>=0; i--) {
		var o = from.options[i];
		if (o.selected) {
			from.options[i] = null;
			}
		}
	if ((arguments.length<3) || (arguments[2]==true)) {
		sortSelect(from);
		sortSelect(to);
		}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
	
	}

// -------------------------------------------------------------------
// copySelectedOptions(select_object,select_object[,autosort(true/false)])
//  This function copies options between select boxes instead of 
//  moving items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
function copySelectedOptions(from,to) {
	var options = new Object();
	if (hasOptions(to)) {
		for (var i=0; i<to.options.length; i++) {
			options[to.options[i].value] = to.options[i].text;
			}
		}
	if (!hasOptions(from)) { return; }
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			if (options[o.value] == null || options[o.value] == "undefined" || options[o.value]!=o.text) {
				if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
				to.options[index] = new Option( o.text, o.value, false, false);
				}
			}
		}
	if ((arguments.length<3) || (arguments[2]==true)) {
		sortSelect(to);
		}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
	}

// -------------------------------------------------------------------
// moveAllOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  Move all options from one select box to another.
// -------------------------------------------------------------------
function moveAllOptions(from,to) {
	selectAllOptions(from);
	if (arguments.length==2) {
		moveSelectedOptions(from,to);
		}
	else if (arguments.length==3) {
		moveSelectedOptions(from,to,arguments[2]);
		}
	else if (arguments.length==4) {
		moveSelectedOptions(from,to,arguments[2],arguments[3]);
		}
	}

// -------------------------------------------------------------------
// copyAllOptions(select_object,select_object[,autosort(true/false)])
//  Copy all options from one select box to another, instead of
//  removing items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
function copyAllOptions(from,to) {
	selectAllOptions(from);
	if (arguments.length==2) {
		copySelectedOptions(from,to);
		}
	else if (arguments.length==3) {
		copySelectedOptions(from,to,arguments[2]);
		}
	}

// -------------------------------------------------------------------
// swapOptions(select_object,option1,option2)
//  Swap positions of two options in a select list
// -------------------------------------------------------------------
function swapOptions(obj,i,j) {
	var o = obj.options;
	var i_selected = o[i].selected;
	var j_selected = o[j].selected;
	var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
	o[i] = temp2;
	o[j] = temp;
	o[i].selected = j_selected;
	o[j].selected = i_selected;
	}
	
// -------------------------------------------------------------------
// moveOptionUp(select_object)
//  Move selected option in a select list up one
// -------------------------------------------------------------------
function moveOptionUp(obj) {
	if (!hasOptions(obj)) { return; }
	for (i=0; i<obj.options.length; i++) {
		if (obj.options[i].selected) {
			if (i != 0 && !obj.options[i-1].selected) {
				swapOptions(obj,i,i-1);
				obj.options[i-1].selected = true;
				}
			}
		}
	}

// -------------------------------------------------------------------
// moveOptionDown(select_object)
//  Move selected option in a select list down one
// -------------------------------------------------------------------
function moveOptionDown(obj) {
	if (!hasOptions(obj)) { return; }
	for (i=obj.options.length-1; i>=0; i--) {
		if (obj.options[i].selected) {
			if (i != (obj.options.length-1) && ! obj.options[i+1].selected) {
				swapOptions(obj,i,i+1);
				obj.options[i+1].selected = true;
				}
			}
		}
	}

// -------------------------------------------------------------------
// removeSelectedOptions(select_object)
//  Remove all selected options from a list
//  (Thanks to Gene Ninestein)
// -------------------------------------------------------------------
function removeSelectedOptions(from) { 
	if (!hasOptions(from)) { return; }
	if (from.type=="select-one") {
		from.options[from.selectedIndex] = null;
		}
	else {
		for (var i=(from.options.length-1); i>=0; i--) { 
			var o=from.options[i]; 
			if (o.selected) { 
				from.options[i] = null; 
				} 
			}
		}
	from.selectedIndex = -1; 
	} 

// -------------------------------------------------------------------
// removeAllOptions(select_object)
//  Remove all options from a list
// -------------------------------------------------------------------
function removeAllOptions(from) { 
	if (!hasOptions(from)) { return; }
	for (var i=(from.options.length-1); i>=0; i--) { 
		from.options[i] = null; 
		} 
	from.selectedIndex = -1; 
	} 

// -------------------------------------------------------------------
// addOption(select_object,display_text,value,selected)
//  Add an option to a list

// -------------------------------------------------------------------
function addOption(obj,text,value,selected) {
	if (obj!=null && obj.options!=null) {
		obj.options[obj.options.length] = new Option(text, value, false, selected);
		}
	}

// -------------------------------------------------------------------
// Select all checkboxes
// -------------------------------------------------------------------

/*
*	Function to swap between various simple searches
*/
function swapoptions(selectedshow) {
	if (document.getElementById) {
		if (firsttime) {
			selectedhide = "titledesc";
			document.getElementById('evmarch_'+selectedshow).style.display = "block";
			document.getElementById('evmarch_'+selectedhide).style.display = "none";
			firsttime = false;
			selectedhide = selectedshow;
		} else {
			document.getElementById('evmarch_'+selectedshow).style.display = "block";
			document.getElementById('evmarch_'+selectedhide).style.display = "none";
			selectedhide = selectedshow;
		}
	}
}

var selectedhide;
//This is attempting to swap by groups, not by id.
function swapoptions2(selectedshow) 
{
	if(!(selectedhide || selectedshow == "allfields"))
	{
		selectedhide = "allfields";
	}	
	alterClass('.gp_'+selectedshow,'display','block');
	alterClass('.gp_'+selectedhide,'display','none');
	selectedhide = selectedshow;
}

function refreshSearchForm()
{
	// Set a hidden variable to clear the form
	document.getElementById('searchAction').value = 'SEARCH_CLEAR';
	
	// Submit the form
	document.getElementById('searchForm').submit();
}

function checkAll(theForm, cName, allNo_stat) 
{
	var n=theForm.elements.length;
	for (var i=0;i<n;i++)
	{
		if (theForm.elements[i].className.indexOf(cName) !=-1)
		{
			if (allNo_stat.checked) 
			{
				theForm.elements[i].checked = true;
			} 
			else 
			{
				theForm.elements[i].checked = false;
			}
		}
	}
}

function trimLeadingZero(theString)
{
	if(theString.substring(0,1) == '0')
	{
		theString = theString.substring(1);
	}
	return(theString);
}