$(function() {
  var recipeLinks = $('.recipe-links a');
  recipeLinks.click(function(e) {
    // Update recipe content
    var contentClass = $(this).attr('rel');
    $('.recipe-content').hide();
    $('.' + contentClass).show();
    
    // Update recipe links
    recipeLinks.removeClass('selected');
    $(this).addClass('selected');
    
    return false;
  });
  
  jQuery.fn.extend({
    switchOn: function() {
      if (this.attr('src')) {
        this.attr('src', this.attr('src').replace('_off', '_on'));
      }
    },
    
    switchOff: function() {
      if (this.attr('src')) {
        this.attr('src', this.attr('src').replace('_on', '_off'));
      }
    }
  });
  
  $('.recipe-preview:nth-child(3n)').filter(':not(:first)').before('<div style="clear: left"></div>');
  $('.recipe-preview').height('auto');
  var maxHeight = 80;
  $('.recipe-preview h4').each(function() {
    if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
  });
  $('.recipe-preview h4').height(maxHeight+15);
});

function Rater(id) {
  var rater = $(id);
  var stars = rater.find('img');
  var me = this;
  
  rater.find('a').hover(function() {
    // Turn off all stars
    stars.switchOff();
    
    // Turn on this star and all stars before
    $(this).parent().prevAll().andSelf().find('img').not('a').switchOn();
    
    // Set text
    rater.find('.message').text($(this).find('img').attr('alt'));
  }, function() {
    if (me.rated) {
      rater.find('.message').text('You rated this recipe ' + me.rating + ' stars!');
      rater.find('a img').switchOn();
      rater.find('a:gt(' + (me.rating-1) + ') img').switchOff();
    } else {
      // Turn off all stars
      rater.find('.message').text('');
      $(this).parents('.rater').find('img').switchOff();
    }
  }).click(function() {
    var rating = rater.find('a').index(this) + 1;
    
    // Perform rating Ajax call
    jQuery.post($(this).attr('href'), { rating: rating });
    
    rater.find('.message').text('You rated this recipe ' + rating + ' stars!');
    
    me.rated = true;
    me.rating = rating;
    return false;
  });
}
