var IE6 = $.browser.msie && $.browser.version <= 6;
var Gallery = function() {
  this.$picture = $(".gallery-block .gallery-picture");
  this.$thumbs = $(".gallery-block .gallery-thumbs a");

  this.fadeSpeed = 100;
  this.thumbWidth = 15;
  this.thumbHeight = 15;

  this.setup();
}
Gallery.prototype = {
  setup: function() {
    var self = this;
    self.$picture.click(function() { self.showGallery(); });
    self.correctSize();
    self.$thumbs.click(function() { self.changePicture(this); return false; })
                .mouseenter(function() { $("img", this).stop(true, true).animate({width: this.getAttribute("swidth"), height: this.getAttribute("sheight")}); })
                .mouseleave(function() { $("img", this).animate({width: self.thumbWidth, height: self.thumbHeight}); });
    self.fbox = $(".gallery-block .gallery-thumbs a img").FBox({
                    animation: true,
                    imagesList: false,
                    smallImagesList: true,
                    showOverlay: true,
                    useLoaderAnim: true,
                    loaderParams: {
                        animatioLength: 400,
                        animationStep: 50,
                        animationTime: 100
                    },
                    slideShowButtons: true,
                    slideShowDelay: 4000,
                    slideShowAutostart: false,
                    constraints: {
                        minWidth: 640,
                        minHeight: 380,
                        maxWidth: 800,
                        maxHeight: 460
                    }
                });
  },
  changePicture: function(a) {
    var self = this;
    self.$picture.find("img").fadeOut(self.fadeSpeed, function() { self.$picture.empty(); self.loadPicture(a); self.showGallery(); });
  },
  loadPicture: function(a) {
    var self = this;
    var img = new Image();
    img.src = a.rel;
    if (!IE6) img.onload = function() { self.correctSize(); };
    $(img).attr({"num": a.getAttribute("num"),
                 "width": self.$picture.parent().width()}).appendTo(self.$picture);
    if (IE6) self.correctSize();
  },
  correctSize: function() {
    var self = this;
    var height = self.$picture.find("img").outerHeight();
    self.$picture.fadeIn(self.fadeSpeed).animate({height: height});
  },
  showGallery: function() {
    var self = this;
    var num = $("img", self.$picture).attr("num") || 1;
    self.fbox.setImageIndex(num - 1);
    self.fbox.show();
  }
}

