// $Id: daterange.js,v 1.2.4.8 2008/02/29 12:37:42 douggreen Exp $

if (Drupal.jsEnabled) {
  $(document).ready(
    function() {
      $('select.daterange-edit').change(function() {
        var index = this.id.substring(12, 13); // assumes less than 10 per form
        var date1 = this.form.elements.namedItem('filter[' + index + '][value][date1]');
        var date2 = this.form.elements.namedItem('filter[' + index + '][value][date2]');
        _dateopOnChange(date1, date2, this);
      });

      $('select.daterange-filter').change(function() {
        var index = this.id.substring(7);
        // NOTE: the index seems to have been lost
        var date1 = this.form.elements.namedItem('edit-filter' + index + '-date1');
        var date2 = this.form.elements.namedItem('edit-filter' + index + '-date2');
        _dateopOnChange(date1, date2, this);
      });

      
      _dateopOnReady();

      // call these functions again so that if jstools adds dates, they are hidden
      setTimeout('_dateopOnReady()', 1000);
    }
  );
}

function _dateopOnReady() {
  $('select.daterange-edit').change();
  $('select.daterange-filter').change();
}

function _dateopOnChange(date1, date2, elm) {
  if (date1 == null || date2 == null) {
    return;
  }
  var jsdate1 = date1.nextSibling;
  if (jsdate1 != null && jsdate1.id != date1.id + '-button') {
    jsdate1 = null;
  }
  var jsdate2 = date2.nextSibling;
  if (jsdate2 != null && jsdate2.id != date2.id + '-button') {
    jsdate2 = null;
  }
  var op = elm.options[elm.selectedIndex].value.substring(0, 16);
  if (op == 'daterange:today-') {
    date1.value = elm.options[elm.selectedIndex].value.substring(10);
    date2.value = 'today';
    setVisibility(date1, jsdate1, false);
    setVisibility(date2, jsdate2, false);
  }
  else if (op == 'daterange:today+') {
    date1.value = 'today';
    date2.value = elm.options[elm.selectedIndex].value.substring(10);
    setVisibility(date1, jsdate1, false);
    setVisibility(date2, jsdate2, false);
  }
  else if (op == 'before' || op == 'after') {
    setVisibility(date1, jsdate1, true);
    setVisibility(date2, jsdate2, false);
  }
  else {
    setVisibility(date1, jsdate1, true);
    setVisibility(date2, jsdate2, true);
  }
}

function setVisibility(elm1, elm2, value) {
  _setVisibility(elm1, value);
  if (elm2 != null) {
    _setVisibility(elm2, value);
  }
}

function _setVisibility(elm, value) {
  elm.style.display = (value == true) ? '' : 'none';
}
