
function _ThumbCrawl()
{
	this.Init = function(Jthumbs)
	{
		this.Jthumbs = Jthumbs
		this.firstTime = true
		
		ThumbTopMargin = 10									// Between the above image
		this.ThumbMargin = 6											// Between each thumbnail
		
		this.centreThumbWidth = 0						// Size of the centre thumbnail
		this.centreThumbHeight = 0					// Size of the centre thumbnail
		Jthumbs.saveSize()
		for (var idx=0; idx<Jthumbs.length; idx++)
		{
				// Save the sizes so the aspect ratio can be maintained as the thumbs are resized
				var Obj = Jthumbs[idx]
				Obj.crawlThumbWidth = Math.round(Obj.originalWidth * 0.7)
				Obj.crawlThumbHeight = Math.round(Obj.originalHeight * 0.7)
				
				// Record the maximum 
				if( this.centreThumbWidth < Obj.originalWidth )
					this.centreThumbWidth = Obj.originalWidth
				if( this.centreThumbHeight < Obj.originalHeight )
					this.centreThumbHeight = Obj.originalHeight
		}	
		this.thumbWidth = Math.round(this.centreThumbWidth * 0.7)
		this.thumbHeight = Math.round(this.centreThumbHeight * 0.7)
		this.thumbWidthAndMargin = this.thumbWidth + this.ThumbMargin
	}

	// Called to show 1st image and when the fullsize image is clicked
	this.Show = function(idx)
	{
		if( this.firstTime )
		{
			this.firstTime = false
			this.pixelVector = 0				// Craw direction and remaining distance to be moved
			this.thumbVector = 0				// Craw direction and remaining distance to be moved
			this.centreIndex = idx			// idx of the centre thumb
			this.OnResize()
		}
		else
		{
			// Calculate the shortest crawl direction
			var Diff = idx - this.centreIndex

			// Assume Inner will be shortest route
			var newVector = idx < this.centreIndex ? 1 : -1
			var Shortest = Math.abs( Diff )

			var Outer = this.Jthumbs.length - Shortest
			if( Outer < Shortest )
			{
				// Outer is the shortest route
				newVector *= -1
				Shortest = Outer
			}

			this.thumbVector += newVector * Shortest
			this.centreIndex = idx
//			Debug.raise( '------------------------  ThumbVector=' + this.thumbVector)

			if( this.timerId == null )
				this.DoCrawl()
		}
	}

	this.OnResize = function()
	{
		// User can resize before Init has been called
		if( this.Jthumbs == undefined )
			return

		this.Hide()

		// Calculate the number of thumbs that can be shown
		var WindowWidth = GetWindowWidth()
		var MaxImgWidth = WindowWidth - (LeftMargin + LogoMenuMaxWidth + RightMargin)
		this.NumOfThumbsOnScreen = Math.floor( MaxImgWidth / this.thumbWidthAndMargin )
		if( this.NumOfThumbsOnScreen > this.Jthumbs.length )
			this.NumOfThumbsOnScreen = this.Jthumbs.length
		if( 0 == (this.NumOfThumbsOnScreen & 1) )																										// Ensure its an odd number
			this.NumOfThumbsOnScreen--;
		this.HalfThumbsOnScreen = Math.floor( this.NumOfThumbsOnScreen / 2 )

		// Calculate the top of the thumbnails
		var WindowHeight = GetWindowHeight()
		this.thumbTop = WindowHeight - (FootNoteMargin + this.ThumbMargin + this.thumbHeight)

		// Calculate the total width and position of the scroll area
		var ThumbsWidth = (this.NumOfThumbsOnScreen * this.thumbWidthAndMargin) - this.ThumbMargin
		this.MinLeft = LeftMargin + Math.floor( (MaxImgWidth - ThumbsWidth) / 2 )										// Position of 1st thumbnail
		this.LeftStop = this.MinLeft - this.thumbWidthAndMargin																			// Minimum left value for any thumnail
		this.RightStop = this.MinLeft + ThumbsWidth	+ this.ThumbMargin															// Maximum left value for any thumnail
		this.WrapWidth = this.Jthumbs.length * this.thumbWidthAndMargin															// Distance to +/- to wrap the thumb right/left
		this.centreLeft = this.MinLeft + (this.HalfThumbsOnScreen * this.thumbWidthAndMargin)				// Position of the Centre thumbnail

		// Assign the TargetLeft position for all thumbs (ignore wrap here)
		var Left = this.MinLeft
		this.SetFirstThumbIndex()
		this.Jthumbs.css({visibility : 'visible'})
		for( var index=0; index<this.Jthumbs.length; index++ )
		{
			var ThumbObj = this.Jthumbs[this.thumbIndex]
			ThumbObj.targetLeft = Left + Math.round((this.thumbWidth - ThumbObj.crawlThumbWidth)/2)
			Left += this.thumbWidthAndMargin
			this.SetNextThumbIndex()
		}

		// Position the End Masks
		$('#ThumbMaskEndLeftId').css({top: this.thumbTop + 'px',
																	left: this.LeftStop + 'px',
																	visibility: 'visible',
																	zIndex: 1})
														.addClass('mask')
														.height(this.thumbHeight)
														.width(this.thumbWidthAndMargin)
														.show()

		$('#ThumbMaskEndRightId').css({top: this.thumbTop + 'px',
																	 left:	this.RightStop - this.ThumbMargin + 'px',
																	 visibility: 'visible',
																	 zIndex: 1})
														 .addClass('mask')
														 .height(this.thumbHeight)
														 .width(this.thumbWidthAndMargin)
														 .show()

		// Set the size of the graduated transparency masks so that they overlap all thumbs except the centre 3
		var MaskWidth = (this.thumbWidthAndMargin * (this.HalfThumbsOnScreen - 1)) - this.ThumbMargin
		if( MaskWidth > 0 )
		{
			$('#ThumbMaskLeftId').css({top: this.thumbTop + 'px',
																 left: this.MinLeft + 'px',
																 visibility: 'visible',
																 zIndex: 1})
													 .addClass('mask')
													 .height(this.thumbHeight)
													 .width(MaskWidth)
													 .show()

			$('#ThumbMaskRightId').css({top: this.thumbTop + 'px',
																	left: this.centreLeft + (2 * this.thumbWidthAndMargin) + 'px',
																	visibility: 'visible',
																	zIndex: 1})
														.addClass('mask')
														.height(this.thumbHeight)
														.width(MaskWidth)
														.show()
		}
		this.DoCrawl()
	}

	this.DoCrawl = function()
	{
		// Do any large movement first. NOTE displacement must (eventually) have the opposite sign to this.pixelVector
		var displacement = 0
		if( this.thumbVector != 0 )
		{
			displacement = this.thumbVector < 0 ? this.thumbWidthAndMargin : -this.thumbWidthAndMargin

			// Set the target positions for all thumbs.
			for( var index=0; index<this.Jthumbs.length; index++ )
			{
				var ThumbObj = this.Jthumbs[index]
				ThumbObj.targetLeft -= displacement

				// Reposition the Target so that the 'end' thumbs slide on from the correct side
				if( displacement >= 0 )
				{
					if( ThumbObj.targetLeft < this.LeftStop )
						ThumbObj.targetLeft += this.WrapWidth
				}
				else if( this.RightStop < ThumbObj.targetLeft )
				{
					ThumbObj.targetLeft -= this.WrapWidth
				}
			}

			var ThumbDistance = this.thumbVector < 0 ? -this.thumbVector : this.thumbVector
			// If, after this repositioning, its within 1/2 a thumbs width....
			if( ThumbDistance == 1 )
			{
				// The final movement will be done in small stages
				this.pixelVector -= displacement
			}

			this.thumbVector += this.thumbVector < 0 ? 1 : -1
		}
		else
		{
			// Reduce the speed (distanceToMove) as it approaches the target position
			var distanceToMove = Math.ceil( Math.abs(this.pixelVector) / 6 )
			this.pixelVector -= this.pixelVector < 0 ? -distanceToMove : distanceToMove
			displacement = - this.pixelVector
		}

		this.SetFirstThumbIndex()
		for( var index=0; index<this.Jthumbs.length; index++ )
		{
			var zIndex = 0
			var ImageObj = this.Jthumbs[this.thumbIndex]
			
			// Set the size and position for a non-centred thumb
			var width = ImageObj.crawlThumbWidth
			var height = ImageObj.crawlThumbHeight
			var thisLeft = ImageObj.targetLeft + displacement
				
			// Is this thumb close enough to the centre, to need enlarging	
			var distanceFromCentre = Math.abs( this.centreLeft - thisLeft )
			var maxExpansion = ImageObj.originalHeight - height				// Max height expansion for this thumb
			var expansion = maxExpansion - distanceFromCentre					// Expansion will be -ve until close to the centre
			if( expansion > 0 )
			{
				height += expansion
				width = Math.floor(height * ImageObj.aspectRatio)
				thisLeft -= Math.floor(expansion * ImageObj.aspectRatio / 2)
				zIndex = index == this.HalfThumbsOnScreen ? 2 : 1
			}
			else if( thisLeft < this.LeftStop || this.RightStop < thisLeft )
				thisLeft = this.RightStop

			$(ImageObj).height(height)
								 .width(width)
								 .css({left: thisLeft + 'px',
											 top : this.thumbTop + Math.floor((this.thumbHeight - height) / 2) + 'px',
											 zIndex: zIndex})
								 .show()
			this.SetNextThumbIndex()
		}

//	Debug.raise('End displacement=' + displacement + ' PixelVector=' + this.pixelVector)
		this.timerId = ( this.pixelVector != 0 || this.thumbVector != 0 ) ? setTimeout('ThumbCrawl.DoCrawl()', 20) : null
	}

	this.SaveCoords = function(event)
	{
		ThumbCrawl.SaveCoordX = event.clientX
	}

	this.ThumbClicked = function()
	{
		// Cannot calculate the correct thumb when moving as TargetLeft is not accurate
		if( this.thumbVector != 0 )
			return

		// Find the Thumb under the cursor
		for( var index=0; index<this.Jthumbs.length; index++ )
		{
			var left = this.Jthumbs[index].targetLeft
			var right = left + this.thumbWidth
			if( left < this.SaveCoordX && this.SaveCoordX < right )
			{
				// Image found. Show it. Will (eventually) call ImageSet.ShowFullSizeJimg()
				var idx = Categories[0].getIdx(this.Jthumbs[index].id)
				ImageLoader.LoadRequestedImage( idx )
				return
			}
		}
	}

	// Set this.thumbIndex to the thumb Object that is to be shown at the 1st (left hand) thumb position
	this.SetFirstThumbIndex = function()
	{
		this.thumbIndex = this.GetCentreThumbIndex( - this.HalfThumbsOnScreen )
	}

	this.SetNextThumbIndex = function()
	{
		if( ++this.thumbIndex == this.Jthumbs.length )
			this.thumbIndex = 0
	}

	// Return idx of the centre thumb (+ indexOffset) Object
	this.GetCentreThumbIndex = function( indexOffset )
	{
		var index = this.centreIndex + indexOffset
		if( index < 0 )
			index += this.Jthumbs.length
		else if( index >= this.Jthumbs.length )
			index -= this.Jthumbs.length

		return index
	}

	// Return idx of the thumb Object that is to be shown at the last (right hand) thumb position
	this.GetLastThumbIndex = function()
	{
		return this.GetCentreThumbIndex( this.HalfThumbsOnScreen )
	}

	this.Hide = function()
	{
		this.Jthumbs
				.add('.mask')
				.css({visibility : 'hidden'})
	}
}

var ThumbCrawl = new _ThumbCrawl()
