


// GLOBAL INIT
$(document).ready(function() {
	
	PinColumn.init();
	NavigationCollapse.init();
	Slideshow.init();
	Layout.setMinHeight();
// 	alert( debugObject(window.document.documentElement, " "));
	
});



/***********************************************
	
	Requires a Localization object
	
	Localization = {
		key1: text1,
		key2: text2,
		...
	}
	
***********************************************/


/***********************************************
	LAYOUT
***********************************************/
var Layout = {
	
	
	columnTop : 115,
	colIds    : { a:"navigation", b:"extra-content" },
	
	
	// SET MIN-HEIGHT
	setMinHeight: function () {
		
		// get DOM elements
		var cols = {};
		for (var key in this.colIds) {
			var elem = document.getElementById(this.colIds[key]);
			if (! elem) continue;
			cols[key] = elem;
			// set heights to defaults
			elem.style.minHeight = "1px";
			elem.style.height = "auto";
		}
		// compute min-height
		var minHeight = document.body.clientHeight - this.columnTop;
		for (var key in cols) {
			minHeight = Math.max(minHeight, cols[key].clientHeight);
		}
		// set height
		for (var key in cols) {
			if (typeof document.body.style.maxHeight == "undefined") {
				cols[key].style.height = minHeight + "px";
			} else {
				cols[key].style.minHeight = minHeight + "px";
			}
		}

	},


	// BODY SHAKE
	bodyShake: function () {
		
		document.body.style.marginRight = "1px";
		setTimeout("document.body.style.marginRight = '0'; ", 1);
		
	}


};



/***********************************************
	PIN & UNPIN COLUMN
************************************************
	call PinColumn.init()
	when document is ready
***********************************************/
var PinColumn = {

	init: function () {
		
		$("#navigation")
		.click    (function(e) { PinColumn.click    (e, this, "Navigation", true) })
		.mousemove(function(e) { PinColumn.mouseMove(e, this, "Navigation", true) })
		;
		
		$("#extra-content")
		.click    (function(e) { PinColumn.click    (e, this, "ExtraContent", false) })
		.mousemove(function(e) { PinColumn.mouseMove(e, this, "ExtraContent", false) })
		;
		
	},

	isBorderTarget: function (e, node) {
		return (
			e.pageX < (node.clientLeft + node.offsetLeft) || 
			(node.clientLeft + node.offsetLeft + node.clientWidth) < e.pageX
		);
	},

	restyle: function (node, bodyClass, west) {
		var p = $("body").hasClass(bodyClass);
// 		node.style.cursor = (p == west) ? "w-resize" : "e-resize";
// 		node.style.cursor = "move";
		node.style.cursor = "help";
		node.title = p ? Localization.html_unpin_column : Localization.html_pin_column;
	},

	unstyle: function (node) {
		node.style.cursor = "default";
		node.title = "";
	},

	click: function (e, node, bodyClass, west) {
		if (! this.isBorderTarget(e, node)) return;
		$("body").toggleClass(bodyClass);
		this.restyle(node, bodyClass, west);
		Layout.setMinHeight();
	},

	mouseMove: function (e, node, bodyClass, west) {
		this.isBorderTarget(e, node) ? this.restyle(node, bodyClass, west) : this.unstyle(node);
	}

};



/***********************************************
	PAGE NAVIGATION COLLAPSE
************************************************
	call NavigationCollapse.init()
	when document is ready
***********************************************/
var NavigationCollapse = {

	// INIT
	init: function () {
		
		// PAGE NAVIGATION COLLAPSING
		var toggleNav = function(e) {
			
			var li = $(this).parent().parent();
			var show = li.hasClass("collapsed");
			var ol = $(this).parent().next();
			if (li.hasClass("collapsed")) {
				$(this).attr("title", Localization.html_collapse_nav);
				li.toggleClass("collapsed expanded");
				ol.slideDown();
			} else {
				$(this).attr("title", Localization.html_expand_nav);
				li.addClass("callback");
				ol.slideUp(function() {
					$("#page-navigation li.callback").toggleClass("callback collapsed expanded");
				});
			}
			e.preventDefault();
			e.stopPropagation();
			
		};
		
		$("#page-navigation li.expanded > a > span.NavIcon")
		.attr("title", Localization.html_collapse_nav)
// 		.css("cursor", "s-resize")
// 		.css("cursor", "move")
		.css("cursor", "help")
		.click(toggleNav)
		;
		
		$("#page-navigation li.collapsed > a > span.NavIcon")
		.attr("title", Localization.html_expand_nav)
// 		.css("cursor", "s-resize")
// 		.css("cursor", "move")
		.css("cursor", "help")
		.click(toggleNav)
		;
		
		$("#page-navigation li.leaf span.NavIcon")
		.addClass("Neutralized")
		.click(function(e) { e.preventDefault(); })
		;
		
	}

};



/***********************************************
	SLIDESHOW
************************************************
	call Slideshow.init()
	when document is ready
***********************************************/
var Slideshow = {

	// SLIDESHOW INTERVAL
	slideShowRefresh : 1000,
	
	// SLIDESHOW
	slideShowSpeed   : 3,
	slideShowPlaying : false,
	slideShowCounter : 0,
	slideNode      : null,
	slideCurrImage : null,
	slideNextImage : null,
	slidePrevImage : null,
	
	// TRANSITIONS
	splashTransitionDuration : 1000,
	
	// SPLASH
	splashContainer : null,
	splashContent   : null,
	splashControls  : null,
	splashTitle     : null,
	splashComment   : null,
	splashImage     : null,
	

	// INIT
	init: function() {

		var myElems = document.getElementsByTagName("DIV");
		for (var i = 0; i < myElems.length; i++) {
			if (hasClass(myElems[i], "Slide")) {
				var myLinks = myElems[i].getElementsByTagName("A");
				if(myLinks[0]) myLinks[0].onclick = function() {
					Slideshow.loadSlide(this.parentNode, null, null, null);
					Slideshow.splashOpen();
					return false;
				};
			}
		}
		
	},


	// BUILD SPLASH CONTAINER
	buildSplash: function() {
		
		var myLink;
		
		document.onkeydown = function(e) {
			if (! Slideshow.openFlag) return true;
			if (!e) var e = window.event; // IE sucks
			if (27 == e.keyCode) Slideshow.splashClose(); // Esc
			if (37 == e.keyCode) Slideshow.slidePrev();   // left arrow
			if (39 == e.keyCode) Slideshow.slideNext();   // right arrow
			if (32 == e.keyCode) {   // space
				Slideshow.slidePlay();
				return false;
			}
// 			window.status = "key pressed : " + e.keyCode;
			return true;
		};
		
		// BODY -> CONTAINER
		var myContainer = document.body.appendChild(document.createElement("DIV"));
		myContainer.id = "SplashContainer";
		
		// CONTAINER -> CURTAIN
		var myCurtain = myContainer.appendChild(document.createElement("DIV"));
		myCurtain.id = "SplashCurtain";
		
		// CONTAINER -> HELP?
		var myHelp = myContainer.appendChild(document.createElement("DIV"));
		myHelp.id = "SplashHelp";
		var helpLines = Localization.slideshow_help.split(/\n/);
		for (var i = 0; i < helpLines.length; i++) {
			myHelp.appendChild(document.createElement("P")).appendChild(document.createTextNode(helpLines[i]));
		}
		
		// CONTAINER -> NAVIGATION
		var myNavigation = myContainer.appendChild(document.createElement("DIV"));
		myNavigation.onclick = function(e) { stopPropagation(e); };
		myNavigation.id = "SplashNav";
		
		// NAVIGATION -> CONTROLS
		var myControls = myNavigation.appendChild(document.createElement("SPAN"));
		myControls.id = "SplashNavControls";
		
		// Set HPrev class (HoverPrevious)
		var mouseover = function() { this.previousSibling.className = "HPrev"; };
		var mouseout  = function() { this.previousSibling.className = ""; };
		
		// separator node to clone
		var sepNode = document.createElement("SPAN");
		sepNode.className = "Separator";
		sepNode.appendChild(document.createTextNode(" | "));
		
		/*
			Unicode for controls: around \u25C0
			▕◀◀  ▶▶▏ ▶  ■  ▮▮  ⏏  ✕
			note: &nbsp; = \u00a0
		*/
		
		myLink = this.buildControl(myControls, "▕◀◀", "Prev", Localization.slideshow_prev);
		myLink.onclick = function(e) { Slideshow.slidePrev(); return false; };
		
		myLink = this.buildControl(myControls, "▶▶▏", "Next", Localization.slideshow_next);
		myLink.onclick = function() { Slideshow.slideNext();  return true; };
// 		myLink.onmouseover = mouseover; myLink.onmouseout = mouseout;
		
		myControls.appendChild(sepNode.cloneNode(true));
		
		myLink = this.buildControl(myControls, "▶/▮▮", "Play", Localization.slideshow_play);
		myLink.onclick = function() { Slideshow.slidePlay(this);  return false; };
		
		myControls.appendChild(sepNode.cloneNode(true));
		
		var mySpeeds = myControls.appendChild(document.createElement("SPAN"));
		mySpeeds.id = "SlideSpeeds";
		
		var hare = mySpeeds.appendChild(document.createElement("SPAN"));
		hare.className = "Hare";
		hare.appendChild(document.createTextNode("\u00a0"));
		
		myLink = this.buildControl(mySpeeds, "1", "SlideSpeed", Localization.slideshow_speed1);
		myLink.onclick = function() { Slideshow.slideSpeed(this, 1);  return false; };
		
		myLink = this.buildControl(mySpeeds, "2", "SlideSpeed", Localization.slideshow_speed2);
		myLink.onclick = function() { Slideshow.slideSpeed(this, 2);  return false; };
// 		myLink.onmouseover = mouseover; myLink.onmouseout = mouseout;
		
		myLink = this.buildControl(mySpeeds, "3", "SlideSpeed Active", Localization.slideshow_speed3);
		myLink.onclick = function() { Slideshow.slideSpeed(this, 3);  return false; };
// 		myLink.onmouseover = mouseover; myLink.onmouseout = mouseout;
		
		myLink = this.buildControl(mySpeeds, "4", "SlideSpeed", Localization.slideshow_speed4);
		myLink.onclick = function() { Slideshow.slideSpeed(this, 4);  return false; };
// 		myLink.onmouseover = mouseover; myLink.onmouseout = mouseout;
		
		myLink = this.buildControl(mySpeeds, "5", "SlideSpeed", Localization.slideshow_speed5);
		myLink.onclick = function() { Slideshow.slideSpeed(this, 5);  return false; };
// 		myLink.onmouseover = mouseover; myLink.onmouseout = mouseout;
		
		var tortoise = mySpeeds.appendChild(document.createElement("SPAN"));
		tortoise.className = "Tortoise";
		tortoise.appendChild(document.createTextNode("\u00a0"));
		
		myControls.appendChild(sepNode.cloneNode(true));
		
		myLink = this.buildControl(myControls, "✕", "Close", Localization.slideshow_close);
		myLink.onclick = function() { Slideshow.splashClose();  return false; };
		
		
		// CONTAINER -> VIEWPORT
		var myViewport = myContainer.appendChild(document.createElement("DIV"));
		myViewport.id = "SplashViewport";
		
		// VIEWPORT -> TABLE
		var myTable = myViewport.appendChild(document.createElement("TABLE"));
		var myCell  = myTable.appendChild(document.createElement("TBODY")).appendChild(document.createElement("TR")).appendChild(document.createElement("TD"));
		myTable.id = "SplashTable";
		myCell.onclick = function(e) { Slideshow.splashClose(); };
		myCell.className = "Splash";
		
		// TABLE CELL -> CONTENT
		var myContent = myCell.appendChild(document.createElement("DIV"));
		myContent.id = "SplashContent";
		myContent.onclick = function(e) { stopPropagation(e); };
		
		// SAVE REFERENCES
		this.splashContainer = myContainer;
		this.splashContent   = myContent;
		this.splashControls  = myControls;
		
		// CONTENT -> TITLE
		this.splashTitle      = myContent.appendChild(document.createElement("DIV"));
		this.splashTitle.id   = "SplashTitle";
		// CONTENT -> IMAGE
		this.splashImage      = myContent.appendChild(document.createElement("DIV"));
		this.splashImage.id   = "SplashImage";
		// CONTENT -> COMMENT
		this.splashComment    = myContent.appendChild(document.createElement("DIV"));
		this.splashComment.id = "SplashComment";
		
		// BUTTONS EFFECT
		$("#SplashNavControls a").each(function (type) {
			$(this).hover(function() {
				$(this).prev("a").addClass("Adj");
				$(this).next("a").addClass("Adj");
			}, function() {
				$(this).prev("a").removeClass("Adj");
				$(this).next("a").removeClass("Adj");
			});
		});
		
	},


	// BUILD CONTROL
	buildControl: function(aParent, aText, aClass, aTitle) {
		
		var myLink;
		myLink = document.createElement("A");
		myLink.className = aClass;
		myLink.title = aTitle;
		myLink.appendChild(document.createTextNode(aText));
		aParent.appendChild(myLink);
		return myLink;
		
	},


	// BUILD IMAGE
	buildImage: function(node) {
		
		var lnk = node.getElementsByTagName("A")[0];
		var img = lnk.getElementsByTagName("IMG")[0];
		
		var isrc = lnk.href.trim();
		// Fix strange IE6 bug
		if (isrc.indexOf("about:blank") == 0) isrc = isrc.substring(11);
		// Fix strange IE7 bug
		if (isrc.indexOf("about:") == 0) isrc = isrc.substring(6);
		
		var spl = lnk.href.split(/\?/);
		var get = spl[spl.length - 1];
		spl = get.split(/-/);
		
		var newImg = new Image;
		// using mywidth & myheight seems to be more reliable...???
		newImg.mywidth  = newImg.width  = spl[0];
		newImg.myheight = newImg.height = spl[1];
		newImg.src = isrc;
		
		return newImg;
		
	},


	// LOAD SLIDE
	loadSlide: function(newNode, prevImage, newImage, nextImage) {
		
		if (! this.splashContainer) this.buildSplash();
		
		//	STEP 1.  BASICS
		
		// SLIDESHOW OR IMAGE ZOOM ?
		var isSlideshow = ! hasClass(newNode, "Image");
		
		// TITLE & COMMENT
		var newTitle   = newNode.firstChild.cloneNode(true);
		var newComment = newNode.firstChild.nextSibling.nextSibling;
		if (newComment) newComment = newComment.cloneNode(true);
		
		//	STEP 2.  CALCULATIONS & PROCESSING
		
		// NEW IMAGE NODE
		if (! newImage) newImage = this.buildImage(newNode);
		if (isSlideshow) {
			newImage.title = Localization.slideshow_next;
			newImage.onclick = function() { Slideshow.slideNext(); };
		}
		
		// WIDTH & HEIGHT
		var newWidth = parseInt(newImage.mywidth);
		var newHeight = parseInt(newImage.myheight);
		// resize to fit inside the window
		var fitWidth  = window.innerWidth;
		var fitHeight = window.innerHeight;
		if (window.document.documentElement) { // I hate IE
			fitWidth = window.document.documentElement.offsetWidth;
			fitHeight = window.document.documentElement.clientHeight;
		}
		var fitWidth  = (fitWidth - 100) / newWidth;
		var fitHeight = (fitHeight - 150) / newHeight;
		var fitRatio  = Math.min(fitWidth, fitHeight);
		if (fitRatio < 1) {
			newHeight = parseInt(fitRatio * newHeight);
			newWidth = parseInt(fitRatio * newWidth);
		}
		
		//	STEP 3.  UPDATING THE DOM
		
		// SET CONTAINER CLASS
		this.splashContainer.className = isSlideshow ? "Slide" : "";
		
		// CLEANUP : only keep the last image
		this.splashClear(false);
		
		// SET DIMENSIONS
		this.splashContent.style.width = 
		this.splashImage.style.width  = newWidth + "px";
		this.splashImage.style.height = newHeight + "px";
		
		// SWITCH OLD & NEW
		if (this.splashImage.firstChild) this.splashImage.firstChild.className = "Old";
		newImage.className = "New";
		this.splashImage.appendChild(newImage);
		
		// TITLE & COMMENT
		this.splashTitle.appendChild(newTitle);
		if (newComment) this.splashComment.appendChild(newComment);
		
		
		//	STEP 4.  UPDATING THE DOM
		
		// PRELOAD NEXT AND PREVIOUS IMAGES if needed
		if (isSlideshow && ! prevImage) {
			var prevNode = newNode.previousSibling;
			if (! prevNode) prevNode = newNode.parentNode.lastChild;
			prevImage = this.buildImage(prevNode);
		}
		if (isSlideshow && ! nextImage) {
			var nextNode = newNode.nextSibling;
			if (! nextNode) nextNode = newNode.parentNode.firstChild;
			nextImage = this.buildImage(nextNode);
		}
		
		// SAVE DATA FOR RECYCLING
		this.slideNode = newNode;
		this.slidePrevImage = prevImage;
		this.slideCurrImage = newImage;
		this.slideNextImage = nextImage;
		
		// IE 6 or worse
		if (typeof document.body.style.maxHeight == "undefined") {
			this.splashContainer.style.top = document.documentElement.scrollTop + "px";
			this.splashContainer.style.height = document.documentElement.clientHeight + "px";
			this.splashContainer.style.borderColor = "lime";
		}
		
	},


	// SPLASH - CLEAR
	splashClear: function(deepFlag) {
		
		while (this.splashTitle.firstChild) this.splashTitle.removeChild(this.splashTitle.firstChild);
		while (this.splashComment.firstChild) this.splashComment.removeChild(this.splashComment.firstChild);
		while (this.splashImage.firstChild != this.splashImage.lastChild) this.splashImage.removeChild(this.splashImage.firstChild);
		if (deepFlag) {
			this.splashImage.removeChild(this.splashImage.firstChild);
			this.splashContent.style.width = "auto";
		}
		
	},


	// SPLASH - OPEN
	splashOpen: function() {

		if (hasClass(document.body, "Splash")) return;
		addClass(document.body, "Splash");  // hides flash and other plugins
		Layout.bodyShake();
		this.openFlag = true;

	},


	// SPLASH - CLOSE
	splashClose: function() {

		this.slideStop();
		this.slideNode = null;
		addClass(document.body, "SplashClosing");
		var callback = function() {
			removeClass(document.body, "SplashClosing");
			removeClass(document.body, "Splash");
			Slideshow.splashClear(true);
		}
		setTimeout(callback, this.splashTransitionDuration);
		this.openFlag = false;

	},


	// SLIDE - NEXT
	slideNext: function() {
		this.slideShowCounter = 0;
		var node = this.slideNode.nextSibling;
		if (!node)  node = this.slideNode.parentNode.firstChild;
		this.loadSlide(node, this.slideCurrImage, this.slideNextImage, null);
	},
	// SLIDE - PREVIOUS
	slidePrev: function() {
		this.slideShowCounter = 1;
		var node = this.slideNode.previousSibling;
		if (!node)  node = this.slideNode.parentNode.lastChild;
		this.loadSlide(node, null, this.slidePrevImage, this.slideCurrImage);
	},
	// SLIDE - PLAY
	slidePlay: function() {
		if (this.slideShowPlaying) {
			this.slideStop();
			return;
		}
		this.slideShowPlaying = true;
		window.setTimeout("Slideshow.slideCount()", this.slideShowRefresh);
		addClass(this.splashControls, "Pause");
	},
	// SLIDE - STOP
	slideStop: function() {
		this.slideShowPlaying = false;
		removeClass(this.splashControls, "Pause");
	},
	// SLIDE - SPEED
	slideSpeed: function(myLink, speed) {
		this.slideShowSpeed = speed;
		if (this.slideShowSpeed > 10) this.slideShowSpeed = 10;
		if (this.slideShowSpeed < 1) this.slideShowSpeed = 1;
		var siblings = myLink.parentNode.childNodes;
		for (var i = 0; i < siblings.length; i++) {
			removeClass(siblings[i], "Active");
		}
		addClass(myLink, "Active");
		if (! this.slideShowPlaying) {
			this.slidePlay();
		}
	},
	// SLIDE COUNT
	slideCount: function() {
		if (! this.slideShowPlaying)  return;
// 		window.status = "slideshow timer : " + this.slideShowCounter;
		if (this.slideShowCounter++ >= this.slideShowSpeed) {
			Slideshow.slideNext();
			this.slideShowCounter = 0;
		}
		window.setTimeout("Slideshow.slideCount()", this.slideShowRefresh);
	}


};



