
var TravelWithTim = {
  
  $form: null,
  
  start: function() {
    this.limitSelectFields();
    this.resetForm();
    this.fixNavigation();
  },
  
  resetForm: function() {
    var $form = this.$form || $('form');
    var $reset = $('<a href="">Reset Form</a>');
    $reset.bind('click', function(e) {
      var prompt = window.confirm('Are you sure you want to reset the form?');
      if (prompt) {
        $form[0].reset();
      }
      e.preventDefault();
    });
    $form.find('.reset').wrapInner('<span/>').append($reset);
  },
  
  limitSelectFields: function() {
    var $form = this.$form || $('form');
    $form.find('select').each(function(i) {
      var $this = $(this);
      if ($this.is('.limit-select')) {
        
        var classNames = this.className.split(' ');
        var id = null;
        for (var j=0; j < classNames.length; j++) {
          if (classNames[j].indexOf('id:') == 0) {
            id = classNames[j].split(':')[1];
            break;
          }
        }
        
        if (id) {
          var how_many = 0;
          var $target = $('#' + id);
          var $selects = $target.find('select');
          $this.bind('click', function() {
            how_many = this.selectedIndex;
            toggleSelect(how_many);            
          });
        }
        
        function toggleSelect(how_many) {
          if (how_many == 0) {
            $selects.attr('disabled', true);
            $target.hide();
          } else {
            $selects.show().removeAttr('disabled')
              .slice(how_many, $selects.length).hide().attr('disabled', true);
            $target.show();
          }
        }
        
        toggleSelect(this.selectedIndex);
        
      }
    });
  },
  
  fixNavigation: function() {
    // used by IE6 via CSS in conditional comments. harmless in other browsers
    // also used by Safari (odd `li:hover + li` bug)
    $('#navigation li').each(function() {
      var $this = $(this);
      var $next = $this.next();
      if ($this.is('.selected')) {
        $next.addClass('hover-sibling');
      }
      $this.hover(function() {
        $next.addClass('hover-sibling');
      }, function() {
        if (!$this.is('.selected')) {
          $next.removeClass('hover-sibling');
        }
      });
    });
    
  }
  
};

$(function() {
  TravelWithTim.start();
});
