// -----------------------------------------------------------------------------

function setBooksMargins() {
  var width = $('#books').width()-40;
  if (width != booksWidth) {
    var booksLi = $('#books li');
    var margin = 9;
    var count = Math.floor(width / (120+2*margin));
    booksLi.css('margin', margin).css('width', Math.floor((width / count) - 2*margin));
    if ((booksLi.length % count) > 0)
      booksLi.first().css('margin-left', (count - (booksLi.length % count))*(2*margin+booksLi.first().outerWidth())+margin);
    booksWidth = width;
  }
  $('#spacer').css('height', $('#books').height()+40);
}

// -----------------------------------------------------------------------------

$(document).ready(function() {

  booksWidth = 0;
  setBooksMargins();
  $(window).resize(setBooksMargins);
  
  $('#contact').click(function() {
    $('#info .images').hide();
    $('#info .images img').hide();
    $('#info #book-contact').show();
    $('#info').not(':animated').slideDown('normal');
    $('#info #book-contact p').css('top', Math.round((350-$('#info #book-contact p').height()) / 2));
  });

  $('#books li img').click(function() {
    var id = $(this).attr('id');
    $('#info .images').hide();
    $('#info .images img').hide();
    $('#info #'+id+'-images').show();
    $('#info #'+id+'-images img:first').show();
    $('#info #'+id+'-images .counter strong').text('1');
    $('#info').not(':animated').slideDown('normal');
  });
  
  $('#info #close').click(function() {
      $(this).parent().not(':animated').slideUp('normal');
  });
  
  $('#info .images img').click(function(e) {
    var forward = e.pageX >= jQuery(window).width() / 2;
    var count = $(this).parent().find('img').length;
    var index = $(this).index() + (forward ? 1 : -1);
    if (index > count-1) index = 0;
    else if (index < 0)  index = count -1;
    $(this).hide();
    $(this).parent().find('img').eq(index).show();
    $(this).parent().find('.counter strong').text(index+1);
  });
  
  $('#info .images .counter').click(function() {
    var index = $(this).parent().find('img:visible').index();
    var next_index = index+1;
    if (next_index > $(this).parent().find('img').length-1)
      next_index = 0;
    $(this).parent().find('img').eq(index).hide();
    $(this).parent().find('img').eq(next_index).show();    
    $(this).find('strong').text(next_index+1);
  });
  
});
