//
// 
//  go.js
//
//

// ------------------------------------------------------------------------------------------------------------
//	constants
// ------------------------------------------------------------------------------------------------------------

// Note: IE barfs if 'const' is used instead of 'var'


var kSeparator 	= '/'


// ------------------------------------------------------------------------------------------------------------
//	pathFromURL
// ------------------------------------------------------------------------------------------------------------
function pathFromURL()
{
	var path = window.location.href.split("#")[1]

	if (!$defined(path))
	{
		path = '0' + kSeparator + '0'
	}
	
	return path
}

// ------------------------------------------------------------------------------------------------------------
//	fixUpEntryComponentsDimensions
// ------------------------------------------------------------------------------------------------------------
function fixUpEntryComponentsDimensions()
{
	var imageNodeCurrentSize = globalz.entryImage.getSize()
	
	var imageNodeNewWidth = (globalz.entryImage.retrieve('fotowidth')*imageNodeCurrentSize.y)/globalz.entryImage.retrieve('fotoheight')
	globalz.entryImage.setStyle('width', imageNodeNewWidth)
	
	// match the caption width to the imagenode width
	var imageNodeGeometry = globalz.entryImage.getCoordinates()
	globalz.entryCaption.setStyles({ 	width : imageNodeGeometry.width - 20, 
										left: imageNodeGeometry.left + 10})
	
}

// ------------------------------------------------------------------------------------------------------------
//	goto
// 
//  newDestinationPath should look like this: "8/2" which means gallery 8, foto 2 
//  (both galleries and fotos use zero-based indexing).
//
// ------------------------------------------------------------------------------------------------------------
function goto(newDestinationPath)
{
	var newGalleryIndex	= Number(newDestinationPath.split(kSeparator)[0])
		
	// Do some sanity checking
	if (isNaN(newGalleryIndex) || newGalleryIndex >= globalz.toc.galleries.length){
		newGalleryIndex = '0'
	}
		
	if (newGalleryIndex >= 0)
	{	
		var newFotoIndex 	= Number(newDestinationPath.split(kSeparator)[1])

		// Do some sanity checking
		if 	(	isNaN(newFotoIndex) ||	// newFotoIndex must be a number
				newFotoIndex==-1 	|| 	// newFotoIndex == -1 means 'go to gallery's current foto'
				newFotoIndex<-1 	|| 	// newFotoIndex must not be negative except unless it is -1
				(newGalleryIndex >= 0 && newFotoIndex >= globalz.toc.galleries[newGalleryIndex].entries.length) // newFotoIndex must point off the end of the entries array
			){
			
			newFotoIndex = globalz.currentFotoIndexes[newGalleryIndex]
		}
	
		var oldGalleryIndex
		var oldFotoIndex 
		if ($defined(globalz.currentPath))
		{
			oldGalleryIndex 		= globalz.currentPath.split(kSeparator)[0]	
			oldFotoIndex 			= globalz.currentPath.split(kSeparator)[1]	
		}
	
		var galleryChanged 	= !$defined(oldGalleryIndex) || (oldGalleryIndex != newGalleryIndex)
		if (galleryChanged)
		{
			makeGalleryLinkCurrent($('nav-overlay'), newGalleryIndex)
			
			
			// new 2008-10-19
			var fotonavIndexes = $('fotonav-indexes')
			fotonavIndexes.retrieve('fader').start(0).chain(function()
												{	
													globalz.fotonavController.syncFotonavNodes(newGalleryIndex, globalz.toc.galleries[newGalleryIndex].entries.length)
													globalz.fotonavController.setCurrentFotonavLink(oldFotoIndex, newFotoIndex)
													fotonavIndexes.retrieve('fader').start(1)
												})
			// end new
		}
		else
		{
			globalz.fotonavController.setCurrentFotonavLink(oldFotoIndex, newFotoIndex)
		}
		
		if (galleryChanged || newFotoIndex != oldFotoIndex) {

			globalz.currentFotoIndexes[newGalleryIndex] = newFotoIndex 	// record which foto is current for the new gallery 
			globalz.entryCluster.retrieve('fader').clearChain()
			globalz.entryCluster.retrieve('fader').cancel()

			globalz.entryImage.onload = function(){}


			// Since Firefox's image.complete implementation doesn't work,
			// we have to completely swap out the old image node and replace
			// it with a new one.
			
			// Build the new image node.
			// Note that we assign the src here so that we can 
			// overlap some load time with the fade out of the 
			// old image.
			var newEntry 			= globalz.toc.galleries[newGalleryIndex].entries[newFotoIndex]
			var newImageNode 		= new Element('img', {id:globalz.entryImage.id, height:globalz.entryImage.height})
			newImageNode.src 		= newEntry.fotopath
			newImageNode.store('fotowidth', newEntry.fotowidth)
			newImageNode.store('fotoheight' , newEntry.fotoheight)
								
			globalz.entryCluster.retrieve('fader').start(0).chain(function(){	

					// Swap in the new image node.
					newImageNode.replaces(globalz.entryImage)
					globalz.entryImage = newImageNode
					
					// We have to explicitly set the image node size because IE sucks.
					fixUpEntryComponentsDimensions()

					// preprocess caption to avoid double quoting
					var re = /&quot;/gi
					var fotocaption = newEntry.fotocaption.replace(re, '')
						
					globalz.entryCaptionText.set('html', fotocaption)
					
					// if we are running in IE or FF, we have to hack in the shadow...
					if (!globalz.cssTextShadowsSupported) {
						globalz.entryCaptionTextShadow.set('html', fotocaption)
					}
										
					globalz.arrowsController.updateLayout(newImageNode.getCoordinates())
					globalz.arrowsController.showPrevious(newFotoIndex>0)
					
					/*
					// If there are more fotos in this gallery, show the 'next' arrow.
					globalz.arrowsController.showNext(newFotoIndex<globalz.toc.galleries[newGalleryIndex].entries.length-1)
					*/
					globalz.arrowsController.showNext(true)
					
					
					
					if (globalz.entryImage.complete){   
						globalz.entrySpinner.spinner.goOffDuty()
					}
					else {
						globalz.entrySpinner.spinner.goOnDuty()
						globalz.entryImage.onload = function(){
								globalz.entrySpinner.spinner.goOffDuty()
							}
					}
				})
		}
	}	

	globalz.currentPath = newGalleryIndex.toString() + kSeparator + newFotoIndex.toString()

	var overlayID = newDestinationPath.split(kSeparator)[2]
	if (overlayID) {
		$(overlayID).retrieve('fader').start(0, 1)
		globalz.currentPath += kSeparator + overlayID
	}

	// Make sure the window's URL field is updated so that bookmarking works properly.
	window.location.href = window.location.href.split("#")[0] + "#" + globalz.currentPath	
	
	// Update the window title
	if (overlayID)
	{
		document.title = "danielle creasey | artist ::: " + overlayID
	}
	else
	{
		document.title = "danielle creasey | artist ::: " + globalz.toc.galleries[newGalleryIndex].name.unEncodeHTML() + " ::: " + (newFotoIndex+1).toString() + "/" + globalz.toc.galleries[newGalleryIndex].entries.length
	}
}

// ------------------------------------------------------------------------------------------------------------
//	goPreviousOrNextEventHandler
// ------------------------------------------------------------------------------------------------------------
	function goPreviousOrNextEventHandler(anEvent)
{
	if (anEvent == undefined){
		// :(  IE.
		anEvent = new Event(window.event)
	}

	if (anEvent.type == 'keydown' || anEvent.type == 'click') {

		var currentgalleryIndex = Number(globalz.currentPath.split(kSeparator)[0])	
		var fotoIndex 			= Number(globalz.currentPath.split(kSeparator)[1])	
		var	fotoCount			= globalz.toc.galleries[currentgalleryIndex].entries.length
		var newFotoIndex		= undefined
		var direction			= undefined
		
		if (anEvent.type == 'keydown'){

			if (anEvent.key == 'left' /* left arrow */){
				direction = 'backward'
			}
			else if (anEvent.key == 'right' /* right arrow */){
				// next
				direction = 'forward'
			}
			else if (anEvent.key == 'up' || anEvent.key == 'down' ) // Prevent up/down keys from scrolling in FF
			{	
				return false;
			}
		}
		else if (anEvent.type == 'click') {
		
			// If the x coord of the click was left of center, we'll go to the previous foto, 
			// otherwise we'll go to the next.
			var xMin = globalz.pagewrap.getPosition()['x']
			var xMax = xMin + globalz.pagewrap.getSize().x

			if (anEvent.client.x < (xMin+xMax)/2){
				// previous
				direction = 'backward'
			}
			else {
				// next
				direction = 'forward'
			}
		}
	
		if (direction != undefined)
		{
			var newFotoIndex = (direction == 'forward') ? (fotoIndex + 1) : Math.max(fotoIndex - 1, 0)
		
			if (newFotoIndex < fotoCount) {
				goto(currentgalleryIndex.toString() + '/' + newFotoIndex.toString())
			
				// reset the gallery's current foto to its first one
				var galleryIndex = globalz.currentPath.split(kSeparator)[0]	
				globalz.currentFotoIndexes[galleryIndex] = 0
			
				return false
			}
			else {
				//globalz.entryCluster.retrieve('fader').start(0).chain(showMenu)
				showMenu()
				return false
			}
		}
	}
	
	return true
}

// ------------------------------------------------------------------------------------------------------------
//	goToGalleryWithName
// ------------------------------------------------------------------------------------------------------------
function goToGalleryWithName(targetGalleryName)
{
	for (var g=0; g < globalz.toc.galleries.length; g++){
		var galleryName = globalz.toc.galleries[g].name.unEncodeHTML()
		if (galleryName == targetGalleryName){
			goto(g.toString())
			return
		}
	}
}

// ------------------------------------------------------------------------------------------------------------
//	makeGalleryLinkCurrent
// ------------------------------------------------------------------------------------------------------------
function makeGalleryLinkCurrent(navOverlayNode, galleryIndex)
{
	var galleryLinks = navOverlayNode.getElements('a')
	
	galleryLinks.each(function(galleryLink, index, array) {

		var linkID = galleryLink.get('id')

		if (linkID && galleryIndex == linkID.split('.')[1]){
			galleryLink.addClass('current')
		}
		else if (galleryLink.hasClass('current')){
			galleryLink.removeClass('current')
		}
	})
}



