/*
 * Zallery JQuery Plugin by Michael Schilbach
 *
 * Copyright 2010 by Michael Schilbach <cimrellik@googlemail.com>
 *
 * 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.
 *
 */


(function($) {
	$.fn.msgallery = function(settings) {
		var defaults = {
			topzoom: 120,		// Higher Number => Stronger Zoom Effect
			startheight: "300px",	// Unexpanded height
			startimg: "",		// Alternate image for unexpanded view
			returntostart: true,	// Back to first pic when stopping slideshow?
			effect: "zoom",		// zoom, fade, none
			effectduration: 1000,	// Duration of effect (duh)
			autostart: true,	// Automatically start when expanding
			autotimer: 7000		// Time to wait between pics if automatic
		};

		var options = $.extend(defaults, settings);

		this.each(function() {  
			var obj = $(this);

///////////////////////////////////////////////////////////


			// Start Values
			var max = $("img", obj).size();
			var zoom = new Array();
			var top = new Array();
			var left = new Array();
			var maxheight = 0;
			var maxwidth = 0;
			var trans = false;
			var current = 1;


			// Get Dimensions of each pic for zoom-out effect
			$(window).load(function() {
				for(i=0;i<max;i=i+1) {
					$("img:eq("+i+")", obj).removeAttr("width").removeAttr("height");
					if($("img:eq("+i+")", obj).height() > maxheight) { maxheight = $("img:eq("+i+")", obj).height(); }
					if($("img:eq("+i+")", obj).width() > maxwidth) { maxwidth = $("img:eq("+i+")", obj).width(); }
					zoom[i] = $("img:eq("+i+")", obj).height() + options.topzoom;
					top[i] = parseInt($("img:eq("+i+")", obj).css("top")) - (options.topzoom / 2);
					left[i] = Math.floor(($("img:eq("+i+")", obj).width() - Math.floor($("img:eq("+i+")", obj).width() / ($("img:eq("+i+")", obj).height() / ($("img:eq("+i+")", obj).height() + options.topzoom)))) / 2);
				}
				// Set width according to images
				obj.css("width", maxwidth);
			});

			$("img", obj).fadeTo(1, 1).hide();


			// Define closed object
			obj.css("height", options.startheight);
			if(options.startimg) {
				obj.css("backgroundImage", "url("+options.startimg+")");
				obj.css("backgroundRepeat", "no-repeat");
			} else {
				$("img:eq(0)", obj).show().css("z-index", 100);
			}


			// Create Menu
			obj.append('<div></div><div id="msblend"></div>');
			$("div", obj).css("position", "static");
			$("div:not(#msblend)", obj).append('<div id="msstartslideshow"></div><div id="msstopslideshow" style="display:none;"></div><div id="msslideshowcontrol" class="paused" style="display:none;"><a href="#" id="msprevklapp"></a><a href="#" id="msnextklapp"></a><a href="#" id="msstopautoklapp"></a></div>');

			// CSS Styles
			obj.css({
				position: "relative",
				overflow: "hidden"
			});
			$("a", obj).css("outline", "none");
			$("img", obj).css({
				border: "none",
				position: "absolute",
				top: 0,
				left: 0
			});
			$("#msstartslideshow").css({
				position: "absolute",
				"z-index": 900
			});
			$("#msstopslideshow").css({
				position: "absolute",
				"z-index": 900
			});
			$("#msblend").css({
				height: "100%",
				width: "100%",
				position: "absolute",
				top: 0,
				left: 0,
				"z-index": 90
			});


			// Transition
			function klappgallery(dir) {
				if(!trans) {
					trans = true;
					setTimeout(function() { trans = false; }, 900);
					prev = current;
					if(dir == "next") {
						current = current + 1;
					} else {
						current = current - 1;
					}
					if(current <= 0) { current = max; }
					if(current > max) { current = 1; }
					if(current != prev) {
						$("img:eq("+(current-1)+")", obj).show().css({ height: "auto", top: 0, left: 0, "z-index": 10 });
						$("img:eq("+(prev-1)+")", obj).css({ height: "auto", left: 0, "z-index": 100 });

						$("#msblend").fadeTo(options.effectduration, 0, function() {
							$("img:eq("+(current-1)+")", obj).css("z-index", 100);
							$(this).fadeTo(1, 1);
						});

						if(options.effect == "zoom") {
							$("img:eq("+(prev-1)+")", obj).animate({ height: zoom[(prev-1)]+"px", top: top[(prev-1)]+"px", left: left[(prev-1)]+"px" }, {duration: options.effectduration, queue: false});
						}
						if(options.effect == "none") {
							$("img:eq("+(prev-1)+")", obj).hide();
						} else {
							$("img:eq("+(prev-1)+")", obj).fadeTo(options.effectduration, 0, function() { $(this).fadeTo(1, 1).hide(); });
						}
					}
				}
			}

			// Auto-Scroller
			var autotimer;
			function autogallery() {
				$("#msslideshowcontrol").removeClass("paused");
				clearTimeout(autotimer);
				autotimer = setTimeout(function() {
					klappgallery("next");
					autogallery();
				}, options.autotimer);
			}

			var run = 1;
			function stopautogallery(override) {
				if(run == 1 || override == 1) {
					clearTimeout(autotimer);
					run = 0;
					$("#msslideshowcontrol").addClass("paused");
				} else {
					autogallery();
					run = 1;
				}
			}


			// Bind Buttons

			// Stop Slideshow
			$("#msstopautoklapp").bind("click", function() {
				stopautogallery();

				return false;
			});

			// Start
			$("#msstartslideshow").bind("click", function() {
				obj.animate({ height: maxheight+"px" }, { duration: 500, queue: false });
				if(options.startimg) {
					obj.fadeTo(250, 0).fadeTo(250, 1);
				}
				setTimeout(function() {
					if(options.startimg) {
						obj.css("backgroundImage", "url()");
						$("img:eq(0)", obj).show();
					}
					$("#msstopslideshow").show().fadeTo(250, 1);
					$("#msstartslideshow").fadeTo(250, 0, function() { $(this).hide(); });
					$("#msslideshowcontrol").show().fadeTo(250, 1);
					$("h1", obj).fadeTo(250, 0, function() { $(this).hide(); });
					obj.show().fadeTo(250, 1);
				}, 250);
				if(options.autostart) {
					autogallery();
					run = 1;
				} else {
					run = 0;
				}
			});

			// Stop
			$("#msstopslideshow").bind("click", function() {
				obj.animate({ height: options.startheight }, { duration: 500, queue: false });
				if(options.returntostart) {
					obj.fadeTo(250, 0).fadeTo(250, 1);
				}
				setTimeout(function() {
					if(options.startimg) {
						obj.css("backgroundImage", "url("+options.startimg+")");
					}
					$("#msstartslideshow").show().fadeTo(250, 1);
					$("#msstopslideshow").fadeTo(250, 0, function() { $(this).hide(); });
					$("#msslideshowcontrol").fadeTo(250, 0, function() { $(this).hide(); });
					$("h1", obj).show().fadeTo(250, 1);

					// Reset to start
					if(options.returntostart) {
						$("img", obj).hide();
						if(options.startimg) {
							obj.css("backgroundImage", "url("+options.startimg+")");
						} else {
							$("img:eq(0)", obj).css({ "top": "0", "left": "0", "height": "auto" }).show();
						}
						current = 1;
					}
				}, 250);
				stopautogallery(1);
			});

			// Previous
			$("#msprevklapp").bind("click", function() {
				klappgallery("prev");
				stopautogallery(1);

				return false;
			});

			// Next
			$("#msnextklapp").bind("click", function() {
				klappgallery("next");
				stopautogallery(1);

				return false;
			});


///////////////////////////////////////////////////////////

		});
	};
})(jQuery);
