/**
 * Класс галереи
 *
 * @param Object layer
 * @param jQuery links
 */
function Gallery(layer, links)
{
  // Me :)
  var me = this;

  // vars
  this.links = links;
  this.layer = layer;
  this.link;
  this.linkIndex;
  this.image = new Image();

  // закрытие слоя
  this.close = function()
  {
    this.layer.div.hide();
  }

  // открытие слоя
  this.open = function()
  {
    this.layer.div.show();
  }

  // показываем картинку
  this.show = function(link)
  {
    var index = this.links.index(link);
    if (index == this.linkIndex && this.layer.div.is(':visible')) {
      return;
    }

    this.link = link;
    this.linkIndex = index;

    if (this.linkIndex == 0) {
      this.layer.prev.hide();
    } else {
      this.layer.prev.show();
    }

    if (this.linkIndex == this.links.length-1) {
      this.layer.next.hide();
    } else {
      this.layer.next.show();
    }

    this.image.onload = function(){
      me.onImage();
      this.onload=null;
    }
    this.image.src = link.href;
  }

  // после загрузки картинки
  this.onImage = function()
  {
    this.layer.image.attr('src', this.image.src);
    this.layer.title.text(this.link.title);
    this.open();
  }

  // следущая фота
  this.next = function()
  {
    var link = this.links[this.linkIndex+1];
    if (link) {
      this.show(link);
    }
  }

  // предыдущая фота
  this.prev = function()
  {
    var link = this.links[this.linkIndex-1];
    if (link) {
      this.show(link);
    }
  }

  // добавляем обработчики
  this.links.bind('click', function(event){
    me.show(this);
    event.preventDefault();
  });
  this.layer.close.bind('click', function(event){
    me.close();
    event.preventDefault();
  });
  this.layer.prev.bind('click', function(event){
    me.prev();
    event.preventDefault();
  });
  this.layer.next.bind('click', function(event){
    me.next();
    event.preventDefault();
  });

}

$(function(){
  new Gallery(
    {
      div:   $('#photo_show'),
      close: $('#photo_show .close-img'),
      image: $('#photo_show img'),
      title: $('#photo_show h3'),
      next:  $('#photo_show .float-r'),
      prev:  $('#photo_show .float-l')
    },
    $('.gallery_image')
  );
});