/*
 * jQuery Store Roller v1.0
 * http://jquery.com/
 *
 * Copyright (c) 2011 IPOS Computer Systems Ltd.
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 */
 
 (function($){
	var StoreRoller = function(element, options) {
		var elem = $(element);
		var obj = this;
		var rollchild = elem.children('li');
		var totalrollchild = rollchild.length;
		var totalrollchildsub = rollchild.children('img').length;
		var rollchildwidth = rollchild.children('img').width();
		var totalrollchildwidth = 0;
		
		var settings = $.extend({
			imgpath : null,
			duration : 16000
		}, options || {});
		
		var init = function() {
			initRollChild();
		};
		
		var initRollChild = function() {
			
			// sum of all img width
			rollchild.children('img').each(function() {
				totalrollchildwidth += $(this).width();
			});
			rollchild.width(totalrollchildwidth);
			
			// detect contents exceed wrapper or not
			if (totalrollchildwidth > elem.width()) {
				duplicate();
				for(i=0;i<totalrollchild;i++) {
					var loopitm = elem.find('li:eq('+i+')');
					loopitm.data('pos',i); // save init index of each child inside to them for later use
					loopitm.css('left',i*totalrollchildwidth);
					loopitm.css('visibility','visible');
				}
				startRoll();
			} else {
				for(i=0;i<totalrollchild;i++) {
					var loopitm = elem.find('li:eq('+i+')');
					loopitm.css('visibility','visible');
				}
			};
			
		};
		
		var duplicate = function() {
			temphtml = elem.html();
			elem.append(temphtml);
			elem.find('li:eq(1)').attr('class','copy');
			totalrollchild = elem.children('li').length;
		};
		
		var startRoll = function() {
			for(i=0;i<totalrollchild;i++){
				var loopitm = elem.find('li:eq('+i+')');
				loopitm.animate({'left':loopitm.position().left-totalrollchildwidth},{duration:settings['duration']*totalrollchildsub,easing:'linear',step:function(now,fx){fx.now=Math.floor(fx.now);},complete:function(){ chkLoop($(this)) }});
			}
		};
		
		var chkLoop = function(target) {

			if (target.position().left == (totalrollchildwidth*-1)) {
				target.css('left',totalrollchildwidth*(totalrollchild-1));
			}
			target.animate({'left':target.position().left-totalrollchildwidth},{duration:settings['duration']*totalrollchildsub,easing:'linear',step:function(now,fx){fx.now=Math.floor(fx.now);},complete:function(){ chkLoop($(this)) }});
		};
		
		init();	
		
	};

	$.fn.storeroller = function(options) {
		return this.each(function() {
			var element = $(this);
			if (element.data('storeroller')) return;
			var storeroller = new StoreRoller(this, options);
			element.data('storeroller', storeroller);
		});
	};
})(jQuery);
