/**
 * Sterling Says - sterlingsays.it
 * 
 * @file main.js
 * @author David Miles
 * 
 * The main JavaScript file for the Sterling Says website. 
 * Handles AJAX requests when voting, adds a carousel using
 * jQuery Tools, and fixes quote-container veritcal positions.
 */
 
$(function(){
 
  // Vote scrolling
  $('#quotes').scrollable({
    circular: false,
    items: 'ul',
    next: '#next',
    prev: '#prev',
    speed: 200
  });
 
  // Scroll buttons
  $('#prev, #next').click(function(e){
    // Ignore actual click
    e.preventDefault();
  });
 
  // Voting
  $('.vote-up, .vote-down').click(function(){
    // For some reason, .not() is not working properly
    // Instead, return false if this button is disabled
    if($(this).hasClass('disabled')) return false;
 
    // Increment
    var i = $(this).hasClass('vote-up') ? 1 : -1;
 
    // Get the parent so that we can get this quote's ID
    var parent = $(this).closest('li');
 
    // Keep a reference of this jQuery object for the closure
    var that = $(this);
 
    // Disable the vote buttons for now
    parent.find('.vote-up, .vote-down').addClass('disabled');
 
    // Make a request for JSON
    var json = $(this).html().toLowerCase() + '/' + parent.attr('id') + '.json';
    $.getJSON(json, function(d){
      // Check if the status returned was success or fail
      if(parseInt(d.status)){
        // First, mark this arrow as "on"
        that.addClass('voted');
 
        // And update the vote count
        parent.find('.votes').html(d.votes);
      }else{
        // Enable the voting buttons again; there was an error
        parent.find('.vote-up, .vote-down').removeClass('disabled');
      }
    });
  });
 
});
 
$(window).load(function(){
  // Fix quote paragraph positions
  $('#quotes p').each(function(){
    $(this).css('margin-top', '-' + ($(this).outerHeight() / 2) + 'px');
  });
});