/** 
Copyright Fabien Di Tore - fabien@ditore.ch

Project started on 2008-07-31

ICEFramework IS NOT OPEN SOURCE.

This file is part of iceFramework

IceFramework n'est pas libre. Si vous avez acces a ces sources, vous pouvez le modifier et l'utiliser dans le contexte 
pour lequel il vous a ete mis a disposition (l'application).
Vous ne pouvez PAS le redistribuer, gratuitement ou contre retribution. 
Vous ne pouvez PAS creer de travaux derives de cette version d'IceFramework, le renommer ou masquer cette license. 
Toutes les modifications sont autorisees dans le cadre de l'application pour laquelle il vous a ete mis a
disposition. Il est modifiable par n'importe quel tiers.

--------------------------------

IceFramework is not free. If you have access to this source code, you can alter and use it in the context of the current application that is used for. You cannot redistribute it, freely or for money.
You cannot create derivate work from this version of IceFramework, rename it or mask, remove this license 
Every modifications are authorized in the context of the current application.



Require jquery UI core  and jquery UI mouse

Events: 

	slideTo
	
	willBeginAnimate
	
	didEndAnimate
	
	
Options:
	effectOptions: 
		fadeBoth: true | false    if true the top layer and the second will fade simultaneously, else the fade one after the other
	pagingOptions:
		showNumbers: false if true insert number into the button
		showPages: true		if true show one button per page
		showPrevNext: false  if true show next and prev button
		
**/


(function( $ ) {

$.widget("ui.akcarousel",$.ui.mouse, {
	// default options
	options: {
		itemSelector: 'ul:first>li',
		containerSelector: 'ul:first',
		viewHeight: 202,
		viewWidth : 480,
		itemWidth : 0,
		itemHeight : 0,
		itemPerPage: 1,
		animationSpeed: 1000,
		swapDelay: 3000,
		autoSlide: false,
		infiniteEffect: true,
		loopEffect: true, //loop effect 
		beingAnimated:false,
		debug: false,
		onBeginSlideCallback: '',
		onEndSlideCallback: '',
		effect: 'left', //top  // fade //flash //left
		effectOptions:{ fadeBoth: false },
		pagingOptions:{showNumbers: false,showPages: true,showPrevNext: false, appendToSlideShow:false },
		debug: false,
		minifiedItemMargin: 5,
		minifiedBackgroundColor: '#000000',
		enableThumbSelect: true,
		pagination:true,
		containerStyleCustom:false,
		itemStyleCustom: false,
		position:'relative',
		safeIndexAttr:'rel'
	},
	
	containerHeight: 0,
	containerWidth: 0,
	currentPage:0,
	numPages:0,
	controlsEnabled:true,
	_create: function() {
		var self = this;
		var o = this.options;
		//$(this).find(o.containerSelector);
		this.container = this.element.find(this.options.containerSelector);
		this.pouet = this.element.find(this.options.containerSelector);
		this.items = this.element.find(this.options.itemSelector);
		if(this.options.debug){
			this.element.css ('overflow','visible');
		}else{
			this.element.css ('overflow','hidden');
		}
		this.element.css({
				width: this.options.viewWidth,
				height: this.options.viewHeight,
				position: this.options.position
		});
		this.numPages = Math.ceil(this.items.length /  o.itemPerPage);
		
		o.itemWidth = Math.ceil(o.viewWidth / o.itemPerPage);
		o.itemHeight = o.viewHeight;
		if(!o.itemStyleCustom){
			this.items.css({
				width: this.options.itemWidth,
				height: o.itemHeight,
				float: 'left'
			});
		}	
	
		if(!o.containerStyleCustom){
			this.container.css('list-style-type','none');
			this.container.css('padding',0);
			this.container.css('position','absolute');
			this.container.css('margin',0);
		}
		var y = 0;
		this.items.each(function(){
			$(this).attr(o.safeIndexAttr,y);
			y++;
		});
		
		if(o.effect=='left' || o.effect =='flash'){
			this.containerHeight = o.viewHeight;
			this.containerWidth= Math.ceil(o.viewWidth*this.numPages);
			//if we want have infinite effect with loop
			//alert('test');
			if(o.infiniteEffect && o.loopEffect && this.items.size()>2){ //we need more than 2 items
				//putting the last item at first 
				
				var first = this.items.last();
				
				var f = first.clone();
				first.remove();
				this.container.prepend(f);
				this.container.css({left: -o.viewWidth});
				//alert(first.html());
				this.items = this.element.find(this.options.itemSelector);
			}
		}else if (o.effect =='top') { // top effect
			this.containerHeight = Math.ceil(o.viewHeight * (this.items.size() / o.itemPerPage));
			this.containerWidth= o.viewWidth;
		}else if(o.effect =='fade'){
			this.containerWidth= o.viewWidth;
			this.containerHeight = o.viewHeight;	
			this.items.css({position:'absolute'});
			i= this.items.length+10;
			y= 0;
			this.items.each(function(){
				
				$(this).css('z-index',i);
				if(y>0){
					$(this).css('display','none');
				}
				i = i-1;
				y = y+1;
			});	
		}
		
		
		this.container.css({
			height: this.containerHeight,
			width: this.containerWidth
		});

		if(o.pagination && this.items.length >1 ){
			if(o.pagingOptions.appendToSlideShow){
				this.pagination = $('<div class="ui-carousel-paging"></div>').appendTo(this.element);
				this.pagination.css('width',o.viewWidth)
			}else{
				this.pagination = $('<div class="ui-carousel-paging"></div>');//.after(this.element);
				this.element.after(this.pagination);
			}
		}
		
		
		if(o.pagination && this.items.length >1 && o.pagingOptions.showPages){
			this.items.each(function(index,element){	
				if(o.pagingOptions.showNumbers){
					$('<a href="#">'+(index+1)+'</a>').appendTo(self.pagination)
										.click(function(event){
											if(self.controlsEnabled){
											self.moveTo(index,event);
											}
											return false;
										});

				}else{
					$('<a href="#"> </a>').appendTo(self.pagination)
										.click(function(event){
											if(self.controlsEnabled){
											self.moveTo(index,event);
											}
											return false;
										});
				}
			});
			
			this.pagination.children('a:eq(0)').addClass('active');
		}
		
		if(o.pagination && o.pagingOptions.showPrevNext){
			$('<div class="ui-carousel-paging-left"></div>').appendTo(this.pagination).click(
				function(event){
					if(self.controlsEnabled){
						self.backward(event);
					}
					return false;
				}
			).css('cursor','pointer');
			$('<div class="ui-carousel-paging-right"></div>').appendTo(this.pagination).click(
				function(event){
					if(self.controlsEnabled){
						self.forward(event);
					}
					return false;
				}
			).css('cursor','pointer');
		}
		
		
		this.minified = false;
		//this._mouseInit();
		
		if(o.autoSlide && this.items.length>1){ // starting timer 
			this.setTimer();
		}
		
	},
	
	disableControls: function(e){
		this.controlsEnabled=false;
	},
	enableControls: function(e){
		this.controlsEnabled=true;
	},
	_mouseStart: function(e){
		this.xStart = e.pageX;
	},

	_mouseDrag: function(e){
		//console.log('drag');
		relativeMouseX = (e.pageX-this.element.position().left);
	//	this.container.css('left',0);
		//console.log(this.container.position().left);
		//console.log('Relative Mouse X '+relativeMouseX);
		//console.log(this.container.position().left + relativeMouseX);
	},
	resetTimer:function(){
		if(this.options.autoSlide){
	//	console.log('setting timer');
		this.element.stopTime("akCarousel");
		this.setTimer();
		}
	},
	setTimer:function(){
	if(this.options.autoSlide){
				var self = this;
		var o = this.options;
		this.element.everyTime(o.swapDelay+o.animationSpeed,'akCarousel',function(e){
			self.forward(e);	
		});
	}
	},
	forward: function(event) {
		
		//alert(this.items.length);
		if(this.currentPage+1 <= this.numPages-1){
			this.moveTo(this.currentPage+1);
		}else{
			this.moveTo(0);
		}
	},
	
	backward: function(event){
	//alert('back');
		if(this.currentPage-1>=0){
			this.moveTo(this.currentPage-1);
		}else{
			this.moveTo(this.numPages-1);
		}
	},
	
	moveTo : function(idx,event){
		if(isNaN(event)){ // if it's a number, that's the timer
			this.resetTimer();
		}
		var self = this;
		var o = this.options;
		this.disableControls();
	//	console.log('moving to '+idx);
		if(o.effect=='left'){
			
			
			if(o.infiniteEffect){
				//alert(self.element.find(self.options.itemSelector).size());
				var i =-1;
				var found =false;
				self.element.find(self.options.itemSelector).each(function(){
				//	console.log('log: '+$(this).attr('rel'));
					if($(this).attr('rel') != idx && !found){
						i++;
						
					}else if($(this).attr('rel')==idx){
						found=true;
						//i++;
					}
				});
			//	console.log('realindex: '+i);
				to = idx;
				from = this.currentPage;
				move = to -from ; 
				var skip = false;
			//	console.log(move);
				
				if(o.loopEffect){
					if(i < 0){ // il faut remettre le dernier en premier si on repart en arrière
					var left = -960;
					//alert(self.element.find(self.options.containerSelector).css('left'));
					//alert(left);
						var first = self.element.find(self.options.itemSelector).last();
						var f = first.clone();
						first.remove();
						self.element.find(self.options.containerSelector).prepend(f);
					//	alert( self.element.find(self.options.containerSelector).offset().left-o.viewWidth);;
					//alert(o.viewWidth);
						self.element.find(self.options.containerSelector).css({left: left-o.viewWidth});
					//	alert( self.element.find(self.options.containerSelector).offset().left-o.viewWidth);;
						move=960;
					}else{
						move= 960*(i+1);
					}
					//exit();
					if(!skip){
					this.container.animate({left:-(move)},{duration:o.animationSpeed,queue:false,complete:function(e){
							if(i>0){
								for(var y = 0; y < i ; y++){
								var first = self.element.find(self.options.itemSelector).first();
							//	console.log(first.html())
							
								var f = first.clone();
								first.remove();
								self.element.find(self.options.containerSelector).append(f);
								self.element.find(self.options.containerSelector).css({left: -o.viewWidth});
								
								}
								
							}
							
						self.enableControls();
					}});
					}
					
			

				}else{
				
					this.container.animate({left:-(o.viewWidth)},{duration:o.animationSpeed,queue:false});
				}
				
				//this.container.animate({left:-(idx*o.viewWidth)},{duration:o.animationSpeed,queue:false});
					/*var first = o.proj.find('li:first').html();
					//alert(first);
					
					o.proj.find('li:first').remove();
					o.proj.css('left',0);
					o.proj.append("<li style=\"width:"+o.itemWidth+"px; float:left;\">"+first+"</li>");
				}
				o.beingAnimated = false;
			*/
			//	var first = self.container.children().eq(0);
				
			}else{
			
				this.container.animate({left:-(idx*o.viewWidth)},{duration:o.animationSpeed,queue:false});
			}

		}else if (o.effect =='top'){
			this.container.animate({top:-(idx*o.viewHeight)},{duration:o.animationSpeed,queue:false});
		} else if(o.effect == 'fade'){ // fade is complex !
			//fade out the first of the stack 
			to = idx;
			from = this.currentPage;
			move = to -from ; 
			if (move < 0){
				//special obscure computation
				// merci fabien pour tes commentaires utiles
				move = Math.abs(from-this.items.length);
				move = move + to;				
			//	alert(move);
			}
		//	console.log('move '+move);
			if(move >0 ){ // we have to move 
				var arr = new Array();
		
				for(var i=move-1 ; i > 0; i--){ // determining wich elements we have to move in the DOM
					
					arr.push(this.container.children().eq(i));
					//arr.push(this.container.children().eq(i));
				}
				
				for(var i = 0; i< arr.length;i++){// removing them
					arr[i].remove();
				}

				if(self.options.effectOptions.fadeBoth){		
					self.container.children().eq(1).fadeIn(o.animationSpeed);
				}
				this.container.children().first().fadeOut(o.animationSpeed,function(){ // animate and rearrange for next iteration
					$(this).remove().appendTo(self.container); //.css('display','block')

					
					if(!self.options.effectOptions.fadeBoth){			
						self.container.children().first().fadeIn(o.animationSpeed);
					}
					self.container.children().first().css('z-index',self.items.length+10);
					$(this).css('z-index',self.container.children().first().css('z-index')-1);
					
					for(var i = arr.length-1 ; i >-1 ; i--){
						arr[i].appendTo(self.container);
						arr[i].css('z-index',arr[i].prev().css('z-index')-1);
					}
				});
			}
			//alert(move);
		}
		if(o.pagination){
			this.pagination.children().removeClass('active');
			this.pagination.children('a:eq('+idx+')').addClass('active');
		}
		
		
		this._trigger('slideTo', event,{selected:idx,id:this.element.find(this.options.itemSelector+':eq('+idx+')').attr('id')});
		this.currentPage = idx;
	},
	
	destroy: function() {
	   $.Widget.prototype.destroy.apply(this, arguments); // default destroy
	}
});
 
 
})(jQuery);


