var gallery = {
  count: 0,
  elements: [],
  container: [],
  animating: false,
  
  init: function(elements, container) {
    this.elements = elements;
    this.container = container;
    
    if($('div#photo img').length < 1)
		$('div#next').hide();
		$('div#previous').hide();
    this.events();
  },
  
  events: function() {
    $('div#next').click(function(e) {
      e.preventDefault();
      gallery.next();
      return false;
    });
    
    $('div#previous').click(function(e) {
      e.preventDefault();
      gallery.previous();
      return false;
    }); 
   
  },
  
  next: function() {
    if(!this.animating && this.count < this.elements.length - 1) {
      this.animating = true;
      $(this.container).animate({
        left: 
          parseInt($(this.container).css('left')) - this.floor_width() + 'px'
      }, 300, function() {
        gallery.animating = false;
      });
      $('div#previous').show();
    }
  },
  
  previous: function() {
    if(!this.animating && this.count > 0) {
      this.animating = true;
      $(this.container).animate({
        left: 
          parseInt($(this.container).css('left')) + this.unfloor_width() + 'px'
      }, 300, function() {
        gallery.animating = false;
      });
      $('div#next').show();
    }
  },
  
  start: function() {
    if(!this.animating) {
      this.count = 0;
      this.animating = true;
      $(this.container).animate({
        left: '0px'
      }, 300, function() {
        gallery.animating = false;
      });
      $('div#next').show();
      $('div#previous').hide();
    }
  },
  
  floor_width: function() {
    var element_width = $(this.elements[this.count]).outerWidth(true);
    var container_width = $(this.container).outerWidth() + $('div#photo', this.container).width();
    if(this.count < this.elements.length - 1)
      this.count++;
    
    if(container_width + parseInt($(this.container).css('left')) - element_width > $(window).width()) {
      return element_width;
    } else {
      $('div#next').hide();
      this.closing_width = container_width + parseInt($(this.container).css('left')) - $(window).width();
      return this.closing_width;
    }
  }, 
  
  unfloor_width: function() {
    if(this.count > 0)
      this.count--;
      
    if(this.count == 0)
      $('div#previous').hide();
    
    var element_width = $(this.elements[this.count]).outerWidth(true);
    var container_width = $(this.container).outerWidth() + $('div#photo', this.container).width();
        
    if(this.closing_width != null) {
      var closing_width = this.closing_width;
      this.closing_width = null;
      return closing_width;
    } else {
      return element_width;
    }
  }
  
}

$(function() {
  var imgs = $('div#photo img');
  for(var i = 0; i < imgs.length; i++) {
    imgs[i].style.marginLeft = 10 + 'px';
  }
  
  gallery.init($('div#photo img'), $('div#gallery'));
  
});
