/*

image_manip.js - holds JavaScript functions to provide gallery image building and manipulation.

*/

// *********************************************************************************************
// This file uses ASSUMED GLOBAL VARIABLES set-up by call to 'IU_ExportImageDataForJavaScript'
// function. If this is not used, unpredictable results and errors will occur. THERE ARE SOME
// ADDITIONAL VARIABLES SET UP IN THIS FILE.
// *********************************************************************************************

/* Globals. */

var gSlideShowIsPaused = false;

/* Callback to set image name on image change. */
function ImageChangeName(curr, next, opts)
{
	/* Extract current slide for data passed in by Cycle plug-in. */
	var index = opts.currSlide + 1;
	
	/* Change image name displayed. */
	$('#Ctrl .Name p').empty().append(this.alt);
	
	/* De-high-light the old thumbnail. */
	$('#Thumbs .Current').removeClass("Current");
	
	/* High-light new thumbnail. */
	$('#Thumb' + index).addClass("Current");
	
	/* Which thumbnail grid would this be on? */
	var newThumbnailGrid = Math.floor(opts.currSlide / (4 * 7)) + 1;
	
	/* Need to update the grid? */
	if (curThumbGrid != newThumbnailGrid)
	{
    	SetThumbnailGrid(newThumbnailGrid, curThumbGrid);
    	curThumbGrid = newThumbnailGrid;
	}
}

/* Callback to change the main image to the previous one. */
function PrevImage()
{
	$('#LargeCycle').cycle('prev');
	PauseSlideshow();
}

/* Callback to change the main image to the next one. */
function NextImage()
{
	$('#LargeCycle').cycle('next');
	PauseSlideshow();
}

/* Callback for playing or pausing the slide-show. */
function PlayPauseSlideshow()
{
	if (gSlideShowIsPaused)
	{
		ResumeSlideshow();
	}
	else
	{
		PauseSlideshow();
	}
}

/* Callback to resume the slide show. */
function ResumeSlideshow()
{
	$('#LargeCycle').cycle('resume');
	gSlideShowIsPaused = false;
	$('#Ctrl .PlayPause a').text('Pause');
}

/* Callback to pause the slide show. */
function PauseSlideshow()
{
	$('#LargeCycle').cycle('pause');
	gSlideShowIsPaused = true;
	$('#Ctrl .PlayPause a').text('Play');
}

/* Callback for 'previous thumbnail grid' request. */
function PrevThumbGrid()
{
	/* Can decrement? */
	if (curThumbGrid > 1)
	{
		/* Keep original for function call. */
		oldGrid = curThumbGrid;
		
		/* Reduce grid. */
		curThumbGrid--;
		
		/* Update visible thumbnails. */
		SetThumbnailGrid(curThumbGrid, oldGrid);
		
		/* Pause the slide show. */
		PauseSlideshow();
	}
}

/* Callback for 'next thumbnail grid' request. */
function NextThumbGrid()
{
	/* Can increment? */
	if (curThumbGrid < maxThumbGrid)
	{
		/* Keep original for function call. */
		oldGrid = curThumbGrid;
		
		/* Increase grid. */
		curThumbGrid++;
		
		/* Update visible thumbnails. */
		SetThumbnailGrid(curThumbGrid, oldGrid);
		
		/* Pause the slide show. */
		PauseSlideshow();
	}
}

/* Called to update the thumbnails. Pass in the previous shown grid (if one) or -1 if none. */
function SetThumbnailGrid(current, old)
{
	var start;
	var end;
	var thumbIndex;

	/* Any old items to hide? */
	if (old > 1)
	{
		/* Limit hide indices. */
		start = gridWidth * gridHeight * (old - 1) + 1;
		end = gridWidth * gridHeight * old;
	}
	else
	{
		/* no, hide all. */
		start = 1;
		end = totalThumbs;
	}

	/* Hide specified range of thumbnails. */	
	for (thumbIndex = start; thumbIndex <= end; thumbIndex++)
	{
		$('#Thumb' + thumbIndex).hide();
	}
	
	/* Build range of thumbnails to show. */
	start = gridWidth * gridHeight * (current - 1) + 1;
	end = gridWidth * gridHeight * current;

	/* Show specified range of thumbnails. */	
	for (thumbIndex = start; thumbIndex <= end; thumbIndex++)
	{
		$('#Thumb' + thumbIndex).show();
	}	
	
	/* Update next & previous thumbnail grid button visibility. */
    if (current <= 1)
    {
        /* No previous as on first. */
        $('#Prev').hide();
    }
    else
    {
        /* Is a previous. */
        $('#Prev').show();
    }
    
    if (current >= maxThumbGrid)
    {
        /* No next as on last. */
        $('#Next').hide();
    }	
    else
    {
        /* Is a next. */
        $('#Next').show();
    }
}

/* Called when thumbnail is clicked. */
function ChangeLargeImage()
{
	var number;
	
	/* Extract index, assuming ident is 'Thumb<number>'. */
	number = Math.floor(this.id.substr(5)) - 1;
	
	/* Set the image to this index and stop the playback. */
	$('#LargeCycle').cycle(number);
	PauseSlideshow();
}

// Function to handle the display of either a Flash or a JavaScript based gallery. This assumes
// that the data necessary has been exported via the 'IU_ExportImageDataForJavaScript' function
// and that the gallery on which it is to act (ie modify) has been exported via the
// 'IU_ExportGalleryHTML' function.
//
//    flashDirUrl    = the full URL to the directory holding the flash gallery. Must end with '/'.
//    imageRequested = true if a specific image was requested on the URL.
//    imageIdent     = only used if 'imageRequested' is true, specifies the SSPdir ident of the
//                     image that was requested.
//    albumIdent     = the SSPdir ident of the album being used.
//
// Optional...
//
//    flashXmlId     = The gallery xml config ident used by the flash piece.
//    flashXmlUrl    = The location of the xml config file to load (full URL), normally uses the
//                     URL of the gallery page but this may not be correct and this overrides.
function IM_DisplayFlashOrJSGallery(flashDirUrl, imageRequested, imageIdent, albumIdent,
	flashXmlId, flashXmlUrl)
{
	/* Hide the none javascript gallery, as we obviously have javascript, if we
		 have flash and it's the correct version... */
/*	if ($.flash.available && $.flash.hasVersion('9.0.115') && !$.flash.activeX)
*/		 
	/* NOTE: no longer using Flash gallery, so alway fail this test. */
	if (false)
	{
		var flashVarArray = new Array();
		
		/* Build array of values for the Flash Vars. */
		flashVarArray['album'] = albumIdent;
		if (imageRequested)
		{
			flashVarArray['image'] = imageIdent;
		}
		if (flashXmlId != null)
		{
			flashVarArray['configName'] = flashXmlId;
		}
		if (flashXmlUrl != null)
		{
			flashVarArray['path'] = flashXmlUrl;
		}
		
		/* Using Flash gallery, so disable any other gallery and show Flash...
		
		   NOTE: it is VITAL that 'allowScriptAccess' is set to 'always' otherwise
		         access to the gallery by other sites will NOT WORK. This is due to
		         the 'shared' nature of the flash file. It's stored (and loaded) from
		         freya. On another domain, the attempt to access the page's
		         javascript, etc will cause a security error if this option is NOT set
		         to 'always'. The flash will see it's domain as 'freya' and not the
		         site it appears on.
		*/
		$('#AltGallery').hide();
		$('#Gallery').flash(
			{
				swf: flashDirUrl + 'ssp_square_rhs_thumbs.swf',
				width: 880,
				height: 594,
				params: {
					allowScriptAccess: 'always'
					},
				flashvars: flashVarArray
			});
	}
	else
	{
		/* Which message is needed? */
		if ($.flash.available && !$.flash.activeX)
		{
			/* Wrong flash or wrong version. */
			msgStr = "Using a an up-to-date <a href='http://get.adobe.com/flashplayer/' target='_blank'>version of Flash</a> would improve your gallery viewing experience";
		}
		else if ($.flash.activeX)
		{
			msgStr = "...";
		}
		else
		{
			/* No flash. */
			msgStr = "Installing <a href='http://get.adobe.com/flashplayer/' target='_blank'>the Flash plug-in</a> would improve your gallery viewing experience";
		}
		
		/* Change the message. NOTE: now defunct as message is not exported in HTML. */
/*
		$('#AltGalleryMsg').empty();
		$('#AltGalleryMsg').append(msgStr);
*/
		/* Instrument the non-JavaScript gallery with JavaScript code.
		   Need all thumbnails, so empty what is currently there and ensure all
		   are in place, with individual idents. */
		$('#Thumbs').empty();

		for (var count = 0; count < thumbUrlArray.length; count++)
		{
			/* Do *NOT* put '\n' on the end of these as it pushes the styling out. */
			tagStr = "<a id='Thumb" + (count + 1) + "'><img style='border-top-width: " +
				thumbEdgeTopArray[count] + "px; border-left-width: " + thumbEdgeLeftArray[count] +
				"px; border-bottom-width: " + thumbEdgeBottomArray[count] +
				"px; border-right-width: " + thumbEdgeRightArray[count] + "px;' src='" +
				thumbUrlArray[count] + "' /></a>";
			$('#Thumbs').append(tagStr);
			
			/* Set the event on this to change the large image. */
			$('#Thumb' + (count + 1)).click(ChangeLargeImage);
		}
		
		/* Ensure correct grid is shown. */
		SetThumbnailGrid(curThumbGrid, -1);
	
		/* Insert all images (large) into the 'Large' div. This uses
			 the arrays set-up in PHP above. */
		$('#Large').empty();
		
		/* Add in tag for cycle. Do this so styling is not effected on the 'Large'
			 div tag. */
		$('#Large').append('<div id="LargeCycle">');
		
		/* All arrays should be the same length. */
		for (var count = 0; count < largeUrlArray.length; count++)
		{
			/* Calculate padding for left, right, top and bottom. */
			vertGap = Math.floor(largeSize - largeHeightArray[count]);
			topPad = Math.floor(vertGap / 2);
			bottomPad = vertGap - topPad;
			
			horizGap = Math.floor(largeSize - largeWidthArray[count]);
			leftPad = Math.floor(horizGap / 2);
			rightPad = horizGap - leftPad;

			/* Build the <img> tag with style for calculated padding. */
			tagStr = "<img alt='" + largeNameArray[count] + "' style='padding: " + topPad +
				"px " + rightPad + "px " + bottomPad + "px " + leftPad + "px; width: " +
				largeWidthArray[count] + "px; height: " + largeHeightArray[count] + "px;' src='" +
				largeUrlArray[count] + "' />";
			$('#LargeCycle').append(tagStr);
		}
		
		/* Close the 'cycle' div, add a 'NavEnd' classed div (to stop collapse if less
			 than a full set of thumbnails)  and apply the 'cycle' plug-in to these
			 images. */
		var cycleOptArray = new Array();
		cycleOptArray['fx'] = 'fade';
		cycleOptArray['after'] = ImageChangeName;
		cycleOptArray['timeout'] = 5000;
		cycleOptArray['speedIn'] = 3000;
		cycleOptArray['speedOut'] = 3000;
		cycleOptArray['fastOnEvent'] = 1;       // Make manual transition instant.
		
		if (imageRequested)
		{
			var imageIndex = 0;
			var searchCount;
			
			// Find the index of the requested ident - only doing this once, so scan for it.
			for (searchCount = 0; searchCount < imageIdArray.length; searchCount++)
			{
				if (imageIdArray[searchCount] == imageIdent)
				{
					imageIndex = searchCount;
					break;
				}
			}
		
			// Select the found image.
			cycleOptArray['startingSlide'] = imageIndex;
			gSlideShowIsPaused = true;
		}
		
		$('#Large').append('</div>');
		$('#LargeCycle').cycle(cycleOptArray);
		
		/* Make thumbnail navigation buttons into JavaScript events. Need to rebuild
			 this as it may not have been included fully by the non-javascript gallery,
			 as it only adds prev & next if in a middle positioned thumbnail grid. */
		$('#ThumbsNav').empty().append('<li id="Prev"><a>Prev Thumbs</a></li><li id="Next"><a>Next Thumbs</a></li>');
		
		/* Add events. */
		$('#Prev a').click(PrevThumbGrid);
		$('#Next a').click(NextThumbGrid);
		
		/* Make only necessary buttons visible. */
		if (maxThumbGrid == 1)
		{
			/* Only one page, no nav needed. */
			$('#Prev').hide();
			$('#Next').hide();
		}
		else
		{
			if (curThumbGrid <= 1)
			{
				/* No previous as on first. */
				$('#Prev').hide();
			}
			if (curThumbGrid >= maxThumbGrid)
			{
				/* No next as on last. */
				$('#Next').hide();
			}
		}
		
		/* Modify the next & previous image buttons to change instantly via JS instead of
		   causing a page reload each time. First, remove href from the links meaning that
		   the do nothing from a HTML point of view and only work via javascript. */
		$('#Ctrl .Prev a').removeAttr('href');
		$('#Ctrl .Next a').removeAttr('href');
		 
		/* Add click events for both buttons. */
		$('#Ctrl .Prev a').click(PrevImage);
		$('#Ctrl .Next a').click(NextImage);
		 
		/* Add play (or pause) button after 'previous image' button and wire up events. */
		$('#Ctrl .Prev').after('<li class="PlayPause"><a></a></li>');
		$('#Ctrl .PlayPause a').click(PlayPauseSlideshow);
		
		/* Fix up padding class. */
		if ($('#Ctrl #Padding').hasClass('Pad2But'))
		{
			$('#Ctrl #Padding').removeClass('Pad2But').addClass('Pad3But');
		}
		else if ($('#Ctrl #Padding').hasClass('Pad3But'))
		{
			$('#Ctrl #Padding').removeClass('Pad3But').addClass('Pad4But');
		}

		/* Ensure initial slideshow state and control naming. */
		if (gSlideShowIsPaused)
		{
			PauseSlideshow();
		}
		else
		{
			ResumeSlideshow();
		}
	
		/* NOTE: the album links are left as page-reloads for the simple reason that
				   otherwise all images from all albums would have to be loaded for the
				   JavaScript to be able to 'instantly switch' which could result in
				   a very, VERY large number of images being loaded. As it is, several
				   hundred could be loaded in any one album but this is manageable in
				   comparison with possibly thousands from multiple albums. */
	}
}
