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

SAPO.Widget.NavThumbnails = function()
{
  this.init(arguments[0]);
};

SAPO.Widget.NavThumbnails.prototype = {
  
  init: function()
  {
    var options = Object.extend({
        getURI: false, 
        initObject: false,
        templatePlace: false,
        contentTarget: false,
        paginationTopTarget: false, 
        paginationBottomTarget: false, 
        paginationPrevTarget: false,
        paginationNextTarget: false,
        paginationInfoTopTarget: false,
        paginationInfoBottomTarget: false,
        optionalQueryString: '',
        loadingCallBack: false,
        callBack: false,
        urlPageVar:'page',
        delimiter: '',
        debug: false
      }, arguments[0] || {}); 

    this.options = options; 


    if(!this.options.getURI) {
      throw 'URI request missed';
      return;
    }

    // utility variables  
    this.data = {};
    this.data.totalItems = false;
    this.data.totalPerPage = false;
    this.data.totalPagesCached = false;
    this.data.currentPage = false; 
    this.data.firstPageCached = false;
    this.data.lastPageCached = false; 

    this.dataObject = false;
    
    this.controlIsLoading = false;

    this.templating = new SAPO.Utility.Templating(); // use this.templating.gen('template_string', dataObject); 

    this.setElementVars();

    this.getData();

  },

  setElementVars: function()
  {
    this.templatePlaceElm = s$(this.options.templatePlace);
    this.contentTargetElm = s$(this.options.contentTarget);
    this.paginationTopTargetElm = s$(this.options.paginationTopTarget);
    this.paginationBottomTargetElm = s$(this.options.paginationBottomTarget);
    if(this.options.paginationPrevTarget){
        this.paginationPrevTargetElm = s$(this.options.paginationPrevTarget);
    }
    if(this.options.paginationNextTarget){
        this.paginationNextTargetElm = s$(this.options.paginationNextTarget);
    }
    if(this.options.paginationInfoTopTarget) {
        this.paginationInfoTopTargetElm = s$(this.options.paginationInfoTopTarget);
    }
    if(this.options.paginationInfoBottomTarget) {
        this.paginationInfoBottomTargetElm = s$(this.options.paginationInfoBottomTarget);
    }
  },

  getData: function(page)
  {
    if(!page || typeof(page) == 'undefined' || page == null) {
      // 
      // Using this temp object to use methods of SAPO.Utility.Pagination 
      //
      var oPag = new SAPO.Utility.Pagination({urlVar: this.options.urlPageVar, totalItems:10, totalPerPage:10});
      page = oPag.getCurrentPage();

      if(page === false) {
        page = 1;
      }
    }
    if(this.options.initObject) {
      if(page >= this.options.initObject.startPageCache && page <= this.options.initObject.endPageCache) {
        this.options.initObject.currentPage = page;
        this.setDataVariables(this.options.initObject); 
        this.options.initObject = false; 
        if(this.hasPageCached(page)) {
        // 
        // write page and go away 
        //
        this.pagination = new SAPO.Utility.Pagination({urlVar: this.options.urlPageVar, totalItems: this.data.totalItems, perPage: this.data.totalPerPage, mode:'slide', delimiter: this.options.delimiter}); 
        this.pagination.setCallBack(this.goToPage.bind(this)); 
        this.goToPage(false, this.data.currentPage);
        return;
        }
      }
    }

    if(this.controlIsLoading) {
      return;
    }

    var options = {
      method: 'get',
      parameters: this.options.urlPageVar+'='+page+'&'+this.options.optionalQueryString,
      onSuccess: this.getDataOnSuccess.bind(this),
      onFailure: this.getDataOnFailure.bind(this)
    };

    this.controlIsLoading = true;
    if(this.options.loadingCallBack) {
      this.options.loadingCallBack();
    }

    new Ajax.Request(this.options.getURI, options);
  }, 

  getDataOnSuccess: function(obj)
  {
    var req = obj.responseText.evalJSON(); 

    if(req.data && typeof(req.data) != 'undefined' && req.data != null) {
      /*
      this.dataObject = req.data;

      this.data.totalItems = req.total;
      this.data.totalPerPage = req.totalPerPage;
      this.data.totalPagesCached = req.totalPagesCached;
      this.data.currentPage = req.currentPage;
      this.data.firstPageCached = req.startPageCache;
      this.data.lastPageCached = req.endPageCache;
      */
      this.setDataVariables(req);
    } else {
      this.dataObject = false;
    }
    this.controlIsLoading = false;

    this.pagination = new SAPO.Utility.Pagination({urlVar: this.options.urlPageVar, totalItems: this.data.totalItems, perPage: this.data.totalPerPage, mode:'slide', delimiter: this.options.delimiter}); 

    this.pagination.setCallBack(this.goToPage.bind(this)); 

    //this.proccessData(0);
    this.goToPage(false, this.data.currentPage);
  },

  getDataOnFailure: function(e)
  {
    this.controlIsLoading = false;
    //alert('Error...');
  },

  setDataVariables: function(req)
  {
    this.dataObject = req.data;

    this.data.totalItems = req.total;
    this.data.totalPerPage = req.totalPerPage;
    this.data.totalPagesCached = req.totalPagesCached;
    this.data.currentPage = req.currentPage;
    this.data.firstPageCached = req.startPageCache;
    this.data.lastPageCached = req.endPageCache;
  },

  hasPageCached: function(page)
  {
    if(page < this.data.firstPageCached || page > this.data.lastPageCached) {
      return false;
    } else {
      return true;
    }
  },

  goToPage: function(e, page)
  {
    if(this.options.loadingCallBack) {
      this.options.loadingCallBack();
    }
    // check if exists cache or not 
    //if(page < this.data.firstPageCached || page > this.data.lastPageCached) {
    if(!this.hasPageCached(page)) {
      this.getData(page);
      return;
    }
    //} 
    this.proccessData(page); 

  if (this.paginationTopTargetElm) {
    this.paginationTopTargetElm.innerHTML = '';
    this.paginationTopTargetElm.appendChild(this.pagination.getLinks(page));
  }
    
    if (this.paginationBottomTargetElm) {
      this.paginationBottomTargetElm.innerHTML = '';
      this.paginationBottomTargetElm.appendChild(this.pagination.getLinks(page));
    }

    if(this.options.paginationInfoTopTarget) {
        this.paginationInfoTopTargetElm.innerHTML = 'P&aacute;gina '+page+' de '+this.pagination.getTotalPages(); 
    }
    if(this.options.paginationInfoBottomTarget) {
        this.paginationInfoBottomTargetElm.innerHTML = 'P&aacute;gina '+page+' de '+this.pagination.getTotalPages();  
    }

    if(this.options.paginationPrevTarget){
        if(this.pagination.isFirstPage()) {
          this.paginationPrevTargetElm.style.visibility= 'hidden';
        } else {
          this.paginationPrevTargetElm.setAttribute('href', '#'+this.pagination.replaceUrlAnchor((page - 1)));

          this.paginationPrevTargetElm.style.visibility = 'visible';
          this.paginationPrevTargetElm.onclick = function(p){ location.href='#'+this.pagination.replaceUrlAnchor(p); this.goToPage(false, p); return false; }.bind(this, (page - 1));
        }
    }
    if(this.options.paginationNextTarget){ 
        if(this.pagination.isLastPage()) {
          this.paginationNextTargetElm.style.visibility = 'hidden';
        } else {
          this.paginationNextTargetElm.setAttribute('href', '#'+this.pagination.replaceUrlAnchor((Number(page) + 1)));

          this.paginationNextTargetElm.style.visibility = 'visible';
          this.paginationNextTargetElm.onclick = function(p){ location.href='#'+this.pagination.replaceUrlAnchor(p); this.goToPage(false, p); return false; }.bind(this, (Number(page) +1));
        }
    }

    if(this.options.callBack) {
      this.options.callBack(); 
    }

  },

  proccessData: function(page)
  {
    if(this.dataObject) {

      if(page === 0) {
        page = 1;
      }

      var source = false;

      this.contentTargetElm.innerHTML = ''; 

      // get Index
      var firstPage = this.data.firstPageCached;
      var lastPage = this.data.lastPageCached; 

      var pageIndex = (page - firstPage);

      //var curPageData = this.dataObject[(page - 1)];
      var curPageData = this.dataObject[pageIndex];

      for(var i=0; i < curPageData.length; i++) {
        //Make sure that title fields are not empty
        //IE fails to load images if the titles are left empty (Miguel Manso 2009.05.07)
        if (curPageData[i]['t'] == '') {
          curPageData[i]['t'] = '&nbsp;';
        }
        
        if (curPageData[i]['f'] == '') {
          curPageData[i]['f'] = '&nbsp;';
        }
        
        source = this.templating.gen(this.templatePlaceElm.innerHTML, curPageData[i]);
        
        //Clean any remaining {$x$} markers, replace them by &nbsp; (necessary for IE's)
        source = source.replace(/(\{\$.\$\})/gi, "&nbsp;");
        
        this.contentTargetElm.innerHTML += source;
      }
    }
  },


  debug: function()
  {
  }
};

