/**
 * NVS_ALBUM 
 * 
 * @author		Sebastiaan Smid <sebastiaan@netvlies.nl>
 * 
 * Optional parameters:
 * @category		jQuery Plugin
 * @package			Netvlies Album
 * @version			1.0
 * @requires		nvs_popup.js, nvs_overlay.js, jquery-easing.js
 *
 */
 
 (function($) {
	
	/**
	* Shows the album in a popup on an overlay
	* Mixed object: 
	*		overlayBackground:		(string) css,
	*		overlayTransparancy: 	(decimal) between 0 and 1,
	*		overlaySpeed:			(int time) milliseconds,
	*		popUpBackground:		(string) css,
	*		imageBtnPrev:			(string) Path and the name of the prev button image,
	*		imageBtnNext:			(string) Path and the name of the next button image,
	*		imageBtnClose:			(string) Path and the name of the next button image,
	
	* @param 	Object	Mixed
	* 
	*/
	
	$.fn.nvsAlbum = function(options) {
		var defaults = { 
		// Overlay config
	    	overlayBackground:		'black',
			overlayTransparancy: 	0.5,
			overlaySpeed:			500,
			popUpBackground:		'white',
			popUpDetailBackground: 	'white',
			popUpWidth: 			250,
			popUpHeight:			250,
			popUpPadding:			'10px',
			popUpFade:				true,
			imageBtnPrev:			'/img/nvsalbum_nav-left.gif',			// (string) Path and the name of the prev button image
			imageBtnNext:			'/img/nvsalbum_nav-right.gif',			// (string) Path and the name of the next button image
			imageBtnClose:			'/img/nvsalbum_nav-close.gif',
			imageBtnCloseBottom:	50,
			imageArray:				[],
			imageCounter:			false,
			fixedsize: 				false,
			activeImage:			0
		}
	
		var options = $.extend(defaults, options);
		var jQueryMatchedObj = this; 
			
		function _initialize() {
			// remove focus from clicked element
			this.blur();
			_start(this,jQueryMatchedObj);
			// stop following the anchor
			return false; 
		}
		
		
		function _start(objClicked,jQueryMatchedObj) { 
		// Reset total images in imageArray & activeImage
			options.imageArray.length = 0;
			options.activeImage = 0;

		// show the nvsOverlay
			$.nvsOverlay.show({ 
				background: options.overlayBackground, 
				transparancy: options.overlayTransparancy, 
				speed: options.overlaySpeed  
			});
		// show the nvsPopup
			$.nvsPopup.show({ 
				background: options.popUpBackground,
				width: 		options.popUpWidth,
				height: 	options.popUpHeight,
				padding:	options.popUpPadding,
				fade:		options.popUpFade,
				callback: function() { 
					_draw_nvsAlbum(objClicked); 
				}
			}); 
		}
		
		function _draw_nvsAlbum(objClicked) {
		// add album image to nvs_popup
			$('<img>').attr({ id: 'nvs_album-image' }).css({
					position: 'relative', 
					opacity: 0
				}).appendTo('#nvs_popup');
	/*		
		// add album navigation to nvs_popup
			$('<div>').attr({ id: 'nvs_album_navigation' }).css({ 
					position: 'absolute', 
					display: 'none',
					top: 0, 
					left: 0, 
					height: '100%', 
					width: '100%'
				}).appendTo('#nvs_popup');
		
			$('<div>').attr({ id: 'nvs_album_nav-left' }).css({ 
					background: 'url('+options.imageBtnPrev+') no-repeat left 20%', 
					left: 0, 
					float: 'left'
				}).appendTo('#nvs_album_navigation');
			$('<div>').attr({ id: 'nvs_album_nav-right' }).css({ 
					background: 'url('+options.imageBtnNext+') no-repeat right 20%', 
					right: 0, 
					float: 'right'
				}).appendTo('#nvs_album_navigation');
			
			$('#nvs_album_nav-left, #nvs_album_nav-right').css({ 
					cursor: 'pointer', 
					width: '49%', 
					height: '100%' });
	*/														   
		// add image details to nvs_popup
			$('<div>').attr({ id: 'nvs_album_image-details'}).css({
					position: 'relative', 
					display: 'none',
					textAlign: 'left',
					background: options.albumDetailBackground
				}).appendTo('#nvs_popup');
			$('<div>').attr({ id: 'nvs_album_image-description'}).appendTo('#nvs_album_image-details');

			if(options.imageCounter) {
				$('<div>').attr({ id: 'nvs_album_image-numbers'}).appendTo('#nvs_album_image-details');
			}
			
			$('<img>').attr({ id: 'nvs_album_image-close', src: options.imageBtnClose }).css({ 
					position: 'absolute',
					cursor: 'pointer', 
					display: 'none', 
					bottom: options.imageBtnCloseBottom,
					right: '17px'
				}).appendTo('#nvs_popup');


  			if ( jQueryMatchedObj.length == 1 ) {
				options.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));
			} else {
				// Add an Array with the href and title atributess		
				for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
					options.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));
				}
			}
			while ( options.imageArray[options.activeImage][0] != objClicked.getAttribute('href') ) {
				options.activeImage++;
			}

		// Show photo
			_add_events();
			image_to_view();
		}
		
		function image_to_view() {
			url =options.imageArray[options.activeImage][0];
			ext = url.substr((url.length-3),3);
			
			if(ext == 'png' || ext == 'gif' || ext == 'jpg' ) {
				var objImagePreloader = new Image();
				objImagePreloader.onload = function() {
					$('#nvs_album-image').attr('src',options.imageArray[options.activeImage][0]);
					_resize_nvs_popup(objImagePreloader.width,objImagePreloader.height);
					if(options.imageCounter) {
						$('#nvs_album_image-numbers').html('Afbeelding '+(options.activeImage+1)+' van '+options.imageArray.length);
					}
					//	clear onLoad, IE behaves strange with animated gifs otherwise
					objImagePreloader.onload=function(){};
				};
				objImagePreloader.src = options.imageArray[options.activeImage][0];	
			} else {
				
				$('#nvs_album-image').remove();
				$('<div>').attr({ id: 'nvs_album-image', width: 548, height: 352 }).css({
					position: 'relative', 
					opacity: 0,
					border: '0px'
				}).prependTo('#nvs_popup');
				
				url = url + "&json=1";
				
				$.ajax({
					type: "POST",
					cache: false,
					url: url,
					dataType: "json",
					success: function(data){
					/*
					*	The Returned JSON looks like this 
					*	msg : is the message that will be displayed when an error occurs or the mail has been send
					*	field: is an object with the form field and an error boolean 
					*
					*	({
					*			"html" : "<html>",
					*			"script" : "script"
					*	})
					*/	
						$("#nvs_album-image").html(data.html);
					
						eval(data.script);
						eval(data.onload);
					},
					error: function() {
						
						// when even the ajax call fails display an error
						alert('ajax call error');
					}
				});
				
				_resize_nvs_popup()
			
			}
		}
		
		function _resize_nvs_popup(w,h) {
			if(!options.fixedsize) {
				$.nvsPopup.resize({width: w, height: h, speed: 500 }, function(){ 
					$('#nvs_album-image').fadeTo(500, 1, function() { 
						$('#nvs_album-image').css("opacity", "");
						$('#nvs_popup').css({height: 'auto'});
						$('#nvs_album_image-description').html('' + options.imageArray[options.activeImage][1]);
						$('#nvs_album_image-details').slideDown(250, function() { 
							_addNavigation();
							$('#nvs_album_image-close').show();
							$('#nvs_album_navigation').show();
						});
					});
				});
			} else {
				$('#nvs_album-image').fadeTo(500, 1, function() { 
					$('#nvs_album-image').css("opacity", "");
					$('#nvs_album_image-description').html('' + options.imageArray[options.activeImage][1]);
					$('#nvs_album_image-details').show(100, function() { 
						_addNavigation();
						$('#nvs_album_image-close').show();
						$('#nvs_album_navigation').show();
					});
				});
			}
		}		
		
		function _add_events() {
		// close album when nvs_overlay, nvs_popup_container or nvs_album_nav-close are clicked
			$('#nvs_overlay, #nvs_popup_container, #nvs_album_image-close').click( function () { _finish(); });
		// do nothing when clicked on the nvs_popup
			$('#nvs_popup').click( function() { return false; });
		}
		
		function _addNavigation() {	
			
			if($('#nvs_album-image').length > 0) { 
				/*  If statement needed because it created an lbiOffset undefined when 
					closing the album while it was sliding down the image-details.
					(maybe do _add_events() in here and remove those events before animating)
				*/
				lbiOffset =  $('#nvs_album-image').position();
	
				$('#nvs_album_navigation').css({ 
					top: lbiOffset['top'], 
					left: lbiOffset['left'], 
					width: $('#nvs_album-image').width(), 
					height :$('#nvs_album-image').height() 
				});
				
				if(options.activeImage != ( options.imageArray.length - 1 ) ) { 
					$('#nvs_album_nav-right').show();
				} else {
					$('#nvs_album_nav-right').hide();	
				}
				if(options.activeImage != 0 ) { 
					$('#nvs_album_nav-left').show(); 
				} else { 
					$('#nvs_album_nav-left').hide(); 
				}
		
				$('#nvs_album_nav-right').click(function() {
					if ( options.activeImage != ( options.imageArray.length - 1 ) ) {
						_removeNavigation();
						options.activeImage = options.activeImage + 1;
						_navClick();
					}								  
				});
				$('#nvs_album_nav-left').click(function() { 
					if ( options.activeImage != 0 ) {
						_removeNavigation();
						options.activeImage = options.activeImage - 1;
						_navClick();
					}							  
				});
				
				$(document).bind('keydown', _keyboard_action);
			}
		}
		
		function _navClick() {
			$('#nvs_album_navigation').hide();
			if(!options.fixedsize) {
				$('#nvs_album_image-details').slideUp(250, function () {
					$('#nvs_popup').css({height: $('#nvs_popup').height()});
					$('#nvs_album-image').fadeTo(250, 0, image_to_view);
				});
			} else {
				$('#nvs_album_image-details').hide(100, function () {
					$('#nvs_album-image').fadeTo(250, 0, image_to_view);
				});
			}
					
		}
		
		function _removeNavigation() {
			$('#nvs_album_image-close').hide();
			$('#nvs_album_nav-left, #nvs_album_nav-right').unbind();
			$(document).unbind('keydown', _keyboard_action);
		}
		
		function _keyboard_action(objEvent) {
			switch(objEvent.keyCode) {
			// key ESC
				case 27: 	_finish(); 
							break;
			// key X
				case 88:	_finish();
							break;
				default: 	break;
			}
		}
		
		function _finish() {
			$(document).unbind('keydown', _keyboard_action);
			if(options.popUpFade) {
				$('#nvs_popup_container').fadeTo('fast', 0, function () { 
					$.nvsOverlay.hide(); 
					$('#nvs_popup_container').remove() 
				});
			} else {
				$.nvsOverlay.hide(); 
				$('#nvs_popup_container').remove() 
			}
		}
		
		return this.unbind('click').click(_initialize);
	}
	
})(jQuery);
