// class to handle custom scrolling on pages
var scroll = {

	offset: 50,

	// stores all elements to be scrolled, the number of steps to scroll and the current step
	objs: [],

	init: function(element, eid) {
		if( typeof(element) === "object" && element.length > 0 ) {
			this.objs[eid] = { el: element, steps: [], totalSteps: 0, currStep: 0 };
			this.getSteps(eid);
			this.setArrowsState(eid);
		}
	},

	getSteps: function(eid) {
		var currObj = this.objs[eid];
		// this is a hack to make Safari and Chrome recalc the height of the scrolling content after we removed the overflow
		currObj.el.css({ "margin-bottom": "1px" });
		var scrollingElementHeight = currObj.el.height() + parseInt(currObj.el.css("padding-top"), 10) + parseInt(currObj.el.css("padding-bottom"), 10);
		var visibleAreaForScroll = currObj.el.parent().height();
		var totalDistanceToMove = scrollingElementHeight - visibleAreaForScroll;
		if( scrollingElementHeight > visibleAreaForScroll ) {
			// number of full scrolls and the remainder
			var fullSteps = Math.floor(totalDistanceToMove / this.offset);
			var remainder = totalDistanceToMove - (fullSteps * this.offset) || 0;

			// create a list of step positions for this element
			currObj.steps = [0];
			for(var i=1; i <= fullSteps; i++) {
				currObj.steps[i] = (i * this.offset) * -1;
			}
			currObj.steps[fullSteps + 1] = ((fullSteps * this.offset) + remainder) * -1;
			// we subtract 1 to skip the first step
			currObj.totalSteps = currObj.steps.length - 1;
		} else {
			currObj.steps = null;
			$("#"+eid+" .scroll-up, #"+eid+" .scroll-down").hide();
		}
	},

	move: function(eid, dir, mode) {
		var currObj = this.objs[eid];
		if( currObj.steps !== null ) {
			var loc = false;
			switch(dir) {
				case "up" :
					if( currObj.currStep > 0 ) {
						currObj.currStep--;
						loc = currObj.steps[currObj.currStep];
					}
				break;
				case "down":
					if( currObj.currStep < currObj.totalSteps ) {
						currObj.currStep++;
						loc = currObj.steps[currObj.currStep];
					}
				break;
			}
			if( loc !== false && typeof(loc) !== "undefined" ) {
				// call recursively for continuous scrolling
				if( mode === "continuous" ) {
					currObj.TO = setTimeout(function() {
						scroll.move(eid, dir, mode);
					}, 50);
					this.moveTo(eid, loc);
				} else {
					this.moveTo(eid, loc);
				}
			}
		}
	},

	moveTo: function(eid, loc) {
		this.objs[eid].el.css({ "marginTop": loc });
		this.setArrowsState(eid);
	},

	stop: function(eid) {
		clearTimeout(this.objs[eid].TO);
	},

	scrollToPoint: function(sel) {
		try {
			var pos = sel.position().top - sel.parent().position().top;
			var parent = sel.parents(".scroll");
			if( typeof(parent) !== "undefined" ) {
				var eid = parent.children(".scroll-arrows").attr("id");
				var currObj = this.objs[eid];
				if( typeof(currObj) !== "undefined" ) {
					var newStep = Math.floor(pos / this.offset);
					newStep = (newStep > currObj.totalSteps) ? currObj.totalSteps : newStep;
					currObj.currStep = newStep;
					this.moveTo(eid, currObj.steps[newStep]);
				}
			}
		} catch(e) {}
	},

	// make arrows active/inactive
	setArrowsState: function(eid) {
		var currObj = this.objs[eid];
		var currStep = currObj.currStep;
		var totalSteps = currObj.totalSteps;
		var c = "scroll-live";
		var up = $("#"+eid+" .scroll-up");
		var down = $("#"+eid+" .scroll-down");
		var next = $("#"+eid+" .scroll-next");
		var prev = $("#"+eid+" .scroll-prev");

		// up arrow
		if( currStep === 0 || totalSteps <= 0 ) { up.removeClass(c); } else { up.addClass(c); }
		// down arrow
		if( currStep === totalSteps || totalSteps <= 0 ) { down.removeClass(c); } else { down.addClass(c); }
		// next arrow
		if( next.attr("href") === "" ) { next.removeClass(c); } else { next.addClass(c); }
		// prev arrow
		if( prev.attr("href") === "" ) { prev.removeClass(c); } else { prev.addClass(c); }
	}
};

$(function() {

	// add scroll arrows
	$(".scroll").each(function() {
		var scrollDiv = "";
		var eid = "scroll_"+Math.floor(Math.random() * 100000);
		scrollDiv += '<div id="'+eid+'" class="scroll-arrows" style="margin-left: '+($(this).width() - 32)+'px;">\n';
		scrollDiv += '  <span class="scroll-up" href="" title="Scroll Up"></span>\n';
		scrollDiv += '  <span class="scroll-down" href="" title="Scroll Down"></span>\n';
		// add left right if needed
		if( !$(this).hasClass("up-down") ) {
			var nextPrevList = null;
			if( typeof(nextPrevListSelector) !== "undefined" ) {
				nextPrevList = $(nextPrevListSelector);
			} else {
				nextPrevList = $("#subsection-menu li.here") || $("#subsection-menu li:first");
			}
			var nextLink = nextPrevList.next().children("a").attr("href") || "";
			var prevLink = nextPrevList.prev().children("a").attr("href") || "";
			scrollDiv += '  <a class="scroll-next same-window" href="'+nextLink+'" title="Next"></a>\n';
			scrollDiv += '  <a class="scroll-prev same-window" href="'+prevLink+'" title="Previous"></a>\n';
		}
		scrollDiv += '</div>';

		// remove overflow, add the navigation arrows and bind the mousewheel event for scrolling
		$(this).css("overflow", "hidden").prepend(scrollDiv).bind("mousewheel", function(e, d) {
			var dir = (d > 0) ? "up" : "down";
			scroll.move(eid, dir);
			return false;
		});
		scroll.init($(this).children(".scroll-content"), eid);
	});

	var continuousScrollTimer;
	// mouse down/up event for scroll arrows (allows for speeeeed-scrolling!)
	$(".scroll-arrows .scroll-up, .scroll-arrows .scroll-down").mouseup(function() {
		var eid = $(this).parent().attr("id");
		var dir = $(this).attr("title").replace("Scroll ", "").toLowerCase();
		scroll.move(eid, dir, null);
		clearTimeout(continuousScrollTimer);
		scroll.stop(eid);
	}).mousedown(function() {
		var eid = $(this).parent().attr("id");
		var dir = $(this).attr("title").replace("Scroll ", "").toLowerCase();
		continuousScrollTimer = setTimeout(function() { scroll.move(eid, dir, "continuous"); }, 200);
	});
	$(".scroll-arrows .scroll-next, .scroll-arrows .scroll-prev").click(function(e) {
		if( this.href === location.href ) {
			e.preventDefault();
		}
	});

	// add captions to images
	$("img.cap").each(function() {
		var caption = $(this).attr("alt") || "";
		if( caption !== "" ) {
			var pos = ($(this).hasClass("right")) ? "right" : "left";
			var cid = "cap_"+Math.floor(Math.random() * 100000);
			$(this).wrap('<div class="'+pos+' caption-wrapper"></div>').before('<span id="'+cid+'" class="caption">'+caption+'</span>');
			// move the caption to the right place
			$("#"+cid).css("margin-top", 400 - $("#"+cid).height()+"px");
		}
	});

	// convert email addresses
	$("span.mail").each(function() {
		var address = $(this).text();
		address = address.replace(/ at /, "@");
		address = address.replace(/ dot /g, ".");
		var link = $(this).attr("title") || address;
		$(this).html('<a href="mailto:'+address+'">'+link+'</a>');
	});

	// open all external links in new window
	$("a[href^=http]:not(.same-window)").click(function() {
		window.open(this.href);
		return false;
	});

	if( $.browser.msie && $.browser.version === "6.0" ) {
		$('<link type="text/css" rel="stylesheet" href="/finalreport/css/ie.css" />').appendTo("head");
		// IE6 fix for 'hidden' positioned absolute elements
		$("#page-icon, #media-images").wrap("<div></div>");	
	}

});

var slideShowTimeout;
function moveSlide() {
	var currSlide = $("#slideshow .slideshow-container .here");
	currSlide.removeClass("here");
	var next = currSlide.next();
	if( typeof(next.attr("id")) !== "undefined" ) {
		currSlide.animate({ "opacity": 0 }, 750);
		next.animate({ "opacity": 1 }, 750, null, function() {
			$(this).addClass("here");
		});
		slideShowTimeout = setTimeout(function() { moveSlide(); }, 2000);
	} else {
		clearTimeout(slideShowTimeout);
		currSlide.animate({ "opacity": 0 }, 750);
		$("#slideshow .slideshow-container .slide:first").animate({ "opacity": 1 }, 750, null, function() {
			$(this).addClass("here");
			$("#slideshow-button").show();
		});
	}
}

function loadSlideshow(id) {
	$.getJSON("/finalreport/slideshow/load.php", function(images) {
		var container = $("#"+id).children(".slideshow-container");
		$.each(images, function(i, image) {
			var ssid = "ss_"+Math.floor(Math.random() * 100000);
			$('<div id="'+ssid+'" class="slide" style="z-index: '+(images.length - i)+';"><span>'+image.alt+'</span><img src="'+image.img+'" alt="" /></div>').appendTo(container);
			$("#"+ssid+" span").css("margin-top", 390 - $("#"+ssid+" span").height()+"px");
		});
		
		$('<div id="slideshow-button"></div>').appendTo("#slideshow");
		// start automatically
		setTimeout(function() { moveSlide(); }, 5000);
		// add handler for replay button
		$("#slideshow-button").click(function() {
			$(this).hide();
			moveSlide();
		});
	});
}
