/*
 * Gallery
 * 
 * 2007 - MagicWand
 */
ns('MagicWand.Gallery');

ns.MagicWand.Gallery.BaseGallery = function(id, view_place) {
  this.id = id;
  this.view_place = view_place;
  this.act_pict = null;
  
  this._init();
}

ns.MagicWand.Gallery.BaseGallery.prototype = {
  _init: function() {
    this._bindHovers();
    this._bindClicks();
    this._bindActivate();
  },
  
  _bindHovers: function() {
    $('img', this.getEl()).hover(function() {
      $(this).toggleClass('hover');
    }, function() {
      $(this).toggleClass('hover');
    })
  },
  
  _bindClicks: function() {
    var _this = this;
    $('img', this.getEl()).click(function() {
      _this.activate(this.id);
    });
  },
  
  _bindActivate: function() {
    var _this = this;
    $(this.getEl()).bind('activate_pict', function(e, id) {
      _this.activate(id);
    });
  },
  
  activate: function(id) {
    this.deactivatePrev();
    var el = $('#' + id).addClass('act');
    var view_src = this.previewSrcToView(el.attr('src'));
    this.setViewPict(view_src, el.attr('title'));
    this.act_pict = id;
    this.getEl().trigger('pict_activated', [this]);
  },
  
  deactivate: function(id) {
    $('#' + id).removeClass('act');
  },
  
  deactivatePrev: function() {
    if(!this.act_pict) return;
    this.deactivate(this.act_pict);
    this.act_pict = null;
  },
  
  previewSrcToView: function(src) {
    return src.replace(/preview\//, '');
  },
  
  setViewPict: function(src, title) {
    var view_place = $(this.view_place);
    if ($.browser.opera) {
      view_place.attr('src', src);
    }
    else {
      view_place.one('load', function(){
        this.src = src;
      }).attr('src', '/i/0.gif');
    }
    view_place.attr('title', title);
    view_place.attr('alt', title);
  },
  
  getActive: function() {
    return this.act_pict;
  },
  
  extractId: function(el_id){
    var matches = el_id.match(/_([0-9]+)$/);
    return matches ? matches[1] : 0;
  },
  
  getEl: function() {
    return $('#' + this.id);
  }
}

