/*
 * *******************************************************************
 *
 *  SKOLESTART.NU :: MAIN SCRIPT
 *  
 *  Written by Anders Gissel
 *  (c) 2010, WildSide A/S
 *  http://www.wildside.dk
 * 
 * *******************************************************************
 */



var skolestart = {
	// How big is the floating topbar thingie?
	topMargin : 180,
	
	// How many milliseconds between each position poll?
	pollingFrequency : 500,
	
	// Placeholder for headline objects
	knownObjects : {},
	
	// Is a scroll animation running?
	animationRunning : false,
	
	// How many milliseconds should the scroll animation take?
	scrollTime : 300,
	
	
	/*
	 * SETUP
	 * This function prepares the site for display. This is where all other functionality
	 * is set up, so... you know, treat it right.
	 * 
	 */
	setup : function() {
	
		// Register each section as a known object. This is where we find its offset and height,
		// so we don't have to do this a lot later.
		$("#contentHolder .section").each(function(){
			var id = $(this).attr("id");
			skolestart.knownObjects[id] = {
				obj : $(this),
				id : id,
				top : $(this).offset().top,
				height : parseInt($(this).find("img.headPic:first").outerHeight())
			}
		});
		
		// Manipulate links in the topbar.
		$("#topbarMenu a").each(function(i) {
			var ident = i+1;
			
			// Get the link text
			var altText = $(this).text();
			
			// Manipulate the link: add corners (you know, the pretty red lines)
			var on = $(this).find(".indicators.button.on");
			var left = $("<span class='indicators corner left'>&nbsp;</span>");
			var right = $("<span class='indicators corner right'>&nbsp;</span>");
			on.css("opacity", 0);
			left.css("opacity", 0);
			right.css("opacity", 0);
			$(this).prepend(left).append(right);
			
			// Set hover functionality
			$(this).hover(
				function() { skolestart.highlightLink.call(this, 1); },
				function() { skolestart.dimLinks.call(this, 1); }
			);
			
			// Set click functionality.
			$(this).click( skolestart.activateLink );
			
		});
		
		// Run through the sections, and find all links starting with anchors. This
		// will most likely only be FCE-based buttons, which is all we need. Then,
		// add onclick-functionality to make the page scroll and all that jazz.
		$("#contentHolder .section a[href^='\\#']").each(function(){
			var e = $(this);
			e.addClass("handled");
			e.click(function(){
				var href = e.attr("href");
				var hashLocation = href.indexOf("#");
				
				if (hashLocation > -1) {
					// Find corresponding link in the top bar, and make sure it's "clicked"
					// when this link is clicked.
					trgt = href.substr(hashLocation+1);
					var theLink = $("#topbarMenu a[href*='#"+trgt+"']");
					if (theLink.length) {
						skolestart.activateLink.call(theLink);
					};
					return false;
				};
			});
		});
		
		// Finally, read the window location, and scroll to a named anchor if one exists.
		var hash = window.location.hash;
		if (hash) {
			var theLink = $("#topbarMenu a[href*='"+hash+"']");
			if (theLink.length) skolestart.activateLink.call(theLink);
		};
		
		// Start the scroll position polling.
		skolestart.checkScrollPosition();
	
	},
	
	/*
	 * ACTIVATE LINK
	 * This function handles clicks on the links in the topbar. This initiates the
	 * scrolling and what not.
	 * 
	 */
	activateLink : function(event) {
		var e = $(this);
		var href = e.attr("href");
		
		// If this is not an external link, do stuff to it.
		if (!e.hasClass("external")) {
			var hashLocation = href.indexOf("#");
			
			if (hashLocation > -1) {
				trgt = href.substr(hashLocation+1);
				
				// Remove "active" class from any other links, and set it on this one.
				$("#topbarMenu a.active").removeClass("active");
				e.addClass("active");
				
				// Highlight current link and dim others.
				skolestart.highlightLink.call(e);
				skolestart.dimLinks();
				
				// Find out where we should be scrolling.
				var windowHeight = parseInt($(window).height());
				var target = skolestart.knownObjects[trgt].top - skolestart.topMargin;
				
				// Initiate scrolling
				skolestart.forceScrollTo.call(e, target);
				
				// Blur the link
				e.blur();
				
				// Set window location hash
				window.location.hash = "#" + trgt;
				
				// Stop event propagation
				return false;
			};
			
		} else {
			// It seems to be an external link, so just go with it.
			window.location = href;
		};
	},
	
	
	
	/*
	 * SCROLLING INITIATOR THINGIE
	 * This function scrolls the browser to a given Y-coordinate using some nice animation.
	 * 
	 */
	forceScrollTo : function(ycoord) {
		// Tell the scroll position poller that an animation is in progress.
		skolestart.animationRunning = true;
		// Run animation, with callback setting the animation-flag to false on completion.
		$("html, body").animate({scrollTop : ycoord}, skolestart.scrollTime, function() { skolestart.animationRunning = false; });
		
	},
	
	
	/*
	 * HIGHLIGHT LINK
	 * This highlights a link in the topbar. If "ishover" is true, it is regarded as a mouse-over event,
	 * which adds the "hover" class to the link as well.
	 * 
	 */
	highlightLink : function(ishover) {
		
		if (ishover) {
			$("#topbarMenu a.hover").removeClass("hover");
			$(this).addClass("hover");
		}
		$(this).find(".indicators:not(.off)").fadeTo('fast', 1);
		$(this).find(".indicators.off").fadeTo('fast', 0);
		
	},
	
	/*
	 * DIM LINKS
	 * This dims all links not currently active (hovered or "selected"). If "ishover" is true,
	 * it will disengage all hover settings.
	 */
	dimLinks : function(ishover) {
		if (ishover) $("#topbarMenu a.hover").removeClass("hover");
		var lnks = $("#topbarMenu a:not(.active,.hover)");
		lnks.find(".indicators:not(.off)").stop().css("opacity", 0);
		lnks.find(".indicators.off").stop().css("opacity", 1);
	},
	
	
	
	/*
	 * CHECK SCROLL POSITION
	 * This function runs once every X milliseconds, and checks the current scroll position
	 * of the browser. If it detects that a certain section on the page is in clear view, it
	 * will automatically mark that section as active in the topbar.
	 * 
	 */
	checkScrollPosition : function() {
		// Only do this if a scroll animation is NOT running.
		if (!skolestart.animationRunning) {
			
			// Get environment settings.
			var windowScroll = parseInt($(window).scrollTop());
			var windowHeight = parseInt($(window).height());
			var documentHeight = parseInt($(document).height());
			var usablePoints = [];
			
			// If the window has been scrolled, find out which of our known objects are visible.
			if (windowScroll) {
				for (obj in this.knownObjects) {
					var t = this.knownObjects[obj].top;
					var h = this.knownObjects[obj].height;
					if (t - windowScroll >= this.topMargin) {
						// Object is not too far "up". But can we see it?
						if (t - windowScroll + h < windowHeight) {
							// Yes we can! Add it to the stack!
							usablePoints.push(this.knownObjects[obj]);
						};
					};
				};
			} else {
				// If we are here, the window hasn't been scrolled, so we just use a pseudo-foreach
				// to select the first object in the known stack.
				for (obj in this.knownObjects) {
					usablePoints.push(this.knownObjects[obj]);
					break;
				};
			};
			
			if (usablePoints.length) {
				// Find out which section to use. Normally we go for the first in the stack,
				// but if we are very close to the bottom, mark the last in the stack instead.
				var usedLink = 0;
				if (windowScroll + windowHeight + 30 >= documentHeight) {
					usedLink = usablePoints.length -1;
				};
				// Now, mark the chosen link as active, and dim all others.
				jQuery("#topbarMenu a.active").removeClass("active");
				jQuery("#topbarMenu a[href*='#"+ usablePoints[usedLink].id +"']").addClass("active");
				
				// Call highlighter and dimmer.
				skolestart.highlightLink.call(jQuery("#topbarMenu a[href*='#"+ usablePoints[usedLink].id +"']"));
				skolestart.dimLinks();
			};
		};
		
		// Set up the next poll.
		window.setTimeout("skolestart.checkScrollPosition()", this.pollingFrequency);
	}
	
};

// Get going once the DOM is ready.
$(document).ready( function() { skolestart.setup(); } );
