var Metropia = function() {
	var	DOMReady = function() {
		$("a[rel=external]").live("click", function(e) {
			e.preventDefault();
			window.open(this);
		});
	};
	return {	
		init: function() {
			$(document).ready(DOMReady);
			$.ajaxSettings.cache = false;
						
			/**
			 * @private
			 */
			$.fn.fadeIn = function(speed, callback) {
				this.animate({opacity: "show"}, speed, function() {
					if (!jQuery.support.opacity) {
						this.style.removeAttribute("filter");
					}
					if (callback != undefined) {
						callback.call(this);
					}
				});
			};
			
			/**
			 * @private
			 */
			$.fn.fadeOut = function(speed, callback) {
				this.animate({opacity: "hide"}, speed, function() {
					if (!jQuery.support.opacity) {
						this.style.removeAttribute("filter");
					}
					if (callback != undefined) {
						callback.call(this);
					}
				});
			};
			
			/*@cc_on
			@if (@_jscript_version < 5.7)
				try {
					document.execCommand("BackgroundImageCache", false, true);
				} catch (e) {}
			@end @*/
			this.isCrappyBrowser = window.XMLHttpRequest ? false : true;

			Metropia.media.init();
			Metropia.slideshow.init();
			Metropia.linkHandler.init();
			Metropia.introduction.init();
		},
		/**
		 * Gets the suffixed value of a class name of a given object
		 * The function assumes the format "prefix-suffix"
		 * @param {object} el A DOM object
		 * @param {string} prefix The prefix of the class name
		 */
		getClassNameValue: function(el, prefix) {
			var ret = new RegExp(".*" + prefix + "-(.*?)(?:\\s|$).*").exec(el.className);
			if (ret) {
				return ret[1];
			}
			return null;
		},
		/**
		 * Returns a value from a cookie
		 * @param {Object} name Cookie name
		 */
		readCookie: function(name) {
			var cookie = document.cookie.split(";");
			for (var i = 0, l = cookie.length; i < l; i++) {
				var c = cookie[i];
				while (c.charAt(0) == " ") {
					c = c.substring(1, c.length);
				}
				if (c.indexOf(name + "=") == 0) {
					return unescape(c.substring((name + "=").length, c.length));
				}
			}
			return null;
		},		
		/**
		 * Stores a value in a cookie for a certain time
		 * @param {Object} name Cookie name
		 * @param {Object} value Cookie value
		 * @param {Object} days Number of days to last (optional)
		 */
		writeCookie: function(name, value, days) {
			var expires = "";
			if (days) {
				var date = new Date();
				date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
				expires = "; expires=" + date.toGMTString();
			}
			document.cookie = name + "=" + escape(value) + "; expires=" + expires + "; path=/";
			return value;
		},
		getViewportSize: function() {
			var viewportwidth;
			var viewportheight;
			
			// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
			if (typeof window.innerWidth != "undefined") {
				viewportwidth = window.innerWidth;
				viewportheight = window.innerHeight;
			}
			// IE6 in standards compliant mode
			else if (typeof document.documentElement != "undefined" && typeof document.documentElement.clientWidth != "undefined" && document.documentElement.clientWidth != 0) {
				viewportwidth = document.documentElement.clientWidth;
				viewportheight = document.documentElement.clientHeight;
			}
			// older versions of IE
			else {
				viewportwidth = document.getElementsByTagName("body")[0].clientWidth;
				viewportheight = document.getElementsByTagName("body")[0].clientHeight;
			}
			return { width : viewportwidth, height : viewportheight };
		}	
	};
}();


/**
 * Turns menu links into ajax calls
 */
Metropia.linkHandler = function() {
	var setLocationHash = function(title) {
		window.location.hash = sektor3.createUrlTitle(title);		
	};
			
	var getLocationHash = function() {
		var hash = window.location.hash;
		if (hash && jQuery.trim(hash).length > 1) {
			return hash.substring(1);
		}
		return null;
	};
	
	var loadPage = function(e, a, loadMovie, activate) {
		if (e.button == 0 && a.protocol == "http:") {
			e.preventDefault();
			if (a.pathname != getLocationHash()) {
				if (activate) {
					var li = $(a).parent();
					li.siblings(".selected").removeClass("selected");
					li.addClass("selected");
					if (a.pathname != "/") {
						window.location.hash = a.pathname;
					} else {
						window.location.hash = "";
					}				
				}
				var content = $("#content");
				var url = a.href;
				Metropia.media.removeVideoPlayer();
				content.animate({opacity: 0}, "fast", null, function() {
					$("#content").load(url, "ajax=true", function() {
						if (loadMovie) {
							var start = $(".start");
							if (start.length > 0) {
								start.css("visibility", "visible");							
								Metropia.media.createVideoPlayer();
							}
						}
						content.animate({opacity: 1}, "fast", null, function() {			
							if (!jQuery.support.opacity) {
								this.style.removeAttribute("filter");
							}
						});
					});
				});
			}
		}	
	};
	
	var DOMReady = function() {
		var hash = getLocationHash();
		if (hash) {
			var content = $("#content");
			content.load(hash, "ajax=true");
			$("UL.menu A, DIV.article-list UL A").each(function() {
				if (hash == this.pathname) {
					var li = $(this).parent();
					li.siblings(".selected").removeClass("selected");
					li.addClass("selected");
				}
			});
		}
		
		$("#header UL.menu A, DIV.article-list UL A").live("click", function(e) {
			loadPage(e, this, true, true);
		});

		$("#footer UL.menu A").live("click", function(e) {
			loadPage(e, this, false, false);
		});
		
		$("FORM INPUT.submit").live("click", function(e) {	
			e.preventDefault();
			var form = $(this.form);
			form.animate({opacity: 0}, "fast", null, function() {
				$.post(this.action, form.serialize() + "&ajax=true");
				var message = $("<p>Thank you!</p>");
				message.hide();
				form.before(message);
				form.remove();
				message.fadeIn("fast");
			});
		});

		
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	}
}();

/** @class 
 * Creates a semi transparent cover over the screen.
 */
Metropia.cover = function() {

	/**
	 * @private
	 */
	var setSize = function() {
        var el = $("#cover");
        var height = Math.max($("html").outerHeight(), Metropia.getViewportSize().height);
        el.css({
            "height": height + "px",
            "display": "block"
        });
	};

    return {
		/**
		 * Shows the cover.
		 */
        show: function(callback) {
            var el = $("#cover");
            if (el.length < 1) {
                $("body").append("<div id=\"cover\"></div>");
                el = $("#cover");
                el.css({
                    "position": "absolute",
                    "left": "0px",
                    "top": "0px",
                    "width": "100%",
                    "z-index": "999",
                    "background": "black",
                    "opacity": "0"
				});
            }
            setSize();
            if (callback) {
	            el.animate({"opacity": 0.6}, "normal", "swing", callback);
            } else {
	            el.animate({"opacity": 0.6}, "normal");
            }
			$(window).bind("resize", setSize);
        },
        
		/**
		 * Hides the cover.
		 * @param {function} callback A function to execute on completion
		 */
        hide: function() {
            var el = $("#cover");
            if (el.length > 0) {
	            el.animate({"opacity": 0}, 600, "swing", function() { el.css("display", "none"); });
				$(window).unbind("resize", setSize);
            }
        }
    }
}();



Metropia.slideshow = function() {
	var index = 0;
	var pictureLinks;
	
	var createSlideshow = function(clickedLink) {
		if (!pictureLinks) {
			pictureLinks = $("ul.slideshow a");
		}
		
		var content = "";
		for (var i = 0, l = pictureLinks.length; i < l; i++) {
			if (pictureLinks[i] === clickedLink) {
				index = i;
			}
		}
		content += "<div id=\"slideshow\" style=\"display: none;\">";
		content += "<img class=\"back\" src=\"\" alt=\"\" style=\"display: none;\"/>";
		content += "<img class=\"front\" src=\"/dynamicContent/pictures/still_dummy.gif\" alt=\"\"/>";
		content += "<div id=\"slideshow-loading\">Loading</div>";
		content += "<div id=\"slideshow-controls\"><span id=\"slideshow-info\"></span><a href=\"#previous\" id=\"slideshow-previous\">Previous</a><a href=\"#next\" id=\"slideshow-next\">Next</a></div>";
		content += "<div id=\"slideshow-close\">Close</div>";
		content += "</div>";

		Metropia.cover.show(function() {
			$("html").addClass("has-cover");
			$("body").append(content);
			$("#slideshow-close").hide();
			$("#slideshow").fadeIn("slow");
			Metropia.slideshow.positionSlideshow();
			showImage();
			$("#cover").click(function() {
				hideSlideshow();
				$(this).unbind("click");
			});
			$(window).resize(Metropia.slideshow.positionSlideshow);
		});
	};
	
	var hideSlideshow = function() {
		$("html").removeClass("has-cover");
		$("#slideshow").fadeOut("fast", function() {
			Metropia.cover.hide();
			$("#slideshow").remove();
		});
	};
	
	var next = function() {
		index = (index == (pictureLinks.length - 1)) ? 0 : (index + 1);
		showImage();
	};

	var previous = function() {
		index = (index == 0) ? (pictureLinks.length -1) : (index - 1);
		showImage();
	};
	
	var showImage = function(callback) {
		var currentBack = $("#slideshow .back");
		currentBack.attr("src", pictureLinks[index].href);
		
		if (!currentBack[0].complete) {
			$("#slideshow-loading").fadeIn();
		}
		currentBack.load(function() {
			var currentFront = $("#slideshow .front");
			var currentBack = $("#slideshow .back");
			$("#slideshow-controls").css("top", currentBack.outerHeight()+10);
			$("#slideshow-loading").fadeOut();

			currentBack.attr("style", "");
			currentFront.fadeOut("normal", function() {
				currentBack.attr("class", "front");
				currentFront.attr("class", "back");
				var slideshowInfo = $("#slideshow-info");
				slideshowInfo.fadeOut("fast", function() {
					slideshowInfo.html(getDescription(index));
					slideshowInfo.fadeIn();
				});
				if (typeof(callback) != "undefined") {
					callback.call();
				}
			});
		});
	};
	
	var getDescription = function(index) {
		var currentLink = $(pictureLinks[index]);
		var hiresLink = "";
		if (currentLink.hasClass("hires")) {
			hiresLink = "<a href=\"" + pictureLinks[index].href.replace("/stills/", "/stills/hires/") + "\">Download 1920 x 1080</a>";
		}
		return currentLink.find("img").attr("alt") + " <span class=\"count\">" + (index+1) + " of " + pictureLinks.length + "</span> " + hiresLink;
	};

	return {
		init: function() {
			$("ul.slideshow a").live("click", function(e) {
				createSlideshow(this);
				e.preventDefault();
			});
			$("#slideshow-next").live("click", function(e) {
				next();
				e.preventDefault();
			});
			$("#slideshow-previous").live("click", function(e) {
				previous();
				e.preventDefault();
			});
			$("#slideshow-close").live("click", function(e) {
				hideSlideshow();
				e.preventDefault();
			});
			$("#slideshow .front").live("mouseover", function() {
				$("#slideshow-close").fadeIn("fast");
			});
			$("#slideshow .front").live("mouseout", function(e) {
				var elm = document.getElementById("slideshow-close");
				if(elm !== e.relatedTarget) {
					$("#slideshow-close").fadeOut("fast");
				}
			});
		},
		
		positionSlideshow: function() {
			var viewPortSize = Metropia.getViewportSize();
			var slideShow = $("#slideshow");
			var slideShowWidth = slideShow.outerWidth();
			slideShow.css({
				"left": (viewPortSize.width - slideShowWidth) / 2 + "px",
				"top": 60 + document.body.scrollTop + document.documentElement.scrollTop + "px"
			});
		}
	};
}();



Metropia.media = function() {
	var video;
	var bgAudioPause;
	var bgAudio;
	var url;
	var pos;
	var movieContainer;
	var volumeBarContainer;
	var volumeBar;
	var volumeBarLength = 40;
	var volumeBarX = 0;
	var volume = 70;
	var positionBarContainer;
	var positionBar;
	var positionBarLength = 500;
	var positionBarX = 0;
	var position = 0;
	var videos = 0;

	var createBg = function() {
		bgAudio = soundManager.createSound({
			id: "bgAudio",
			url: "/dynamicContent/audio/background-64.mp3",
			volume: 0,
			autoPlay: true,
			onfinish: function() {
				bgAudio.play();
			}
		});
	};
	
	var fadeInBg = function() {
		var targetVolume = 70;
		var currentVolume = bgAudio.volume;
		bgAudio.setVolume(currentVolume + 10);
		if (bgAudio.volume < targetVolume) {
			setTimeout(fadeInBg, 400);
		}
	}
	
	var togglePauseBg = function() {
		var pauseButton = $("#toggle-pause-bg");
		if (bgAudio.paused) {
			pauseButton.html("<span>Pause background music</span>");
			bgAudio.resume();
			bgAudio.setVolume(0);
			fadeInBg();
			Metropia.writeCookie("bg-pause", "false", 14);
			bgAudioPause = false;
		} else {
			pauseButton.html("<span>Resume background music</span>");
			bgAudio.pause();
			Metropia.writeCookie("bg-pause", "true", 14);
			bgAudioPause = true;
		}
		pauseButton.toggleClass("resume");
		pauseButton.toggleClass("pause");
	};

	var togglePlay = function(initPos) {
		if (!video) {
			url = Metropia.getClassNameValue($("#movie")[0], "src");
			if ($("#loader").length == 0) {
				$("#movie").prepend("<div id=\"loader\">Loading</div>")
			}
			video = soundManager.createVideo({
			    id: "movie-" + videos,
			    url: url,
			    volume: 0,
			    autoPlay: false,
			    autoLoad: true,
			    whileplaying: updatePosition,
			    onfinish: finish,
			    onload: videoOnLoad
			});
			video.setVolume(0);
			videos++;
		}
		if (video.readyState === 3) {
			if (video.paused) {
				video.resume();
				bgAudio.pause();
			} else if (video.playState == 0) {
				video.setPosition(0);
				video.play();
			} else {
				video.pause();
				if (!bgAudioPause) {
					bgAudio.setVolume(0);
					bgAudio.resume();
					fadeInBg();
				}
			}
		}

		$("body").toggleClass("video-playing");
		togglePlayButton();
	};

	var videoOnLoad = function() {
		video.setPosition(0);
		video.setVolume(volume);
		video.play();
		bgAudio.pause();
		soundManager.oMC.style.width = "600px";
		soundManager.oMC.style.height = "338px";
		soundManager.oMC.style.left = pos.left + "px";
		soundManager.oMC.style.top = pos.top + "px";
	};

	var togglePlayButton = function() {
		var playButton = $("#play-movie-button");
		if (playButton.hasClass("play")) {
			playButton.html("Pause");
		} else {
			playButton.html("Play");
		}
		playButton.toggleClass("play");
		playButton.toggleClass("pause");
	};

	var updatePosition = function() {
		if (video.loaded) {
			var length = Math.round(positionBarLength * (this.position / this.duration));
			if (length != position) {
				positionBar.css("width", length + "px");
				position = length;
			}
		}
	};

	var finish = function() {
		togglePlayButton();
		video.stop();
	}

	var setVolume = function(volume) {
		var l = Math.ceil(volumeBarLength * (volume / 100));
		volumeBar.css("width", l + "px");
		if (video) {
			video.setVolume(volume);
		}
		Metropia.writeCookie("video-volume", volume, 14);
	};

	var getClickPosition = function(e) {
		var posx = 0;
		var posy = 0;
		if (e.pageX || e.pageY) 	{
			posx = e.pageX;
			posy = e.pageY;
		}
		else if (e.clientX || e.clientY) 	{
			posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
			posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
		}
		return { x: posx, y: posy };
	};
	
	var createBgAudio = function() {
		createBg();
		var preSetBgPause = Metropia.readCookie("bg-pause");
		if (preSetBgPause && preSetBgPause === "true") { 
			$("#page").append("<div id=\"toggle-pause-bg\" class=\"resume\"><span>Resume background music</span></div>");
			bgAudio.play();
			bgAudio.pause();
			bgAudioPause = true;
		} else {
			$("#page").append("<div id=\"toggle-pause-bg\" class=\"pause\"><span>Pause background music</span></div>");
			fadeInBg();
			bgAudioPause = false;
		}
		$("#toggle-pause-bg").live("click", function() {
			togglePauseBg();
		});
	};
	
	return {
		init: function() {
			soundManager.url = "/flash/";
			soundManager.flashVersion = 9;
			//soundManager.useMovieStar = true;
			soundManager.useVideo = true;
			soundManager.allowFullScreen = true;
			soundManager.debugMode = false;
			
			
			soundManager.onready(function(oStatus) {
				if (oStatus.success) {
					createBgAudio();
					
					var el = $("#movie");
					if (el.length > 0) {
						Metropia.media.createVideoPlayer();
					}
					
					$(".media-list LI A").live("click", function(e) {
						e.preventDefault();
						var el = $("#movie");
						if (el.length == 0) {
							var parent = $(this).parents(".media-list");
							var el2 = jQuery("<div class=\"movie-player\"></div>");
							parent.prepend(el2);
							el = jQuery("<div id=\"movie\"></div>");
							el2.append(el);
							el.addClass("src-" + this.href);
							Metropia.media.createVideoPlayer();
						} else {
							el.removeClass();
							Metropia.media.removeVideoPlayer();
							el.addClass("src-" + this.href);
						}
						togglePlay();
					});				
				}
			});
		},
		
		createVideoPlayer: function() {
			movieContainer = $("#movie");
			if (movieContainer.length > 0) {
				pos = movieContainer.offset();
				
				var content = "";
				content += "<div id=\"movie-controls\">";
				content += "<a href=\"#\" id=\"play-movie-button\" class=\"play\">Play</a>";
				content += "<span id=\"movie-position\"><span></span></span>";
				content += "<span class=\"txt\">Vol:</span> <span id=\"movie-volume\"><span></span></span>";
				content += "</div>";
				movieContainer.after(content);
				
				$("#play-movie-button").live("click", function(e) {
					e.preventDefault();
					togglePlay();
				});
				$("#movie img").live("click", function(e) {
					e.preventDefault();
					togglePlay();
				});
	
				// position bar handling
				positionBarContainer = $("#movie-position");
				positionBarLength = positionBarContainer.outerWidth();
				positionBar = $("#movie-position span");
				positionBarX = positionBarContainer.offset().left;
				positionBarContainer.live("click", function(e) {
					if (!e) var e = window.event;
					if (video) {
						var pos = 0;
						var posInBar = ((getClickPosition(e).x - positionBarX) / positionBarLength);
						if (posInBar > 0.01) {
							pos = Math.floor(video.duration * posInBar);
						}
						if (video.playState == 0) {
							togglePlay();
							video.setPosition(pos);
						} else {
							video.setPosition(pos);
						}
					}
				});
				
				// volume bar handling
				volumeBarContainer = $("#movie-volume");
				volumeBar = $("#movie-volume span");
				volumeBarLength = volumeBarContainer.outerWidth();
				volumeBarX = volumeBarContainer.offset().left;
				$("#movie-controls .txt").live("click", function(e) {
					if (!e) var e = window.event;
					var pos = 0;
					var posInBar = ((getClickPosition(e).x - volumeBarX) / volumeBarLength);
					var volume = Math.ceil(posInBar * 100);
					volume = volume > 97 ? 100 : (volume < 10 ? 0 : volume);
					setVolume(volume);
				});
				
				// check if volume is preset in a cookie
				var preSetVolume = Metropia.readCookie("video-volume");
				if (preSetVolume) { setVolume(preSetVolume); }
			}
		},
		
		removeVideoPlayer: function() {
			$("#sm2-container").css("left", "-9999px");
			if (video) {
				togglePlay();
				soundManager.destroyVideo(video.sID);
				video = null;
			}
		}
	};
}();


Metropia.introduction = function() {
	var fadeTime = 1500;
	var defaultDelay = 6000;
	var show = function(el) {
		if (el.hasClass("movie-player")) {
			el.hide();
			el.css("visibility", "visible");
		}
		el.fadeIn(fadeTime, function() {
			var next = el.next();
			if (next.length > 0) {
				var elDelay = Metropia.getClassNameValue(el[0], "delay");
				setTimeout(function() {
					el.fadeOut(fadeTime, function() {
						show(next);
					});
				}, elDelay ? elDelay : defaultDelay);			
			}
		});
	}
	var DOMReady = function() {
		var start = $(".start");
		if (start.length > 0) {
			start.css("visibility", "visible");
			var ps = start.find("P.intro");
			if (ps.length > 0) {
				$(".movie-player").css("visibility", "hidden");
				setTimeout(function() {
					show($(ps[0]));
				}, 1000);
			}
		}
	};
	return {
 		init: function() {
 			$(document).ready(DOMReady);
 		}
 	};
}();

Metropia.init();

// Google analytics
var gaJsHost = ((" https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
try{
	var pageTracker = _gat._getTracker("UA-1910703-27");
	pageTracker._trackPageview();
} catch(err) {}