/**
 *								scrollbarHeight	-	The height of the generated scrollbar in pixels
 *								scrollbarMargin	-	The amount of space to leave on the side of the scrollbar in pixels
 *								wheelSpeed		-	The speed the pane will scroll in response to the mouse wheel in pixels
 *								animateTo		-	Whether to animate when calling scrollTo and scrollBy
 *								animateInterval	-	The interval in milliseconds to update an animating scrollHorizontalPane (default 100)
 *								animateStep		-	The amount to divide the remaining scroll distance by when animating (default 3)
 * 								minimumWidth    - 	The minimum width to allow the jScrollHorizontalPane to be resized to.  Only effective when resize is on.
 * 								reset			-	When set to 'true' all the global properties will be reset.  This is useful for dynamic refreshes on the page.
 * @return jQuery
 * @cat Plugins/jScrollHorizontalPane
 * @author Threeformed Media ( www.threeformed.com, info@threeformed.com )
 * @version 1.0.0
 */

var _jscr_originalSizes = new Array();
var _jscr_differenceSizes = new Array();
var _jscr_previousWindowSize = new Array();
var _jscr_originalPercentages = new Array();
var _jscr_intervals = new Array();
var _jscr_trackInt = new Array();
var _jscr_originalPos = new Array();
var _jscr_globalProperties = new Array();

var contentObject;
var contentWidth = 0;

jQuery.jScrollHorizontalPane = {
	active : []
};

jQuery.fn.jScrollHorizontalPane = function(settings)
{
	settings = jQuery.extend(
		{
			scrollbarHeight : 10,
			scrollbarMargin : 5,
			wheelSpeed : 18,
			animateTo : false,
			animateInterval : 100,
			animateStep: 3,
			minimumWidth: 846,
			reset: true
		}, settings
	);
	
	return this.each(
		function()
		{
			if(settings.reset == true) {
				jQuery.fn.jScrollHorizontalPane.reset();
			}
			
			//This holds each one of the intervals, defaulting with one at the beginning.
			var $this = jQuery(this);			
			var mouseWheelNext = 0;
			var mouseWheelMove = false;
			var currentId = $this.attr('id');
			
			if(currentId == undefined) {
				currentId = $this.attr('class');
			}
			
			var previousWindow = _jscr_previousWindowSize[currentId];
			_jscr_originalPos[currentId] = -1;
			_jscr_globalProperties[currentId] = settings;
			_jscr_previousWindowSize[currentId] = $(window).width();

			//On initial load, set values needed for percentage resizing.
			if(_jscr_originalSizes[currentId] == undefined) {		

				//ie6 hack, since jquery width doesnt get the right value on an inproper refresh
				if((jQuery.browser.msie) && (parseInt(jQuery.browser.version) == 6)) {
					var outerWidth = parseInt($this.outerWidth()) - parseInt($this.offset().left);
					_jscr_differenceSizes[currentId] = $this.offset().left / $(window).width();
				} else {
					var outerWidth = $this.outerWidth();
					_jscr_differenceSizes[currentId] = $this.position().left / $(window).width();
				}

				percentageWidth = (outerWidth / $(window).width());			
				_jscr_originalPercentages[currentId] = percentageWidth;
				_jscr_originalSizes[currentId] = $(window).width();
			} else { 
				percentageWidth = _jscr_originalPercentages[currentId];
				diff = _jscr_differenceSizes[currentId] - (($this.offset().left + _jscr_originalPos[currentId])/ $(window).width());
				percentageWidth = percentageWidth + diff;
			}

			var halfIntervals = new Array();
			_jscr_intervals = new Array();
			halfIntervals[0] = 0;
			_jscr_intervals[0] = 0;
			margin = $this.position().left;
			offset = 1;
			
			if(margin < 0) {
				margin = 0;
			}

			if(_jscr_intervals.length <= 1) { 
				_jscr_intervals = new Array();
			}

			var currentScrollPosition = 0;
			this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
			this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
			var paneWidth = $this.outerWidth();
			var rightPos = $this.offset().left + _jscr_originalPos[currentId] + paneWidth;

			if((rightPos) > $(window).width()) { 
				paneWidth = $(window).width() *  percentageWidth; 
			}
			
			if(paneWidth < settings.minimumWidth){
				paneWidth = settings.minimumWidth;
			}
				
			var paneHeight = $this.innerHeight();
			var trackWidth = paneWidth;
			
			$this.wrap(
				jQuery('<div></div>').attr(
					{'className':'jScrollPaneContainer'}
				).css(
					{
						'height':paneHeight+'px', 
						'width':paneWidth+'px'
					}
				)
			);

			var p = this.originalSidePaddingTotal;
			
			$this.css(
				{
					'height': paneHeight - settings.scrollbarHeight - p + 'px',
					'width': 'auto',
					'paddingRight':settings.scrollbarMargin + 'px'
				}
			);

			contentObject = $this;
			contentWidth = contentObject.outerWidth();
			
			//ie6 and 7, outside width does not always guarantee the full size of the div
			//is returned for outerWidth
			if($.browser.msie || $.browser.opera || $.browser.safari) {
				var ieWidth = 0;
				$this.children().each(function(i, elem) { if($(elem).outerWidth() > ieWidth) { ieWidth = $(elem).outerWidth();}});
				if(ieWidth > contentWidth) {
					contentWidth = ieWidth;
				}				
			}

			var percentInView = paneWidth / contentWidth;
			var trackIntervals = new Array();

			if (percentInView < 0.99) {
				var $container = $this.parent();

				$container.append(
					jQuery('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'height':settings.scrollbarHeight+'px'}).append(
						jQuery('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'height':settings.scrollbarHeight+'px'}).append(
							jQuery('<div></div>').attr({'className':'jScrollPaneDragLeft'}).css({'height':settings.scrollbarHeight+'px'}),
							jQuery('<div></div>').attr({'className':'jScrollPaneDragCenter'}).css({'height':settings.scrollbarHeight+'px'}).append(
								jQuery('<div></div>').attr({'className':'jScrollPaneDragCenterLine'}).css({'height':settings.scrollbarHeight+'px'})),
							jQuery('<div></div>').attr({'className':'jScrollPaneDragRight'}).css({'height':settings.scrollbarHeight+'px'})
						)
					)
				);
				
				var $track = jQuery('>.jScrollPaneTrack', $container);

				var $drag = jQuery('>.jScrollPaneTrack .jScrollPaneDrag', $container);
				
				var $pane = jQuery(this).css({'position':'absolute', 'overflow':'visible'});
				
				var currentOffset;
				var maxX;
				var mouseWheelMultiplier;
				
				// store this in a seperate variable so we can keep track more accurately than just updating the css property..
				var dragPosition = 0;
				var dragMiddle = percentInView*paneWidth/2;
				
				// pos function borrowed from tooltip plugin and adapted...
				var getPos = function (event, c) {
					var p = c == 'X' ? 'Left' : 'Bottom';
					return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
				};
				
				var ignoreNativeDrag = function() {	return false; };
				var currentInterval = 0;
				var direction = 1;
				var intervalMove = false;
				_jscr_trackInt[currentId] = -1;;

				var initDrag = function()
				{
					ceaseAnimation();
					currentOffset = $drag.offset(false);
					currentOffset.left -= dragPosition;
					maxX = trackWidth - $drag[0].offsetWidth;
					mouseWheelMultiplier = 2 * settings.wheelSpeed * maxX / contentWidth;
				};
				
				var onStartDrag = function(event)
				{
					initDrag();
					dragMiddle = getPos(event, 'X') - dragPosition - currentOffset.left;
					jQuery('body').bind('mouseup', onStopDrag).bind('mousemove', updateScroll);
					if (jQuery.browser.msie) {
						jQuery('body').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
					}
					return false;
				};
				var onStopDrag = function()
				{
					jQuery('body').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
					dragMiddle = percentInView*paneWidth/2;
					moveIntervals();
					
					if (jQuery.browser.msie) {
						jQuery('body').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
					}
				};
				var positionDrag = function(destX)
				{
					//Figure out if we need to adjust because of intervals.
					evaluateIntervals(dragPosition, destX);
					destX = destX < 0 ? 0 : (destX > maxX ? maxX : destX);
					dragPosition = destX;

					$drag.css({'left':destX +'px'});
					var p = destX / maxX;
					_jscr_originalPos[currentId] = (paneWidth-contentWidth) * p * -1;
					$pane.css({'left':((paneWidth-contentWidth)*p) + 'px'});
					$this.trigger('scroll');
				};
				
				var updateScroll = function(e)
				{
					positionDrag(getPos(e, 'X') - currentOffset.left - dragMiddle);
				};
				
				var evaluateIntervals = function(position, destX) { 
	
					if((intervalMove == false) && (mouseWheelMove != true)) { 
							_jscr_trackInt[currentId] = -1;
							halfInter = -1;
							
							smallInter = -1;
							bigInter = -1;
							
							endDragPos = destX + $drag.width();
							fullTrackWidth = $('.jScrollPaneTrack').width();

							for(inter in trackIntervals) { 
								if((endDragPos >= fullTrackWidth) && (endDragPos >= trackIntervals[inter])) {
									_jscr_trackInt[currentId] = inter;
								} else if(destX >= trackIntervals[inter]) {
									smallInter = inter;
								}	else { 
									bigInter = inter;
									break;
								}
								
							}

							if(_jscr_trackInt[currentId] == -1) {
								smallDistance = destX - trackIntervals[smallInter];
								largeDistance = trackIntervals[bigInter] - destX;
								
								if(smallDistance <= largeDistance) {
									_jscr_trackInt[currentId] = smallInter;
								} else { 
									_jscr_trackInt[currentId] = bigInter;
								}
							}
					} else { 
						intervalMove = false;
					}
	
				}
				
				var moveIntervals = function() { 
					if(_jscr_trackInt[currentId] != -1) { 
						intervalMove = true;
						positionDrag(trackIntervals[_jscr_trackInt[currentId]]);
						currentInterval = _jscr_trackInt[currentId];
					}
				}

				var dragH = percentInView*(paneWidth);
				
				$drag.css(
					{'width':dragH+'px'}
				).bind('mousedown', onStartDrag);

				$('.jScrollPaneDragCenter').width((dragH-($('.jScrollPaneDragRight').width()+$('.jScrollPaneDragLeft').width()))+'px');
				$('.jScrollPaneDragCenterLine').width((dragH-($('.jScrollPaneDragRight').width()+$('.jScrollPaneDragLeft').width()))+'px');

				var trackScrollInterval;
				var trackScrollInc;
				var trackScrollMousePos;
				var doTrackScroll = function()
				{
					if (trackScrollInc > 8 || trackScrollInc%4==0) {
						var destPosition = -(dragPosition - ((dragPosition - trackScrollMousePos)))*(paneWidth-contentWidth) / maxX;
						scrollTo(destPosition);
					}
					trackScrollInc ++;
				};
				var onStopTrackClick = function()
				{
					clearInterval(trackScrollInterval);
					moveIntervals();
					jQuery('body').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
				};
				var onTrackMouseMove = function(event)
				{
					trackScrollMousePos = getPos(event, 'X') - currentOffset.left - dragMiddle;
				};
				var onTrackClick = function(event)
				{
					initDrag();
					onTrackMouseMove(event);
					trackScrollInc = 0;
					jQuery('body').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
					//trackScrollInterval = setInterval(doTrackScroll, 100);
					doTrackScroll();
				};
				
				$track.bind('mousedown', onTrackClick);
				
				// if the mousewheel plugin has been included then also react to the mousewheel
				if ($container.mousewheel) {

					$container.mousewheel (
						function (event, delta) {
							var movePos = -1;
							
							if($.browser.opera) {
								delta = event.wheelDelta / 120;	
							}

							//The following handles intervals with the mouse wheel
							if(trackIntervals.length > 1) {
								mouseWheelMove = true;
										
								//increase or decrease the interval we are currently on, depending
								//on the direction of the mouse wheel
								if(delta < 0) {
									_jscr_trackInt[currentId] = parseInt(_jscr_trackInt[currentId]) + 1;

									if((_jscr_trackInt[currentId]) >= trackIntervals.length - 1) {
										_jscr_trackInt[currentId] = trackIntervals.length - 1;
									}
									
									//If the next interval is beyond the dragWidth then recalculate.
									if((parseInt($drag.width())+ parseInt(trackIntervals[_jscr_trackInt[currentId]])) > parseInt($('.jScrollPaneTrack').width())) {
										movePos = parseInt($('.jScrollPaneTrack').width()) - $drag.width();
									}
									
								} else { 
									_jscr_trackInt[currentId] = parseInt(_jscr_trackInt[currentId]) - 1;
									if(_jscr_trackInt[currentId] < 0) {
										_jscr_trackInt[currentId] = 0;
									}
								}
							}

							initDrag();
							ceaseAnimation();
							var d = dragPosition;
							
							//when intervals are in use, mouseWheelMove is set to true
							/*if(mouseWheelMove == true) {
								if(movePos == -1) {
									positionDrag(trackIntervals[_jscr_trackInt[currentId]]);
								} else {
									positionDrag(movePos);
								}
							} else {
								positionDrag(dragPosition - delta * mouseWheelMultiplier);
							}*/
							$this[0].scrollBy(287 * -delta);
							
							moveIntervals();
							var dragOccured = d != dragPosition;
							mouseWheelMove = false;
							return !dragOccured;
						},
						false
					);					
				}
				var _animateToPosition;
				var _animateToInterval;
				function animateToPosition()
				{

					var diff = (_animateToPosition - dragPosition) / settings.animateStep;
					
					if ((diff > 1 || diff < -1) && ((dragPosition + diff + $drag.width()) < (paneWidth))) {
						positionDrag(dragPosition + diff);
					} else {
						positionDrag(_animateToPosition);
						ceaseAnimation();
					}
				}
				var ceaseAnimation = function()
				{
					if (_animateToInterval) {
						clearInterval(_animateToInterval);
						delete _animateToPosition;
					}
				};
				var scrollTo = function(pos, preventAni)
				{
					if (typeof pos == "string") {
						$e = jQuery(pos, this);

						if (!$e.length) return;
						pos = $e.position().left;
					}

					ceaseAnimation();
					var destDragPosition = -pos/(paneWidth-contentWidth) * maxX;
					if (!preventAni || settings.animateTo) {
						_animateToPosition = destDragPosition;
						_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
		
					} else {
						positionDrag(destDragPosition);
					}	
				};
				$this[0].scrollTo = scrollTo;
				
				$this[0].scrollBy = function(delta)
				{
					var currentPos = -parseInt($pane.css('left')) || 0;
					scrollTo(currentPos + delta);
				};
				
				initDrag();
				
				scrollTo(-currentScrollPosition, true);
				
				jQuery.jScrollHorizontalPane.active.push($this[0]);

			} else {
				var scrollTo = function(pos, preventAni) {}
				$this[0].scrollTo = scrollTo;
				
				$this.css(
					{
						'height':paneHeight-this.originalSidePaddingTotal+'px',
						'width': paneWidth+'px',
						'padding':this.originalPadding
					}
				);
				// remove from active list?
			}
			
		}
	)
};

jQuery.fn.jScrollHorizontalPane.reset = function() {
	/*_jscr_originalSizes = new Array();
	_jscr_differenceSizes = new Array();
	_jscr_previousWindowSize = new Array();
	_jscr_originalPercentages = new Array();
	_jscr_intervals = new Array();
	_jscr_trackInt = new Array();
	_jscr_originalPos = new Array();
	_jscr_globalProperties = new Array();*/

	if (contentObject) contentWidth = contentObject.outerWidth();
}

// clean up the scrollTo expandos
jQuery(window)
	.bind('unload', function() {
		var els = jQuery.jScrollHorizontalPane.active;
		for (var i=0; i<els.length; i++) {
			els[i].scrollTo = els[i].scrollBy = null;
		}
	}
);