/**
 * @param oArgs object
 *      id
 *      visibleItems
 *      totalRecords
 *      initCount
 *      remoteUrl
 *      remoteMinItems
 *      paginatorConfig
 */
iYIM.CarouselBlock = function(oArgs) {
  this._insertItem = function(item) {
    if (item) {
      this.carousel.addItem(item, 0);
      this.totalRecords++;
      this.currentCount++;
      this.paginator.setTotalRecords(this.paginator.getTotalRecords()+1);
      this.paginator.setStartIndex(0);
    }
  }
  
  /**
   * @param object data  
   */
  this.insertItem = function(data) {
    var item = data || null;
    if (!item) {
      var url = this.remoteUrl+'/0/1';
      var myCB = this;
      iYU.Connect.asyncRequest("GET", url, {
          success: function (o) {
              var newitems = Drupal.parseJson(o.responseText);
              if (newitems[0]) {
                var old_item = myCB.carousel.getItem(0);
                if (newitems[0] != old_item.item) {
                  myCB._insertItem(newitems[0]);
                }
              }
          }
      });      
    }    
  }
  
  this.id = oArgs.id;  
  this.pageSize = oArgs.visibleItems || 3; 
  this.totalRecords = oArgs.totalRecords;
  this.currentCount = oArgs.initCount || 0;
  this.remoteUrl = oArgs.remoteUrl || null;
  this.remoteMinItems = oArgs.remoteMinItems || this.pageSize; 
  this.speed = oArgs.speed || 0.5;
  this.paginatorConfig = oArgs.paginatorConfig || {};  
  this.vertical = oArgs.vertical || false;
  this.circular = oArgs.circular || false;
  this.minWidth = oArgs.minWidth || 99;
  this.className = oArgs.className;
  if (oArgs.autoPlay) {
    this.autoPlay = oArgs.autoPlay;
  }
  this.carousel = new iYW.Carousel("imedia-carousel-"+this.id+"-container", {
    animation: { speed: this.speed },
    numVisible: this.pageSize,
    isVertical: this.vertical,
    autoPlay: this.autoPlay,
    isCircular: this.circular
  });
  this.carousel.CONFIG.MIN_WIDTH = this.minWidth;
  
  this.carousel.render();
  this.carousel.show();
  if (this.autoPlay) {
    this.carousel.startAutoPlay(this.autoPlay);
  }    
  iYUDm.setStyle("imedia-carousel-"+this.id+"-container", "visibility", "visible");
  
  this.carousel.on("beforeScroll", function(state, cb){
    if (!cb.pageChanging) {
      if (state.dir == 'forward') {
        cb.paginator.setPage(cb.paginator.getCurrentPage()+1); 
      }
      else {
        cb.paginator.setPage(cb.paginator.getCurrentPage()-1);
      }
    }
  }, this);
  
  this.handlePagination = function(state) {
    var startIndex = state.recordOffset;
    if (((startIndex > this.currentCount) || (startIndex+this.pageSize > this.currentCount)) && (this.totalRecords > this.currentCount)) {
        //we need to get some data from server:
        var myCB = this;
        var item_required = ((this.currentCount+this.remoteMinItems) <= this.totalRecords) ? this.remoteMinItems : (this.totalRecords-this.currentCount);
        var url = this.remoteUrl+'/'+this.currentCount+'/'+item_required;
        iYUDm.setStyle("imedia-carousel-loading-"+this.id, "visibility", "visible");
        iYU.Connect.asyncRequest("GET", url, {
            success: function (o) {
                var newitems = Drupal.parseJson(o.responseText);
                for (var i=0; i < newitems.length; i++) {
                  myCB.carousel.addItem(newitems[i]);
                }
                myCB.currentCount += newitems.length;
                iYUDm.setStyle("imedia-carousel-loading-"+myCB.id, "visibility", "hidden");
                myCB.pageChanging = true;
                myCB.carousel.scrollTo(startIndex);      
                myCB.paginator.setState(state);
                myCB.pageChanging = false;
            },      
            failure: function (o) {
                //Ajax failed!
                iYUDm.setStyle("imedia-carousel-loading-"+myCB.id, "visibility", "hidden");
            }
        });      
    }
    else {
      this.pageChanging = true;
      this.carousel.scrollTo(startIndex);      
      this.paginator.setState(state);
      this.pageChanging = false;
    }
  };
  
  this.paginator = new iYW.Paginator({
    rowsPerPage: this.pageSize,
    totalRecords: this.totalRecords,
    containers: "carousel-paginator-"+this.id,
    template: this.paginatorConfig.template || "{PreviousPageLink} {CurrentPageReport} {NextPageLink}",
    previousPageLinkLabel: this.paginatorConfig.previousPageLinkLabel || "&lt;",
    nextPageLinkLabel: this.paginatorConfig.nextPageLinkLabel || "&gt;",
    pageReportTemplate: this.paginatorConfig.pageReportTemplate || "{currentPage} of {totalPages}"
  });
  
  this.paginator.subscribe('changeRequest', this.handlePagination, this, true);
  this.paginator.render();
  this.handlePagination(this.paginator.getState());
};

/**
 * returns an array of carouselBlocks which their class names matches c
 */

iYIM.findIMediaCarouselByClassName = function(c) {
  var res = [];
  if (document.imediaCarousels) {
  	// changed loop due to IE bug with for i in XXX
    for(var i = 0; i < document.imediaCarousels.length; i++) {
      if (document.imediaCarousels[i].className == c) {
        res.push(document.imediaCarousels[i]);
      }
    }
  }
  return res;
}
