//--------------------------------------------------
//	Image gallery with auto rotator
//--------------------------------------------------
var imagesInGallery = 0;
var currentGalleryItemKey = 0; // galleryImages array key
var timerFadeTogglerObject = false;
var timeoutInterval = 5500;
var imageTransitionSpeed = 600;
var currentNavItem = '';
var pauseGallery = false;
var imgNavEvent = false;

$('document').ready(function() {
	preLoadImages(galleryImages);
	
	// number of images in gallery
	imagesInGallery = galleryImages.length;
	
	// Set image transition timer
	timerFadeTogglerObject = setTimeout("fadeToggler()", timeoutInterval);

	//	Event for play/pause button
	$('#playPause').click(function(){
		timerToggle('#playPause');
		return false;
	});
	
	// Event for item navigation buttons
	$('#galleryNav').click(function(event) {
		
		var goToGalleryItem = event.target.parentNode.id.substr(4);
		
		// Event can be fired from other elements as we rely on catching by event bubbling
		//console.log("item click 1 "+timerFadeTogglerObject);
		
		if(false == isNaN(goToGalleryItem))
		{
			// stop multiple click on same button
			if(event.target.parentNode.id == currentNavItem)
			{
				$("#photoSlide").stop(true, true);
				return false;
			}
			currentNavItem = event.target.parentNode.id;
			
			imgNavEvent = true;
			
			// stop currently running animation 
			$("#photoSlide").stop(true); //clearQueue = true 
	
			// cancel current fade in timer
			if(timerFadeTogglerObject)
			{
				clearTimeout(timerFadeTogglerObject);
				timerFadeTogglerObject = false;
			}
			
			// The gallery will start rotation if it was paused
			$('#playPause').attr('src', '/img/n_pause.png').attr('alt', 'pause');
			
			fadeToggler(goToGalleryItem, 1);
		}
		return false;
	});	
	
	
	// Event for vertical gallery image clicks
	$('#vGalleryItems').click(function(event) {
		
		var goToGalleryItemFromVertical = event.target.id.substr(3);
		
		// Event can be fired from other elements as we rely on catching by event bubbling
		if(false == isNaN(goToGalleryItemFromVertical))
		{
			// cancel current fade in timer
			if(timerFadeTogglerObject)
			{
				clearTimeout(timerFadeTogglerObject);
				timerFadeTogglerObject = false;
			}
			
			// stop currently running animation 
			$("#photoSlide").stop(true); //clearQueue = true 
			
			fadeToggler(goToGalleryItemFromVertical, 1);
		}
		return false;
	});	
})


//----------------------------------------------------
//	Fade image out and new image in
//----------------------------------------------------
function fadeToggler(goToGalleryItem, navAction)
{
	// Image to show next
	if(goToGalleryItem)
	{
		currentGalleryItemKey = goToGalleryItem - 1;
	}
	else
	{
		if(currentGalleryItemKey >= imagesInGallery - 1)
		{
			currentGalleryItemKey = 0;
		}
		else
		{
			currentGalleryItemKey++;
		}
	}
	

	// fade current image out
	$('#canvasRight').fadeOut(imageTransitionSpeed, function() {
		// 	reset div photo slide to 0 for when 
		//	vertical slider is stopped during progress 
		$("#photoSlide").stop(true, true);
		$("#photoSlide").css("top", "0px");
		
		// change to next image
		$(this).attr('src', '/uploads/images/image_'+galleryImages[currentGalleryItemKey].imageUrl);
		
		// Title text update
		$('#galleryTitle').html(galleryImages[currentGalleryItemKey].title);
		
		// Read more link update
		$('#readMore').attr('href', galleryImages[currentGalleryItemKey].href);
		
		// highlight current gallery item page
		$('#galleryNav li').removeClass('current');
		$('#item'+(currentGalleryItemKey+1) ).addClass('current');
	
		// show loader gif until the next main image loads
		$('#loading').attr('display', 'block');
		
		//var imgHeight = $('#canvasRight').height(); // new image might not have loaded yet so not reliable. 
		var imgHeight = galleryImages[currentGalleryItemKey].height;
		var dstHeight = 286;
		var startHeight = 0;
		
		// If image has greater height than viewable area, move it up so that the bottom is visable
		if (imgHeight > dstHeight) {
			startHeight = imgHeight - dstHeight;
			$("#photoSlide").css("top", "-"+startHeight+"px");
		}
		
		
		// fade the image new in
		$(this).fadeIn(imageTransitionSpeed,function(){
			
			// if the height of image is over the visible section scroll image up
			if(0 < startHeight)
			{
				$("#photoSlide").stop(true, true).animate({top:'0px'},
				{
					complete: function(){
						$(this).stop(true); 
						$(this).css("top", "0px");
						
						//	Allow user to view the image for set interval 
						// start next image load iteration. This allows user to view image for set time interval
						if(timerFadeTogglerObject)
						{
							clearTimeout(timerFadeTogglerObject);
							timerFadeTogglerObject = false;
						}
						
						if(false == pauseGallery)
						{
							timerFadeTogglerObject = setTimeout("fadeToggler()", timeoutInterval);
						}
					},
					queue:true,
					duration:3000
				});
			}
			else
			{
				// start next image load iteration. This allows user to view image for set time interval
				if(timerFadeTogglerObject)
				{
					clearTimeout(timerFadeTogglerObject);
					timerFadeTogglerObject = false;
				}
				timerFadeTogglerObject = setTimeout("fadeToggler()", timeoutInterval);
			}
			currentNavItem = "";
		});
		
		// move the vertical gallery
		vGallery['imageShowNext'] = currentGalleryItemKey+1;
		verticalScroller(navAction);
	});
}


//----------------------------------------------------
//	Play / Pause gallery rotation
//----------------------------------------------------

function timerToggle(elementId)
{
	
	if(timerFadeTogglerObject || true == imgNavEvent)
	{
		// Stop the gallery rotation
		pauseGallery = true;
		clearTimeout(timerFadeTogglerObject);
		timerFadeTogglerObject = false;
		$(elementId).attr('src', '/img/n_play.png');
		$(elementId).attr('alt', 'play');
		imgNavEvent = false;
	}
	else
	{
		// play the gallery rotation
		timerFadeTogglerObject = setTimeout("fadeToggler()", timeoutInterval);
		pauseGallery = false;
		$(elementId).attr('src', '/img/n_pause.png');
		$(elementId).attr('alt', 'pause');
	}
}


//----------------------------------------------------
//	Preload all images in the background
//----------------------------------------------------
function preLoadImages(arrayName)
{
	var images = new Array();
	var galleryKeyMax = arrayName.length - 1;
	
	// load from second image
	for(var i = 1; i <= galleryKeyMax; i++)
	{
		$('#wrapper').append('<img class="preloadImg" src="/uploads/images/image_'+arrayName[i].imageUrl+'" />');
	}
}


//--------------------------------------------------
// Vertical auto-scrolling gallery 
//--------------------------------------------------

var vGallery = {
	'totalImages' : 0,      
	'imageHeight': 126,          
	//'timeInterval' : 6000, //ms
	'transitionSpeed' : 600,
	'timerObj' : false,
	'scrollHeight' : 0,
	'showImagesCount' : 3,
	'currentLastImage' : 3,
	'imageShowNext' : 3
};

$('document').ready(function() {
	vGallery['totalImages'] = galleryImages.length;
});


function verticalScroller(navAction)
{
	// Setup the items
	
	if (navAction) {
		// If jumping to an item, remove all existing and recreate
		$('ul#vGalleryItems li:not(:first)').remove();
		appendvGalleryItem(vGallery['imageShowNext']-2);
		appendvGalleryItem(vGallery['imageShowNext']-1);
		appendvGalleryItem(vGallery['imageShowNext']);
	} else {
		appendvGalleryItem(vGallery['imageShowNext']);
	}
	
	
	// then scroll list up 
	$("#vGalleryItems").animate({
		top: '-'+vGallery['imageHeight']
	}, vGallery['transitionSpeed'], function(){
		
		// remove the element that has gone off the display area
		$('ul#vGalleryItems li:first').remove();
		
		// set the stop back to zero
		$(this).css('top', '0px');
	});
}

function appendvGalleryItem(c)
{
	if (c<0) {
		c = vGallery['totalImages']-1;	
	} else if (c>vGallery['totalImages']-1) {
		c = 0;
	}
	$('#vGalleryItems').append('<li id="vGItem'+(vGallery['imageShowNext']+c)+'"><a href=""><img src="/uploads/images/thumb_'+galleryImages[c].imageUrl +'" id="'+galleryImages[c].idx +'" width="198" height="126" /></a></li>')
}



