/*!
 *
 * 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_over() {
		arguments[0] = 'CrossSlide: ' + arguments[0];
		throw new Error(format.apply(null, arguments));
	}

	

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

		var freezed;
		
		// must be called on exactly 1 element
		if (self.length != 1)
			abort_over('crossSlide() must be called on exactly 1 element')

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

		// 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 (! freezed) {
			freezed = false;
		}

		// 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++;
					plan[i].width = img.width;
					plan[i].height = img.height;
					if (n_loaded == plan.length)
						proceed();
				}
				img.src = plan[i].src;
				if (i + 1 < plan.length)
					loop(i + 1, new Image());
			}
			loop(0, new Image());

		})(function() { // then proceed

			// check global params
			if (! opts.fade)
				abort_over('missing fade parameter.');
			if (opts.speed && opts.sleep)
				abort_over('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_over('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_over('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_over('missing or malformed dir parameter in picture {0}.', i+1);
					}
					if (slide_px <= 0)
						abort_over('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_over('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_over('malformed "from" parameter in picture {0}.', i + 1);
					}
					try {
						p.to = parse_position_param(p.to)
					} catch (e) {
						abort_over('malformed "to" parameter in picture {0}.', i + 1);
					}
					if (! p.time)
						abort_over('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);
			}
			delete speed; // speed mode has now been translated to full mode


			// 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
			});

			for (var i=0;i<=imgs.length-1;i++)
			{	
				imgs[i].setAttribute("permalink", plan[i].permalink);
				imgs[i].setAttribute("class", "homelinkimg");
			}
			
			// 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;
			
			/* 
			console.log("initFade"); 
			console.log(sleep); 
			console.log(plan.length);
			console.log(imgs); 
			console.log(fade_ms);			
			*/
			
			self.get(0).idx = 0;
			function loopImages (currentIndex) {
				
				if (plan.length < 2) {
					return;	
				}
				
				var shouldPause = self.get(0).crossSlideArgs[3];
				if (shouldPause) {
					return;
				}
					
				currentIndex = currentIndex % plan.length;
				var previousIndex = currentIndex - 1 >= 0 ? currentIndex - 1 : plan.length - 1;	
				
				self.get(0).idx = currentIndex;
				
				callback(currentIndex);				
				
				$(imgs[currentIndex]).css("display", "block");
				$(imgs[currentIndex]).css("opacity", 0.0);
				$(imgs[currentIndex]).css("top","-300px");
				$(imgs[currentIndex]).css("left","0px");

				
				  var Paths = {"arc":[]}
  
				  var path_fns = {
				    arc: function(i) {
				      return new $.path.arc({
				        center: [0,-20],	
				    		radius: 20,	
				    		start: 0,
				    		end: (i % 2) ? 90 + i * 10 : -90 - i * 10,
				    		dir: (i % 2) ? 1 : -1
				      })
				    }
				  }
				  
				  
				  for(var type in Paths) {

				    for(var i=0; i<=10; i++ ) {
				        
				      var path = path_fns[type](i);
				      Paths[type].push(path);
				        //marginLeft: -10*(1+i), // offset the div, so center is at origin
				        //marginTop: -10*(1+i) 

				    }
				  }
				
				var type = "arc";
				
				var numLow = 1;
		        var numHigh = 2;
		
		        var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
		
		        var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);

		        // Animate in
				$(imgs[currentIndex]).animate({
						opacity: 1.0, 
						top: "0px"
					}, 
					fade_ms, 
					function() {

						// Animate with "fantasy" animation
						//console.log("animate fantasy " + currentIndex);
						$(imgs[currentIndex]).animate({
							path: Paths[type][numRand] 
						}, 3000,
						function () {
							// Animate out
							//console.log("animate out " + currentIndex);
							$(imgs[currentIndex]).animate({
								opacity: 0.0, 
								left: "200px"
							}, 
							fade_ms, 
							function() {
								$(this).css("display", "none");
							});								
						});
					}
				);
					
				if (!shouldPause) {
					setTimeout(function(){
						loopImages(currentIndex + 1);
					}, fade_ms * 2 + 4000);
				}
			}
			
			loopImages(self.get(0).idx);
			
			self.get(0).loopImageFn = loopImages;
					
		});
		
		return self;
	};

	$.fn.crossSlideFreeze_over = function()
	{
		this.get(0).crossSlideArgs[3] = true;				
		this.find('img').stop();
	}

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

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

	$.fn.crossSlidePause_over = function()
	{
		this.get(0).crossSlideArgs[3] = true;
	}

	$.fn.crossSlideResume_over = function()
	{
		if (this.get(0).crossSlideArgs[3] = true) {
			this.get(0).crossSlideArgs[3] = false;
			var currentIndex = this.get(0).idx;
			this.get(0).loopImageFn(currentIndex);			
		}
	}
	
	$.fn.fadeToImage_over = function(requestedIndex, callback)
	{
		var self = this;
		
		if (self.get(0).crossSlideFadingInProgress == true) {
			return;
		}
		
		self.get(0).crossSlideFadingInProgress = true;
		
		$(self).crossSlidePause_over();
		var plan = self.get(0).crossSlideArgs[1];
		var currentIndex = self.get(0).idx;
		
		if (requestedIndex < plan.length && currentIndex != requestedIndex) {
			
			var opts = self.get(0).crossSlideArgs[0];
			var fade_ms = Math.round(opts.fade * 1000);
			
			var imgs = self.find('img').css({
				position: 'absolute',
				visibility: 'hidden',
				top: 0,
				left: 0,
				border: 0
			});
			
			callback(requestedIndex);
			
			$(imgs[requestedIndex]).css("visibility", "visible");
			$(imgs[currentIndex]).css("visibility", "visible");
			
			$(imgs[currentIndex]).animate({
					opacity: 0.0
				}, 
				fade_ms, 
				function() {
					$(imgs[currentIndex]).css("visibility", "hidden");
				});
			
			$(imgs[requestedIndex]).animate({
					opacity: 1.0
				}, 
				fade_ms, 
				function() {
					self.get(0).idx = requestedIndex;
					self.get(0).crossSlideFadingInProgress = false;
				});
		}
	}
	
	$.fn.isPaused_over = function() {
		return this.get(0).crossSlideArgs[3];
	}
	
	$.fn.goToNextImage_over = 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_over(currentIndex, callback);
		
	}
	
	$.fn.goToPreviousImage_over = 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_over(currentIndex, callback);
		
	}
})();


