// The Images are stored in Categories[]. See Categories.js
//
// When selecting the next Image, just increment by Direction and cycle round the list

function _ScreenSaver()
{
	this.AbortShow = false
	this.TimeEvent = null
	this.dateNextShowTime = new Date();								// Set to already expired
	this.HasBeenShown = Array()
	this.JqImgIn = Array($(),$(),$(),$())
	this.JqImgOut = Array($(),$(),$(),$())
	this.CatIndex = -1
	this.Init = true

	this.Begin = Begin
	this.LoadImagePair = LoadImagePair
	this.LoadNextImage = LoadNextImage
	this.GetNextCategory = GetNextCategory
	this.ImageLoadedOk = ImageLoadedOk
	this.ImageLoadedBad = ImageLoadedBad
	this.Wait4ShowTime = Wait4ShowTime
	this.ShowNextImagePair = ShowNextImagePair
	this.End = End

	function Begin()
	{
		if ( Categories.length == 0 )
			return;
			
		this.ImagePosition = -1					// 0 = top left, 1 = bottom right, 2 = bottom left, 3 = top right

		this.GetNextCategory()
		if ( this.Images.length > 1 )
			this.LoadImagePair()
	}

	function LoadImagePair()
	{
		this.LoadCount = 2
		this.LoadNextImage()
		this.LoadNextImage()
	}

	function LoadNextImage()
	{
		// Set the Next Image idx
		var ImgId
		do {
			this.GetNextImageId()
			ImgId = this.Category.getImageId( this.idx )
		}
		while ( this.ImageShowing( ImgId ) )
		
		// Load this image if it's not already in the document
		this.ImagePosition = this.ImagePosition == 3 ? 0 : this.ImagePosition + 1
		this.JqImgOut[this.ImagePosition] = this.JqImgIn[this.ImagePosition]
		var Jimg = this.JqImgIn[this.ImagePosition] = $( '#' + ImgId )
		if( Jimg.length != 0 )
		{
			Jimg.ImagePosition = this.ImagePosition
			this.Wait4ShowTime()
		}
		else
		{
			Jimg = this.JqImgIn[this.ImagePosition] = $(new Image())
			Jimg.attr({src : this.Category.getImagePath() + this.Images[ this.idx ],
								 id : ImgId})
					.addClass('photo')
					.css({display:'none',
								position:'absolute',
								top:0,
								left:0,
								border:0,
								opacity:'hide'
								})
					.bind('load', ScreenSaver.ImageLoadedOk)
					.bind('error', ScreenSaver.ImageLoadedBad)

			// Note, we use a <div> to avoid flashing scroll bars
			$('#imgAreaId').append( Jimg )
			Jimg.ImagePosition = this.ImagePosition
		}
	}

	this.ImageShowing = function(id)
	{
		for(var i in this.JqImgIn)
		{
			if (id == this.JqImgIn[i][0].id)
				return true
		}
		return false
	}
	
	function GetNextCategory()
	{
		// Pick a category at random, but it must not be the same
		var NewCatIndex = Math.floor(Math.random() * Categories.length)
		if( NewCatIndex == this.CatIndex )
		{
			this.CatIndex++
			if( this.CatIndex == Categories.length)
				this.CatIndex = 0
		}
		else
			this.CatIndex = NewCatIndex
		this.Category = Categories[this.CatIndex]
		this.Images = this.Category.ImageNames
	}

	this.GetNextImageId = function()
	{
		// Pick an Image at random
		this.idx = Math.floor(Math.random() * this.Images.length)

		// Round robin search from the random start for a image that has not been shown
		for( var index=0; index<this.Images.length; index++ )
		{
			if( this.HasBeenShown[this.idx] == null )
			{
				this.HasBeenShown[this.idx] = true
				return
			}
			this.idx++
			if ( this.idx == this.Images.length )
				this.idx = 0
		}

		// All the Images have been shown. Start again with the next Category
		for( index=0; index<this.Images.length; index++ )
			this.HasBeenShown[index] = null
		this.GetNextCategory()
		this.GetNextImageId()
	}

	function ImageLoadedOk()
	{
		ScreenSaver.Wait4ShowTime()
	}

	function ImageLoadedBad()
	{
//		Debug.raise( "Bad Load" )
		ScreenSaver.Wait4ShowTime()
	}

	function Wait4ShowTime()
	{
		if ( this.AbortShow )
			return

		// If this is the second of the two Images
		if( --this.LoadCount == 0 )
		{
			// Wait until its time to display the new image(s)
			var now = new Date()
			var timeRemaining = this.dateNextShowTime - now.getTime()

			if( timeRemaining <= 0 )
				this.ShowNextImagePair()
			else
				this.TimeEvent = setTimeout('ScreenSaver.ShowNextImagePair()', timeRemaining)
		}
	}

	function ShowNextImagePair()
	{
		if ( this.AbortShow )
			return

		this.ReDrawImage(false, this.Init)
		this.Init = false
		ReDrawFunc = 'ScreenSaver.ReDrawImage(true, false)'

		// Set the next change time to 5 seconds
		var now = new Date()
		this.dateNextShowTime = now.getTime() + 5000

		// Preload the next images
		this.LoadImagePair()
	}

	function End()
	{
		if( this.AbortShow )
			return
		this.AbortShow = true

		for(idx in this.JqImgIn)
		{
			this.JqImgIn[idx].stop().animate({opacity:'hide'}, 'slow')
			this.JqImgOut[idx].stop().animate({opacity:'hide'}, 'slow')
		}

		$('#ScreenSaverNullImageId').hide()
		$('#LineHoriId').hide('slow')
		$('#LineVertId').hide('slow')

		if( this.TimeEvent )
		{
			clearTimeout( this.TimeEvent )
			this.TimeEvent = null
		}
	}

	this.ReDrawImage = function ReDrawImage(resizing, init)
	{
		// Get the size of the window, and clip it, by subtracting Margins and the Menu area on the right
		var WindowWidth = GetWindowWidth()
		var WindowHeight = GetWindowHeight()
		var MaxAreaWidth = WindowWidth - (LeftMargin + LogoMenuMaxWidth + RightMargin)
		var MaxAreaHeight = WindowHeight - (TopMargin + FootNoteMargin)
		var MaxImgWidth = Math.floor((MaxAreaWidth - CentreMargin) / 2)
		var MaxImgHeight = Math.floor((MaxAreaHeight - CentreMargin) / 2)

		// Place the Null image over the whole Image area
		$('#ScreenSaverNullImageId').width(MaxAreaWidth)
																.height(MaxAreaHeight)
																.css({left:LeftMargin, top:TopMargin})
																.show()

		// Calculate the mid point of the Images
		var MidXleft 		= LeftMargin 	+ MaxImgWidth
		var MidYtop 		= TopMargin 	+ MaxImgHeight
		var MidX 				= MidXleft 		+ CentreMarginHalf
		var MidY 				= MidYtop 		+ CentreMarginHalf
		var MidXright 	= MidX 		+ 1 + CentreMarginHalf	// Line width is 1
		var MidYbottom 	= MidY 		+ 1 + CentreMarginHalf	// Line width is 1

		// Shrink the whole area
		MaxImgWidth  = Math.floor(MaxImgWidth * 3 / 4)
		MaxImgHeight = Math.floor(MaxImgHeight * 3 / 4)

		if( init )
		{
			$('#LineHoriId').height(1)
											.width(1)
											.css({top  : MidY,
														left : MidX})
											.animate({left : LeftMargin + LineMargin}, {duration: 'slow', queue:false})
											.animate({width : MaxAreaWidth - 2 * LineMargin}, {duration: 'slow', queue:false})
			$('#LineVertId').height(1)
											.width(1)
											.css({top  : MidY,
														left : MidX})
											.animate({top : TopMargin + LineMargin}, {duration: 'slow', queue:false})
											.animate({height : MaxAreaHeight - 2 * LineMargin}, {duration: 'slow', queue:false})
		}
		else if( resizing )
		{
			$('#LineHoriId').css({top  : MidY,
														left : LeftMargin + LineMargin,
														width : MaxAreaWidth - 2 * LineMargin})
			$('#LineVertId').css({top : TopMargin + LineMargin,
														left : MidX,
														height : MaxAreaHeight - 2 * LineMargin})
	}
		
		// Update the two Images
		var JqImgIn = this.JqImgIn
		var JqImgOut = this.JqImgOut
		var Do_BottmLeft_TopRight = (this.ImagePosition & 2) == 2
		var outSpeed = resizing ? 'fast' : 4000
		if( resizing || Do_BottmLeft_TopRight )
		{
			JqImgOut[2].stop().animate({opacity:'hide'}, outSpeed)
			JqImgOut[3].stop().animate({opacity:'hide'}, outSpeed)
			JqImgIn[2].fitToSize( MaxImgWidth, MaxImgHeight )		// Bottom Left
								.css({left : MidXleft - JqImgIn[2].width(),
											top  : MidYbottom,
											opacity: 1})
								.animate({opacity:'show'}, 4000)
			JqImgIn[3].fitToSize( MaxImgWidth, MaxImgHeight )		// Top Right
								.css({left : MidXright,
											top  : MidYtop - JqImgIn[3].height(),
											opacity: 1})
								.animate({opacity:'show'}, 4000)
		}

		if( resizing || ! Do_BottmLeft_TopRight )
		{
			JqImgOut[0].stop().animate({opacity:'hide'}, outSpeed)
			JqImgOut[1].stop().animate({opacity:'hide'}, outSpeed)
			JqImgIn[0].fitToSize( MaxImgWidth, MaxImgHeight )		// Top Left
								.css({left : MidXleft - JqImgIn[0].width(),
											top  : MidYtop - JqImgIn[0].height(),
											opacity: 1})
								.animate({opacity:'show'}, 4000)
			JqImgIn[1].fitToSize( MaxImgWidth, MaxImgHeight )		// Bottom Right
								.css({left : MidXright,
											top  : MidYbottom,
											opacity: 1})
								.animate({opacity:'show'}, 4000)
		}

		PositionPageItems()
	}
}
