// -------------------------------------------------------------------
// 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);
		for (var i=0; i<obj.options.length; i++) {
			if (re.test(obj.options[i].text)) {
			  alert("selecting " + obj.options[i].text);
				obj.options[i].selected = selected1;
			}
			else {
			  alert("unselecting " + obj.options[i].text);
				if (only == true) {
					obj.options[i].selected = selected2;
				}
			}
		}
	}
}


function selectUnselectMatchingOptionsValue(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);
		for (var i=0; i<obj.options.length; i++) {
			if (re.test(obj.options[i].value)) {
				obj.options[i].selected = selected1;
			}
			else {
				if (only == true) {
					obj.options[i].selected = selected2;
				}
			}
		}
	}
}


function selectItem(obj, text){
  for (var i=0; i < obj.options.length; i++){
    if(obj.options[i].value == text){
      obj.options.selectedIndex = i;
      return true;
    }
  }
  return true;
}


function selectSelectedValue(obj) {
  if(obj.selectedIndex == null || obj.selectedIndex == -1) {
    return null;
  }
  return obj.options[obj.selectedIndex].value;
}

		
// -------------------------------------------------------------------
// 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);
}

function selectOnlyMatchingOptionsValue(obj,regex) {
	selectUnselectMatchingOptionsValue(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();
	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) ;
	}
	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) {
	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,flag) {
	// Unselect matching options, if required
        
	// Move them over
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {

		  if(flag == 'add_sort') {
		    to.options[to.options.length] = new Option( o.text + ', Ascending', o.value + '|a', false, false);
		  } else if(flag == 'remove_sort') {
		    value_parts = o.value.split("|");
		    text_parts = o.text.split(", ");
		    to.options[to.options.length] = new Option(text_parts[0], value_parts[0], false, false);
		  } else {
		    to.options[to.options.length] = new Option( o.text, o.value, false, false);
		  }
		}
	}
	// 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;
		}
	}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
}

// Clear all options, remove all options from a select box.
function removeAllOptions(from) {
	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;
}



// -------------------------------------------------------------------
// 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();
	for (var i=0; i<to.options.length; i++) {
		options[to.options[i].text] = true;
	}
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			if (options[o.text] == null || options[o.text] == "undefined") {
				to.options[to.options.length] = new Option( o.text, o.value, false, false);
			}
		}
	}
	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,flag) {
	selectAllOptions(from);
	moveSelectedOptions(from, to, flag);
}

// -------------------------------------------------------------------
// 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 > 1 option selected, do nothing
	var selectedCount=0;
	for (i=0; i<obj.options.length; i++) {
		if (obj.options[i].selected) {
			selectedCount++;
		}
	}
	if (selectedCount > 1) {
		return;
	}
	// If this is the first item in the list, do nothing
	var i = obj.selectedIndex;
	if (i == 0) {
		return;
	}
	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 > 1 option selected, do nothing
	var selectedCount=0;
	for (i=0; i<obj.options.length; i++) {
		if (obj.options[i].selected) {
			selectedCount++;
		}
	}
	if (selectedCount > 1) {
		return;
	}
	// If this is the last item in the list, do nothing
	var i = obj.selectedIndex;
	if (i == (obj.options.length-1)) {
		return;
	}
	swapOptions(obj,i,i+1);
	obj.options[i+1].selected = true;
}

// --------------------------------------------------------------------
// toggleAscending
// --------------------------------------------------------------------
function toggleAscending(obj) {
  // If > 1 option is selected, do nothing
  var selectedCount=0;
  for (i=0; i<obj.options.length; i++) {
    if (obj.options[i].selected) {
      selectedCount++;
    }
  }
  if (selectedCount > 1) {
    return;
  }
  
  var i = obj.selectedIndex;
  
  // Get the value of the object selected
  var value = obj.options[i].value;
  parts = value.split("|");
  
  var new_direction;
  var new_text_direction;
  if(parts.length == 2 && parts[1] == 'a') {
    new_direction = 'd';
    new_text_direction = 'Descending';
  } else {
    new_direction = 'a';
    new_text_direction = 'Ascending';
  }

  obj.options[i].value = parts[0] + '|' + new_direction;

  var text_parts = obj.options[i].text.split(", ");
  
  var new_text = text_parts[0] + ', ' + new_text_direction;

  obj.options[i].text = new_text;
}

function igview_selectAll(formObj, elementName) { 
  for(var i = 0; i < formObj.length;i++) { 
    fldObj = formObj.elements[i]; 
    if(fldObj.type == 'checkbox' && (!elementName || typeof(elementName) == 'undefined' || fldObj.name == elementName)  ) { 
      viewToggleHighlight(fldObj.parentNode.parentNode, 1);
      fldObj.checked=true; 
    } 
  } 
} 

// returns true if a selected option exists. useful for multiple selects.
function haveSelectedOption(obj){
  for(var i=0; i < obj.options.length; i++){
    if (obj.options[i].selected){
      return true;
    }
  }

  return false;
}


// returns index of option with specified value or null if not found.
// useful for determining if an item is in a select box or not.
function getFirstExistingOptionIndex(obj, value){
  for(var i=0; i < obj.options.length; i++){
    if (obj.options[i].value == value){
      return i;
    }
  }

  return null;
}

// Selects the current option with value specified or creates a new one if value not found.
function addOrSelectExistingOption(obj, value, label){
  var found_item = false;
  if(obj.multiple){ //clear all values first.
    obj.selectedIndex = -1;
  }
  for(var i=0; i < obj.options.length; i++){
    if (obj.options[i].value == value){
      if(!obj.multiple){
	obj.selectedIndex = i;
	return true;
      }
      obj.options[i].selected = true;
      found_item = true;
    }
  }

  if(found_item){
    return true;
  }

  obj.options[obj.options.length] = new Option( label, value, false, false);
  obj.selectedIndex = obj.options.length - 1;

  return true;
}



 
function igview_clearAll(formObj, elementName) { 
  for(var i = 0; i < formObj.length;i++) { 
    fldObj = formObj.elements[i]; 
    if(fldObj.type == 'checkbox' && (!elementName || typeof(elementName) == 'undefined' || fldObj.name == elementName)   ) { 
      viewToggleHighlight(fldObj.parentNode.parentNode, -1);
      fldObj.checked=false; 
    } 
  } 
} 


function setDropdownDisabled(sb, entry) {
  var disabled_value = !(sb.options[sb.selectedIndex].value == '');
  entry.disabled = disabled_value;
}

function tiedSelectOptionsExists() {
  var argv = new Array;

  for(var i = 0; i < arguments.length; i++) {
    argv.push(arguments[i]);
  }
  var array_name = argv.shift();

  if(array_name == null) {
    alert('array name for exists is null');
  }

  var source_array = eval(array_name);

  if(source_array == null) {
    alert('source array for exists is null');
  }

  var current = source_array;

  for(var i = 0; i < argv.length; i++) {
    current = current[argv.shift()];

    if(current == null) {
      return 0;
    }
  }

  if(current == null) {
    return 0;
  }
  return 1;
}

// Functions for tied select boxes.
// Select boxes that get their values by lookups in javascript data structures.
function tiedSelectPopulateOptions() {
  var argv = new Array;

  for(var i = 0; i < arguments.length; i++) {
    argv.push(arguments[i]);
  }

  if(argv.length == 1) {
    alert('Called with args: ' + argv.length);
  }

  
  var select_box = argv.shift();
  var array_name = argv.shift();

  if(select_box == null) {
    alert('attempting to populate null selectbox');
    return;
  }
  
  if(array_name == null) {
    alert('array name for populate is null obj' + select_box + ' Args: ' + arguments.toString());
    return;
  }

  var source_array = eval(array_name);

  if(source_array == null) {
    alert('source array for populate is null');
    return;
  }


  var current_selected_value = selectSelectedValue(select_box);



  var current = source_array;

  for(var i = 0; i < argv.length; i++) {
    current = current[argv.shift()];
  }

  if(current == null) {
    alert('Lookup resulted in null value.');
    return;
  }

  while(select_box.options.length > 0) {
    select_box.options[0] = null;
  }

  for(var i = 0; i < current.length; i++) {
    select_box.options[select_box.options.length] = new Option(current[i][1], current[i][0], false, false);
  }

  select_box.selectedIndex = 0;

  for(var i = 0; i < select_box.options.length; i++) {
    if(select_box.options[i].value == current_selected_value) {
      select_box.selectedIndex = i;
      break;
    }
  }
}

function cleanIntervalType(t) {
  if(t == 'years') {
    return 'year';
  } else if(t == 'mons') {
    return 'mon';
  } else if(t == 'days') {
    return 'day'
  }
  return t;
}



// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
  if(!radioObj)
    return "";
  var radioLength = radioObj.length;
  if(radioLength == undefined)
    if(radioObj.checked)
      return radioObj.value;
  else
    return "";
  for(var i = 0; i < radioLength; i++) {
    if(radioObj[i].checked) {
      return radioObj[i].value;
    }
  }
  return "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
// use noreset parameter to leave all other checkboxes alone.
function setCheckedValue(radioObj, newValue, noreset) {
  if(!radioObj)
    return;
  var radioLength = radioObj.length;
  if(radioLength == undefined) {
    radioObj.checked = (radioObj.value == newValue.toString());
    return;
  }
  for(var i = 0; i < radioLength; i++) {
    radioObj[i].checked = false;
    if(radioObj[i].value == newValue.toString()) {
      radioObj[i].checked = true;
    }
  }
}


// Return the actual radio buttons in a set that have the specified value.
function getRadioElementsByValue(radioObj, value) {
  var return_array = [];

  if(!radioObj)
    return return_array;

  var radioLength = radioObj.length;
  if(radioLength == undefined) {
    if (radioObj.value == value.toString()){
      return_array.push(radioObj);
    }
    return return_array;
  }

  for(var i = 0; i < radioLength; i++) {
    if(radioObj[i].value == value.toString()) {
      return_array.push(radioObj[i]);
    }
  }
  return return_array;
}

function isAnyRadioChecked(radioObj){
  if(!radioObj){
    return false;
  }

  var radioLength = radioObj.length;
  if(radioLength == undefined){
    if(radioObj.checked)
      return true;
    else
      return false;
  }

  for(var i = 0; i < radioLength; i++) {
    if(radioObj[i].checked) {
      return true;
    }
  }
  return false;
}

// Check all boxes.
function checkAllCheckboxes(radioObj){
  if(!radioObj){
    return false;
  }

  var radioLength = radioObj.length;
  if(radioLength == undefined){ // only one.
    if(!radioObj.checked){
      radioObj.checked = true;
    }
  }else{
    for(var i = 0; i < radioLength; i++) {
      if(!radioObj[i].checked) {
	radioObj[i].checked = true;
      }
    }
  }
  return true;
}
// Uncheck all boxes
function clearAllCheckboxes(radioObj){
  if(!radioObj){
    return false;
  }

  var radioLength = radioObj.length;
  if(radioLength == undefined){ // only one.
    if(radioObj.checked){
      radioObj.checked = false;
    }
  }else{
    for(var i = 0; i < radioLength; i++) {
      if(radioObj[i].checked) {
	radioObj[i].checked = false;
      }
    }
  }
  return true;
}
