/*!
 * Welcome Screen - jQuery Plugin
 * http://www.veverka.eu/jquery/welcomescreen
 *
 * Copyright 2011, Martin Veverka
 *
 * Version: 1.0 (2011-03-03)
 * Requires: jQuery v1.4.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

(function($){
	$.fn.welcomeScreen = function(){

		var defaults = {
			fadeSpeed: 1000,
			animationMinTimeout: 5000,
			animationMaxTimeout: 15000
		};
		var options = $.extend(defaults, options);

		function getRandomNumber(min, max)
		{
			return Math.round((Math.random() * (max - min)) + min);
		}

		function getAreaSpeedRatio($area)
		{
			if ($area.attr('rel') == 'slow')
				return 1.5;

			if ($area.attr('rel') == 'fast')
				return 0.7;

			return 1;
		}

		function setFadeoutTimeout($area)
		{
			if ($area.children().length > 1)
			{
				setTimeout(
					function(){
						$area.trigger('animation');
						setFadeoutTimeout($area);
					},
					parseInt(getRandomNumber(options.animationMinTimeout, options.animationMaxTimeout) * getAreaSpeedRatio($area))
				);
			}
		}

		function initArea($area)
		{
			setFadeoutTimeout($area);

			$area.data('animationEnabled', true).bind('animation', function(){
				if ($area.data('animationEnabled'))
				{
					$area.data('animationEnabled', false);

					var total = $area.children().length;
					var $current = $area.find('img:visible');
					var $next = ($current.index() == total - 1) ? $area.children(':first') : $current.next();

					$next.show();
					$current.fadeOut(options.fadeSpeed, function(){
						$current.css('z-index', '1');
						$next.css('z-index', '9999');
						$area.data('animationEnabled', true);
					});
				}
			});
		}

		return this.each(function(){
			var $wsContainer = $(this);
			var $wsAreas = $wsContainer.find('.wsArea');
			var $wsImages = $wsContainer.find('img');
			var imageCount = 0;

			$wsImages.each(function(){
				var $currentImage = $(this);

				$currentImage.bind('click', function(){
					if ($currentImage.attr('rel'))
						window.location = window.location.protocol + '//' + window.location.hostname + '/' + $currentImage.attr('rel');
				});

				$('<img/>').attr('src', $currentImage.attr('src')).load(function(){
					++imageCount;

					if (imageCount == $wsImages.length)
					{
						$wsAreas.each(function(i){
							var $area = $(this);
							initArea($area);
						});
					}
				});
			});
		});
	};
})(jQuery);

