/*
Roller
by Jon Krauss, vinagency.com


This plugin ...


_How to instantiate



_Example HTML


*/


(function($) {	

	$.fn.roller = function(options) {	

		var 	el = this,
			defaults = {
			
				button_left_id:'button-left',
				button_right_id:'button-right',
				scroll_stage_id:'scrolling_stage'
			},
			settings = $.extend(defaults, options),
			$left,// = $('#'+settings.button_left_id),
			$right,// = $('#'+settings.button_right_id),
			$roller = $('#'+settings.scroll_stage_id),
			$outer = $roller.parent(),
			$items = $roller.find('> div'),
			current = 0,
			is_draggable = false,
			min_x;

		init = function(){
			
			//initDraggable();
			//resetDrag();
			
			$('#container').append( $('<div id="drag-tooltip">< Drag to Scroll ></div>') );
			$('body').append( $('<div id="scrolling-button-left">&laquo;</div><div id="scrolling-button-right">&raquo;</div>') );
			
			$left = $('#'+settings.button_left_id);
			$right = $('#'+settings.button_right_id);
			
			attachEvents();
			
			resizeRoller();
			
			onResize();
		};
		
		log = function (s) {
			if (typeof console != "undefined" && typeof console.debug != "undefined") {
				console.log(s);
			} else {
				//alert(s);
			}
		};
		
		/*resetDrag = function(){
			$("#scrolling-wrapper").removeOverscroll();
			$("#scrolling-wrapper").overscroll({
				showThumbs: false,
				scrollDelta: 20
			});	
		};*/
		
		resizeRoller = function(){
			
			var 	running_total = 0;

			$items.each(function(i){
				var $this = $(this),
					extra = 80;//for border
				running_total += $this.width() + parseInt($this.css('margin-right')) + extra;
			});
			
//log('resizeRoller  '+ running_total);
			
			$roller.width(running_total);
			
			//var c = constrain( $roller.width() );
			
//log('resizeRoller '+ $roller.width() +' '+$outer.width());
			
			if ( $roller.width() < $outer.width() ){
				$left.stop().fadeOut('fast');
				$right.stop().fadeOut('fast');
//log('hide nav');
			} else {
				//$left.stop().fadeIn('fast');
				$right.stop().fadeIn('fast');
			}
			if ($roller.width() == null || $outer.width() == null){
				$left.stop().fadeOut('fast');
				$right.stop().fadeOut('fast');
			}
			
			$('#container').height( $(document).height()-100 );
		};

		attachEvents = function(){		

			$left.bind('click',function(e){
				moveIt(-1);
				e.preventDefault();
			});
			
			$right.bind('click',function(e){
				moveIt(1);
				e.preventDefault();
			});
			/*
			$left.bind('dblclick',function(e){
				//move left to last first
log('dblclick');

				var first = $items.eq( 0 );
				moveToItem( first );
				
				e.preventDefault();
			});
			
			$right.bind('dblclick',function(e){
				//move right to last item
log('dblclick');
				var last = $items.eq( $items.length -1 );
				moveToItem( last );
				e.preventDefault();
			});*/
			
			/*
			$left.singleDoubleClick(
				function(e){
					moveIt(-1);
					e.preventDefault();
				},
				function(e){
					var first = $items.eq( 0 );
					moveToItem( first );
					e.preventDefault();
				});
						
			$right.singleDoubleClick(
				function(e){
					moveIt(1);
					e.preventDefault();
				},
				function(e){
					//move right to last item
					var last = $items.eq( $items.length -1 );
					moveToItem( last );
					e.preventDefault();
				});			
			*/
			
			//inner menu
			if ( $('#inner-nav').length > 0 ){
				
				$('#inner-nav').find('a').bind('click',function(e){
				
					var t = $(this).attr('rel');
			
//log('inner menu click');
//log(t);
					moveToItem( $('#'+t) );
			
					return false;
				});
			}
			
			//$items.bind('click',function(e){
				
//log('item click');
				//moveToItem( $(e.target) );
	
			//});
			
			//$roller.hoverIntent(showDragTip, hideDragTip);
			
			$(window).resize(function(){
				onResize();
			});
			
			
			$roller.hover(
				function(){
					$(this).bind('mousewheel',mousewheelHandler);
				},
				function(){
					$(this).unbind('mousewheel',mousewheelHandler);
				}
			);
		};
		
		showDragTip = function(){
			//$('#drag-tooltip').fadeIn('fast');
		};
		
		hideDragTip = function(){
			$('#drag-tooltip').fadeOut('fast');
		};
		
		onResize = function(){
			//if mobile, don't position
			if ( $('body').width() < 640 ){
				is_draggable = false;
				deactivateDraggable();
				return;
			//} else if ( $('body').width() < $roller.width() ){

			} else {

				if (!is_draggable){
					is_draggable = true;
					initDraggable();
				}
			}
		};
		
		moveToItem = function(the_item){
			
			var 	//$item = $(the_item),
				screen_width = $outer.width(),
				item_width = the_item.width(),
				from_left = (screen_width - item_width) / 2,
				item_x = the_item.position().left,
				new_left = - item_x ,//+ from_left  - 200
				speed; //item centered
				
				new_left = constrain(new_left);
				speed = (item_x - new_left)/2;
				
				
				//speed = (speed > 3000) ? 3000 : (item_x - new_left)/2 ;
				speed = (speed > 1000) ? speed : 1000 ;
				
				$roller.animate({ left :new_left}, speed, function(){ doneAnimating() });//, function(){ resetDrag(); }	
		};
		
		moveIt = function(direction){
			
			var 	new_left, 
				old_left = $roller.offset().left,
				scr_width = $outer.width() -200;
				
			new_left = (direction < 0) ? old_left += scr_width : old_left -= scr_width;
			
			new_left = constrain(new_left);

//log('moveIt '+old_left+' '+new_left);

			$roller.animate({ left :new_left}, 1000, function(){ doneAnimating() });

			//$roller.animate({ left :new_left}, 1000, function(){ resetDrag(); });	
		};
		
		doneAnimating = function(){
		
			//adjust buttons
			//var i = constrain( $roller.position().left );
			
		};
		
		constrain = function(input){
			
			var 	min_x = -$roller.width() + $outer.width(),//+ 170
				max_x = 0,
				output = input;
			
//log('constrain   '+min_x+'  '+input+'  '+max_x);
			
			if (input < min_x){
				
				$left.stop().fadeIn();
				$right.stop().fadeOut();
				output = min_x;
				
			} else if (input >= max_x){
				
				$left.stop().fadeOut();
				$right.stop().fadeIn();
				output = max_x;
				
			//} else if ( $('body').width() > $roller.width() ){
				
				
			//	$left.fadeOut();
			//	$right.fadeOut();
			} else {
			
				$left.stop().fadeIn();
				$right.stop().fadeIn();
			}
			
			
			return output;
		};
		

		initDraggable = function(){
			
			$roller.draggable({
				axis:'x',
				scroll: false,
				// start and stop. We add in the momentum functions here.
				start: function(e, ui) {
					dragMomentum.start(this.id, e.clientX, e.clientY, e.timeStamp);
				},
				stop: function(e, ui) {
					dragMomentum.end(this.id, e.clientX, e.clientY, e.timeStamp);
				}  
			});		
			
		};	
		
		deactivateDraggable = function(){
			//$roller.draggable("disable");
			$roller.draggable("destroy");
		};
		
		mousewheelHandler = function(e, delta){
		
			//$("body").mousewheel(function(e, delta) {
		    
			  // this.scrollLeft -= (delta * 30);
			   var new_left = parseInt( $roller.css('left') ) + (delta * 60);
			   
			   new_left = constrain(new_left);
			   
			   $roller.css('left', new_left );
			   
			   e.preventDefault();
			//});
		};
		
		var dragMomentum = new function () {    
		    var howMuch = 200;  // change this for greater or lesser momentum
		    var minDrift = 0; // minimum drift after a drag move
		    var easeType = 'easeOutBack';
		
		    var dXa =[0];
		    var dYa =[0];
		    var dTa =[0];
		    
		    this.start = function (elemId, Xa, Ya, Ta)  {
				dXa[elemId] = Xa;
			   dYa[elemId] = Ya;
			   dTa[elemId] = Ta;
			   
			 }; // END dragmomentum.start()
		
		    this.end = function (elemId, Xb, Yb, Tb)  {        
			   var Xa = dXa[elemId];
			   var Ya = dYa[elemId];
			   var Ta = dTa[elemId];
			   var Xc = 0;
			   var Yc = 0;
		
			   var dDist = Math.sqrt(Math.pow(Xa-Xb, 2) + Math.pow(Ya-Yb, 2));
			   var dTime = Tb - Ta;
			   var dSpeed = dDist / dTime;
			   dSpeed = Math.round(dSpeed*100)/100;
		
			   var distX =  Math.abs(Xa - Xb);
			   var distY =  Math.abs(Ya - Yb);
		
			   var dVelX = (minDrift+(Math.round(distX*dSpeed*howMuch / (distX+distY))));
			   var dVelY = (minDrift+(Math.round(distY*dSpeed*howMuch / (distX+distY))));
		
			   var position = $('#'+elemId).position();
			   var locX = position.left;
			   var locY = position.top;
			   
			   if ( Xa > Xb ){  // we are moving left
				  Xc = locX - dVelX;
			   } else {  //  we are moving right
				  Xc = locX + dVelX;
			   }
		    
			   if ( Ya > Yb ){  // we are moving up
				  Yc = (locY - dVelY);
			   } else {  // we are moving down
				  Yc = (locY + dVelY);
			   }
			   
			   if (Xc == undefined){ Xc = 0; }//jk
			   
			   var newLocX = constrain(Xc) + 'px';//jk
			   var newLocY = Yc + 'px';
//log('!!!!!'+newLocX);
			   $('#'+elemId).animate({ left: newLocX }, 700, easeType );//, top:newLocY
		
		    }; // END  dragmomentum.end()
		
		};  // END dragMomentum
		
		init();
	};
})(jQuery);


/*
 * jQuery UI Touch Punch 0.2.2
 *
 * Copyright 2011, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Depends:
 *  jquery.ui.widget.js
 *  jquery.ui.mouse.js
 */
(function(b){b.support.touch="ontouchend" in document;if(!b.support.touch){return;}var c=b.ui.mouse.prototype,e=c._mouseInit,a;function d(g,h){if(g.originalEvent.touches.length>1){return;}g.preventDefault();var i=g.originalEvent.changedTouches[0],f=document.createEvent("MouseEvents");f.initMouseEvent(h,true,true,window,1,i.screenX,i.screenY,i.clientX,i.clientY,false,false,false,false,0,null);g.target.dispatchEvent(f);}c._touchStart=function(g){var f=this;if(a||!f._mouseCapture(g.originalEvent.changedTouches[0])){return;}a=true;f._touchMoved=false;d(g,"mouseover");d(g,"mousemove");d(g,"mousedown");};c._touchMove=function(f){if(!a){return;}this._touchMoved=true;d(f,"mousemove");};c._touchEnd=function(f){if(!a){return;}d(f,"mouseup");d(f,"mouseout");if(!this._touchMoved){d(f,"click");}a=false;};c._mouseInit=function(){var f=this;f.element.bind("touchstart",b.proxy(f,"_touchStart")).bind("touchmove",b.proxy(f,"_touchMove")).bind("touchend",b.proxy(f,"_touchEnd"));e.call(f);};})(jQuery);


/* Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * Version: 3.0.2
 * 
 * Requires: 1.2.2+
 */
(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(f){var d=[].slice.call(arguments,1),g=0,e=true;f=c.event.fix(f||window.event);f.type="mousewheel";if(f.wheelDelta){g=f.wheelDelta/120}if(f.detail){g=-f.detail/3}d.unshift(f,g);return c.event.handle.apply(this,d)}})(jQuery);
