window.addEvent('domready', function() {
  
  if ($('transcript') && $$('#right a.show').length > 0) {
    var show = $$('#right a.show')[0];
    var hide = $$('#right a.hide')[0];
    
    show.addEvent('click', function(e) {
      new Event(e).preventDefault();
      show.setStyle('display', 'none');
      hide.setStyle('display', 'inline');
      if ($('excerpt')) {
        $('excerpt').setStyle('display', 'none');
      }
      if ($('transcript')) {
        $('transcript').setStyle('display', 'block');
      }
    });
    
    hide.addEvent('click', function(e) {
      new Event(e).preventDefault();
      show.setStyle('display', 'inline');
      hide.setStyle('display', 'none');
      if ($('excerpt')) {
        $('excerpt').setStyle('display', 'block');
      }
      if ($('transcript')) {
        $('transcript').setStyle('display', 'none');
      }
    });
  }
  
  if ($('browse') && $('browse-options')) {
    var slider = new Fx.Slide('browse-options', {
      duration: 500,
      transition: Fx.Transitions.Quart.easeOut
    });
    slider.hide();
    $('browse-options').setStyle('display', 'block');
    $('browse').addEvent('click', function() {
      slider.toggle();
    });
    document.addEvent('click', function() {
      slider.slideOut();
    });
    $$('#browse a').each(function(link) {
      link.addEvent('click', function(e) {
        new Event(e).preventDefault();
        $$('#browse div.selected')[0].setText(link.getText());
        $$('#browse a.selected')[0].removeClass('selected');
        link.addClass('selected');
        var nav = link.getAttribute('rel').split(',');
        var by = link.getAttribute('href').match(/(\?by=[^&]+)/)[1];
        if (nav[0] != '') {
          $$('#nav a.prev')[0].setAttribute('href', nav[0] + by);
          $$('#nav span.prev')[0].addClass('hidden');
          $$('#nav a.prev')[0].removeClass('hidden');
        } else {
          $$('#nav span.prev')[0].removeClass('hidden');
          $$('#nav a.prev')[0].addClass('hidden');
        }
        if (nav[1] != '') {
          $$('#nav a.next')[0].setAttribute('href', nav[1] + by);
          $$('#nav span.next')[0].addClass('hidden');
          $$('#nav a.next')[0].removeClass('hidden');
        } else {
          $$('#nav span.next')[0].removeClass('hidden');
          $$('#nav a.next')[0].addClass('hidden');
        }
      })
    });
  }
  
  if ($('rate')) {
    var rating = $('rate').className.match(/rating(\d\d)/);
    if (rating) {
      setRating(parseInt(rating[1]) / 10);
    }
    var sendingRating = false;
    $$('#rate .star').each(function(star) {
      var num = parseInt(star.getAttribute('id').substr(4));
      star.addEvent('mouseover', function() {
        for (var i = 1; i <= num; i++) {
          $('star' + i).addClass('hover');
        }
      });
      star.addEvent('mouseout', function() {
        for (var i = 1; i <= num; i++) {
          $('star' + i).removeClass('hover');
        }
      });
      star.addEvent('click', function() {
        if (sendingRating) {
          return;
        }
        if (!$('video_id')) {
          alert('Sorry, you must be logged in to rate videos.');
          return;
        }
        sendingRating = true;
        $('score').setHTML('Please wait...');
        var xhr = new XHR({
          onSuccess: function() {
            sendingRating = false;
            $('score').setHTML(xhr.response.text);
            var score = parseFloat(xhr.response.text);
            setRating(score);
          }
        });
        xhr.send('/rate', 'video=' + $('video_id').value + '&score=' + num);
      });
    });
  }
  
  if ($('tags')) {
    $('tags').addEvent('submit', function(e) {
      new Event(e).preventDefault();
      if (!$('video_id')) {
        alert('Sorry, you must be logged in to tag videos.');
        return;
      }
      var issue = $('issue-input').value;
      $('issue-input').value = '';
      new XHR({
        onSuccess: function() {
          var list = $$('#tags ul')[0];
          var item = new Element('li');
          var url = '/tag/' + this.response.text;
          item.setHTML('<a href="' + url + '">' + issue + '</a>');
          item.inject(list);
        }
      }).send('/add-issue-tag', 'video=' + $('video_id').value +
                                '&issue=' + encodeURIComponent(issue));
    });
  }
  
  if ($E('a.show-hidden')) {
    $E('a.show-hidden').addEvent('click', function(e) {
      new Event(e).preventDefault();
      $$('.comment').each(function(div) {
        if (div.hasClass('hidden')) {
          div.addClass('gray');
          div.removeClass('hidden');
        }
        div.removeClass('last');
      });
      var lastIndex = $$('.comment').length - 1;
      $$('.comment')[lastIndex].addClass('last');
      $E('a.show-hidden').remove();
    });
  }
  
  if ($('video-notify')) {
    $('video-notify').addEvent('change', updateNotification);
    if (window.location.search &&
        window.location.search.match(/notify=([01])/)) {
      var notify = window.location.search.match(/notify=([01])/)[1];
      if (notify == '0') {
        $('video-notify').checked = false;
      } else {
        $('video-notify').checked = true;
      }
      updateNotification();
    }
  }
  
  $$('a.unhelpful').each(function(link) {
    link.addEvent('click', function(event) {
      var event = new Event(event);
      event.preventDefault();
      var node = event.target;
      while (!node.hasClass('comment')) {
        node = node.parentNode;
      }
      var id = node.getAttribute('id').substr(7);
      var feedback = link.parentNode;
      var retract = link.hasClass('retract') ? '&retract=1' : '';
      feedback.setHTML('Saving...');
      new XHR({
        onSuccess: function() {
          feedback.setHTML('Thanks, your report has been saved.');
        }
      }).send('/unhelpful', 'id=' + id + retract);
    });
  });
  
  $$('a.edit').each(function(link) {
    var id = link.getAttribute('rel');
    link.addEvent('click', function(event) {
      new Event(event).preventDefault();
      $('edit' + id).setStyle('display', 'block');
      $('content' + id).setStyle('display', 'none');
      $$('#comment' + id + ' .controls').each(function(div) {
        div.setStyle('display', 'none');
      });
    });
    $E('#comment' + id + ' .cancel').addEvent('click', function(e) {
      new Event(e).preventDefault();
      $('edit' + id).setStyle('display', 'none');
      $('content' + id).setStyle('display', 'block');
      $$('#comment' + id + ' .controls').each(function(div) {
        div.setStyle('display', 'block');
      });
    });
  });
});

function updateNotification() {
  new XHR({
    onSuccess: function() {
      $('video-notify-response').setHTML('Your notification preference has been saved.');
      flash('video-notify-response');
    }
  }).send('/notifications', 'video=' + $$('h1')[0].getAttribute('id') +
                            '&notify=' + ($('video-notify').checked ? 1 : 0));
}
