if(typeof(SAPO.Widget)=="undefined" || !SAPO.Widget){
  SAPO.namespace("Widget");
}

SAPO.Widget.NavAlbumThumbnails = function(options){
  this.init(options);
};

SAPO.Widget.NavAlbumThumbnails.prototype = {
  _haltNavigation: false,
  _pictures: [],
  _currentPage: 0,
  _prevLock: false,
  _nextLock: false,
  _prevLoaded: false,
  _nextLoaded: false,
  
  init: function(options){
    var options = Object.extend({
      jsonUrl:          '/ajax/images.php', 
      startImages:      [], /* MUST be filled with 2 images */
      albumId:          '',
      userId:           '',
      currentImage:     '',
      prevBtn:          false,
      nextBtn:          false,
      prevImageLink:    false,
      prevImage:        false,
      prevImageCover:   false,
      nextImageLink:    false,
      nextImage:        false,
      nextImageCover:   false,
      beginImage:       'imgs/begin88x66.gif',
      endImage:         'imgs/end88x66.gif',
      beginTitle:       'Inicio',
      endTitle:         'Fim',
      imgJsonElem:      'r',
      hrefJsonElem:     'l',
      titleJsonElem:    't',
      altJsonElem:      't',
      matureJsonElem:   'm',
      uidJsonElem:      'u',
      imgLoadRetries:   50
    },arguments[0] || {});
    
    this.options = options;
    
    this._pictures.push(this.options.startImages['p']);
    this._pictures.push(this.options.startImages['n']);
    
    if(this.options.prevBtn){
      this._prevBtn = s$(this.options.prevBtn);
    }
    if(this.options.nextBtn){
      this._nextBtn = s$(this.options.nextBtn);
    }
    this._prevImageLink = s$(this.options.prevImageLink);
    this._prevImage = s$(this.options.prevImage);
    if(this.options.prevImageCover) {
        this._prevImageCover = s$(this.options.prevImageCover);
    }
    this._nextImageLink = s$(this.options.nextImageLink);
    this._nextImage = s$(this.options.nextImage);
    if(this.options.nextImageCover) {
        this._nextImageCover = s$(this.options.nextImageCover);
    }
    this._setBtnEvents();
    this._setImages(this._currentPage);

  },
  
  _setBtnEvents: function(){
    if(this._prevBtn){
      Event.observe(this._prevBtn,'click',this._previous.bind(this));
    }
    if(this._nextBtn){
      Event.observe(this._nextBtn,'click',this._next.bind(this));
    }
  },
  
  _previous: function(){
    if(this._haltNavigation){
      return false;
    }
    this._haltNavigation = true;
    if(this._currentPage==0 && this._pictures[0]!=false){
      this._ajax('p');
    } else {
      if(this._currentPage){
        --this._currentPage;
        this._setImages();
      } 
    }
  },
  
  _next: function(){
    if(this._haltNavigation){
      return false;
    }
    this._haltNavigation = true;
    if(this._currentPage==(this._pictures.length-2) && this._pictures[this._pictures.length-1]!=false){
      this._ajax('n');
    } else if(this._currentPage!=(this._pictures.length-2) || (this._currentPage==(this._pictures.length-2) && this._pictures[this._pictures.length-1])){
      ++this._currentPage;
      this._setImages();
    }
  },
  
  _ajax: function(option){
    var queryString = {
      x: 'p',
      r: this._pictures[this._currentPage + ((option=='n') ? 1 : 0)][this.options.uidJsonElem],
      cr: this.options.currentImage,
      u: this.options.userId,
      a: this.options.albumId
    };
    
    var query="";
    
    for(var i in queryString){
      query+="&" + i + "=" + queryString[i];
    }
    
    var url = this.options.jsonUrl + '?' + query;
    
    this._ajaxRequest = new Ajax.Request(url,{
      method: 'get',
      onSuccess: this._addImages.bind(this,option),
      onFailure: this._unHaltNavigation.bind(this)
    });


  },
  
  _unHaltNavigation: function(){
    this._haltNavigation=false;
  },

  _addImages: function(){
    if(!arguments[0] || (arguments[0]!='p' && arguments[0]!='n')){
      return false;
    }
    if(arguments[1]){
      if(typeof(arguments[1])!='undefined'){
        var json = arguments[1].responseJSON || arguments[1].responseText.evalJSON(true);
        if(arguments[0]=='p'){
          this._pictures.splice(0, 0, json.p);
          this._setImages();
        } else if(arguments[0]=='n'){
          this._pictures.push(json.n);
          this._setImages(++this._currentPage);
        } else {
          this._haltNavigation = false;
        }
      }
    }
  },
  
  _setImages: function(){
    var page = this._currentPage;
    var url = "/";
    
    if(this._pictures[page]){ 
        var pic = this._pictures[page][this.options.imgJsonElem];
    } else {
        var pic = false;
    }
    if(this._pictures[page+1]){
        var pic2 = this._pictures[page+1][this.options.imgJsonElem];
    } else {
        var pic2 = false;
    }
    
    this._oldPrevImage = this._prevImage;
    this._oldNextImage = this._nextImage;
    
    var prevImg = this._prevImage.cloneNode(0);
    var nextImg = this._nextImage.cloneNode(0);
    
    prevImg.removeAttribute('src');
    nextImg.removeAttribute('src');

    this._prevImage = prevImg;
    this._nextImage = nextImg;
    

    if(pic){
      this._unlockNav('p'); 
      this._prevImageLink.href=url+this._pictures[page][this.options.hrefJsonElem];
    } else {
      this._lockNav('p');
    }
    
    if(pic2){
      this._unlockNav('n');
      this._nextImageLink.href=url+this._pictures[page+1][this.options.hrefJsonElem];
    } else {
      this._lockNav('n');
    }
    
    var pic_url  = ( pic) ? pic : this.options.beginImage;
    var pic2_url = (pic2) ? pic2 : this.options.endImage;
    
    this._prevImage.title = (pic) ?  this._pictures[page][this.options.titleJsonElem] : this.options.beginTitle;
    this._prevImage.alt = (pic) ? this._pictures[page][this.options.altJsonElem] : this.options.beginTitle;
    this._nextImage.title = (pic2) ? this._pictures[page+1][this.options.titleJsonElem] : this.options.endTitle;
    this._nextImage.alt = (pic2) ? this._pictures[page+1][this.options.altJsonElem] : this.options.endTitle;

    this._prevImage.style.display = 'none';
    this._nextImage.style.display = 'none';
    
    Element.observe(this._prevImage,'load', function(){
      Event.stopObserving(this._prevImage,'load');
      this._prevLoaded = true;
    }.bindAsEventListener(this));
    Element.observe(this._nextImage,'load', function(){
      Event.stopObserving(this._nextImage,'load');
      this._nextLoaded = true;
    }.bindAsEventListener(this));
    
    this._prevImageLink.appendChild(this._prevImage);
    this._nextImageLink.appendChild(this._nextImage);
    
    this._prevImage.writeAttribute('src', pic_url);
    this._nextImage.writeAttribute('src', pic2_url);
    this.retryCounter = 0;
    this._intervalHandler = setInterval(this._checkLoadedImages.bind(this),200);

  },
  
  _checkLoadedImages: function(){
    if((this._prevLoaded && this._nextLoaded) || this.options.imgLoadRetries<this.retryCounter){
      clearInterval(this._intervalHandler);

      if(this._prevImageCover && this._prevImageCover != null) { 
        var prevImgCover = this._prevImageCover.cloneNode(1);
      }
      if(this._nextImageCover && this._nextImageCover != null) {
        var nextImgCover = this._nextImageCover.cloneNode(1);
      }
      
      var prevImgLink = this._prevImageLink.cloneNode(1);
      prevImgLink.innerHTML = '';

      var nextImgLink = this._nextImageLink.cloneNode(1);
      nextImgLink.innerHTML = '';
      
      if(this._prevImageCover && this._prevImageCover != null) { 
      this._prevImageCover = prevImgCover;
      }
      if(this._nextImageCover && this._nextImageCover != null) {
          this._nextImageCover = nextImgCover;
      }
      
      this._prevImage = Element.remove(this._prevImage); 
      this._nextImage = Element.remove(this._nextImage); 

      prevImgLink.appendChild(this._prevImage);
      nextImgLink.appendChild(this._nextImage);
      this._prevImage.style.display = 'block';
      this._nextImage.style.display = 'block';
      
      var prevLinkHTML = prevImgLink.innerHTML;
      var nextLinkHTML = nextImgLink.innerHTML;

      this._prevImageLink.innerHTML = prevLinkHTML;
      this._nextImageLink.innerHTML = nextLinkHTML;

      this._haltNavigation = false;
      var page = this._currentPage;
      if (this._pictures[page][this.options.matureJsonElem]) {
          if(this._prevImageCover && this._prevImageCover != null) { 
              this._prevImageCover.style.display = 'block';
          }
      } else {
          if(this._prevImageCover && this._prevImageCover != null) { 
              this._prevImageCover.style.display = 'none';
          }
      }
      if (this._pictures[page+1][this.options.matureJsonElem]) {
          if(this._nextImageCover && this._nextImageCover != null) {
              this._nextImageCover.style.display = 'block';
          }
      } else {
          if(this._nextImageCover && this._nextImageCover != null) {
              this._nextImageCover.style.display = 'none';
          }
      }
      
      if(this._prevImageCover && this._prevImageCover != null) { 
          this._prevImageLink.appendChild(this._prevImageCover);
      }
      if(this._nextImageCover && this._nextImageCover != null) {
        this._nextImageLink.appendChild(this._nextImageCover);
      }
    } else {
        this.retryCounter++;
    }
  },
  
  _lockNav: function(option){
    if(option=='p'){
      this._prevLock = true;
      this._prevBtn.style.visibility = 'hidden';
      this._prevImageLink.removeAttribute('href');
   } else if(option=='n'){
      this._nextLock = true;
      this._nextBtn.style.visibility = 'hidden';
      this._nextImageLink.removeAttribute('href');
    }

  },
  
  _unlockNav: function(option){
    if(option=='p'){
      this._prevLock = false;
      this._prevBtn.style.visibility = 'visible';
      Element.writeAttribute(this._prevImageLink,'href','');
    } else if(option=='n'){
      this._nextLock = false;
      this._nextBtn.style.visibility = 'visible';
      Element.writeAttribute(this._nextImageLink,'href','');
    }
  },
  
  debug: function(){
  
  }

};

