/*	
 *	jQuery jdragger
 *	Created by Stuart Mackie - http://www.stu-cms.com
*/
(function($) {
	$.fn.jdragger = function(options) {
		return this.each(function() {	
			var opts 			= $.extend({}, $.fn.jdragger.defaults, options);
			var $ul 			= $(this);
			var $items 			= $("li", $ul);
			var totalItems		= $items.length;
			var firstItem		= totalItems-1;
			var onPause		= 0;
			var itemWidth		= 0;
			var itemHeight		= 0;
			var active		= 0;
			var isDragging		= 0;
                        var posArray            = new Array();
			var unique		= Math.floor(Math.random()*1001);
			  
			for(var a = 0; a < $items.length; a++)
			{
				$($items[a]).css("display","block");
				$($items[a]).css("list-style", "none none inside");
				$($items[a]).css("margin",0);
				$($items[a]).css("padding",0);
                                $($items[a]).css("float","left");
                                $($items[a]).css("width",parseInt($($items[a]).width()));
                                
                                if(opts.dragging==1)
                                {
                                    posArray[a] = itemWidth+parseInt($($items[a]).width(),10);
                                }
                                
				itemWidth = itemWidth+parseInt($($items[a]).width(),10);
				
				if(parseInt($($items[a]).height())>itemHeight){
					itemHeight = parseInt($($items[a]).height(),10);
				}
			}
			
			$ul
				.bind("pause", function() {
					onPause = 1;
				})
				.bind("play", function() {
					onPause = 0;
				})
				.css({
					top: 0,
					left: 0,
					position: 'relative'
				}).bind("next", function(){
                            if((active+opts.visibleItems)<$items.length){
                                    $ul.animate({"left": "-="+(parseInt($($items[active]).width()))+"px"}, opts.scrollSpeed);
                                    active++;
                            } else {
                                    var leftPos = (parseInt($ul.css('left'))*-1);
                                    var end = (parseInt($('.jdragger_wrapper'+unique).width())-$ul.parent().parent().width());
                                    if(leftPos>=end)
                                    {
                                        $ul.animate({"left": "+="+(parseInt($ul.css('left'))*-1)+"px"}, opts.scrollSpeed);
                                        active=0;
                                    } else {
                                        var end = (parseInt($ul.css('left'))+parseInt($('.jdragger_wrapper'+unique).width())-$ul.parent().parent().width());
                                        $ul.animate({"left": "-="+end+"px"}, opts.scrollSpeed);
                                    }
                            }
                        }).bind("prev",function(){
                            if(active>0){
                                    var leftPos = (parseInt($ul.css('left'))*-1);
                                    var end = (parseInt($('.jdragger_wrapper'+unique).width())-$ul.parent().parent().width());
                                    if(leftPos>=end)
                                    {
                                            var leftPosition = parseInt($ul.css('left'))*-1;
                                            var leftSide = (posArray[$items.length-opts.visibleItems-1]-leftPosition)*-1;
                                            if(leftSide>0){
                                                    $ul.animate({"left": "+="+leftSide+"px"}, opts.scrollSpeed);
                                                    active = $items.length-opts.visibleItems;
                                            } else {
                                                    $ul.animate({"left": "+="+(parseInt($($items[active-1]).width()))+"px"}, opts.scrollSpeed);
                                                    active--;
                                            }
                                    } else {
                                            $ul.animate({"left": "+="+(parseInt($($items[active-1]).width()))+"px"}, opts.scrollSpeed);
                                            active--;
                                    }
                            } else {
                                    var leftPosition = parseInt($ul.css('left'))*-1;
                                    var leftSide = ((posArray[$items.length-opts.visibleItems-1]-leftPosition)*-1);
                                    
                                    $ul.animate({"left": "+="+leftSide+"px"}, opts.scrollSpeed);
                                    active = $items.length-opts.visibleItems;
                            }
                        }).wrap('<div class="jdragger_wrapper'+unique+'" />');
			$('.jdragger_wrapper'+unique).css({ 
				width		: itemWidth+"px",
				height		: itemHeight+"px",
				position	: "relative",
                                padding         : 0,
                                margin          : 0
			})
                        
                        
                        $(this).css('padding',0);
                        $(this).css('margin',0);			
			
			$ul.parent().parent().css('overflow','hidden');
                        $ul.parent().parent().css('position','relative');
			
			
			if ($.browser.msie && $.browser.version.substr(0,1)<7)
			{
				$ul.css('height',itemHeight);
			}
			
			if(opts.visibleItems==0){
				var visibleArea = parseInt($ul.parent().parent().width());
				var pixels = 0;
				for(var a = 0; a < $items.length; a++)
				{
					pixels = pixels+parseInt($($items[a]).width())
					if(pixels<=visibleArea)
					{
						opts.visibleItems++;
					}
				}
			}

			if (opts.next != null || opts.prev != null) {
				if (opts.next != null) {
					opts.next.click(function() {
					    $ul.trigger("next");
					});
				}
				if (opts.prev != null) {
					opts.prev.click(function() {
					    $ul.trigger("prev");
					});
				}
			}
                        
                        if(opts.timeout>0)
                        {
                            t = setInterval(function() {
                                if(opts.pauseOnHover){
                                    $ul.trigger("next");
                                } else {
					if(onPause==0 && isDragging==0){
						$ul.trigger("next");
					}
				}      
                            }, opts.timeout);
                        }
                        
                        $ul.parent().parent().bind('mouseover', function(){
                            $ul.trigger("pause");
                        }).bind('mouseout', function(){
                            $ul.trigger("play");
                        });
                        
                        if(opts.dragging==1)
                        {
				$ul.easydrag();
				$ul.ondrag(function(){
					isDragging = 1;
				});
				$ul.ondrop(function(e, element){
				     isDragging = 0;
				     var leftPosition = parseInt($ul.css('left'))*-1;
				     var animated = 0;
				     for(var a = 0; a < $items.length-opts.visibleItems; a++)
				     {
					 if(leftPosition>posArray[a-1]&&leftPosition<posArray[a])
					 {
					     var leftSide = leftPosition-posArray[a-1];
					     var rightSide = posArray[a]-leftPosition;
					     
					     if(leftSide>rightSide){
						 $ul.animate({"left": "-="+rightSide+"px"}, opts.scrollSpeed);
						 active=a+1;
						 animated = 1;
					     } else {
						 $ul.animate({"left": "+="+leftSide+"px"}, opts.scrollSpeed);
						 active=a;
						 animated = 1;
					     }
					 }
				     }
				     
				     if(animated==0){
					 if(leftPosition>posArray[0])
					 {
					     var leftPosition = parseInt($ul.css('left'))*-1;
					     var leftSide = (posArray[$items.length-opts.visibleItems-1]-leftPosition)*-1;
					     
					     $ul.animate({"left": "+="+leftSide+"px"}, opts.scrollSpeed);
					     active = $items.length-opts.visibleItems;
					 } else {
					     var leftSide = leftPosition-0;
					     var rightSide = posArray[0]-leftPosition;
					     
					     if(leftSide>rightSide){
						     $ul.animate({"left": "-="+rightSide+"px"}, opts.scrollSpeed);
						     active=1;
					     } else {
						     $ul.animate({"left": "+="+leftSide+"px"}, opts.scrollSpeed);
						     active = 0;
					     }
					 }
				     }
				});
			   
                        }
			
			});
	}
	$.fn.jdragger.defaults = {
		visibleItems	: 0,
		scrollSpeed		: "slow",
		next			: null,
		prev			: null,
		pauseOnHover	: false,
                dragging  :   1,
                timeout :   0,
		reloaded : 0
	}
})(jQuery);

(function($){

	// to track if the mouse button is pressed
	var isMouseDown    = false;

	// to track the current element being dragged
	var currentElement = null;

	// callback holders
	var dropCallbacks = {};
	var dragCallbacks = {};

	// global position records
	var lastMouseX;
	var lastMouseY;
	var lastElemTop;
	var lastElemLeft;
	
	// track element dragStatus
	var dragStatus = {};	

	// returns the mouse (cursor) current position
	$.getMousePosition = function(e){
		var posx = 0;
		var posy = 0;

		if (!e) var e = window.event;

		if (e.pageX || e.pageY) {
			posx = e.pageX;
			posy = e.pageY;
		}
		else if (e.clientX || e.clientY) {
			posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
			posy = e.clientY + document.body.scrollTop  + document.documentElement.scrollTop;
		}

		return { 'x': posx, 'y': posy };
	};

	// updates the position of the current element being dragged
	$.updatePosition = function(e) {
		var pos = $.getMousePosition(e);

		var spanX = (pos.x - lastMouseX);
		var spanY = (pos.y - lastMouseY);

		//$(currentElement).css("top",  (lastElemTop + spanY));
		$(currentElement).css("left", (lastElemLeft + spanX));
	};

	// when the mouse is moved while the mouse button is pressed
	$(document).mousemove(function(e){
		if(isMouseDown && dragStatus[currentElement.id] == 'on'){
			// update the position and call the registered function
			$.updatePosition(e);
			if(dragCallbacks[currentElement.id] != undefined){
				dragCallbacks[currentElement.id](e, currentElement);
			}

			return false;
		}
	});

	// when the mouse button is released
	$(document).mouseup(function(e){
		if(isMouseDown && dragStatus[currentElement.id] == 'on'){
			isMouseDown = false;
			if(dropCallbacks[currentElement.id] != undefined){
				dropCallbacks[currentElement.id](e, currentElement);
			}

			return false;
		}
	});

	// register the function to be called while an element is being dragged
	$.fn.ondrag = function(callback){
		return this.each(function(){
			dragCallbacks[this.id] = callback;
		});
	};

	// register the function to be called when an element is dropped
	$.fn.ondrop = function(callback){
		return this.each(function(){
			dropCallbacks[this.id] = callback;
		});
	};
	
	// stop the element dragging feature
	$.fn.dragOff = function(){
		return this.each(function(){
			dragStatus[this.id] = 'off';
		});
	};
	
	
	$.fn.dragOn = function(){
		return this.each(function(){
			dragStatus[this.id] = 'on';
		});
	};

	// set an element as draggable - allowBubbling enables/disables event bubbling
	$.fn.easydrag = function(allowBubbling){

		return this.each(function(){

			// if no id is defined assign a unique one
			if(undefined == this.id || !this.id.length) this.id = "easydrag"+(new Date().getTime());

			// set dragStatus 
			dragStatus[this.id] = "on";
			
			// change the mouse pointer
			$(this).css("cursor", "move");

			// when an element receives a mouse press
			$(this).mousedown(function(e){

				// set it as absolute positioned
				//$(this).css("position", "absolute");

				// set z-index
				//$(this).css("z-index", "10000");

				// update track variables
				isMouseDown    = true;
				currentElement = this;

				// retrieve positioning properties
				var pos    = $.getMousePosition(e);
				lastMouseX = pos.x;
				lastMouseY = pos.y;

				lastElemTop  = this.offsetTop;
				lastElemLeft = this.offsetLeft;

				$.updatePosition(e);

				return allowBubbling ? true : false;
			});
		});
	};

})(jQuery);
