/*!
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

(function() {
	var $ = jQuery,
		animate = ($.fn.startAnimation ? 'startAnimation' : 'animate'),
		pause_missing = 'pause plugin missing.';

	// utility to format a string with {0}, {1}... placeholders
	function format(str) {
		for (var i = 1; i < arguments.length; i++)
			str = str.replace(new RegExp('\\{' + (i-1) + '}', 'g'), arguments[i]);
		return str;
	}

	// utility to abort with a message to the error console
	function abort() {
		arguments[0] = 'CrossSlide: ' + arguments[0];
		throw new Error(format.apply(null, arguments));
	}

	// utility to parse "from" and "to" parameters
	function parse_position_param(param) {
		var zoom = 1;
		var tokens = param.replace(/^\s*|\s*$/g, '').split(/\s+/);
		if (tokens.length > 3) throw new Error();
		if (tokens[0] == 'center')
			if (tokens.length == 1)
				tokens = ['center', 'center'];
			else if (tokens.length == 2 && tokens[1].match(/^[\d.]+x$/i))
				tokens = ['center', 'center', tokens[1]];
		if (tokens.length == 3)
			zoom = parseFloat(tokens[2].match(/^([\d.]+)x$/i)[1]);
		var pos = tokens[0] + ' ' + tokens[1];
		if (pos == 'left top' || pos == 'top left')
			return { xrel: 0, yrel: 0, zoom: zoom };
		if (pos == 'left center' || pos == 'center left')
			return { xrel: 0, yrel: .5, zoom: zoom };
		if (pos == 'left bottom' || pos == 'bottom left')
			return { xrel: 0, yrel: 1, zoom: zoom };
		if (pos == 'center top' || pos == 'top center')
			return { xrel: .5, yrel: 0, zoom: zoom };
		if (pos == 'center center')
			return { xrel: .5, yrel: .5, zoom: zoom };
		if (pos == 'center bottom' || pos == 'bottom center')
			return { xrel: .5, yrel: 1, zoom: zoom };
		if (pos == 'right top' || pos == 'top right')
			return { xrel: 1, yrel: 0, zoom: zoom };
		if (pos == 'right center' || pos == 'center right')
			return { xrel: 1, yrel: .5, zoom: zoom };
		if (pos == 'right bottom' || pos == 'bottom right')
			return { xrel: 1, yrel: 1, zoom: zoom };
		return {
			xrel: parseInt(tokens[0].match(/^(\d+)%$/)[1]) / 100,
			yrel: parseInt(tokens[1].match(/^(\d+)%$/)[1]) / 100,
			zoom: zoom
		};
	}

	$.fn.adjustImageSizes = function() {
		var $bgContainer = $(this);
		$(this).find("img").each(function() {
			if ($bgContainer.width() / $bgContainer.height() < $(this).width() / $(this).height()) {
				$(this).css({
					width: "auto",
					height: "100%"
				});
				var w = ($bgContainer.width() - $(this).width()) / 2;
				$(this).css({
					"left": w + 'px',
					"top": '0px'
				});
			} else {
				$(this).css({
					width: "100%",
					height: "auto"
				});
				var h = ($bgContainer.height() - $(this).height()) / 2;
				$(this).css({
					"top": h + 'px',
					"left": '0px'
				});
			}			
		});
	},

	$.fn.crossSlide = function(opts, plan, callback, creationCallback)
	{
		var self = this,
				self_width = this.width(),
				self_height = this.height();

		// must be called on exactly 1 element
		if (self.length != 1)
			abort('crossSlide() must be called on exactly 1 element')

		// saving params for crossSlide.restart
		self.get(0).crossSlideArgs = [ opts, plan, callback ];

		// make working copy of plan
		plan = $.map(plan, function(p) {
			return $.extend({}, p);
		});

		// options with default values
		if (! opts.easing)
			opts.easing = opts.variant ? 'swing' : 'linear';
		if (! callback)
			callback = function() {};
		if (!creationCallback)
			creationCallback = function() {};


		// function loadMoreImagesIfNeeded() {
		// 	console.log(self.get(0).idx);
		// 	if (self.get(0).idx == SS_PRELOADING_WINDOW - 1 && SS_PRELOADING_WINDOW < originalPlan.length) {
		// 		var n_loaded = 0;
		// 		function loop(i, img) {
		// 			// this loop is a for (i = 0; i < plan.length; i++)
		// 			// with independent var i, img (for the onload closures)
		// 			img.onload = function(e) {
		// 				n_loaded++;
		// 				newPlan[newPlanCounter] = originalPlan[i];
		// 				newPlan[newPlanCounter].width = img.width;
		// 				newPlan[newPlanCounter].height = img.height;
		// 				newPlanCounter++;

		// 				proceedIfNeeded(n_loaded, null);
		// 			}

		// 			img.onerror = function(e) {
		// 				n_loaded++;
		// 				proceedIfNeeded(n_loaded, null);	
		// 			}

		// 			img.src = originalPlan[i].src;
		// 			console.log("incremental window");
		// 			console.log(SS_PRELOADING_WINDOW * parseInt(self.get(0).idx / SS_PRELOADING_WINDOW + 1.0));
		// 			console.log("--");
		// 			if (i + 1 < Math.min(originalPlan.length, SS_PRELOADING_WINDOW * parseInt(self.get(0).idx / SS_PRELOADING_WINDOW + 1.0) ))
		// 				loop(i + 1, new Image());
		// 		}
		// 		loop(self.get(0).idx, new Image());

		// 	}
		// }


		function proceedIfNeeded(n_loaded, proceed) {
			/*  || newPlanCounter >= Math.min(originalPlan.length, SS_PRELOADING_WINDOW) */
			if (n_loaded == originalPlan.length) {
				plan = newPlan;
				self.get(0).crossSlideArgs[1] = newPlan;
				if (proceed != null) {
					proceed();
				}							
			}
		}

		var originalPlan = plan;
		var newPlan = new Array();
		var newPlanCounter = 0;

		// first preload all the images, while getting their actual width and height
		(function(proceed) {

			var n_loaded = 0;
			function loop(i, img) {
				// this loop is a for (i = 0; i < plan.length; i++)
				// with independent var i, img (for the onload closures)
				img.onload = function(e) {				

					n_loaded++;
					newPlan[newPlanCounter] = originalPlan[i];
					newPlan[newPlanCounter].width = img.width;
					newPlan[newPlanCounter].height = img.height;
					var tmpAdditionalData = typeof(img.additionalData) == 'undefined' ? new Object() : img.additionalData;
					newPlan[newPlanCounter].additionalData = tmpAdditionalData;
					newPlan[newPlanCounter].additionalData.index = i;
					newPlanCounter++;

					proceedIfNeeded(n_loaded, proceed);
				}

				img.onerror = function(e) {
					n_loaded++;
					proceedIfNeeded(n_loaded, proceed);	
				}

				img.src = originalPlan[i].src;
				img.additionalData = originalPlan[i].data;
				if (i + 1 < originalPlan.length)
					loop(i + 1, new Image());
			}
			loop(0, new Image());

		})(function() { // then proceed

			// Sort the plan according to the original sort order
			plan.sort(function(a, b) {
				if (a.additionalData.index < b.additionalData.index)
					return -1;
				if (a.additionalData.index > b.additionalData.index)
					return 1;
				return 0;
			});
			self.get(0).crossSlideArgs[1] = plan;

			// check global params
			if (! opts.fade)
				abort('missing fade parameter.');
			if (opts.speed && opts.sleep)
				abort('you cannot set both speed and sleep at the same time.');

			// conversion from sec to ms; from px/sec to px/ms
			var fade_ms = Math.round(opts.fade * 1000);
			if (opts.sleep)
				var sleep = Math.round(opts.sleep * 1000);
			if (opts.speed)
				var speed = opts.speed / 1000,
						fade_px = Math.round(fade_ms * speed);

			// set container css
			self.empty().css({
				overflow: 'hidden',
				padding: 0
			});
			if (! /^(absolute|relative|fixed)$/.test(self.css('position')))
				self.css({ position: 'relative' });
			if (! self.width() || ! self.height())
				abort('container element does not have its own width and height');

			// random sorting
			if (opts.shuffle)
				plan.sort(function() {
					return Math.random() - 0.5;
				});

			// prepare each image
			for (var i = 0; i < plan.length; ++i) {

				var p = plan[i];
				if (! p.src)
					abort('missing src parameter in picture {0}.', i + 1);

				if (speed) { // speed/dir mode

					// check parameters and translate speed/dir mode into full mode
					// (from/to/time)
					switch (p.dir) {
						case 'up':
							p.from = { xrel: .5, yrel: 0, zoom: 1 };
							p.to = { xrel: .5, yrel: 1, zoom: 1 };
							var slide_px = p.height - self_height - 2 * fade_px;
							break;
						case 'down':
							p.from = { xrel: .5, yrel: 1, zoom: 1 };
							p.to = { xrel: .5, yrel: 0, zoom: 1 };
							var slide_px = p.height - self_height - 2 * fade_px;
							break;
						case 'left':
							p.from = { xrel: 0, yrel: .5, zoom: 1 };
							p.to = { xrel: 1, yrel: .5, zoom: 1 };
							var slide_px = p.width - self_width - 2 * fade_px;
							break;
						case 'right':
							p.from = { xrel: 1, yrel: .5, zoom: 1 };
							p.to = { xrel: 0, yrel: .5, zoom: 1 };
							var slide_px = p.width - self_width - 2 * fade_px;
							break;
						default:
							abort('missing or malformed dir parameter in picture {0}.', i+1);
					}
					if (slide_px <= 0)
						abort('impossible animation: either picture {0} is too small or '
							+ 'div is too large or fade duration too long.', i + 1);
					p.time_ms = Math.round(slide_px / speed);

				} else if (! sleep) { // full mode

					// check and parse parameters
					if (! p.from || ! p.to || ! p.time)
						abort('missing either speed/sleep option, or from/to/time params '
							+ 'in picture {0}.', i + 1);
					try {
						p.from = parse_position_param(p.from)
					} catch (e) {
						abort('malformed "from" parameter in picture {0}.', i + 1);
					}
					try {
						p.to = parse_position_param(p.to)
					} catch (e) {
						abort('malformed "to" parameter in picture {0}.', i + 1);
					}
					if (! p.time)
						abort('missing "time" parameter in picture {0}.', i + 1);
					p.time_ms = Math.round(p.time * 1000)
				}

				// precalculate left/top/width/height bounding values
				if (p.from)
					$.each([ p.from, p.to ], function(i, each) {
						each.width = Math.round(p.width * each.zoom);
						each.height = Math.round(p.height * each.zoom);
						each.left = Math.round((self_width - each.width) * each.xrel);
						each.top = Math.round((self_height - each.height) * each.yrel);
					});

				// append the image (or anchor) element to the container
				var img, elm;
				elm = img = $(format('<img src="{0}"/>', p.src));
				if (p.href)
					elm = $(format('<a href="{0}"></a>', p.href)).append(img);
				if (p.onclick)
					elm.click(p.onclick);
				if (p.alt)
					img.attr('alt', p.alt);
				if (p.rel)
					elm.attr('rel', p.rel);
				if (p.href && p.target)
					elm.attr('target', p.target);
				elm.appendTo(self);
				$(self).adjustImageSizes();

				// Refresh the image size 100ms after it has been added to the dom.
			}
			setTimeout(function() { creationCallback(plan[0].additionalData); }, 100);

			delete speed; // speed mode has now been translated to full mode

			// utility to compute the css for a given phase between p.from and p.to
			// 0: begin fade-in, 1: end fade-in, 2: begin fade-out, 3: end fade-out
			function position_to_css(p, phase) {
				var pos = [ 0, fade_ms / (p.time_ms + 2 * fade_ms),
					1 - fade_ms / (p.time_ms + 2 * fade_ms), 1 ][phase];
				return {
					left: Math.round(p.from.left + pos * (p.to.left - p.from.left)),
					top: Math.round(p.from.top + pos * (p.to.top - p.from.top)),
					width: Math.round(p.from.width + pos * (p.to.width - p.from.width)),
					height: Math.round(p.from.height + pos * (p.to.height-p.from.height))
				};
			}

			// find images to animate and set initial css attributes
			var imgs = self.find('img').css({
				position: 'absolute',
				display: 'none',
				top: 0,
				left: 0,
				border: 0
			});

			// show first image
			imgs.eq(0).css({ display: 'block' });
			if (! sleep)
				imgs.eq(0).css(position_to_css(plan[0], opts.variant ? 0 : 1));

			// create animation chain
			var countdown = opts.loop;
			
			self.get(0).idx = 0;
			function loopImages (currentIndex) {
				
				if (plan.length < 2) {
					return;	
				}
				
				var shouldPause = self.get(0).shouldPause;
				if (shouldPause === true) {
					self.get(0).isPaused = true;
					return;
				}
					
				currentIndex = currentIndex % plan.length;
				var previousIndex = currentIndex - 1 >= 0 ? currentIndex - 1 : plan.length - 1;	
				
				self.get(0).idx = currentIndex;
				callback(currentIndex, plan[currentIndex].additionalData);				
				
				$(imgs[currentIndex]).css("display", "block");
				$(imgs[currentIndex]).css("opacity", 0.0);
				
				setTimeout(function() {
					$(imgs[currentIndex]).parent().append($(imgs[currentIndex]));
					$(imgs[currentIndex]).animate({
							opacity: 1.0
						}, 
						fade_ms, 
						function() {
							$(imgs[previousIndex]).css("display", "none");
						});					
				}, 100);

					
				if (!shouldPause) {
					setTimeout(function(){
						loopImages(currentIndex + 1);
					}, sleep);
				}
			}
			
			loopImages(self.get(0).idx);
			
			self.get(0).loopImageFn = loopImages;			
			
		});
		return self;
	};

	$.fn.crossSlideStop = function()
	{
		this.find('img').stop().remove();
	}

	$.fn.crossSlideRestart = function()
	{
		this.find('img').stop().remove();
		$.fn.crossSlide.apply(this, this.get(0).crossSlideArgs);
	}

	$.fn.crossSlidePause = function()
	{
		this.get(0).shouldPause = true;
	}

	$.fn.crossSlideResume = function()
	{

		if (this.get(0).isPaused === true) {
			this.get(0).shouldPause = false;
			this.get(0).isPaused = false;

			var currentIndex = this.get(0).idx + 1;
			var plan = this.get(0).crossSlideArgs[1];
			currentIndex = currentIndex % plan.length;
			this.get(0).loopImageFn(currentIndex);			
		}
	}
	
	$.fn.fadeToImage = function (requestedIndex, callback) {
		var self = this;

		$(self).crossSlidePause();
		var plan = self.get(0).crossSlideArgs[1];
		var previousIndex = self.get(0).idx;
		var requestedPicture = plan[requestedIndex];
		var previousPicture = plan[previousIndex];

		if (requestedIndex < plan.length && previousIndex != requestedIndex) {

			var opts = self.get(0).crossSlideArgs[0];
			var fade_ms = Math.round(opts.fade * 1000);

			self.find('img').each(function () {
				$(this).stop();
			});

			callback(requestedIndex, plan[requestedIndex].additionalData);

			var $requestedImage = $("img[src='" + requestedPicture.src + "']");
			var $previousImage = $("img[src='" + previousPicture.src + "']");

			$requestedImage.css("display", "block");
			$requestedImage.css("opacity", 0.0);

			setTimeout(function () {
				$requestedImage.parent().append($requestedImage);
				$requestedImage.animate({
					opacity: 1.0
				}, fade_ms, function () {
					self.get(0).idx = requestedIndex;
					$previousImage.css("display", "none");
				});					
			}, 100);
		}
	}
	
	$.fn.isPaused = function() {
		return this.get(0).isPaused === true;
	}
	
	$.fn.goToNextImage = function(callback)
	{
		var self = this;
	
		var plan = self.get(0).crossSlideArgs[1];
		var currentIndex = self.get(0).idx + 1;
		currentIndex = currentIndex % plan.length;
		
		$(this).fadeToImage(currentIndex, callback);
		
	}
	
	$.fn.goToPreviousImage = function(callback)
	{
		var self = this;
	
		var plan = self.get(0).crossSlideArgs[1];
		var currentIndex = self.get(0).idx - 1;
		if (currentIndex == -1) {
			currentIndex = plan.length - 1;
		}
		
		$(this).fadeToImage(currentIndex, callback);
		
	}
})();
