// JavaScript Document
// @param - html element contenant le caroussel
// @param - hash contenant le callback -> {evt: 'click', obj: window, fn: 'nomDeLaFonction', args: ['', '']}
// @param - object containing width/gap properties to force
var cspkUICaroussel = function(elt, callback, params){
	this.canMove = false;
  this.canLoadMore = false;
  this.ajaxFeed = false;
  this.ajaxGap = 0;
	this.container = elt;	
  this.container_sub = elt;	
	this.callbacks = new Array();
	if(params){
		if(params.gap)
			this.gapToMove = params.gap;
		if(params.width) 
    	this.initialize(params.width);
	}
	else this.initialize();
	this.gapToMove = this.gapToMove || 1;
	this.nbEltsToDisplay = this.getNbEltsDisplay();
	this.currentFrame = this.nbEltsToDisplay;
	this.initActions();
	if(callback){
		this.addCallback(callback);
	}
};

// initialise les proprietes de l'objet
cspkUICaroussel.prototype.initialize = function(widthToForce){
	this.nbElt = $('.c_elt', this.container).length;
	this.moveWidth = widthToForce ? widthToForce : $($('.c_elt', this.container)[0]).width();
	this.setEltsContainerWidth();
};

// re-initialise les proprietes de l'objet : apres vidage et re-remplissage par call api
cspkUICaroussel.prototype.reinitialize = function(widthToForce, ajaxFeed, nbElem, ajaxCorrection, noclear){
	//this.canMove = false; // XXX
  this.canMove = true;
	this.callbacks = new Array();
  this.nbElt = 0 ;
  this.ajaxFeed = (ajaxFeed) ? ajaxFeed : false;
  this.canLoadMore = true;
  this.ajaxGap = ajaxCorrection ? ajaxCorrection : 0;
  if(nbElem)
    this.nbElt = nbElem;
  else
    this.nbElt = $('.c_elt', this.container).length;
  //console.log("ajaxCorrection="+ajaxCorrection);
	this.moveWidth =  widthToForce ? widthToForce : $($('.c_elt', this.container)[0]).width();
	var scrollElt = $('.preview_scroll', this.container)[0];
  if(!noclear || (noclear==0)) $(scrollElt).css('left','0px');
  
  this.setEltsContainerWidth();
  this.gapToMove = this.gapToMove || 1;
	this.nbEltsToDisplay = this.getNbEltsDisplay();
	this.currentFrame = this.nbEltsToDisplay;
	//this.initActions();
  this.getBtnsAction();
  this.checkBtnDesabled();
};


// ajout un callbak les elements du caroussel
cspkUICaroussel.prototype.addCallback = function(callback){
	if(callback.evt){
		var elts = $('.c_elt img', this.container);
		elts.each(function(index, elt){
			var args = new Array(elt, index);
			for(var j = 0; j < callback.args.length; j++){
				args.push(callback.args[j]);
			}
			$(elt).bind(callback.evt, function(evt){
				callback.obj[callback.fn].apply(callback.obj, args);
			});				
		});
	}
};

// determine la largeur du container HTML devant scroller
cspkUICaroussel.prototype.setEltsContainerWidth = function(){
	var containerWidth = this.nbElt * this.moveWidth;
	var containerElts = $('.preview_scroll', this.container)[0];
	if(!containerElts.tagName) return;
	$(containerElts).css('width', containerWidth + 'px');
};

// determine le nbre d'elements visibles pour le caroussel
// @return integer - nb elements dans le caroussel
cspkUICaroussel.prototype.getNbEltsDisplay = function(){
	var batch = $('.preview_batch', this.container)[0];
	var batchWidth = $(batch).width();
	var nbEltsDisplay = parseInt(batchWidth) / parseInt(this.moveWidth);
	return (nbEltsDisplay)? Math.ceil(nbEltsDisplay) : 1; 	
};

// catch les boutons droit et gauche
cspkUICaroussel.prototype.getBtnsAction = function(){
	var btnLeft = $('.bt_left',this.container)[0];
	var btnRight = $('.bt_right',this.container)[0];
	this.btnLeft = (!btnLeft.tagName)? false : btnLeft;
	this.btnRight = (!btnRight.tagName)? false : btnRight;	
};

// set les actions sur les boutons - evenement click
cspkUICaroussel.prototype.initActions = function(){
	this.getBtnsAction();
  this.canMove = ((this.nbElt > this.nbEltsToDisplay) || (this.canLoadMore)) ? true : false;
  //alert("canmove="+this.canMove+" nbelem:"+this.nbElt+" nbdisplay:"+this.nbEltsToDisplay);
	if(!this.canMove){
		this.checkBtnDesabled();
		return;
	}
	var that = this;
	if(this.btnRight.tagName){
		$(this.btnRight).click(function(e){
			that.move('right');
		});
	}
	if(this.btnLeft.tagName){
		this.checkBtnDesabled();
		$(this.btnLeft).click(function(e){
			that.move('left');	
		});
	}
};
  
// deplace le container scroll vers la droite ou la gauche
// @param right ou left - string
cspkUICaroussel.prototype.move = function(direction){
	if( !this.isCanMove(direction) ) {return;}
	var scrollElt = $('.preview_scroll', this.container)[0];
	if(scrollElt.tagName){
		var position = parseInt($(scrollElt).css('left').replace('px',''));
		position = (isNaN(position))? 0 : position;
		if(direction == 'right'){
			var newPosition = new Number(position - this.getMoveTo('right'));
			this.canMove = false;
			var that = this;
      if(this.ajaxFeed) {
        //$(scrollElt).animate({opacity: 0}, 300);
        $(scrollElt).queue(function(){
          var tmp_scroll = parseInt((-1) * that.moveWidth);
          tmp_scroll =  parseInt(tmp_scroll * that.ajaxGap);
          $(this).css('left', tmp_scroll+'px' ); 
          $(this).dequeue();
          that.canMove = true;
  				//that.incrementCurrentFrame();
  				that.checkBtnDesabled();
        });
        //$(scrollElt).animate({opacity: 1.0}, 300 );
      }	else {
  			$(scrollElt).animate({left : newPosition}, 'fast', 'linear', function(){ 
  				that.canMove = true;
  				that.incrementCurrentFrame();
  				that.checkBtnDesabled();
  			});
      }
		}	
		else 
    {
			var newPosition = new Number(position + this.getMoveTo('left'));
			this.canMove = false;
			var that = this;
      if(this.ajaxFeed) {
        //$(scrollElt).animate({opacity: 0}, 500);
        $(scrollElt).queue(function(){
          var tmp_scroll = parseInt((-1) * that.moveWidth);
          tmp_scroll =  parseInt(tmp_scroll * that.ajaxGap);
          $(this).css('left', tmp_scroll+'px' ); 
          $(this).dequeue();
          that.canMove = true;
  				//that.decrementCurrentFrame();
  				that.checkBtnDesabled();
        });
        //$(scrollElt).animate({opacity: 1.0}, 500 );
      }	else {
  			$(scrollElt).animate({left : newPosition}, 'fast', 'linear', function(){
  				that.canMove = true;
  				that.decrementCurrentFrame();
  				that.checkBtnDesabled();
  			});
      }		
		}	
	}
};

// determine si les bouton doivent etre activer ou desactiver en fontion de la position du container scroll
cspkUICaroussel.prototype.checkBtnDesabled = function(){
	(this.isCanMove('right'))? this.removeDesabledClass(this.btnRight) : this.setDesabledClass(this.btnRight);
	(this.isCanMove('left'))? this.removeDesabledClass(this.btnLeft) : this.setDesabledClass(this.btnLeft);
};

// determine si le container scroll peut bouger
cspkUICaroussel.prototype.isCanMove = function(direction){
	if(!this.canMove) return;
	if(direction == 'left'){
		return ((this.currentFrame > this.nbEltsToDisplay) || (this.canLoadMore) ) ? true : false;
	}
	else {
    return ((this.currentFrame < this.nbElt) || (this.canLoadMore))? true : false;
  }
};

// attribue la classe desabled pour les boutons
cspkUICaroussel.prototype.setDesabledClass = function(elt){
	if(!$(elt).hasClass('desabled')){
		$(elt).addClass('desabled');
	}
};

// supprime la classe desabled pour les boutons
cspkUICaroussel.prototype.removeDesabledClass = function(elt){
	if($(elt).hasClass('desabled')){
		$(elt).removeClass('desabled');
	}
};

// set la taille des elements du caroussel
cspkUICaroussel.prototype.setMoveWidth = function(size){
	if(size) this.moveWidth = size;
	
};

// set le nb des elements du caroussel
cspkUICaroussel.prototype.setNbElements = function(nb){
	if(nb) this.nbElt = nb;
	
};

// set le nombre d'elements devant defiler a chaque deplacement
cspkUICaroussel.prototype.setGapToMove = function(gap){
	if(gap) this.gapToMove = gap;
};

// set la frame courante
cspkUICaroussel.prototype.incrementCurrentFrame = function(){
	if((this.currentFrame + this.gapToMove) > this.nbElt){
		this.currentFrame = this.nbElt;
	}
	else this.currentFrame += this.gapToMove;	
};

// set la frame courante
cspkUICaroussel.prototype.decrementCurrentFrame = function(){
	if((this.currentFrame - this.gapToMove) < this.nbEltsToDisplay){
		this.currentFrame = this.nbEltsToDisplay;
	}
	else this.currentFrame -= this.gapToMove;
};

// determine la distance de deplacement
cspkUICaroussel.prototype.getMoveTo = function(direction){
	if(direction == 'left'){
		var gap = ((this.currentFrame - this.gapToMove) < this.nbEltsToDisplay)? this.currentFrame - this.nbEltsToDisplay : this.gapToMove;
	}
	else var gap = ((this.gapToMove + this.currentFrame) > this.nbElt)? this.nbElt - this.currentFrame : this.gapToMove;
	var moveToValue = gap * this.moveWidth;  
	return parseInt(moveToValue);
};
