if (typeof Util == 'undefined') {
  Util = {};
}

Util.Dom = {
  /**
   * Add an option a given select.
   *
   * @static
   * @access public
   * @param HTMLSelect HTMLSelect
   * @param HTMLOption HTMLOption
   * @return void
   */
  addSelectOption: function (HTMLSelect, HTMLOption)
  {
    try {
      HTMLSelect.add(HTMLOption, null);
    }
    catch(e) {
      HTMLSelect.add(HTMLOption, -1);
    }
  },

  /**
   * Populate a given select with a list of options
   * Optional one can provide a default selected option. If
   * a default is not provided, the function will take the currently
   * selected item in the select if there is one and try to use that
   * to select an item in the new list.
   *
   * The select item can be a dom element or a string id that references one.
   *
   * @static
   * @access public
   * @param HTMLSelect|string select_el
   * @param object|array select_options
   * @param string|int selected_option
   * @return boolean.
   */
  populateSelect: function (select_el, select_options, selected_option)
  {
    /* make sure we have the right type, if the select el
     * is a string id, then we will fetch the element
     * otherwise we assume it is safe to proceed using it as an element.
     */
    if (typeof select_el == 'string') {
      select_el = document.getElementById(select_el);
    }

    // make sure element is not empty.
    if (!select_el) {
      return false;
    }

    // if no selected option was passed in then initialize to null.
    // and if there are items in the select, preserve the one that is selected.
    if (!selected_option) {
      selected_option = null;

      if (select_el.selectedIndex > -1) {
        selected_option = select_el.options[select_el.selectedIndex].value;
      }
    }

    // Clear list of options from select.
    select_el.options.length = 0;

    for (i in select_options) {

      // Create a new option.
      var option = new Option(select_options[i], i);

      // if the option's value equals our selected value then set option selected to true.
      if (selected_option && i == selected_option) {
        option.selected = true;
      }

      // Add option to select.
      Util.Dom.addSelectOption(select_el, option);
    }

    return true;
  }

}