/*
 * ImageViewer (dev) - jQuery Plugin
 *
 * Copyright (c) 2008 Robert Andersson/Profundis - http://www.profundis.se
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Requirements:
 * - reflection.js
 * - jquery [http://www.jquery.com]
 * - jquery.simplemodal.js [http://plugins.jquery.com/project/SimpleModal]
 * - jquery.HorizontalAutoscrollMenuReflectivePhoto [included]
 */
 (function($) {

	var current_gallery = null;
	var slideshow_interval_id = null;
	var slideshow_interval_ms = 8000;

	// Create a gallery
	$.fn.ImageViewer = function(options) {

		var gallery = { title: options.title, width: options.width, height: options.height, images: [], current: -1 };

		this.each(function() {
			var a = $(this);
			var img = $("img", a);
			if(img.length == 0) { img = [{ src: null, text: null }]; }
			var image = { thumb: img[0].src, full: a[0].href, text: img[0].title };
			gallery.images.push(image);
			// Bind click to open gallery
			if(!a.hasClass('imageViewerNoClick')) {
				a.bind("click", function() { open_gallery(gallery, image); return false; });
			}
		});
		gallery.use_image_list = gallery.images.length > 1;
		gallery.use_nav_controls = gallery.use_image_list;
	}

	function open_gallery(gallery, image)
	{
		current_gallery = gallery;

		var content =
			"<div class='image_viewer'>" + 
			// - Gallery Title
			"<h1>" + gallery.title + "</h1>" +
			// - Prev
			// - Next
			// - Slideshow
			'<div class="controls">' +
				'<ul>' +
					(gallery.use_nav_controls ? ('<li class="prev"><a href="">Föregående</a></li>' +
					'<li class="next"><a href="">Nästa</a></li>' +
					'<li class="slideshow"><a href="">Starta bildspel</a></li>') : '') +
					'<li class="close"><a class="modalClose" href="">Stäng</a></li>' +
				'</ul>' +
			'</div>' +

			// Content
			"<div class='iv_content'>" +
				// - Image
				"<div class='iv_image_container'>" + 
					// - Actual image and text
					"<div class='iv_image_content'>" +
						"<div class='iv_image'><img src='' alt='' /></div>" +
						"<div class='iv_text'><div class='iv_backdrop'></div><p>sdfgsdfg</p></div>" +
					"</div>" +
					// - Loader overlay
					"<div class='iv_loading'>" + // style="position: absolute; display: none; left: 0; top: 0; width: 100%; height: 100%;">
						"<div class='iv_loading_curtain'></div>" + // style="position: absolute; left: 0; top: 0; width: 100%; height: 100%; background-color: #000;"></div>
						"<div class='iv_loading_text'>" + // style="position: absolute; width: 100%; top: 50%; margin-top: -25px; text-align:center;color: white;">
							//"<p><img src='/_gfx/image_viewer/loader.gif' alt='' /></p>" +
							"<p>Laddar...</p>" +
						"</div>" +
					"</div>" +
					// - Curtain
					"<div class='iv_curtain'></div>" + // style="display: none;position:absolute; left: 0; top: 0; width: 100%; height: 100%; background-color:#fff;"></div>
				"</div>" +
				// - Text
				// - Image list
				(gallery.use_image_list ? "<div class='iv_image_list'><ul></ul></div>" : "") +
			"</div>";
		
		content = $(content);
		//$(".iv_image img", content).attr("src", image.full);
		//$(".iv_text p", content).text(image.text);
		for(var i = 0; i < gallery.images.length; ++i) {
			if(current_gallery.use_image_list) {
				$(".iv_image_list ul", content).append("<li><a id='iv_img"+i+"' href=''><img src='" + gallery.images[i].thumb + "' alt='' width='96' height='54' /></a></li>");
			}
			if(gallery.images[i].thumb == image.thumb) {
				current_gallery.current = i;
			}
		}

		// Link gallery thumbs to image container
		$(".iv_image_list ul li a", content).bind("click", function() { set_image(this.id); return false; });
		// Link controls
		if(gallery.use_nav_controls) {
			$(".controls li.next a", content).bind("click", next);
			$(".controls li.prev a", content).bind("click", prev);
			$(".controls li.slideshow a", content).bind("click", slideshow);
		}

		$(".iv_text", content).css({ opacity: 0.5 });
		$(".iv_image_container", content).css({width: gallery.width+"px", height: gallery.height+"px" });
		$(".iv_image_content", content).css({width: gallery.width+"px", height: gallery.height+"px" });
		$(".iv_image", content).css({width: gallery.width+"px", height: gallery.height+"px" });

		var ww = gallery.width + 2*12
		var wh = 20 + 12 + gallery.height + (current_gallery.use_image_list ? (120) : 0) + 12;

		function onclose(dialog) {
			if(slideshow_interval_id) {
				window.clearInterval(slideshow_interval_id);
				slideshow_interval_id = null;	
			}
			dialog.data.hide();
			dialog.container.hide();
			dialog.overlay.fadeOut(500, function() {
				$.modal.close();
			});
		}

		var container_css = { width: ww+"px", height: wh+"px", left: "50%", marginLeft: (-ww/2)+"px", top: "50%", marginTop: (-wh/2)+"px" };

		content.modal({
			containerCss: container_css,
			close: false,
			onOpen: function(dialog) {
				if($.browser.msie && parseInt($.browser.version) < 7) {
					dialog.container[0].style.marginTop = 0;
					dialog.container[0].style.setExpression("top", "(document.documentElement.scrollTop || document.body.scrollTop) + Math.round(15 * (document.documentElement.offsetHeight || document.body.clientHeight) / 100) + 'px'");
				}
				dialog.overlay.fadeIn(1000, function () {
					//dialog.container.css({ height: "20px" }).animate({height: wh+"px"}, 2000);
					dialog.container.show();
					dialog.data.show();
				});
			},
			onShow: function(dialog) {
				if(gallery.use_image_list) $(".iv_image_list ul").HorizontalAutoscrollMenuReflectivePhoto({ width: gallery.width });
				set_image(current_gallery.current, true);
				dialog.overlay.css({cursor: "pointer"});
				dialog.overlay.attr("title", "Click outside window to close it");
				dialog.overlay.bind("click", function() { onclose(dialog); });
			},
			onClose: onclose
		});
	}

	function transition(image)
	{
		// Some handy vars
		var container = $(".iv_image_container");
		var img = $(".iv_image img");
		var curtain = $(".iv_curtain");
		var loading = $(".iv_loading");
		var loading_curtain = $(".iv_loading_curtain");
		var loading_text = $(".iv_loading_text");
		var text = $(".iv_text");

		// Add new image (hidden)
		var new_img_loaded = false;
		var img_new = new Image();
		$(img_new).bind("load", function() { new_img_loaded = true; });
		img_new.src = image.full;
		var thumb_new = new Image();
		thumb_new.src = image.thumb;

		// Fade out current image
		curtain.stop().css({ display: "block", opacity: 0 }).animate({ opacity: 1 }, 500, function() {
			// Wait a tiny while
			window.setTimeout(function() {

				// Clean up some stuff
				text.css({visibility: "hidden"});

				function show_image() {
					var w = img_new.width;
					var h = img_new.height;
					$(".iv_image_content").css({width: Math.min(w, current_gallery.width), height: Math.min(h, current_gallery.height)});
					img.replaceWith(img_new);
					$(img_new).css({
						marginLeft: Math.min((current_gallery.width - w) / 2, 0)+"px",
						marginTop: Math.min((current_gallery.height - h) / 2, 0)+"px"
					});
				}

				// 
				function show_text() {
					if(image.text) {
						window.setTimeout(function() {
							text.empty().append("<p>"+image.text+"</p>").css({bottom: "-"+(text[0].clientHeight)+"px", visibility: "visible"}).animate({bottom: 0}, 1000);
						}, 750);
					}
				}

				// If new image has loaded already
				if(new_img_loaded) {
					// Set new image
					//container.css({width: img_new.width+"px"});
					show_image();
					// Fade in (by fading out the curtain)
					curtain.animate({opacity: 0}, 500, function() {
						curtain.css({ display: "none" });
					});
					show_text();
				}
			
				// Otherwise we must show a loader
				else {
					var gw = current_gallery.width;
					var gh = current_gallery.height;
					var tw = thumb_new.width;
					var th = thumb_new.height;
					$(".iv_image_content").css({width: gw, height: gh});
					img.replaceWith($(thumb_new)); //.css({ width: "100%", height: "100%" }));
					img = $(thumb_new);

					if(tw > 0 && th > 0) {
						var tr = tw / th;
						var gr = gw / gh;
						if(tr > gr) {
							img.css({ width: (tr * gh)+"px", height: gh+"px", marginLeft: (-(tr*gh-gw)/2)+"px", marginTop: 0 });
						}
						else {
							img.css({ width: gw+"px", height: (gw / tr)+"px", marginLeft: 0, marginTop: (-(gw/tr-gh)/2)+"px" });
						}
					}

					loading_curtain.css({opacity: 0.8 });
					loading.css({display: "block" });
					loading_text.css({display: "block" });

					curtain.animate({opacity: 0}, 500, function() {
						curtain.css({ display: "none" });

						var wait_interval_id = window.setInterval(function() {
							if(new_img_loaded) {
								window.clearInterval(wait_interval_id);
								loading_text.css({ display: "none" });
								show_image();
								loading_curtain.animate({ opacity: 0}, 500, function() {
									loading.css({ display: "none" });
								});
								show_text();
							}
						}, 500);
					});
				}

			}, 100);
		});
	}

	function set_image(id, set_focus)
	{
		if(id.substr && id.substr(0, 6) == "iv_img") id = new Number(id.substr(6));
		var img = current_gallery.images[id];
		if(!img) return;

		transition(img);

		if(0) {

			// Set current image, text, etc
			$(".iv_image img").attr("src", img.full);
			//$(".iv_text p").text(img.text);
			$(".iv_text").empty().append(img.text ? "<p>"+img.text+"</p>" : "");
		}


		// Adjust image list
		if(current_gallery.use_image_list) {
			$(".iv_image_list li.current").removeClass("current");
			$(".iv_image_list li a#" + id).parent().addClass("current");
			if(set_focus) {
				//$(".iv_image_list ul").get(0).focus_image("iv_img"+id);
			}
		}

		current_gallery.current = id;
	}
	function next()
	{
		var next_img_id = current_gallery.current + 1;
		// If we are on last image, goto first image (probably slideshow calling)
		if(next_img_id >= current_gallery.images.length) next_img_id = 0;
		set_image(next_img_id, true);
		// If now on last image, disable "next", and if slideshow is started, stop it
		next_img_id = current_gallery.current + 1;
		if(next_img_id >= current_gallery.images.length) {
			if(slideshow_interval_id) slideshow();
		}
		return false;
	}
	function prev()
	{
		set_image(current_gallery.current - 1, true);
		return false;
	}
	function slideshow()
	{
		// - preload next image as soon as the current is finnished
		if(slideshow_interval_id) {
			$(".controls li.slideshow a").text("Starta bildspel");
			window.clearInterval(slideshow_interval_id);
			slideshow_interval_id = null;
		}
		else {
			$(".controls li.slideshow a").text("Stoppa bildspel");
			slideshow_interval_id = window.setInterval(function() {
				next();
			}, slideshow_interval_ms);
			next();
		}
		return false;
	}

})(jQuery);



/*
 * jQuery HorizontalAutoscrollMenuReflectivePhoto
 *
 * Copyright (c) 2008 Profundis www.profundis.se
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
 (function($) {

	// Our only function
	$.fn.HorizontalAutoscrollMenuReflectivePhoto = function(options) {

		// Iterate and apply over the set
		this.each(function() {

			var tw = 96;
			var th = 54;


			// Element is/should be a ul. Create necessary parents (window and field)
			var list = $(this);
			list.wrap("<div class='thumbwindow'><div class='thumbfield'></div></div>");
			var twindow = $(this.parentNode.parentNode);
			var tfield = $(this.parentNode);

			// Some useful information
			var img_count = $("li", this).length;

			// In order to avoid wrapping, we must set a fixed width of the field
			var tfield_width = img_count * (tw + 30);
			tfield.css("width", tfield_width + "px");

			if(options.width && tfield_width < options.width) {
				//alert(((options.width - tfield_width) / 2)+"px");
				tfield.css({ left: ((options.width - (tfield_width + 120)) / 2)+"px" });
			}

			// Focus/scroll-to function 
			this.focus_image = function(id) {
				var img = $("#" + id, list);
				var li = img.parent();
				var left = 0 - ((li[0].offsetLeft + 45) - (twindow[0].offsetWidth / 2));
				if(tfield_width < twindow[0].offsetWidth) return;
				tfield.animate({left: left + "px"}, 750, function() { });
			};

			// Reflection
			var reflection_options = { opacity: 0.5 }
			$("li img:first-child", this).bind("load", function() {
				// IE7 seems to call this before the image width/height is available; so reflection screws up everything.
				// Delaying it slighty seems to work most of the time.
				var img = this;
				window.setTimeout(function() {
					if(img.width) {
						Reflection.add(img, reflection_options);
					}
					// Reflection adds a container around our img, and appends the reflection to it
					var container = $(img.parentNode);
					container.css( { display: "block", position: "absolute", left: "0px", top: "0px" } );
					container.children().css({ width: "100%", height: "auto" });
				}, 500);
			});

			// Set styles, so things keep in place when animating the thumbs
			$("li", this).css( { width: tw+"px", height: (th * 1.5 + 3)+"px" } );

			// Event handlers
			twindow.hover(
				// over
				function() {
					var el = this;
					var field = $(".thumbfield", el);
					field.stop();
					this.thumbwindow_velocity = 2;

					// Find elements position
					this.absolute_left = 0;
					var obj = el;
					while(obj.parentNode) {
						this.absolute_left += obj.offsetLeft;
						obj = obj.parentNode;
						// alert(this.absolute_left + " (" + obj + "," + obj.tagName + ")");
					}

					// continously update position/velocity
					$(el).bind("mousemove", el.mousemove_handler = function(e) {
						//var x_c = e.clientX - this.offsetLeft;
						var x_c = e.clientX - this.absolute_left;
						var w_w = this.offsetWidth;
						var v_control = -2 * ((x_c) / w_w) + 1;
						//var p = -(2 * ((x) / $(el).width()) - 1)
						el.thumbwindow_mouse_x = x_c;
						el.thumbwindow_v_control = v_control;
						//$("#data").text(x + " => " + p);

						var x_f = field[0].offsetLeft;
						var w_f = field[0].offsetWidth;

						if(w_f < w_w) return;

						var target = -(w_f - w_w) * x_c / w_w;
						field.css({left: (x_f + (target - x_f) * 0.1)+"px" });
						field.stop().animate({left: target+"px"}, 1000);

					});
					// continously animate thumb field
					/*this.thumbwindow_interval_id = window.setInterval(function() {
						if(el.thumbwindow_block_scroll) return;
						var x_c = el.thumbwindow_mouse_x;
						var x_f = field[0].offsetLeft;
						var w_f = field[0].offsetWidth;
						var w_w = el.offsetWidth;
						var v_max = 10;
						var softstop_width = 50;

						var overflow_left = -x_f;
						var overflow_right = x_f + w_f - w_w;

						var v_control = el.thumbwindow_v_control;
						var softstop = Math.min(((v_control > 0) ? overflow_left : overflow_right) / softstop_width, 1);
						var v = Math.round(v_max * v_control * softstop);
						if(v == 0) return;
						field.css("left",  (field[0].offsetLeft + v) + "px");
						//$("#data").text(w_w + "," + w_f + "," + x_f + ", " + v_control + ", " + softstop);
					}, 25);*/
				},
				// out
				function() {
					clearInterval(this.thumbwindow_interval_id);
					$(this).unbind("mousemove", this.mousemove_handler);
				}
				
			);

			$("li img:first-child", this)
				.bind("mouseover", function() {

					// preparations
					var el_li = this.parentNode.parentNode.parentNode;
					var el_field = el_li.parentNode.parentNode;
					var el_window = el_field.parentNode;
					var container = $(this.parentNode);

					// config
					var o = 200;
					var d = 10;

					// config / run-time variables
					var w = tw;
					var h = th;
					var h_r = th * 0.5;

					// calculations
					var x = el_li.offsetLeft + el_field.offsetLeft - el_window.offsetWidth / 2;
					var x_ = (o+d) * x / o;
					var w_ = (o+d) * w / o;
					var y_ = d;

					// Animate the container
					var anim = { left: (x_-x)+"px", top: y_+"px", width: w_+"px", height: ((h + h_r) / w * w_)+"px" };
					container.stop();
					container.animate(anim, 250, function() {} );
				})
				.bind("mouseout", function() {
					// config / run-time variables
					var w = tw;
					var h = th;
					var h_r = th * 0.5;

					// Animate the container
					var anim = { left: "0px", top: "0px", width: w+"px", height: (h+h_r)+"px" };
					$(this.parentNode).animate(anim, 750);
				});
		});
	}
})(jQuery);

