// Class name: LqCarousel
// Author: Antoine Grant

LqCarousel = new Class({
	Implements: [Options,Events],
	
	options: {
		_cWrap : 'cWrap',
		_cItemsPerRow : 4,
		_numItemScroll : 'all',
		_scrollWheel : true
	},
	
	initialize: function(options) {
		
		// Check to see if Mootools is included in the page
		//if(typeof MooTools == "undefined" || MooTools['version']<'1.2.0') {alert('The Mootools framework version 1.2.x is needed in your html file!');return false;}
		
		this.setOptions(options);
		var _cItemsPerRow = this.options._cItemsPerRow;
		var _cWrap = (!this.options._cWrap)?'cWrap':this.options._cWrap;
		var _cWrapWidth = Math.floor($(_cWrap).getStyle('width').toInt());
		
		// Set the cContentWrap id and create cContentScroll
		$$('#'+_cWrap+' .cContentWrap').setProperty('id','cContentWrap'+_cWrap);
		$$('#'+_cWrap+' .apNav').setProperty('id','apNav'+_cWrap);
		var cContentScroll = new Element('div', {'id' : 'cContentScroll'+_cWrap, 'class' : 'cContentScroll'}).injectInside('cContentWrap'+_cWrap);
		
		// Get the number of cItem and fix there width
		var _count_cItem = $(_cWrap).getElements('#cContentWrap'+_cWrap+' .cItem').length;
		if(_count_cItem<=_cItemsPerRow) {_cItemsPerRow = _count_cItem;}
		var _cItemWidth = Math.floor((_cWrapWidth/_cItemsPerRow));
		$$('#'+_cWrap+' .cItem').each(function(cItem,index) {
			cItem.setStyle("width",_cItemWidth+"px");
		});
		
		var _numItemScroll = this.options._numItemScroll;
		if(_numItemScroll!='all') {
			var arrayNumItem = _numItemScroll.split("-");
			_numItemScroll = arrayNumItem[0].toInt();	
		} else {
			_numItemScroll = _count_cItem;
		}
		
		// Add some cItem to fit a round number per row
		if(_numItemScroll>=_cItemsPerRow) {
			if((_count_cItem/_cItemsPerRow)!=2) {
				var numToAdd = (Math.ceil(_count_cItem/_cItemsPerRow)*_cItemsPerRow)-_count_cItem;
				for(i=1;i<=numToAdd;i++) {
					var _cItemXtra = new Element('div', {'class' : 'cItem empty'}).injectInside('cContentScroll'+_cWrap);
					$$('#'+_cWrap+' .empty').setStyle("width",_cItemWidth+"px");
					_count_cItem = _count_cItem+1;
				}
			}
		}
		
		// Clone, destroy, create the citems div and inject the cloned cItem
		var clone = $$('#'+_cWrap+' .cItem').clone();
		$$('#'+_cWrap+' .cItem').each(function(cItem,index) {
			cItem.destroy();
		});
		var _cItems = new Element('div', {'id' : 'cItems'+_cWrap, 'class' : 'cItems'}).injectInside('cContentScroll'+_cWrap);
		clone.injectInside('cItems'+_cWrap);
		
		// Set the width of cContentWrap according to the number of cItem
		$('cContentScroll'+_cWrap).setStyle('width', Math.floor(_cItemWidth*_count_cItem)+'px');
		
		// If the number of cItem is smaller or equal then the items per row then there's no need to continu
		if(_count_cItem<=_cItemsPerRow) {return false;}
		
		// Clone the cItems div and inject them to the beginning and end of cContentScroll, then ajust the width and margin of cContentScroll
		$('cItems'+_cWrap).clone().setProperty('id','cItems'+_cWrap).injectTop('cContentScroll'+_cWrap);
		$('cItems'+_cWrap).clone().setProperty('id','cItems'+_cWrap).injectInside('cContentScroll'+_cWrap);
		$('cContentScroll'+_cWrap).setStyles({
			'width': (Math.floor($('cContentScroll'+_cWrap).getStyle('width').toInt()*3)),
			'margin-left': -Math.floor(_cItemWidth*_count_cItem)
		});
		
		// Create the animation
		var noScrollEvents = false;
		var scrollPosStart;
		var _pageActiveNum=1;
		var cItemsFx = new Fx.Morph($('cContentScroll'+_cWrap), {
			link: 'ignore',
			duration: 500,
			transition: Fx.Transitions.Circ.easeInOut,
			// OnStart make sure you can't scroll
			onStart: function(el) {
				noScrollEvents = true;
				scrollPosStart = el.getStyle('margin-left').toInt();
			},
			// OnComplete check to see if cContentScroll is at the start or end of the cycle and then ajust the elements
			onComplete: function(el) {
				if(Math.floor(el.getStyle('margin-left').toInt())>=-5 && Math.floor(el.getStyle('margin-left').toInt())<=5) {
					$('cItems'+_cWrap).clone().setProperty('id','cItems'+_cWrap).injectTop('cContentScroll'+_cWrap);
					el.setStyles({
						'width': Math.floor(el.getStyle('width').toInt()),
						'margin-left': -Math.floor(_cItemWidth*_count_cItem)
					});
					el.getLast().destroy();
				} else if(Math.floor(el.getStyle('margin-left').toInt()) <= -((el.getStyle('width').toInt()-(_cItemWidth*_cItemsPerRow)-5)) && Math.floor(el.getStyle('margin-left').toInt()) >= -((el.getStyle('width').toInt()-(_cItemWidth*_cItemsPerRow)+5))) {
					$('cItems'+_cWrap).clone().setProperty('id','cItems'+_cWrap).injectInside('cContentScroll'+_cWrap);
					el.setStyles({
						'width': Math.floor(el.getStyle('width').toInt()),
						'margin-left': -Math.floor((_cItemWidth*_count_cItem)+((_count_cItem-_cItemsPerRow)*_cItemWidth))
					});
					el.getLast().destroy();
				}
				
				if(_scrollDirection=="foward") {
					if(_pageActiveNum<_numOfPage) {
						_pageActiveNum = _pageActiveNum+1;
					} else {
						_pageActiveNum = _pageActiveNum-(_numOfPage-1);
					}
					_scrollDirection='';
				} else if(_scrollDirection=="backward") {
					if(_pageActiveNum==1) {
						_pageActiveNum = _numOfPage;
					} else if(_pageActiveNum<=_numOfPage) {
						_pageActiveNum = _pageActiveNum-1;
					}
					_scrollDirection='';
				}
				if(_numItemScroll>=_cItemsPerRow) {
					$$('#apNav'+_cWrap+' .apItem').each(function(el,index) {
						index = (index+1);
						(index==_pageActiveNum)?el.addClass('selected'):el.removeClass('selected');
					});	
				}
				
				noScrollEvents = false;
			}
		});
		
		// Ajust the scroll increment depending on the option _numItemScroll
		if(_numItemScroll<=_cItemsPerRow) {
			if(_numItemScroll%2) {
				_widthToScroll = _cItemWidth*(_numItemScroll+1);
			} else {
				_widthToScroll = _cItemWidth*_numItemScroll;
			}
		} else {
			_widthToScroll = _cItemWidth*_cItemsPerRow;
		}
		
		// Manage the events handler for the scroll
		// Find how many pages there are
		var _numOfPage = Math.ceil(_count_cItem/_cItemsPerRow);
		var _scrollDirection;
		var initMargLeft = Math.floor($('cContentScroll'+_cWrap).getStyle('margin-left').toInt());
		if(_numItemScroll>=_cItemsPerRow) {
			for(i=1;i<=_numOfPage;i++) {
				var _cItemXtra = new Element('a', {'class' : 'apItem'}).appendText(i).injectInside('apNav'+_cWrap);
				var widthWrap = _cItemXtra.getStyle("width").toInt();
				widthWrap = (widthWrap+_cItemXtra.getStyle("margin-left").toInt());
				widthWrap = (widthWrap+_cItemXtra.getStyle("margin-right").toInt());
				widthWrap = (widthWrap+_cItemXtra.getStyle("padding-left").toInt());
				widthWrap = (widthWrap+_cItemXtra.getStyle("padding-right").toInt());
				_cItemXtra.getParent().setStyle("width",(widthWrap*_numOfPage)+4);
				(i==1)?_cItemXtra.addClass('selected'):'';
			}	
		}
		$$('#apNav'+_cWrap+' .apItem').each(function(el,index) {
			el.addEvent('click',function() {
				cItemsFx.start({'margin-left':[$('cContentScroll'+_cWrap).getStyle('margin-left').toInt(),(initMargLeft - (_cWrapWidth*index))]});
				_pageActiveNum = (index+1);
			});
		});
		
		// Go foward - Reveal items to the right
		$$('#'+_cWrap+' .foward').addEvent('click',function() {
			cItemsFx.start({'margin-left':[$('cContentScroll'+_cWrap).getStyle('margin-left').toInt(),(Math.floor($('cContentScroll'+_cWrap).getStyle('margin-left').toInt()) - _widthToScroll)]});
			_scrollDirection = 'foward';
		});
		// Go backwards - Reveal items to the left
		$$('#'+_cWrap+' .backward').addEvent('click',function() {
			cItemsFx.start({'margin-left':[$('cContentScroll'+_cWrap).getStyle('margin-left').toInt(),($('cContentScroll'+_cWrap).getStyle('margin-left').toInt() + _widthToScroll)]});
			_scrollDirection = 'backward';
		});
		
		if(this.options._scrollWheel==true) {
			// Manage the scroll event - left and right
			$('cContentScroll'+_cWrap).addEvent('mousewheel', function(e) {
				e.preventDefault();
				if(noScrollEvents==false) {
					e = new Event(e);
					if(e.wheel<0) { // left
						cItemsFx.start({'margin-left':[$('cContentScroll'+_cWrap).getStyle('margin-left').toInt(),(Math.floor($('cContentScroll'+_cWrap).getStyle('margin-left').toInt()) - _widthToScroll)]});
						_scrollDirection = 'foward';
					} else { // Right
						cItemsFx.start({'margin-left':[$('cContentScroll'+_cWrap).getStyle('margin-left').toInt(),($('cContentScroll'+_cWrap).getStyle('margin-left').toInt() + _widthToScroll)]});
						_scrollDirection = 'backward';
					}
				}
			}.bind(this));
			$('cContentScroll'+_cWrap).addEvent("mouseleave", function() {
				document.removeEvent('mousewheel', function(e) {
					e.preventDefault();
				});
			}.bind(this));
		}
		
	}
	
});










