/*!
 * Overscroll v1.3.0
 *  A jQuery Plugin for emulating the iPhone scrolling experience in a browser.
 *  http://azoffdesign.com/overscroll
 *
 * Intended for use with the latest jQuery
 *  http://code.jquery.com/jquery-latest.min.js
 *
 * Copyright 2010, Jonathan Azoff
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *  http://jquery.org/license
 *
 * Date: Wednesday, March 31st 2010
 */

/* 
 * Usage:
 * 
 * $(selector).overscroll([options]);
 *  "options" is an optional JavaScript object that you may pass if you would like to customize
 *  the experience of the overscroll element. Below is a list of properties that you may set on
 *  the options object and their respective effect:
 *   - options.showThumbs   {Boolean} Designates whether or not to show the scroll-bar thumbs
 *                                    on the scrollable container (default true).
 *   - options.openedCursor {String}  A url pointing at a .cur file to be used as the cursor when
 *                                    hovering over the overscrolled element (default 'opened.cur').
 *   - options.closedCursor {String}  A url pointing at a .cur file to be used as the cursor when
 *                                    dragging the overscrolled element (default 'closed.cur').
 *
 * Notes:
 * 
 * In order to get the most out of this plugin, make sure to only apply it to parent elements 
 * that are smaller than the collective width and/or height then their children. This way,
 * you can see the actual scroll effect as you pan the element.
 *
 * You MUST have two cursors to get the "hand" to show up, open, and close during the panning 
 * process. You can store the cursors wherever you want, just make sure to reference them in 
 * the code below. I have provided initial static linkages to these cursors for your 
 * convenience.        
 *
 * Changelog:
 *
 * 1.3.0
 *   - Merged iThumbs and Overscroll
 *   - Added the ability to pass in options
 *   - Moved all code to GitHub
 *   - Several improvements to the thumb code
 *   - Greased up the scroll a bit more
 *   - Removed the jerky animation on mouse wheel
 *   - Added caching for cursors
 * 1.2.1
 *   - Made "smart" click support "smarter" :)
 *   - Added JSLint validation to the build process
 *	 - Removed unused variables and cleaned up code
 * 1.2.0
 *   - Updated license to match the jQuery license (thanks Jesse)
 *   - Added vertical scroll wheel support (thanks Pwakman)
 *   - Added support to ignore proprietary drag events (thanks Raphael)
 *   - Added "smart" click support for clickable elements (thanks Mark)
 * 1.1.2
 *   - Added the correct click handling to the scroll operation (thanks Evilc)
 * 1.1.1
 *   - Made scroll a bit smoother (thanks Nick)
 * 1.1.0
 *   - Optimized scrolling-internals so that it is both smoother and more memory efficient 
 *     (relies entirely on event model now). 
 *   - Added the ability to scroll horizontally (if the overscrolled element has wider children).
 * 1.0.3
 *   - Extended the easing object, as opposed to the $ object (thanks Andre)
 * 1.0.2
 *   - Fixed timer to actually return milliseconds (thanks Don)
 * 1.0.1
 *   - Fixed bug with interactive elements and made scrolling smoother (thanks Paul and Aktar)
 */

/*jslint onevar: true, strict: true */
/*global jQuery: false */
"use strict"; 

(function($, o){

	// create overscroll
	o = $.fn.thumbscroll = function(options) {
		return this.each(function(){
			o.init($(this), options);
		});
	};
	
	$.extend(o, {
		
		// events handled by overscroll
		events: {
			wheel: "mousewheel DOMMouseScroll",
			start: "select mousedown touchstart",
			drag: "mousemove touchmove",
			end: "mouseup mouseleave touchend",
			scroll: "scroll",
			ignored: "dragstart drag",
			click :  "click"
		},
		
		// to save a couble bits
		div: "<div/>",
		
		// constants used to tune scrollability and thumbs
		constants: {
			scrollDuration: 400,
			captureThreshold: 4,
			wheelDeltaMod: -18,
			scrollDeltaMod: 5.7,
			thumbThickness: 8,
			thumbOpacity: 0.7,
			boundingBox: 1000000,
			thumbnailsBorder: 0
		},
		
		globals: {
			currentArrayIndex:0,
			thumbnailsGroupToSwitch:0,
			scollableThumbnails: null,
			bufferThumbnails:null,
			scrollArrow:0
			
		},
		
		// main initialization function
		init: function(target, options, data) {
			target.before("<div></div>").prev().addClass("galleryContainer");
			
			var galleryContainerStyle = {
			 'width': options.imgWidth+(options.thumbnailsWidth) * options.showedThumbnailsColumn + o.constants.thumbnailsBorder*(options.showedThumbnailsColumn-1)+5+'px',
			 'height':options.imgHeight+(options.thumbnailsHeight) * options.showedThumbnailsRow +o.constants.thumbnailsBorder * (options.showedThumbnailsRow-1)+5+'px', 
			 'margin': 'auto'
			 };
			
			var scrollStyle = {'width': (options.thumbnailsWidth) * options.showedThumbnailsColumn + o.constants.thumbnailsBorder*(options.showedThumbnailsColumn-1) +'px',
			 'height': (options.thumbnailsHeight) * options.showedThumbnailsRow +o.constants.thumbnailsBorder * (options.showedThumbnailsRow-1)+'px', 
			 'margin': 'auto',
			 'position': 'relative'};
            
            var scrollPicsStyle = {'width': (options.thumbnailsWidth+o.constants.thumbnailsBorder) * options.showedThumbnailsColumn * 3+'px',
			 'height': (options.thumbnailsHeight) * options.showedThumbnailsRow +o.constants.thumbnailsBorder*(options.showedThumbnailsRow-1)+'px',
			 'position': 'relative',
			 'clear': 'both'};
            
           	var picsDivStyle = {'float': 'left',
			 'width': (options.thumbnailsWidth+o.constants.thumbnailsBorder) * options.showedThumbnailsColumn +'px',
			 'height':(options.thumbnailsHeight)* options.showedThumbnailsRow +o.constants.thumbnailsBorder*(options.showedThumbnailsRow-1)+'px',
			 'margin': '0px'};
			
			var thumbnailsContainerStyle = {'float': 'left',
			 'width':options.thumbnailsWidth +'px',
			 'height': options.thumbnailsHeight+'px',
			 'margin': '0px', 
			 'border-bottom': 'solid '+o.constants.thumbnailsBorder+'px gray',
			 'border-right': 'solid '+o.constants.thumbnailsBorder+'px gray',
			 'background-repeat': 'no-repeat',
			 'background-position': 'center center'
			};
			
			var thumbsWithoutBottomBorderStyle={
				'border-bottom': 'solid 0px gray'
			}
			
			var galleryStyle = {'float': 'left',
			 'width':options.imgWidth +'px',
			 'height': options.imgHeight+'px',
			 'margin': '0px'};
			 
			 
			o.globals.captionStart = "" +
				"<span class=\"caption\">" +
				"<span class=\"socialnet\">" +
				"<img onclick=\"animateSN(this);return false;\" class=\"folpetto\" src=\"" + options.themeBaseUrl + "/images/scroll_gallery/folpetto.png\" border=\"0\" alt=\"logo\" /><br />" +
				
				
				//"<a  onClick=\"window.open('http://www.facebook.com/sharer.php?u={imageLoaded}&t={title}','name', 'width=620, height=440')\"><img width=\"24\" height=\"24\" class=\"sn-facebook\" src=\"" + options.themeBaseUrl + "/images/custom_bcom/FaceBook-icon.png\" border=\"0\" alt=\"facebook\" /></a><br />" +
				//"<a  onClick=\"window.open('http://twitter.com/home?status={imageLoaded}','name', 'width=1024, height=650')\"><img width=\"24\" height=\"24\" class=\"sn-twitter\" src=\"" + options.themeBaseUrl + "/images/custom_bcom/Twitter-icon.png\" border=\"0\" alt=\"twitter\" /></a>" +
				
				
				"<a  onClick=\"window.open('http://www.facebook.com/sharer.php?u={currentPath}&t={title}','name', 'width=620, height=440')\"><img class=\"sn-facebook\" src=\"" + options.themeBaseUrl + "/images/custom_bcom/FaceBook-icon.png\" border=\"0\" alt=\"facebook\" /></a><br />" +
				"<a  onClick=\"window.open('http://twitter.com/home?status={currentPath}','name', 'width=1024, height=650')\"><img class=\"sn-twitter\" src=\"" + options.themeBaseUrl + "/images/custom_bcom/Twitter-icon.png\" border=\"0\" alt=\"twitter\" /></a>" +
				
				
				
				"</span>" +
				"<span style=\"visibility:hidden;width:" + (options.imgWidth - 20) + "px;\" onclick=\"hideCaption(this)\" class=\"content captionToHide\">";
			o.globals.captionEnd = "</span>" + 
				"<img width=\"21\" height=\"21\" style=\"top:" + (options.imgHeight - 31) + "px\" class=\"info\" onclick=\"showCaption(this)\" src=\"" + options.themeBaseUrl + "/images/custom_bcom/info.png\" border=\"0\" alt=\"info\" />" + 
				"</span>";

			
			target.addClass("scroll"); 
			
										
			
			target.append("<div></div>").children(':last').addClass("pics").addClass("showed");
			
			target.children(':last').append("<div></div>").append("<div></div>").append("<div></div>").children().addClass("thumbnailsContainer");
			
			target.after("<img src=\"/bcom30_main-theme/images/custom_bcom/dx.png\" style=\"position: relative; top: 10px; left: 200px\"/>").next().addClass("backScroll");
			
			target.after("<img style=\"position: relative; top: 10px; left: 160px\" src=\"/bcom30_main-theme/images/custom_bcom/sx.png\"/>").next().addClass("nextScroll");
			
			target.after("<div></div>").next().addClass("pics").addClass("buffer").append("<div></div>").append("<div></div>").append("<div></div>").children().addClass("thumbnailsContainer");
			
			target.before("<div class=\"tooltip\"></div>").prev().addClass("gallery");
if(options.showedThumbnailsRow * options.showedThumbnailsColumn>options.tmbArray.length){      
   $(".backScroll").hide();
   $(".nextScroll").hide();
}			
			o.globals.scollableThumbnails= $(".showed");
			o.globals.bufferThumbnails = $(".buffer").hide();
			
						
			for (k = 0; k < options.showedThumbnailsRow * options.showedThumbnailsColumn; k++) {
				if(k>=options.showedThumbnailsColumn*options.showedThumbnailsRow - options.showedThumbnailsColumn){
					o.globals.scollableThumbnails.children().append("<div class=\"thumbsWithoutBottomBorder\"></div>");
					o.globals.bufferThumbnails.children().append("<div class=\"thumbsWithoutBottomBorder\"></div>");
				}else{
					o.globals.scollableThumbnails.children().append("<div></div>");
					o.globals.bufferThumbnails.children().append("<div></div>");
				} 	
			}
			
			o.globals.scollableThumbnails.children().children().addClass("thumbnail");
			o.globals.scollableThumbnails.children().each(
				function(index) {
					$(this).children(":first").addClass("firstfirst");
					
					$(this).children().each(function(idx) {
						if (idx < options.showedThumbnailsColumn) {
							$(this).addClass("firstRow");
						}
						$(this).addClass("rowindex" + (idx % options.showedThumbnailsColumn));
					})
				}
			);
			o.globals.bufferThumbnails.children().children().addClass("thumbnail");
			o.globals.bufferThumbnails.children().children(":first").addClass("first");
	//		o.globals.bufferThumbnails.find(".first").css("");
	//		o.globals.bufferThumbnails.find(".firstOnRow").css("");
			
             for (i = 0; i < 3; i++) {
                
				var showedThumbnails = options.showedThumbnailsRow * options.showedThumbnailsColumn
				var initThumbnailsIndex = 0;
				var showedThumbnailsShift=i*showedThumbnails;
				
				for (k = 0; k < showedThumbnails; k++) {
                    var residual=options.tmbArray.length%showedThumbnails;
					
                    if (k+showedThumbnailsShift < showedThumbnails) {
                        initThumbnailsIndex = options.tmbArray.length + k  - residual;
						 if (residual==0) {
                        	initThumbnailsIndex = options.tmbArray.length + k  - showedThumbnails;
                    	}
                    }
                    else {
                        initThumbnailsIndex = k - showedThumbnails +showedThumbnailsShift;
                    }
                    
					
                    if(initThumbnailsIndex < options.tmbArray.length ){
						var imgLoaded = options.tmbArray[initThumbnailsIndex];
                    
                    	var scollableThumbnails = o.globals.scollableThumbnails[0].children[i].children[k];
			scollableThumbnails.style.backgroundImage = "url(" + imgLoaded + ")";
						scollableThumbnails.imgArrayIndex=initThumbnailsIndex;
						
                   
                    	var bufferThumbnails = o.globals.bufferThumbnails[0].children[i].children[k];
                    	bufferThumbnails.style.backgroundImage = "url(" + imgLoaded + ")";
						bufferThumbnails.imgArrayIndex=initThumbnailsIndex;
						
					}else{
						var scollableThumbnails = o.globals.scollableThumbnails[0].children[i].children[k];
                    	scollableThumbnails.style.backgroundColor = "white";
						scollableThumbnails.imgArrayIndex="undefined";
                    
                   
                    	var bufferThumbnails = o.globals.bufferThumbnails[0].children[i].children[k];
                    	bufferThumbnails.style.backgroundColor = "white";
						bufferThumbnails.imgArrayIndex="undefined";						
					}
					
                }
            }
			
			if(options.tmbArray.length%showedThumbnails==0){
				o.globals.currentArrayIndex = options.tmbArray.length -showedThumbnails;
			}else{
				o.globals.currentArrayIndex = options.tmbArray.length -options.tmbArray.length%showedThumbnails;
			}
						
											
			o.globals.currentArrayIndex += showedThumbnails*o.globals.thumbnailsGroupToSwitch;
						
							
			if (options.imageSearchIndex != 0) {
								
				var bufferThumbnails = o.globals.bufferThumbnails;
				var showedThumbnails = options.showedThumbnailsRow * options.showedThumbnailsColumn;
				var scollableThumbnails = o.globals.scollableThumbnails;
				
				o.globals.currentArrayIndex =  ((options.imageSearchIndex-(options.imageSearchIndex%showedThumbnails))/showedThumbnails-1)*showedThumbnails;
							
				if (o.globals.currentArrayIndex >= options.tmbArray.length) {
					o.globals.currentArrayIndex = 0;
				}
				if (o.globals.currentArrayIndex < 0) {
					if (options.tmbArray.length % showedThumbnails == 0) {
						o.globals.currentArrayIndex = options.tmbArray.length - showedThumbnails;
					}else {
						o.globals.currentArrayIndex = options.tmbArray.length - options.tmbArray.length % showedThumbnails;
					}
				}
								
				var arrayShift = o.globals.currentArrayIndex;
						
				for (i = 0; i < 3; i++) {
														
					var showedThumbnailsShift = i * showedThumbnails;
									
					for (k = 0; k < showedThumbnails; k++) {
								
						var modifiedIndex = k + arrayShift + showedThumbnailsShift;
						if (modifiedIndex >= options.tmbArray.length) {
							if (options.tmbArray.length % showedThumbnails == 0 && modifiedIndex < options.tmbArray.length + showedThumbnails) {
								modifiedIndex = k;
								}else 
									if (modifiedIndex >= options.tmbArray.length + showedThumbnails - options.tmbArray.length % showedThumbnails) {
										if (options.tmbArray.length % showedThumbnails == 0) {
											modifiedIndex = modifiedIndex - options.tmbArray.length;
										}
										else {
											modifiedIndex = modifiedIndex - options.tmbArray.length - (showedThumbnails - options.tmbArray.length % showedThumbnails);
										}	
									}
									else {
										var singleChild = bufferThumbnails[0].children[i].children[k];
										singleChild.style.backgroundImage = "";
										singleChild.style.backgroundColor = "white";
										singleChild.imgArrayIndex = "undefined";
									}
								}
							if (modifiedIndex < options.tmbArray.length) {
								var imgLoaded = options.tmbArray[modifiedIndex];
								var singleChild = bufferThumbnails[0].children[i].children[k];
										
								singleChild.style.backgroundImage = "url(" + imgLoaded + ")";
								singleChild.imgArrayIndex = modifiedIndex;
							}
					}
				}
					scollableThumbnails.html(bufferThumbnails.html());
					for (i = 0; i < 3; i++) {
						for (k = 0; k < showedThumbnails; k++) {
							bufferThumbnails[0].children[i].children[k];
							scollableThumbnails[0].children[i].children[k].imgArrayIndex = bufferThumbnails[0].children[i].children[k].imgArrayIndex;
						}
					}
		}
			
			$(".scroll").css(scrollStyle);
			$(".scroll .pics").css(scrollPicsStyle);
			$(".pics div").css(picsDivStyle);
			$(".thumbnailsContainer div").css(thumbnailsContainerStyle);
			$(".gallery").css(galleryStyle);

			var imgLoaded = options.imgArray[options.imageSearchIndex];
			//var currCaptionStart = o.globals.captionStart.replace(/{imageLoaded}/g, "http://www.benetton.com/" + escape(imgLoaded));
			var pathname = window.location.pathname;
			var currCaptionStart = o.globals.captionStart.replace(/{currentPath}/g, "http://www.benetton.com/" + pathname+escape("?imageIndex=" +0));
			currCaptionStart = currCaptionStart.replace(/{title}/g, "www.benetton.com");
			
			if (options.imageSearchIndex != 0) {
				$(".gallery").css({
					'backgroundImage': "url(" + options.imgArray[options.imageSearchIndex] + ")"
				});
				$(".tooltip").html(currCaptionStart + options.tooltipArray[options.imageSearchIndex] + o.globals.captionEnd);
			}else{
				$(".gallery").css({
					'backgroundImage': "url(" + options.imgArray[0] + ")"
				});
				$(".tooltip").html(currCaptionStart + options.tooltipArray[0] + o.globals.captionEnd);
			}

			
	//		$(".galleryContainer").css(galleryContainerStyle).append($(".gallery")).append($(".tooltipButton")).append($(".tooltip")).append($(".scroll")).append($(".backScroll")).append($(".nextScroll")).append($(".buffer"));
			data = {
				sizing: o.getSizing(target)
			};
			
			$(".thumbsWithoutBottomBorder").css(thumbsWithoutBottomBorderStyle);
			
			options = $.extend({
				openedCursor: options.themeBaseUrl + "/cursors/opened.cur",
				closedCursor: options.themeBaseUrl + "/cursors/	closed.cur",
				showThumbs: true,
				showedThumbnailsRow: 1,
				showedThumbnailsColumn: 1,
				imgWidth :0,
				imgHeight :0,
				thumbnailsWidth:0,
				thumbnailsHeight:0,
				imageSearchIndex:0,
				tmbArray : [],
				imgArray : [],
				tooltipArray:[]						
			}, (options || {}));
			
			
			// cache cursors
			options.cache = { openedCursor: new Image(), closedCursor: new Image() };
			options.cache.openedCursor.src = options.openedCursor;
			options.cache.closedCursor.src = options.closedCursor;
			if(options.showedThumbnailsColumn*options.showedThumbnailsRow < options.tmbArray.length){
			target.css({"cursor":"url("+options.openedCursor+"), default", "overflow": "hidden"})
				.bind(o.events.wheel, data, o.wheel)
				.bind(o.events.start, data, o.start)
				.bind(o.events.end, data, o.stop)
				.bind(o.events.ignored, function(){return false;}); // disable proprietary drag handlers
			}else{
				target.css({"overflow": "hidden"})
			}
			$(".thumbnail").bind(o.events.click,data,o.thumbnailClick);
			
			$(".backScroll").bind(o.events.click,data, function(event){
				o.globals.scrollArrow=-(options.showedThumbnailsColumn*options.thumbnailsWidth + options.showedThumbnailsColumn*o.constants.thumbnailsBorder);
				o.stop(event);
			});
			$(".nextScroll").bind(o.events.click,data, function(event){
				o.globals.scrollArrow=(options.showedThumbnailsColumn*options.thumbnailsWidth + options.showedThumbnailsColumn*o.constants.thumbnailsBorder);
				o.stop(event);
			});
			target.scrollTop(0).scrollLeft(options.showedThumbnailsColumn*options.thumbnailsWidth + options.showedThumbnailsColumn*o.constants.thumbnailsBorder);// to ensure corect initialization	
			$(".tooltip").bind(o.events.start, null, 
                        	function() {
					$(".captionToHide").each(
                                		function() {
                                        		hideCaption($(this));
                                		});
				}
                        );

			if(options.showThumbs) {
				
				data.thumbs = { visible: false };
								
				if(data.sizing.container.scrollWidth > 0) {
					data.thumbs.horizontal = $(o.div).css(o.getThumbCss(data.sizing.thumbs.horizontal)).fadeTo(0, 0);
					target.prepend(data.thumbs.horizontal);	
				}
				
				if(data.sizing.container.scrollHeight > 0) {
					data.thumbs.vertical = $(o.div).css(o.getThumbCss(data.sizing.thumbs.vertical)).fadeTo(0, 0);
					target.prepend(data.thumbs.vertical);				
				}
				
				data.sizing.relative = data.thumbs.vertical || data.thumbs.horizontal;
				
				target.scrollTop(0).scrollLeft(options.showedThumbnailsColumn*options.thumbnailsWidth + options.showedThumbnailsColumn*o.constants.thumbnailsBorder);// to ensure corect initialization	
				
				if(data.sizing.relative) {
					data.sizing.relative.oldOffset = data.sizing.relative.offset();
					target.scrollTop(o.constants.boundingBox).scrollLeft(o.constants.boundingBox);
					data.sizing.relative.remove().prependTo(target);
					data.sizing.relative.newOffset = data.sizing.relative.offset();
					data.sizing.relative = 
						data.sizing.relative.oldOffset.left != data.sizing.relative.newOffset.left ||
						data.sizing.relative.oldOffset.top != data.sizing.relative.newOffset.top;
					target.scrollTop(0).scrollLeft(options.showedThumbnailsColumn*options.thumbnailsWidth + options.showedThumbnailsColumn*o.constants.thumbnailsBorder);
					
					target.bind(o.events.scroll, data, o.scroll);
				}

			}
			
			data.target = target;
			data.options = options;
				
		},
		
		thumbnailClick : function(event){
			var imgArrayIndex = this.imgArrayIndex;
	
        	if(o.globals.thumbnailsGroupToSwitch == 0 && imgArrayIndex!="undefined" ){
                        var imgLoaded = event.data.options.imgArray[imgArrayIndex];
                        // var currCaptionStart = o.globals.captionStart.replace(/{imageLoaded}/g, "http://www.benetton.com/" + escape(imgLoaded));
						var pathname = window.location.pathname;
						var currCaptionStart = o.globals.captionStart.replace(/{currentPath}/g, "http://www.benetton.com/" + pathname+escape("?imageIndex=" +imgArrayIndex));
						currCaptionStart = currCaptionStart.replace(/{title}/g, "www.benetton.com");


				var backGroundUrl = event.target.style.backgroundImage;
				$(".gallery").animate({
				    opacity: 0	
					}, 30, function() {
					   $(".gallery").css({
					'backgroundImage': "url(" + event.data.options.imgArray[imgArrayIndex] + ")"})
					.animate({
				    		opacity: 1
						}, 700);
					})
				$(".tooltip").html(currCaptionStart + event.data.options.tooltipArray[imgArrayIndex] + o.globals.captionEnd);
			}
			
			$(".backScroll").bind(o.events.click, event.data, function(event){
					o.globals.scrollArrow=-( event.data.options.showedThumbnailsColumn* event.data.options.thumbnailsWidth +  event.data.options.showedThumbnailsColumn*o.constants.thumbnailsBorder);
					o.stop(event);
			});
			$(".nextScroll").bind(o.events.click, event.data, function(event){
					o.globals.scrollArrow=+(event.data.options.showedThumbnailsColumn* event.data.options.thumbnailsWidth +  event.data.options.showedThumbnailsColumn*o.constants.thumbnailsBorder);
					o.stop(event);
			});
			return false;
		},
		// handles mouse wheel scroll events
		wheel: function(event, delta) {
			
			if ( event.wheelDelta ) { delta = event.wheelDelta/12000; }
			if ( event.detail     ) { delta = -event.detail/3; }
			
			event.data.thumbs.vertical.stop(true, true).fadeTo(0, o.constants.thumbOpacity);
			event.data.target.scrollTop(event.data.target.scrollTop() - (delta * o.constants.wheelDeltaMod));
			event.data.thumbs.vertical.stop(true, true).fadeTo("fast", 0);
			
			return false;
			
		},
		
		// starts the drag operation and binds the mouse move handler
		start: function(event) {
			
			event.data.target
				.css("cursor", "url("+event.data.options.closedCursor+"), default")
				.bind(o.events.drag, event.data, o.drag)
				.stop(true, true);
			
			event.data.position = { 
				x: event.pageX,
				y: event.pageY
			};
			
			event.data.clickPosition = { 
				x: event.pageX,
				y: event.pageY
			};
			
			event.data.capture = {};
			
			event.data.isDragging = false;
			
			return false;
			
		},
		
		// updates the current scroll location during a mouse move
		drag: function(event) {
			
			this.scrollLeft -= (event.pageX - event.data.position.x);
			this.scrollTop -= (event.pageY - event.data.position.y);
			event.data.position.x = event.pageX;
			event.data.position.y = event.pageY;
			
			if (typeof event.data.capture.index === "undefined" || --event.data.capture.index === 0 ) {
				event.data.isDragging = true;
				event.data.capture = {
					x: event.pageX,
					y: event.pageY,
					index: o.constants.captureThreshold
				};
				
				if(event.data.thumbs && !event.data.thumbs.visible) {
					event.data.thumbs.visible = true;
					if(event.data.thumbs.vertical) {
						event.data.thumbs.vertical.stop(true, true).fadeTo("fast", o.constants.thumbOpacity);
					}
					if(event.data.thumbs.horizontal) {
						event.data.thumbs.horizontal.stop(true, true).fadeTo("fast", o.constants.thumbOpacity);
					}
				}
			}

			return true;
		
		},
		
		// called after a scroll event, moves the thumbs
		scroll: function(event, ml, mt, left, top) {

			left = event.data.target.scrollLeft();
			
			top = event.data.target.scrollTop();

			if (event.data.thumbs.horizontal) {
				ml = left * event.data.sizing.container.width / event.data.sizing.container.scrollWidth;
				mt = event.data.sizing.thumbs.horizontal.top;
				if(event.data.sizing.relative) { ml += left; mt += top; }
				event.data.thumbs.horizontal.css("margin", mt + "px 0 0 " + ml + "px");	
			}
			
			if (event.data.thumbs.vertical) {
				ml = event.data.sizing.thumbs.vertical.left;
				mt = top * event.data.sizing.container.height / event.data.sizing.container.scrollHeight;
				if(event.data.sizing.relative) { ml += left; mt += top; }
				event.data.thumbs.vertical.css("margin", mt + "px 0 0 " + ml + "px");
			}

		},
		
		// ends the drag operation and unbinds the mouse move handler
		stop: function(event, dx, dy) {
			
			if( typeof event.data.position !== "undefined" || o.globals.scrollArrow!=0 ) {	
                        $(".captionToHide").each(
                                function() {
                                        hideCaption($(this));
                                }
                        );

				if (o.globals.scrollArrow == 0) {
					event.data.target.css("cursor", "url(" + event.data.options.openedCursor + "), default").unbind(o.events.drag, o.drag);
			
				 	var maxScroll = 2*(event.data.options.showedThumbnailsColumn * event.data.options.thumbnailsWidth+ event.data.options.showedThumbnailsColumn*o.constants.thumbnailsBorder);
					var delta = event.pageX - event.data.clickPosition.x;
					var thumbnailWidth = event.data.options.thumbnailsWidth;
					var showedThumbnailsColumn = event.data.options.showedThumbnailsColumn;
					var borderShift = o.constants.thumbnailsBorder * (showedThumbnailsColumn + 1);
					
					
					if (delta > 0 && delta > thumbnailWidth) {
						//dx = showedThumbnailsColumn * thumbnailWidth + borderShift - delta;
						dx=this.scrollLeft; 
						o.globals.thumbnailsGroupToSwitch = -1;
					}
					else 
						if (delta >= 0) {
							//dx = -delta;
							dx=this.scrollLeft-maxScroll/2; 
							o.globals.thumbnailsGroupToSwitch = 0;
						}
					
					
					if (delta < 0 && delta < -thumbnailWidth) {
						//dx = -showedThumbnailsColumn * thumbnailWidth - borderShift - delta;
						dx=this.scrollLeft - maxScroll;
						o.globals.thumbnailsGroupToSwitch = 1;
					}
					else 
						if (delta <= 0) {
							//dx = -delta;
							dx=-maxScroll/2+this.scrollLeft; 
							o.globals.thumbnailsGroupToSwitch = 0;
						}
					
				//dy = o.constants.scrollDeltaMod * (event.pageY - event.data.capture.y);
				}
					
				if (o.globals.scrollArrow != 0) {
					if (o.globals.scrollArrow > 0) {
						dx = o.globals.scrollArrow
						o.globals.thumbnailsGroupToSwitch = -1;
						o.globals.scrollArrow = 0;
					}
					if (o.globals.scrollArrow < 0) {
						dx = o.globals.scrollArrow
						o.globals.thumbnailsGroupToSwitch = +1;
						o.globals.scrollArrow = 0;
					}
				}	
					
					dy=0;
					
					
					var bufferThumbnails = o.globals.bufferThumbnails;
					var showedThumbnails = event.data.options.showedThumbnailsRow * event.data.options.showedThumbnailsColumn;
							
					o.globals.currentArrayIndex += showedThumbnails*o.globals.thumbnailsGroupToSwitch;
							
							
					if (o.globals.thumbnailsGroupToSwitch != 0) {
							
						if (o.globals.currentArrayIndex >= event.data.options.tmbArray.length) {
							o.globals.currentArrayIndex = 0;
						}
						if (o.globals.currentArrayIndex < 0) {
							if (event.data.options.tmbArray.length % showedThumbnails == 0) {
								o.globals.currentArrayIndex = event.data.options.tmbArray.length - showedThumbnails;
							}
							else {
								o.globals.currentArrayIndex = event.data.options.tmbArray.length - event.data.options.tmbArray.length % showedThumbnails;
							}
						}
								
						var arrayShift = o.globals.currentArrayIndex;
						
						for (i = 0; i < 3; i++) {
														
							var showedThumbnailsShift = i * showedThumbnails;
									
							for (k = 0; k < showedThumbnails; k++) {
									
								var modifiedIndex = k + arrayShift + showedThumbnailsShift;
								if (modifiedIndex >= event.data.options.tmbArray.length) {
										if ((event.data.options.tmbArray.length % showedThumbnails == 0) && (modifiedIndex < event.data.options.tmbArray.length + showedThumbnails)) {
												modifiedIndex = k;
											}
											else 
												if ((modifiedIndex >= event.data.options.tmbArray.length + showedThumbnails - event.data.options.tmbArray.length % showedThumbnails)&& modifiedIndex<(2*event.data.options.tmbArray.length +(showedThumbnails - event.data.options.tmbArray.length % showedThumbnails))) {
													if (event.data.options.tmbArray.length % showedThumbnails == 0) {
														modifiedIndex = modifiedIndex - event.data.options.tmbArray.length;
													}
													else {
														modifiedIndex = modifiedIndex - event.data.options.tmbArray.length - (showedThumbnails - event.data.options.tmbArray.length % showedThumbnails);
													}
													
												}
												else {
													var singleChild = bufferThumbnails[0].children[i].children[k];
													singleChild.style.backgroundImage = "";
													singleChild.style.backgroundColor = "white";
													singleChild.imgArrayIndex = "undefined";
												}
										}
										
										if (modifiedIndex < event.data.options.tmbArray.length) {
											var imgLoaded = event.data.options.tmbArray[modifiedIndex];
											var singleChild = bufferThumbnails[0].children[i].children[k];
											
											singleChild.style.backgroundImage = "url(" + imgLoaded + ")";
											singleChild.imgArrayIndex = modifiedIndex;
										}
									}
								}
							}
					$(".backScroll").unbind(o.events.click);
					$(".nextScroll").unbind(o.events.click);
					
					event.data.target.stop(true,true).animate({
						scrollLeft: event.data.target.scrollLeft() - dx,
						scrollTop: event.data.target.scrollLeft() - dy
					},{ 
						queue: true, 
						duration: o.constants.scrollDuration, 
						easing: "cubicEaseOut",
						complete: function(){
							if (event.data.thumbs && event.data.thumbs.visible) {
								event.data.thumbs.visible = false;
								if (event.data.thumbs.vertical) {
									event.data.thumbs.vertical.stop(true, true).fadeTo("fast", 0);
								}
								if (event.data.thumbs.horizontal) {
									event.data.thumbs.horizontal.stop(true, true).fadeTo("fast", 0);
								}
							}
							var scollableThumbnails = o.globals.scollableThumbnails;
							var bufferThumbnails = o.globals.bufferThumbnails;
							var showedThumbnails = event.data.options.showedThumbnailsRow * event.data.options.showedThumbnailsColumn;
							
							if (o.globals.thumbnailsGroupToSwitch  != 0) {	
								scollableThumbnails.html(bufferThumbnails.html());
								this.scrollLeft = event.data.options.showedThumbnailsColumn * event.data.options.thumbnailsWidth+ event.data.options.showedThumbnailsColumn*o.constants.thumbnailsBorder;
								$(".thumbnail").bind(o.events.click, event.data, o.thumbnailClick);
								$(".backScroll").bind(o.events.click, event.data, function(event){
									o.globals.scrollArrow=-( event.data.options.showedThumbnailsColumn* event.data.options.thumbnailsWidth +  event.data.options.showedThumbnailsColumn*o.constants.thumbnailsBorder);
									o.stop(event);
								});
								$(".nextScroll").bind(o.events.click, event.data, function(event){
									o.globals.scrollArrow=(event.data.options.showedThumbnailsColumn* event.data.options.thumbnailsWidth +  event.data.options.showedThumbnailsColumn*o.constants.thumbnailsBorder);
									o.stop(event);
								});
								o.globals.thumbnailsGroupToSwitch=0;
								for (i = 0; i < 3; i++) {
									for (k = 0; k < showedThumbnails; k++) {
										bufferThumbnails[0].children[i].children[k];
										scollableThumbnails[0].children[i].children[k].imgArrayIndex=bufferThumbnails[0].children[i].children[k].imgArrayIndex;
									}
								}
							}
							
						}
					});
				event.data.capture = event.data.position = undefined;
			}
			
			return !event.data.isDragging;
		},
		
		// gets sizing for the container and thumbs
		getSizing: function(container, sizing) {
		
			sizing = { };
			
			sizing.container = {
				width: container.width(),
				height: container.height()
			};
			
			container.scrollLeft(o.constants.boundingBox).scrollTop(o.constants.boundingBox);
			sizing.container.scrollWidth = container.scrollLeft();
			sizing.container.scrollHeight = container.scrollTop();							
			container.scrollTop(0).scrollLeft(0);
					
			sizing.thumbs = {
				horizontal: {
					width: sizing.container.width * sizing.container.width / sizing.container.scrollWidth,
					height: o.constants.thumbThickness,
					corner: o.constants.thumbThickness / 2,
					left: 0,
					top: sizing.container.height - o.constants.thumbThickness
				},
				vertical: {
					width: o.constants.thumbThickness,
					height: sizing.container.height * sizing.container.height / sizing.container.scrollHeight,
					corner: o.constants.thumbThickness / 2,
					left: sizing.container.width - o.constants.thumbThickness,
					top: 0
				}
			};
			
			sizing.container.width -= sizing.thumbs.horizontal.width;
			sizing.container.height -= sizing.thumbs.vertical.height;
			
			return sizing;
			
		},
		
		// gets the CSS object for a thumb
		getThumbCss: function(size) {
		
			return {
				position: "absolute",
				"background-color": "black",
				width: size.width + "px",
				height: size.height + "px",
				"margin": size.top + "px 0 0 " + size.left + "px",
				"-moz-border-radius": size.corner + "px",
				"-webkit-border-radius":  size.corner + "px", 
				"border-radius":  size.corner + "px"
			};
			
		}
		
	});

	// jQuery adapted Penner animation
	//    created by Jamie Lemon
	$.extend($.easing, {
		
		cubicEaseOut: function(p, n, firstNum, diff) {
			var c = firstNum + diff;
			return c*((p=p/1-1)*p*p + 1) + firstNum;
		}
		
	});

})(jQuery);

