/**
 * jQuery timedImageSwap plugin
 */
(function(jQuery) {
	/**
	 * jQuery is an alias to jQuery object
	 *
	 */
	jQuery.fn.timedImageSwap = function(settings) {
		var IMGSRC = 0;
		var IMGLNK = 1;
		var IMGCAP = 2;
		settings = jQuery.extend({
			// Internal variables
			imageArray:				[],
			activeImage:			0,
			activeCont:				0,
			
			// Default configuration
			imageClass:				'',			// Image class
			captionClass:			'',			// Caption class
	
			randomStart:			0,			// Randomize start Image
			swap:							1,			// Swap between images
			swapRandom:				0,			// Randomize swap order
			swapTime:					'5s',		// Swap interval
			fadeTime:					0.7,		// Image fade time
			
			caption:					1,			// Show caption
			captionFx:				'fade',	// Show caption effect
			captionFxTime:		1,			// Show caption effect time
			captionFxDelay:		0,			// Show caption effect time
			captionRte:				0				// Caption is substituted with RTE text
			
		},settings);

		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object

		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		//return this.unbind('click').click(_initialize);

		_initialize();

		/**
		 * Initializing the plugin calling the start function
		 */
		function _initialize() {
			// Create Array with src and title attributes
			jQueryMatchedObj.each(function () {
				settings.imageArray.push(
					new Array(jQuery(this).attr('src'),
										jQuery(this).attr('alt'),
										jQuery(this).attr('title')));				
			});
			
			// set timer if we want to swap image
			if(settings.swap == 1){
				jQuery('.'+settings.imageClass+'_0').everyTime(settings.swapTime, 'swapImage', function() {
					_swap();
				});
			}

			// randomly choose start image?
			if(settings.randomStart == 1){
				settings.activeImage = _randomize(settings.imageArray.length);
			} else {
				settings.activeImage = 0;
			}

			// set image
			_set_image_to_view(true);

			return false; // Avoid the browser following the link
		}

		/**
		 * The function that will be called by the timer
		 */
		function _swap() {
			if(settings.swapRandom == 1){
				// randomly select next active image
				settings.activeImage = _randomize(settings.imageArray.length);
			} else {
				// increment active image by 1
				settings.activeImage = (settings.activeImage + 1) % settings.imageArray.length;
			}

			// set the new image
			_set_image_to_view(false);
		}

		/**
		 * Prepares image exibition; doing a imageīs preloader to calculate itīs size
		 */
		function _set_image_to_view(skipfade) {
			// Image preload process
			var objImagePreloader = new Image();
			objImagePreloader.onload = function() {
				_show_image(skipfade);
				//clear onLoad, IE behaves irratically with animated gifs otherwise
				//objImagePreloader.onload=function(){};
			};
			objImagePreloader.src = settings.imageArray[settings.activeImage][IMGSRC];
		};

		/**
		 * Show the prepared image
		 *
		 */
		function _show_image(skipfade) {
			var imageTime = settings.fadeTime*1000;
			var captionTime = settings.captionFxTime*1000;
			var captionDelay = settings.captionFxDelay*1000;
			
			var caption = '.'+settings.captionClass;
			var captionText = '.'+settings.captionClass+'_text';

			// fade
			if(!skipfade){
				var fadeOut = (settings.activeCont == 0 ? '.'+settings.imageClass+'_0' : '.'+settings.imageClass+'_1');
				var fadeIn = (settings.activeCont == 0 ? '.'+settings.imageClass+'_1' : '.'+settings.imageClass+'_0');

				// set image
				jQuery(fadeIn).attr('src',settings.imageArray[settings.activeImage][IMGSRC]);

				// only fade if we swap to a different image
				if(jQuery(fadeIn).attr('src') != jQuery(fadeOut).attr('src')){
					jQuery(fadeOut).fadeOut(imageTime);
					jQuery(fadeIn).fadeIn(imageTime);
					
					_bind_click(fadeIn, fadeOut, settings.imageArray[settings.activeImage][IMGLNK]);
					
					if(settings.caption == 1){
						// don't change caption if rte text is used
						if(settings.captionRte == 0){
							// set caption
							jQuery(captionText).oneTime(imageTime/2, 'swapCaption', function() {
								jQuery(captionText).html(settings.imageArray[settings.activeImage][IMGCAP]);
							});
						}
	
						_bind_click(caption, null, settings.imageArray[settings.activeImage][IMGLNK]);
						_bind_click(captionText, null, settings.imageArray[settings.activeImage][IMGLNK]);
					}
					
					settings.activeCont = (settings.activeCont == 0 ? 1 : 0);
				}

			// dont fade (page load)
			} else {
				var fadeOut = '.'+settings.imageClass+'_1';
				var fadeIn = '.'+settings.imageClass+'_0';
				
				jQuery(captionText).html(settings.imageArray[settings.activeImage][IMGCAP]);

				// set new image (set image on fadeOut aswell to fix broken image bug in IE7)
				jQuery(fadeIn).attr('src',settings.imageArray[settings.activeImage][IMGSRC]);
				jQuery(fadeOut).attr('src',settings.imageArray[settings.activeImage][IMGSRC]);
				
				_bind_click(fadeIn, fadeOut, settings.imageArray[settings.activeImage][IMGLNK]);
				
				// animate caption container and caption text
				if(settings.caption == 1){
					// callback
					var cb = '';
					if(typeof gc_gallery_callback_caption_effect == 'function') {
						var cb = 'gc_gallery_callback_caption_effect();';
					}
					
					if(settings.captionFx == 'fade'){
						setTimeout(function() {
							jQuery(caption).fadeIn(captionTime);
							jQuery(captionText).fadeIn(captionTime, function(){eval(cb);});
						}, captionDelay);
					} else if(settings.captionFx == 'slide') {
						setTimeout(function() {
							jQuery(caption).slideDown(captionTime);
							jQuery(captionText).slideDown(captionTime, function(){eval(cb);});
						}, captionDelay);
					} else {
						jQuery(caption).show();
						jQuery(captionText).show();
						eval(cb);
					}
					
					_bind_click(caption, null, settings.imageArray[settings.activeImage][IMGLNK]);
					_bind_click(captionText, null, settings.imageArray[settings.activeImage][IMGLNK]);
				}
			}

			if(settings.swapRandom == 0){
				_preload_next_images();
			}
		};

		function _bind_click(fadeIn, fadeOut, linkurl){
		  // bind new click event to both images (if url is not empty)
		  if(linkurl != ""){
		  	jQuery(fadeIn).css('cursor','pointer').click(function(){window.location = linkurl;})
		  	if(fadeOut != null){jQuery(fadeOut).css('cursor','pointer').click(function(){window.location = linkurl;})}
		  } else {
				jQuery(fadeIn).css('cursor','default');
				if(fadeOut != null){jQuery(fadeOut).css('cursor','default')};
		  }
		}


		/**
		 * Preload next image to show
		 *
		 */
		function _preload_next_images() {
			if ((settings.imageArray.length - 1) > settings.activeImage ) {
				objNext = new Image();
				objNext.src = settings.imageArray[settings.activeImage + 1][IMGSRC];
			} else {
				objNext = new Image();
				objNext.src = settings.imageArray[0][IMGSRC];
			}
		}

		/**
		 * Return a random number between 0 and maxval
		 */
		function _randomize(maxval){
			return Math.floor(Math.random()*maxval)
		}

	};
})(jQuery); // Call and execute the function immediately passing the jQuery object