/*
 * jQuery jScrollTouch plugin 1.1
 *
 * Copyright (c) 2010 Damien Rottemberg damien@dealinium.com
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 *
 */

/* 
 	2010-07-01/MM : added CSS class + scrollbarV_width
 	2010-07-01/MM : check on e.originalEvent.touches when touchstart is triggered
	2010-07-01/MM : recalc scrollbar dim/pos when touchstart is triggered => allow change of orientation
	2010-07-29/MM : removed mouse events to prevent mouse bug under Webkit (Safari, Chrome)
*/

(function($){
  $.fn.jScrollTouch = function () {
	if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) 
	{
 		var isTouchScreen = 1;
 	} 
	else
 	{
 		var isTouchScreen = 0;
 	}	
 	$(this).css({'overflow': 'auto','position':'relative'});
 	
	return this.each(function() {
		var cont = $(this);
		
		cont.bind(/*'mousedown */'touchstart',function(e){					
			var height = 0;
			var cpos = cont.scrollTop();
			cont.scrollTop(100000);
			height = cont.scrollTop();
			cont.scrollTop(cpos);
			var fullheight = height + cont.outerHeight();
			var scrollbarV_length = cont.innerHeight()*(cont.innerHeight()/fullheight)+2;
			
			var width = 0;
			var lpos = cont.scrollLeft();
			cont.scrollLeft(100000);
			width = cont.scrollLeft();
			cont.scrollLeft(lpos);
			var fullwidth = width + cont.outerWidth();		
			
			if (isTouchScreen)
			{
				var scrollbarV = $('<div></div>').addClass('touch-scrollbar');
				var scrollbarV_width = 10;
				
				scrollbarV.css({'height':scrollbarV_length+'px','left':cont.innerWidth()-scrollbarV_width+'px','top':0});
				if (height) cont.append(scrollbarV);
			}
			
			//cpos = cont.scrollTop();
					
			if (isTouchScreen)
			{
				if (e.originalEvent.touches)
				{
					e = e.originalEvent.touches[0];
				}
				else
				{
					return true;
				}
				
				scrollbarV.show();
			}
			
			var sY = e.pageY;
			var sX = e.pageX;
			
			cont.bind(/*'mousemove */'touchmove ',function(ev){
				if (isTouchScreen)
				{
					ev.preventDefault();
					ev = ev.originalEvent.touches[0];
				}	
				
				var top = cpos-(ev.pageY-sY);
				var left =  lpos-(ev.pageX-sX);
				
				cont.scrollTop(top);
				cpos = cont.scrollTop();
				sY = ev.pageY;
				
				cont.scrollLeft(left);
				lpos = cont.scrollLeft();
				sX = ev.pageX;
				if (isTouchScreen)
				{
					scrollbarV.css({'left':Math.min(cont.innerWidth()-scrollbarV_width+lpos,fullwidth)+'px','top':Math.min(cpos+cpos*cont.innerHeight()/fullheight,fullheight-scrollbarV_length)+'px'});
				}	
			});
			cont.bind(/*'mouseup */'touchend',function(ev){	
				cont.unbind(/*'mousemove mouseup */'touchmove touchend');
				if (isTouchScreen)
				{
					scrollbarV.fadeOut();
				}				
			});
		});
	});
  };
})(jQuery);   