/**
 *  CUserInterface.js
 *  Common user interface tools.  Things that manipulate controls & inputs.
 */

// Create an instance of the object
window.wvUI = new Object();
// Create an instance of the select object
window.wvUI.Select = new Object();

// toggleBlock
// el - element object or string identifying the object's ID
// Toggle the visibility of a block level object
window.wvUI.toggleBlock = function(el){
  try{
    el = htmlDOM.getElementById(el);
    if(el.style.display == "none"){
      el.style.display = "";
    }else{
      el.style.display = "none";
    }
  }catch(e){
    alert("Error: wvUI: toggleBlock");
  }
  return;
}

// selectAll
// sel - the select control
// Select all elements of a select control
window.wvUI.Select.selectAll = function(sel){
  try{
    sel = htmlDOM.getElementById(sel);
    for(var i = 0; i < sel.length; i++){
      sel.options[i].selected = true;
    }
  }catch(e){
    alert("Error: wvUI.Select: selectAll");
  }
  return;
}

// selectNone
// sel - the select control
// Select none of the elements of a select control
window.wvUI.Select.selectNone = function(sel){
  try{
    sel = htmlDOM.getElementById(sel);
    for(var i = 0; i < sel.length; i++){
      sel.options[i].selected = false;
    }
  }catch(e){
    alert("Error: wvUI.Select: selectNone");
  }
  return;
}

// goTo
// sel - the select control
// idx - 'first', 'last', 'next', 'prev', or an integer index
// RETURN: new index of control
window.wvUI.Select.goTo = function(sel, idx){
  try{
    var len = sel.options.length;
    var curIdx = sel.selectedIndex;
    // If idx is text, we must change it to a valid index
    if(typeof(idx) == "string"){
      switch(idx){
        case "first":
          idx = 0;
          break;
        case "last":
          idx = len - 1;
          break;
        case "prev":
          idx = curIdx - 1;
          if(idx < 0){
            idx = len - 1;
          }
          break;
        case "next":
          idx = curIdx + 1;
          if(idx >= len){
            idx = 0;
          }
          break;
      }
    }else if(typeof(idx) == "number"){
      // Make sure idx is within bounds
      if(idx < 0){
        idx = 0;
      }else if(idx >= len){
        idx = len - 1;
      }
    }else{
      // Other type, change to first element
      idx = 0;
    }
    // Now idx is a valid integer index, change it only if it differs
    // from the selected index
    if(idx != curIdx){
      sel.selectedIndex = idx;
    }
    return sel.selectedIndex;
  }catch(e){
    alert("Error: wvUI.Select: goTo");
  }
  return null;
}