$(function(){
  //carousel
  (function(){
    var number_of_items = $("#pages li").size(),
        visible_items = 1,
        current_index = 0,
        item_width =  817;

    function scroll_carousel(index) {
      var scroll_amount = item_width * index;
      $("#pages-container").stop().animate({scrollLeft: scroll_amount}, 500);
    }      

    // Next Button
    $("#pages-container + .prev + .next").click(function(){
      current_index++;
      if(current_index > number_of_items-visible_items) {
        current_index = 0;
      }
      scroll_carousel(current_index);
    });

    // Previous Button
    $("#pages-container + .prev").click(function(){
      current_index--;
      if(current_index < 0) {
        current_index = number_of_items - visible_items
      } 
      scroll_carousel(current_index);
    });

    if(number_of_items <= 1) {
      $("#pages-container + .prev").hide();
      $("#pages-container + .prev + .next").hide();
    }
  })();

  $("#content ul").sortable({
    stop: function(event, ui) {
      var ids = [];
      $("#content li").each(function(i){
        ids.push($(this).attr("id"));
      });
      
      $.post("/pages/sort",{ids: ids.toString()});
    }
  });
});