/**
 * NIFAB Image Gallery Script
 * (read doc/README for info)
 *
 * Compile http://closure-compiler.appspot.com
 **/


/**
 *
 * nifabgallery
 *
 * @param string gid node id to use for image gallery
 * @param string layout name of player layout - 'fullversion', 'mainmedia' or 'inline'
 **/
function nifabgallery( gid, layout )
{
	
	// Reference to container DOM element.
	var gallery = $('#ig' + gid );
	gallery.find('div.poster').css({ opacity: '0.5' });
	
	var layout = layout;
	
	var nifabGalleryVersion = { 
								FULLVIEW: 'full',
								EMBED: 'embed',
								MAIN: 'main' 
							  };
	
	if( layout == nifabGalleryVersion.EMBED &&  $('#NodeClass').val() == 'news' )
		gallery.addClass( 'embednews' );
	
	// If true, gallery is autoplaying.
	var autoplay = false;
	
	// In autoplaying, how long should every image be displayed before 
	// switching to next. In milliseconds ( 1000 = 1 sec ).
	var delay = 5000;
	
	var playerHeight = 0;
	
	// Index of currently display image. -1 == posterimage is displayed.
	var index = -1;
	
	// Maximium value the gallery can have. Is set in jsonCallback function.
	var maxIndex = -1;
	
	// Constants for navigation and playing
	var GOTO_FIRST='goto_first', GOTO_PREVIOUS='goto_previous', GOTO_NEXT='goto_next', GOTO_LAST='goto_last';
	
	
	/**
	 * jsonCallback
	 *
	 * Handles the jQuery callback function for the AJAX call to fetch images in imageinfo.
	 *
	 * After images are loaded into DOM, events are attached to poster and 
	 * gallery navigation DOM elements.
	 *
	 * @param object data Data returned from the server is in JSON format. jQuery passes it
	 * 					  to this function as an object.
	 **/
	var jsonCallback = function( data )
	{		
		// Define max index for gallery.
		maxIndex = data.imageCount - 1;
		delay = data.delay;
		playerHeight = data.playerHeight;
		
		// Loop through every image in JSON and create image and imageinfo to DOM.
		for( var image in data.images )
		{
			//var img = $( '<div class="image hidden"><img src="' +  data.images[image].image.url + '" /></div>' );
			var img = $( '<div class="image hidden" style="height:' + playerHeight + 'px;background: url(' +  data.images[image].image.url + ') center center no-repeat;"></div>' );
 			$('#ig' + gid + '_images .imagecell').append( img );
			
			gallery.find( '.loader' ).addClass( 'hidden' );
			gallery.find( '.navigator' ).removeClass('hidden');
			
			// Only add info if we are in fullview
			if( layout == nifabGalleryVersion.FULLVIEW )
			{
				var info = $( '<div class="info hidden">' + data.images[image].caption + '</div>' );
 				$('#ig' + gid + '_info').append( info );
				
				gallery.find( '.infocontainer .counter .maxIndex' ).html( maxIndex+1 );
				
			}
			
		}
		
		// Attached event to initial poster. When clicked it will execute a
		// goPlayPause event.
		gallery.find('div.poster-overlay').click( function(){ goPlayPause(); return false; } );
		
		gallery.find( '.canvas .imagescontainer .image' ).click( function(){ goPlayPause(); return false; });
		
		// Attach events to navigation elements
		gallery.find( '.navigator .first A' ).click( function(){  prepareGoTo( GOTO_FIRST ); return false; } );
		gallery.find( '.navigator .previous A' ).click( function(){ prepareGoTo(GOTO_PREVIOUS); return false; } );
		gallery.find( '.navigator .playpause A' ).click( function(){ goPlayPause(); return false; } );
		gallery.find( '.navigator .next A' ).click( function(){ prepareGoTo(GOTO_NEXT); return false; } );
		gallery.find( '.navigator .last A' ).click( function(){ prepareGoTo(GOTO_LAST); return false; } );
		
		gallery.find( '.poster-overlay IMG' ).attr('src', '/extension/nifabgallery/design/standard/images/player-starter.gif');
	}
	
	
	/**
	 * 
	 **/
	var prepareGoTo = function( action )
	{
		gallery.find( '.timeslider .slider' ).stop().css({ width:0 }); 
		autoplay=false; 
		//togglePlayPauseButtonIcon();
		gallery.find( '.navigator .buttons .playpause' ).removeClass( 'playing' );
		
		goTo(action);
	}
	
	
	/**
	* goTo
	*
	* This function switches the image in the gallery. The param @navAction indicates what kind of
	* action we want to take upon the gallery. 
	* 
	* @param int action Can be GOTO_FIRST, GOTO_PREVIOUS, GOTO_NEXT, GOTO_LAST. 
	*                   The same as used in switch within this function.
	**/
	var goTo = function( action )
	{
		var nextIndex = index;
		var next = -1;
		
		// Hide poster
		if( !gallery.find( '.canvas .poster-overlay' ).hasClass( 'hidden' ) )
			gallery.find( '.canvas .poster-overlay' ).addClass( 'hidden' );
		
		// Find action, and calculate nextIndex.
		switch( action )
		{
			case GOTO_FIRST:
				nextIndex = 0;
				break;
			case GOTO_PREVIOUS: 
				nextIndex--;
				break;
			case GOTO_NEXT:
				nextIndex++;
				break;
			case GOTO_LAST:
				nextIndex = maxIndex;
				break;
			default:
				nextIndex++;
				break;
		}
		
				
		// Check if nextIndex is out of bounds and correct it inside.
		if( nextIndex < 0 )
			nextIndex = maxIndex;
		else if( nextIndex > maxIndex )
			nextIndex = 0;
		
		// Hides all images.
		gallery.find( '.canvas .imagescontainer .image' ).addClass('hidden');
		
		// Gallery has not started. Hide poster, remove hidden from 
		// .imagescontainer and set index to 0.
		if( index == -1 )
		{
			gallery.find( '.canvas .poster' ).hide();
			gallery.find( '.canvas .imagescontainer' ).removeClass( 'hidden' );
		}
		
		// Only try to switch image info in full version.
		if( layout == nifabGalleryVersion.FULLVIEW )
		{
			// Show info for image
			var infos = gallery.find( '.infocontainer .info' );
			infos.addClass( 'hidden' );
			infos.eq(nextIndex).removeClass( 'hidden' ).show();	
			
			gallery.find( '.infocontainer .counter .index' ).html( nextIndex+1 );			
		}
		
		// Store index
		index = nextIndex;
				
		// Show image
		var images = gallery.find( '.canvas .imagescontainer .image' );
		images.eq(nextIndex).hide().removeClass('hidden').fadeIn(function(){
			if( autoplay )
				_autoplay();
		});
	}
	
	
	/**
	 * _autoplay
	 *
	 * This functino is used to handle autoplaying. When called, it will wait 5 seconds
	 * and call the function @goTo. 
	 *
	 * Internally, it controls the timeslider. And the function doesn't use the setTimeout
	 * function for the delay, but the animation function of jQuery. When the animation is
	 * complete the function @goTo is called. 
	 **/
	var _autoplay = function()
	{
		// DOM handles to the timeslider
		var p = gallery.find( '.timeslider' );
		var s = p.find( '.slider' );
		
		// If gallery is paused, we need to calculate the remaining time left of delay,
		// before the animation was paused. 
		_delay = delay;
		
		
		if( s.width() == p.width() )
		{
			s.css({ width:0 });
		}
		else
		{
			_delay = Math.ceil(delay - (delay * ( ( ( s.width() / p.width() ) * 100 ) / 100 )));
		}
		
		// Animate the timeslider and call function @goTo on complete. For easing, use
		// 'linear' or 'swing', which are the default internal easing methods in jQuery.
		s.animate({ width: p.width() + 'px' }, { duration: _delay, complete: function(){ s.css({width:0}); goTo(GOTO_NEXT); }, easing: 'linear' });
	}
	
	
	/**
	* goPlayPause
	*
	* Eventlistener for the Galleries Play/Pause button. 
	**/
	var goPlayPause = function()
	{
		var playbtn = gallery.find( '.navigator .buttons .playpause' );
		
		if( autoplay === false )
		{
			autoplay = true;
			togglePlayPauseButtonIcon();
			index === -1 ? goTo(GOTO_NEXT) : _autoplay();
		}
		else
		{
			togglePlayPauseButtonIcon();
			gallery.find( '.timeslider .slider' ).stop();
			autoplay = false;
		}
	}
	
	var togglePlayPauseButtonIcon = function()
	{
		var playBtn = gallery.find( '.navigator .buttons .playpause' );
		
		//if( playBtn.hasClass( 'playing' ) )
		//	console.log( 'change' );
		
		if( autoplay )
			playBtn.toggleClass( 'playing' );
		//else
		//	console.log( 'whaaat' );
	}
	
	// Prepares the url and calls on server to return the gallery as an JSON object.
	// Function @jsonCallback handles the callback, when jQuery has data returned from server.
	//var url = '/nifabgallery/get/' + gid + '/' + layout + '/' + new Date().getTime();
	var url = '/nifabgallery/get/' + $('#NodeID').val() + '/' + gid + '/' + layout + '/' + new Date().getTime();
	
	gallery.ajaxError(function(event, request, settings){
		//console.log( event );
		//console.log( request );
		//console.log( settings );
		gallery.find( '.loader' ).html('<span style="color:red">An error has occured for the image gallery. Please try to reload page.<br><b>' + request.responseText + '</b></span>');
	});
	
	gallery.find( '.poster-overlay' ).css({ 
		left: gallery.find( '.canvas' ).position().left + 'px', 
		top: gallery.find( '.canvas' ).position().top + 'px',
		width: gallery.find( '.canvas' ).width() + 'px',
		height: gallery.find( '.canvas' ).height() + 'px'
	});
	
	$.getJSON( url, null, jsonCallback );
	
}
