var Photos = new Class({

  Implements : [Options],


  /**
   * Opciones de la clase
   *  container   : string - id del contenedor
   *  loaderSteps : int - numero de cuadros que contendrá el cargador (loading)
   *  loaderSize  : object - tamaño del cargador x:width, y:height
   *  gateway     : string - url al archivo ajax que se le arán diferentes llamadas
   *  autoplay    : boolean - indica si esta actiada la reproduccion automatica
   *  duration    : int - milisegundos que demorará en pasar al siguiente item de la galeria
   *  playmode    : string - "normal" | "random" | "rand" el modo en que se mostrarán las imagenes
   *  repeat      : boolean - si esta activado junto con autoplay, cuando llega al final del ciclo de reproduccion comienza nuevamente
   **/
  options : {
    'container'  : 'PhotoGallery',
    'loaderSteps': 18,
    'loaderSize' : {x:48, y:48},
    'gateway'    : 'applications/app_photos/themes/site/html/ajax/bridge.php',
    'autoplay'   : true,
    'duration'   : 5000,
    'playmode'   : 'normal',
    'repeat'     : false
  },

  /**
   * Inicializa la clase Photos
   * @param object options
   **/
  initialize : function(options){
    this.setOptions(options);

    if(!document.id(this.options.container)) return;
    this.options.container = document.id(this.options.container);

    this.collectElements();
    
    // Loader
    this.loader_step  = 0;
    this.loader_n = 0;
    this.loader(true);

    // Se inicia cargando las galerias o categorias
    this.getGalleries.delay(500, this);
  },

  /**
   *  Collecciona todos los elementos que se usarán en la galeria
   **/
  collectElements : function(){
    this.eLoader           = this.options.container.getElement('.mp-loader');
    this.eInfo             = this.options.container.getElement('.mp-photoinfo');
    this.ePhoto            = this.options.container.getElement('.mp-photo');
    this.eGallery          = this.options.container.getElement('.mp-categories');
    this.eGalleryContainer = this.eGallery.getElement('.mp-categories-container');
    this.eToolbar          = this.options.container.getElement('.mp-toolbar');
    this.eThumbs           = this.options.container.getElement('.mp-thumbs');
    this.eThumbsWrapper  = this.options.container.getElement('.mp-thumbs-wrapper');
    this.eThumbsLeft       = this.eThumbs.getElement('.mp-thumbs-left');
    this.eThumbsRight      = this.eThumbs.getElement('.mp-thumbs-right');
    this.eThumbsItems      = this.eThumbs.getElement('.mp-thumbs-items');
    this.eButtons          = this.eToolbar.getElement('.mp-buttons');

    this.panel.gallery.y   = this.eGallery.getStyle('margin-top').toInt();

    this.setButtons();
  },

  /**
   * Configura los botones del panel
   *  Abrir y cerrar categorias
   *  Maximizar imagen
   *  Orden aleatorio
   *  Repetir reproduccion automática
   *  Imagen anterior
   *  Imagen siguiente
   *  Play / Stop
   **/
  setButtons : function(){

    // Cierra el panel de galerias
    var btnClosePanelGallery = this.eGallery.getElement('.mp-btn-categories-close a');
    if(btnClosePanelGallery){
      btnClosePanelGallery.addEvent('click', this.closePanel.pass('gallery', this));
    }

    // Abre el panel de galerias
    this.setButton('categories', 'normal', this.openPanel, 'gallery');

    // Botones que deslizan las miniaturas
    this.setButton('left', 'disable', this.left, null, 'mp-thumbs-');
    this.setButton('right', 'disable', this.right, null, 'mp-thumbs-');
    //this.eThumbsLeft.addEvent('click', this.left.pass(null, this));
    //this.eThumbsRight.addEvent('click', this.right.pass(null, this));

    // fullscreen
    this.setButton('fullscreen', 'disable', this.fullscreen, this.CurrentImage);

    // repeat
    this.setButton('repeat', (this.options.repeat) ? 'active' : 'normal', this.toggleButton, 'repeat');

    // random
    this.setButton('random', (this.options.playmode == 'random') ? 'active' : 'normal', this.toggleButton, 'random');

    // prev
    this.setButton('prev', 'disable', this.prev);

    // next
    this.setButton('next', 'disable', this.next);

    // play
    this.setButton('play', 'disable', this.playstop);

    // stop
    this.setButton('stop', 'disable', this.playstop);
    
  },

  toggleButton : function(btn){

    switch(btn){
      case 'random':
        var mode = this.options.playmode;
        this.options.playmode = (mode == 'normal') ? 'random' : 'normal';
        if(this.options.playmode == 'random')
          this.setButton('random', 'active');
        else
          this.setButton('random', 'normal');
        break;

      case 'repeat':
        this.options.repeat = !this.options.repeat;
        this.setButton('repeat', (this.options.repeat)?'active':'normal');
        this.toggleButton('next');
        this.toggleButton('prev');
        break;

      case 'next':
        var last = this.Galleries.get(this.CurrentGallery).images.length -1;
        
        if(this.options.repeat || this.CurrentImage < last)
          this.setButton('next', 'normal');
        else if(this.CurrentImage == last && !this.options.repeat)
          this.setButton('next', 'disable');
        break;

      case 'prev':
        if(this.options.repeat || this.CurrentImage > 0)
          this.setButton('prev', 'normal');
        else if(this.CurrentImage == 0 && !this.options.repeat)
          this.setButton('prev', 'disable');
        break;
    }

    return false;
  },

  /**
   *  Configura un boton de la barra de herramientas
   *  @param string btn : Nombre del boton. Parte de la clase .mp-btn-###
   *  @param string state : Nuevo estado del boton. disable|active|normal
   *  @param function onClick: Funcion que se le pasará al evento click del boton
   *  @param mixed args : Argumentos pasados a la funcion onClick. Si son varios se pasan en forma de array
   **/
  setButton : function(btn, state, onClick, args, classname){
    if(!$defined(classname)) classname = 'mp-btn-';
    var button = this.options.container.getElement('.'+classname+btn+' a');
    if(!button) return;
    if(['disable', 'active', 'normal'].contains(state) === false) return;

    var button_state = button.retrieve('state');
    button.removeClass(button_state);
    button.addClass(state);

    switch(state){
      case 'disable':
        button.mask();
        break;

      case 'active':
        if(button.retrieve('mask'))
          button.unmask();
        break;

      case 'normal':
        if(button.retrieve('mask'))
          button.unmask();
        break;
    }
    button.store('state', state);

    if($type(onClick) == 'function'){
      args = (!$defined(args)) ? null : args;
      button.addEvent('click', onClick.pass(args, this));
    }
  },

  /**********************
   *  GALLERY
   **********************/

  /**
   *  Hash que contendrá las diferentes galerias o categorias y sus imagenes
   *  @type Hash
   **/
  Galleries : $H({}),

  /**
   *  Timer utilizado para la auto reproduccion
   *  @type int
   **/
  Timer : 0,

  /**
   *  Indica si actualmente se esta reproduciendo la galeria
   *  @type bool
   **/
  Playing : false,

  /**
   *  Id de la galería actual
   *  @type int
   **/
  CurrentGallery : null,

  /**
   * Id de la imagen actual
   * @type int
   **/
  CurrentImage : null,

  /**
   *  Este objeto contiene 2 arrays, all y current.
   *  "all" : contiene los id's de la galeria actual
   *  "current" : contiene los id's que aun no se han visto en el ciclo
   *  @type object
   **/
  CurrentImages : {'all':[], 'current':[]},

  /**
   *  Obtiene las diferentes galerías mediante ajax
   *  Luego de obtener el resultado, se lo envia al metodo galleriesResponse
   **/
  getGalleries : function(){
    this.loader();

    new Request.JSON({
      url : this.options.gateway,
      onSuccess : this.galleriesResponse.bind(this)
    }).post({mod:'galeries'});
  },

  /**
   *  Procesa el resultado obtenido desde getGalleries
   *  @param object json
   *  @param string text
   **/
  galleriesResponse : function(json, text){
    this.loader(true);
    
    if(!$defined(json)) return this.msg(text, 'Gallery Response Error', {animate:false});
    if($type(json) != 'array') return;

    var ul = new Element('ul', {'class':'mp-category-wrapper'}).inject(this.eGalleryContainer);
    json.each(function(gallery){
      var li  = new Element('li').inject(ul);
      var div = new Element('div', {'class':'mp-category-content'}).inject(li);
      new Element('div', {'class':'mp-category-thumb', 'html':gallery.preview}).inject(div);
      new Element('div', {'class':'mp-category-title', 'html':gallery.title}).inject(div);
      div.addEvent('click', this.getImages.pass(gallery.id, this));
      gallery.images = [];
      this.Galleries.set(gallery.id, gallery);
    }, this);

    this.openPanel('gallery');
  },

  /**
   * Obtiene las imagenes de la categoria category_id
   * @param int category_id
   **/
  getImages : function(category_id){

    if(category_id == this.CurrentGallery){
      this.closePanel('gallery');
      return;
    }

    this.CurrentGallery = category_id;

    if(this.Galleries.get(category_id).images.length){
      this.setGallery(category_id);
      return;
    }

    new Request.JSON({
      url : this.options.gateway,
      onSuccess : this.addImages.bind(this)
    }).post({'mod':'photos', 'category_id':category_id});
    
  },

  /**
   * Procesa el resultado obtenido de getImages
   * Se agregan todas las imagenes a la categoria
   * @param object json
   * @param string text
   **/
  addImages : function(json, text){
    if(!$defined(json)) return this.msg(text, 'Gallery Response Error', {animate:false});
    if($type(json) != 'array') return;
    var category_id = 0;
    json.each(function(image){
      category_id = (category_id === 0) ? image.category_id : category_id;
      var images = this.Galleries.get(category_id).images;
      images.push(image);
      //if(!this.Galleries.get('images').has(image.category_id)) this.Galleries.get(image.category_id).set();
    }, this);

    this.setGallery(category_id);
  },

  /**
   * Se configuran los botones left y right
   **/
  setThumbs : function(){
    var cw = this.eThumbsWrapper.getComputedSize().totalWidth;  // Ancho de wrapper
    var iw = this.eThumbsItems.getComputedSize().totalWidth;      // Ancho de contenedor

    // Si el contenedor es mas pequeño que el wrapper se sale
    if(cw < iw){
      //this.disable([this.eThumbsLeft, this.eThumbsRight], this.eThumbs);
      this.setButton('left', 'disable', null, null, 'mp-thumbs-');
      this.setButton('right', 'disable', null, null, 'mp-thumbs-');
    }
    else{
      var ip        = this.eThumbsWrapper.getPosition(this.eThumbsItems);
      var reference = this.eThumbsWrapper.getElement('.mp-thumb');  // Se toma una miniatura como referencia para conocer sus medidas
      var rwidth    = reference.getComputedSize().totalWidth + reference.getStyle('margin-right').toInt(); // Tamaño total de la miniatura, sumando el margen derecho
      var rtotal    = (iw / rwidth).toInt(); // cantidad de miniaturas que se verán completas en el area visual

      var movew = rwidth * rtotal; // Dimensión que se moverá el wrapper
      if(ip.x < 0){
        //this.enable(this.eThumbsLeft);
        this.setButton('left', 'normal', null, null, 'mp-thumbs-');

        if(cw - Math.abs(ip.x) < movew || ((cw - Math.abs(ip.x)) - movew) < rwidth)
          this.setButton('right', 'disable', null, null, 'mp-thumbs-');//this.disable(this.eThumbsRight);
        else
          this.setButton('right', 'normal', null, null, 'mp-thumbs-');//this.enable(this.eThumbsRight);
      }
      else{
        //this.disable(this.eThumbsLeft);
        this.setButton('left', 'disable', null, null, 'mp-thumbs-');
        if(ip.x + movew < iw)
          this.setButton('right', 'normal', null, null, 'mp-thumbs-');
          //this.enable(this.eThumbsRight);
      }
    }
  },

  setGallery : function(category_id){
    var images = this.Galleries.get(category_id).images;
    if($type(images) != 'array') return;
    if(!images.length) return;
    
    this.clearPanel('photo');
    var gallery_images = [];
    images.each(function(img, i){
      //this.addThumb(i, img.thumb);
      gallery_images.push(img.thumb);
      this.CurrentImages.all.push(i);
    }, this);
    this.CurrentImages.current = this.CurrentImages.all;

    var self = this;
    new Asset.images(gallery_images, {
      onProgress : function(total, id){
        var thumb = new Element('div', {'class':'mp-thumb'}).inject(self.eThumbsWrapper);
        //thumb.fade('hide');
        this.inject(thumb);
        var w = self.eThumbsWrapper.getComputedSize().totalWidth + thumb.getComputedSize().totalWidth + thumb.getStyle('margin-right').toInt() + 5;
        self.eThumbsWrapper.setStyle('width', w);
        thumb.addEvent('click', self.display.pass(id, self));
        //thumb.fade('in');
      },
      onComplete : function(){
        self.setThumbs();
        self.CurrentImage = null;
        //self.display(0);
        self.play();
      }
    });

    this.closePanel('gallery');
  },

  /**********************
   *  LOADER
   **********************/

  /**
   * loader
   * @param bool hide - Si es true oculta el cargador
   */
  loader : function(hide){
    if($defined(hide)){
      $clear(this.loader_n);
      this.loader_n = 0;
      this.eLoader.hide();
      return;
    }

    this.loader_n = this.loader_loop.delay(100, this);
  },

  /**
   * loader_loop
   * 
   */
  loader_loop : function(){
    this.eLoader.show();
    this.eLoader.setStyle('background-position', '-' + (this.loader_step * this.options.loaderSize.x) + 'px 0');
    this.loader_step = (this.loader_step+1 == this.options.loaderSteps) ? 0 : this.loader_step+1;
    this.loader();
  },

  left : function(){
    var cw = this.eThumbsWrapper.getComputedSize().totalWidth;  // Ancho de wrapper
    var iw = this.eThumbsItems.getComputedSize().totalWidth;    // Ancho de contenedor

    // Si el contenedor es mas pequeño que el wrapper se sale
    if(iw >= cw) return false;

    var ip        = this.eThumbsWrapper.getPosition(this.eThumbsItems);
    if(ip.x >= 0) return false;
    
    var reference = this.eThumbsWrapper.getElement('.mp-thumb');  // Se toma una miniatura como referencia para conocer sus medidas
    var rwidth    = reference.getComputedSize().totalWidth + reference.getStyle('margin-right').toInt(); // Tamaño total de la miniatura, sumando el margen derecho
    var rtotal    = (iw / rwidth).toInt(); // cantidad de miniaturas que se verán completas en el area visual

    var movew = rwidth * rtotal; // Dimensión que se moverá el wrapper
    var movex = ip.x + movew;
    if(movex > 0) movex = 0;
    
    new Fx.Tween(this.eThumbsWrapper, {onComplete : this.setThumbs.bind(this)}).start('left', movex);

    return false;
  },

  right : function(){
    var cw = this.eThumbsWrapper.getComputedSize().totalWidth;  // Ancho de wrapper
    var iw = this.eThumbsItems.getComputedSize().totalWidth;      // Ancho de contenedor
    
    // Si el contenedor es mas pequeño que el wrapper se sale
    if(iw >= cw) return false;

    var ip        = this.eThumbsWrapper.getPosition(this.eThumbsItems);
    var reference = this.eThumbsWrapper.getElement('.mp-thumb');  // Se toma una miniatura como referencia para conocer sus medidas
    var rwidth    = reference.getComputedSize().totalWidth + reference.getStyle('margin-right').toInt(); // Tamaño total de la miniatura, sumando el margen derecho
    var rtotal    = (iw / rwidth).toInt(); // cantidad de miniaturas que se verán completas en el area visual

    var movew = rwidth * rtotal; // Dimensión que se moverá el wrapper
    var movex = ip.x - movew;
    if(ip.x < 0){
      if(cw - Math.abs(ip.x) < movew || ((cw - Math.abs(ip.x)) - movew) < rwidth){
        return false;
      }
    }

    new Fx.Tween(this.eThumbsWrapper, {onComplete : this.setThumbs.bind(this)}).start('left', movex);

    return false;
  },

  display : function(image_id){
    var image = this.Galleries.get(this.CurrentGallery).images[image_id];
    if(!image) return;
    if(!$defined(image.preview)) return;

    this.loader();
    $clear(this.Timer);

    var thumbs = this.eThumbsWrapper.getElements('.mp-thumb');
    if(this.CurrentImage != null) document.id(thumbs[this.CurrentImage]).removeClass('mp-thumb-current');
    document.id(thumbs[image_id]).addClass('mp-thumb-current');

    var currentimg = this.ePhoto.getElements('img');
    var self = this;
    new Asset.image(image.preview, {onload : function(){ self.show(this, currentimg, image_id) } });
    
  },

  show : function(image_show, image_hide, image_id){
    if(image_hide) $$(image_hide).each(this.hide.bind(this));

    if(image_show){
      var image = this.Galleries.get(this.CurrentGallery).images[image_id];
      var size  = this.ePhoto.getSize();
      image_show.inject(this.ePhoto);
      if(image.width > size.x || image.height > size.y ){
        var aspectRatio = (image.width <= image.height) ? image.height / image.width : image.width / image.height;
        if(image.width < image.height){
          image_show.width  = size.x;
          image_show.height = (image.width <= image.height) ? size.x * aspectRatio : size.x/ aspectRatio;
        }
        
        if(image.height > image.width){
          image_show.width  = (image.width <= image.height) ? size.y / aspectRatio : size.y * aspectRatio;
          image_show.height = size.y;
        }
      }
      
      image_show.fade('hide');
      image_show.position({relativeTo : this.ePhoto});
      image_show.fade('in');
      this.CurrentImage = image_id;
      this.CurrentImages.current.erase(image_id);
      this.setButton('fullscreen', 'normal');
      this.toggleButton('next');
      this.toggleButton('prev');
      this.loader(true);
      if(this.options.autoplay && this.Playing)
        this.play();
    }
  },

  hide : function(image){
    if(image){
      new Fx.Tween(image, {onComplete : function(){ image.destroy()} }).start('opacity', 0);
    }
  },

  /**
   * Devuelve el identificador de la siguiente imagen
   * @param string "prev"|"next"
   * @return int
   **/
  getImageId : function(where){
    where = (!$defined(where)) ? "next" : where;
    where = (where != "next" && where != "prev") ? "next" : where;
    var id = this.CurrentImage;

    if(this.CurrentImage === null && this.options.playmode == 'normal'){
      return 0;
    }

    // Numero total de imagenes
    var total = this.Galleries.get(this.CurrentGallery).images.length;
    
    switch(where){
      case "next":
        if(this.CurrentImage+1 === total && this.options.playmode == 'normal'){
          return 0;
        }
        if(this.CurrentImage < total-1 && this.options.playmode == 'normal'){
          id = this.CurrentImage +1;
        }
        break;

      case "prev":
        if(this.CurrentImage === 0 && this.options.playmode == 'normal'){
          return total-1;
        }
        if(this.CurrentImage > 0 && this.options.playmode == 'normal'){
          return this.CurrentImage -1;
        }
        break;
    }

    if(this.options.playmode == 'random'){
      if(!this.CurrentImages.all.length) return false;
      if(!this.CurrentImages.current.length)
        this.CurrentImages.current = this.CurrentImages.all;

      id = this.CurrentImages.current.getRandom();
    }

    return id;
  },


  /**
   * next
   * muestra el siguiente elemento de la galeria
   */
  next : function(){
    var last = this.Galleries.get(this.CurrentGallery).images.length -1;
    
    if(this.options.playmode == 'normal'){
      if(this.Playing && this.options.autoplay && !this.options.repeat && this.CurrentImage == last){
        this.setButton('next', 'disable');
        return this.stop();
      }
    }else{
      if(this.Playing && this.options.autoplay && !this.options.repeat && !this.CurrentImages.current.length){
        this.setButton('next', 'disable');
        return this.stop();
      }
    }

    var id = this.getImageId('next');

    if(id == last && !this.options.repeat){
      this.setButton('next', 'disable');
    }else{
      this.setButton('next', 'normal');
    }

    this.display(id);
    return false;
  },

  /**
   * prev
   * Mestra el elemento anterior
   */
  prev : function(){
    if(this.Playing && this.options.autoplay && !this.options.repeat && this.CurrentImage == 0){
      this.setButton('prev', 'disable');
      return this.stop();
    }

    var id = this.getImageId('prev');
    this.display(id);
    this.stop();
    return false;
  },

  /**
   * play
   * Reproduce los elementos de la galeria de manera automática
   */
  play : function(){
    if(this.CurrentImage === null){
      this.display(0);
    }

    if(this.options.autoplay){
      this.Timer = this.next.delay(this.options.duration, this);
      this.Playing = true;

      this.setButton('stop', 'normal');
      this.setButton('play', 'disable');
    }else if(!this.options.autoplay){
      this.next();
      this.stop();
    }

    return false;
  },

  /**
   * stop
   * Detiene la reproducción automática
   */
  stop : function(){
    if(this.Playing === false) return false;
    
    $clear(this.Timer);
    this.Playing = false;
    this.setButton('stop', 'disable');
    this.setButton('play', 'normal');

    return false;
  },

  /**
   * playstop
   * Reproduce o detiene la auto reproduccion
   */
  playstop : function(){
    if(this.Playing)
      return this.stop();
    else
      return this.play();

  },

  /**
   * fullscreen
   * Muestra en pantalla completa el elemento actual
   * @param int id - Indice del array de elementos
   */
  fullscreen : function(){
    var mask = null;
    var el   = this.ePhoto.clone();
    var img  = el.getElement('img');
    img.setStyle('position', 'static');
    this.stop();

    el.removeClass('mp-photo').addClass('mp-photo-fullscreen');
    el.setStyles({
      'position' : 'absolute',
      'z-index'  : 1000,
      'width'    : img.get('width').toInt(),
      'height'   : img.get('height').toInt(),
      'cursor'   : 'pointer'
    });
    el.addEvent('click', function(){ mask.hide(); return false; });
    mask = new Mask(document.body, {
      'hideOnClick' : true,
      'destroyOnHide' : true,
      'class' : 'mp-mask',
      onShow : function(){
        el.inject(document.body);
        el.position();
        el.fade('hide').fade('in');
      },
      onHide : function(){
        this.hide(el);
        if(this.options.autoplay)
          this.play();
      }.bind(this)
    });

    mask.show();
    return false;
  },

  /**
   * showInfo
   * Muestra la información del elemento actual
   */
  showInfo : function(info){

  },

  /**********************
   *  UI
   **********************/

  panel : {
    gallery : {
      open : false,
      y    : 0
    },
    info : {
      open : false,
      y    : 0
    }
  },

  openPanel : function(panel){
    switch(panel){
      case 'gallery':
        if(this.panel.gallery.open) return;
        this.eGalleryContainer.setStyle('overflow', 'hidden');
        new Fx.Tween(this.eGallery, {
          onComplete : function(){
            this.panel.gallery.open = true;
            this.eGalleryContainer.setStyle('overflow', 'auto');
          }.bind(this)
        }).start('margin-top', 0);
        break;
    }

    return false;
  },

  closePanel : function(panel){
    switch(panel){
      case 'gallery':
        if(!this.panel.gallery.open) return;
        this.eGalleryContainer.setStyle('overflow', 'hidden');
        new Fx.Tween(this.eGallery, {
          onComplete : function(){
            this.panel.gallery.open = false;
            this.eGalleryContainer.setStyle('overflow', 'auto');
          }.bind(this)
        }).start('margin-top', this.panel.gallery.y);
        break;
    }

    return false;
  },

  clearPanel : function(panel){
    switch(panel){
      case 'photo':
        this.ePhoto.empty();
        this.eThumbsWrapper.empty();
        this.eThumbsWrapper.setStyle('width', 1);
        this.eThumbsWrapper.move({relativeTo : this.eThumbsItems, position: 'upperLeft'});
        this.CurrentImages.all = [];
        this.CurrentImages.current = [];
        break;
    }
  },

  /**********************
   *  UTILITIES
   **********************/

  /**
   * msg
   * Configura una ventana de mensaje mediante MooBox (requerido)
   * @param mixed message - Mensaje de la ventana, puede ser string o element
   * @param string title
   * @param object options
   */
  msg : function(message, title, options){
    if(!$defined(MooBox)) return;
    
    options = $H({'width':500, 'height':'auto', 'animate':true}).extend(options||{});
    options = options.getClean();
    var mb = new MooBox({animate:options.animate});
    var content = new Element('div', {
      'styles' : {
        'background' : '#fff',
        'display'    : 'block',
        'padding'    : '10px 0',
        'width'      : options.width,
        'height'     : options.height
      }
    });
    if($type(message) == 'string')
      content.set('html', message);
    else if($type(message) == 'element')
      content.adopt(message);

    mb.addContent(content, (title || null));

    if($type(options.actions) == 'array'){
      options.actions.each(function(action){
        mb.addButton('custom', action.text, action.event);
      });
    }
  },

  disable : function(item, el){
    if($type(item) == 'array'){
      item.each(this.disable.bind(this));
      return;
    }
    var options = {};
    if(document.id(el)) options.inject = document.id(el);

    item = document.id(item);
    if(!item) return;
    item.fade(0.5);
    item.mask(options);
  },

  enable : function(item){
    if($type(item) == 'array'){
      item.each(this.enable.bind(this));
      return;
    }

    item = document.id(item);
    if(!item) return;
    item.fade('show');
    if( item.retrieve('mask') ) item.unmask();
  }
});

window.addEvent('domready', function(){
  new Photos();
});
