/**
 * scrollerScroll plugin for jQuery
 *
 * v0.1
 *
 * Copyright (c) 2010 casper houde
 *
 * Dual licensed under the MIT and GPL licenses:
 *	 http://www.opensource.org/licenses/mit-license.php
 *	 http://www.gnu.org/licenses/gpl.html
 */

/**
 * Usage:
 * 
 * // using default options
 * $(document).scrollerScroll();
 *
 * In a div where there is more room to scroll.
 */

(function($){

	$.fn.scrollerScroll = function(options){
		
		var defaults = {
			data: ""
			, circular: true
			, maxspeeed: 4
			, minspeeed: 4
		};
		var options = $.extend(defaults, options);
		
		return this.each(function() {
			var firstChild;
			var firstChildW;
			var items;
			
			var initChild = function() {
				firstChild = $(items).children("div").eq(0);
				firstChildW = $(firstChild).outerWidth();
			}
			var playTime = function() {
				if(options.circular) {
					items = $(me).find(".items");
					initChild();
				}
				
				clearInterval(tim);
				tim = setInterval(function scroller() {
					l = $(me).scrollLeft();
					sp = l+speed;
					if(options.circular) {
						if(sp > firstChildW) {
							f = $(firstChild).detach();
							$(items).append(f);
							sp = sp - firstChildW;
							
							initChild();
						}
						if(sp <= 0) {
							console.log("c");
							l = $(items).children("div").length;
							lastChild = $(items).children("div").eq(l-1);
							w = $(firstChild).outerWidth();
							sp = sp + w;
							f = $(lastChild).detach();
							$(items).prepend(f);
							
							initChild();
						}
					}
					$(me).scrollLeft(sp);
				}, 29);
			}
			
			var cancleClick = false;
			var posX;
			var posY;
			
			var posW = $(this).width();
			p = $(this).position();
			posX = p.left;
			posY = p.top;
			var speed = 0;
			var play;
			var tim;
			var me = $(this);
			$(this).mouseup(function(evt){});
			/*
			$(this).mouseleave(function(evt){
				play = false;
				if(speed < 0) {
					speed = 0 - options.minspeeed;
				} else {
					speed = options.minspeeed;
				}
				playTime();
	
			});
			$(this).mouseenter(function(evt){
				if(!play) {
					playTime();
					play = true;
				}
			});
			
			$(this).mousemove(function(e){
				mX = e.pageX - posX;
				mY = e.pageY - posY;
				
				
				if(mX < (posW/2)) {
					if(mX < (posW/4)) {
						speed = 0 - options.maxspeeed;
					} else {
						speed = 0;
					}
				} else {
					if(mX > (posW/4*3)) {
						speed = options.maxspeeed;
					} else {
						speed = 0;
					}
				}
			});
			*/
			speed = 2.5;
			playTime();
		});
	};

})(jQuery);
