var gallery = function() {
  this.items = $('#gallery .thumbs a');
  this.prev = $('#gallery .prev');
  this.next = $('#gallery .next');
  this.close = $('#gallery .close');
  this.holder = $('#gallery .thumbs');
  this.description = $('#gallery .info strong');
  this.photo_index = $('#gallery .info span');
  this.current_page = 0;
  this.image = $('#gallery .large img')
  this.pages = parseInt(this.items.length / 6) + 1;
  
  $('#overlay').height($('#page').height());
  
  var that = this;
  
  this.prevPage = function() {
    if(that.current_page == 0) return false;
    
    that.current_page--;
    that.next.removeClass('disabled');
    if(that.current_page == 0) {
      that.prev.addClass('disabled');
    }
    that.holder.stop().animate({marginLeft: -480 * that.current_page});
    return false;
  }
  
  this.nextPage = function() {
    if(that.current_page == that.pages-1) return false;
    
    that.current_page++;
    that.prev.removeClass('disabled');
    if(that.current_page == that.pages-1) {
      that.next.addClass('disabled');
    }
    that.holder.stop().animate({marginLeft: -480 * that.current_page});
    return false;
  }
  
  this.prev.click(function() {
    that.prevPage();
    return false;
  });
  
  this.next.click(function() {
    that.nextPage();
    return false;
  });
  
  this.close.click(function() {
    $('#overlay').remove();
    return false;
  });
  
  this.items.click(function() {
    $this = $(this);
    that.image.attr('src', $this.attr('href'));
    that.description.text($this.attr('title'));
    that.photo_index.text('Viewing photo ' + (that.items.index(this)+1) + ' of ' + that.items.length);
    return false;
  });
  
  this.items[0].click();
}

$(document).ready(function() {
  
  $('.calendar input').datepick({minDate: new Date(), showAnim:''});
  
  var carousel_items = $('#carousel a');
  var carousel_imageholder = $('#carousel .imageholder');
  var carousel_index = carousel_items.index($('#carousel .current'));
  
  function carouselMove(index) {
    carousel_items.eq(carousel_index).removeClass('current').end().eq(index).addClass('current');
    carousel_index = index;
    carousel_imageholder.stop().animate({marginLeft: -700 * index, duration: 1000, queue: false});
  }
  
  function carouselNext() {
    var next_index = (carousel_index == carousel_items.length-1 ? 0 : carousel_index+1);
    carouselMove(next_index);
  }
  
  var carouselTimer = setInterval(carouselNext, 4000);
  
  carousel_items.mouseover(function() {
    clearInterval(carouselTimer);
    carouselMove(carousel_items.index(this));
  }).mouseout(function() {
    carouselTimer = setInterval(carouselNext, 4000);
  });
  
  $('a[href$=/gallery/]').click(function(){
    $.ajax({
      url: $(this).attr('href'),
      method: 'get',
      cache: false,
      success: function(response) { 
        $('body').append(response);
        gallery();
      }
    });
    return false;
  });
  
});
