$(window).load(function() {
	// Bind the overlays
	if ($('#FPInline').length) { // Only bind the inline content if it exist
		bindOverlay("FPInline", null, 3000);
		bindTcSlideShow($("#FPInline-tc-slideshow"));
	}
	if ($('#FPOverlay').length) { // Only bind the overlay content if it exist
		bindOverlay("FPOverlay", "http://www.dokumera.se/out_fp_overlay_content.asp?Name=FPOverlay", 3000);
	}

	$(window).resize(function () {
		// Center overlay
		var overlays = $("div.overlay-ajax");
		overlays.each(function(i) {
			if($(this).hasClass("visible")) {
				centerOverlay($(this));
			}
		});

		// Resize overlay
		var overlayMasks = $("div.overlay-mask");
		overlayMasks.each(function(i) {
			$(this).css({width: $(window).width() + "px", height: $(window).height() + "px"});
		});
	});

	// Bind Esc key to fade out overlay
	document.onkeydown = function(e){
		if (e == null) { // ie
			keycode = event.keyCode;
		} else { // mozilla
			keycode = e.which;
		}
		if(keycode == 27){ // escape, close box
			var overlays = $(".overlay"); // Get all overlays
			overlays.each(function(i) { // Loop through all overlays
				if($(this).hasClass("visible")) { // If overlay is visible
					fadeOutOverlay($(this)); // Hide the overlay
				}
			});
		}
	}
});

function fixOverlayForIE6(overlay, caller, data) {
	if(overlay.hasClass("overlay-ajax")) { // If overlay is ajax loaded
		if(caller == "bind") {
			overlay.css({position: "absolute", top: 0, left: 0}); // Set position to absolute instead of fixed on the overlay
			overlay.prev().css({position: "absolute", top: 0, left: 0, width: $(window).width() + "px", height: $(window).height() + "px"}); // Set position to absolute instead of fixed on the mask

			$(window).scroll(function() { // On window scroll
				$("div.overlay-ajax").each(function(i, ajaxOverlay) { // Loop through all ajax overlays
					if($(ajaxOverlay).hasClass("visible")) { // If overlay is visible
						var scrollTop = $(window).scrollTop(); // Get window top scroll
						var scrollLeft = $(window).scrollLeft(); // Get window left scroll
						centerOverlay($(ajaxOverlay)); // Center overlay
						var ajaxOverlayTop = parseInt($(ajaxOverlay).css("top")); // Get overlay current top position
						var ajaxOverlayLeft = parseInt($(ajaxOverlay).css("left")); // Get overlay current left position
						$(ajaxOverlay).css({top: (ajaxOverlayTop + scrollTop) + "px", left: (ajaxOverlayLeft + scrollLeft) + "px"}); // Correct overlay position to center it after current scroll
						$(ajaxOverlay).prev().css({top: scrollTop + "px", left: scrollLeft + "px"}); // Correct mask position to center it after current scroll						
					}
				});
			});
		}
		else if(caller == "fadein") {
			$(window).scrollTop(0).scrollLeft(0);
		}
		else if(caller == "correctwrapperwidth") {
			var overlaySlideWrapper = overlay.find(".overlay-slide-wrapper");
			overlaySlideWrapper.width((data.overlaySlideWidth + 100) * data.overlaySlideCount);
		}
	}
}

function createNewOverlayCallback(overlay) {
	if(overlay.attr("id") == "FPOverlay") {
		bindTcSlideShow($("#FPOverlay-tc-slideshow"));
	}
}

function bindOverlay(overlayId, overlaySource, slideSpeed) {

	// Define current overlay element
	var overlay = $("#" + overlayId);

	// Set slide speed
	overlay.attr("speed", slideSpeed);

	// If external source
	if(overlaySource) {

	// Add class ajax to separate from overlays that starts loaded
		overlay.addClass("overlay-ajax");

		// Set external source
		overlay.attr("src", overlaySource);

		// Insert mask to damp background
		$("<div/>").addClass("overlay-mask").insertBefore(overlay);

		// Get links for opening the overlay
		var overlayOpenButtons = $("ul." + overlayId + " > li > a");

		// Bind the links to open overlay on click
		overlayOpenButtons.click(function(event) {
			event.preventDefault();

			// Get the corresponding overlay
			var overlayId = $(event.target).parent().parent().attr("class");
			var overlay = $('#' + overlayId);

			// Get the corresponding slide id
			var slideId = $(event.target).attr("class");

			// If corresponding overlay element is empty
			if (!overlay.html()) {
				// Load content into overlay
				createNewOverlay(overlay, overlay.attr("src"), slideId);
			}
			else {
				// Content already loaded, fade in overlay
				fadeInOverlay(overlay, slideId);
			}
		});
	}
	else
	{
		var slides = overlay.find(".overlay-slide");
		var active = overlay.find(".active");
		if(!active.attr("class")) {
			var active = $(slides[0]).addClass("active");
		}
		if(window.location.hash && window.location.hash.replace("#id", "#") != "#") {
//			var startSlide = overlay.find(window.location.hash.replace(/^#id/, "#"));
			var startSlide = overlay.find(window.location.hash.replace("#id", "#"));
			if(startSlide.length != 0) {
				active.removeClass("active");
				active = startSlide.addClass("active");
			}
		}
		// Find the slide wrapper
		var overlaySlideWrapper = overlay.find(".overlay-slide-wrapper");

		// Get the number of slides and the current slide and append to div.overlay.slide-number
		var overlaySlideCount = overlay.find(".overlay-slide-wrapper .overlay-slide").length;
		var currentSlide = overlaySlideWrapper.children().index(active) + 1;
		overlay.find(".overlay-slide-number").text(currentSlide + "/" + overlaySlideCount);
		slideTo(overlay, active, 0);

	}

	// Bind next button to slide right
	overlay.find(".overlay-next-button > a").live("click", function(event) {
		event.preventDefault();
		var overlay = $(event.target).parent().parent().parent();
		if(!overlay.hasClass("animating")) {
			slide(overlay, "next");
		}
	});

	// Bind prev button to slide left
	overlay.find(".overlay-prev-button > a").live("click", function(event) {
		event.preventDefault();
		var overlay = $(event.target).parent().parent().parent();
		if(!overlay.hasClass("animating")) {
			slide(overlay, "prev");
		}
		
	});

	// Bind menu buttons to slide to that slide
	overlay.find(".overlay-menu a").live("click", function(event) {
		event.preventDefault();
		var overlay = $(event.target).parent().parent().parent().parent().parent();
		var goal = overlay.find("#" + $(event.target).attr("class"));
		if($(event.target).attr("class") != overlay.find("active").attr("id")) {
			slideTo(overlay, goal, overlay.attr("speed"));
		}
	});

	// Bind onlick event to close button
	overlay.find(".overlay-close-button > a").live("click", function(event) {
		event.preventDefault();
		
		// Get the close buttons overlay and fade it out
		var overlay = $(event.target).parent().parent();
		fadeOutOverlay(overlay);
	});

	// Fix for IE6 that does not handle position: fixed; on the overlay
	if (jQuery.browser.msie) {
		if(parseInt(jQuery.browser.version) == 6) {
			fixOverlayForIE6(overlay, "bind", null);
		}
	}
}

function centerOverlay(overlay) {
	var overlayLeft = $(window).width()/2 - overlay.outerWidth(true)/2;
	if(overlayLeft < 0) {
		overlayLeft = 0;
	}
	var overlayTop = $(window).height()/2 - overlay.outerHeight(true)/2;
	if(overlayTop < 20) {
		overlayTop = 20;
	}
	overlay.css({left: overlayLeft, top: overlayTop});
}

function slide(overlay, direction) {
	var slides = overlay.find(".overlay-slide");
	var active = overlay.find(".active");

	var index = slides.index(active);
	if(direction == "next") {
		if(index != slides.length - 1) {
			slideTo(overlay, active.next(), overlay.attr("speed"));
		}
	}
	else {
		if(index > 0) {
			slideTo(overlay, active.prev(), overlay.attr("speed"));
		}
	}
}

function createNewOverlay(overlay, source, slideId) {
	// ajax call to get overlay content
	$.get(source, function(data) {

		// Append content to overlay
		$(data).appendTo(overlay);

		// Declare some objects
		var overlaySlideCount = overlay.find(".overlay-slide-wrapper .overlay-slide").length;
		var overlaySlideWrapper = overlay.find(".overlay-slide-wrapper");

		// Get active slide
		var active = $("#" + slideId);

		// Get slide width
		overlaySlideWidth = active.outerWidth(true);

		// Hide overlay
		overlay.css({visibility: "hidden"});
		
		// Correct the width of the wrapper
		overlaySlideWrapper.width(overlaySlideWidth * overlaySlideCount);

		// Fix for IE6 to prevent the wrapper to be to narrow
		if (jQuery.browser.msie) {
			if(parseInt(jQuery.browser.version) == 6) {
				fixOverlayForIE6(overlay, "correctwrapperwidth", {overlaySlideWidth: overlaySlideWidth, overlaySlideCount: overlaySlideCount});
			}
		}

		// Fade in overlay
		fadeInOverlay(overlay, slideId);
		
		// createNewOverlay callback function
		createNewOverlayCallback(overlay);
	});
}

function fadeInOverlay(overlay, slideId) {
	// Add class visible
	overlay.addClass("visible");

	// Get active slide
	var activeSlide = $("#" + slideId);

	// Get overlay mask
	overlay.prev()
		.stop()
		.fadeTo(0,0)
		.css({display: "block"}) // Make overlay mask ready to fade in
		.fadeTo("fast", .75, function() { // Fade in mask, when finished, get overlay ready to fade in
			// Get size of overlay
			var overlayWidth = overlay.width();
			var overlayHeight = overlay.height();

			// Center overlay
			var overlayLeft = $(window).width()/2 - overlayWidth/2;
			if(overlayLeft < 0) {
				overlayLeft = 0;
			}
			var overlayTop = $(window).height()/2 - overlayHeight/2;
			if(overlayTop < 20) {
				overlayTop = 20;
			}

			// Create an overlay dummy
			var overlayDummy = $("<div/>").insertAfter(overlay);

			// Set general css values of overlay dummy
			overlayDummy.css({display: "none", zIndex: 21, position: "fixed", backgroundColor: "#fff"});
			// Set overlay dummy position
			overlayDummy.css({left: $(window).width()/2 - overlayWidth*.3/2 + "px", top: $(window).height()/2 - overlayHeight*.6/2 + "px"});
			// Set overlay dummy start size
			overlayDummy.css({width: overlayWidth*0.3 + "px", height: overlayHeight*.6 + "px"});
			// Fade in dummy
			overlayDummy.stop().fadeTo(0,0).css({display: "block"}).fadeTo("fast", 1);
			// Animate size and position of dummy
			overlayDummy.animate({height: overlayHeight + "px", top: overlayTop + "px"}, 100, function() {
				overlayDummy.animate({width: overlayWidth + "px", left: overlayLeft + "px"}, 300, function() {
					// Position and show overlay
					overlay.css({visibility: "visible", left: overlayLeft + "px", top: overlayTop + "px", zIndex: 20});

					slideTo(overlay, activeSlide, 0);
					// Fade out and remove overlay dummy to reveal overlay
					overlayDummy.fadeTo("fast", 0, function () {
						overlayDummy.remove();
					});

					// Fix for IE6 that makes scroll jump to top
					if (jQuery.browser.msie) {
						if(parseInt(jQuery.browser.version) == 6) {
							fixOverlayForIE6(overlay, "fadein", null);
						}
					}
				});
			});
		});	
}

function slideTo(overlay, goal, speed) {
	// Check that overlay is not already animating
	if(!overlay.hasClass("animating")) {
		overlay.addClass("animating");
		// Get menu pointer
		var overlayMenuPointer = overlay.find(".overlay-menu-pointer");
		// Get the id of the goal slide
		var targetId = goal.attr("id");
		// Get the goal menu element
		var overlayMenuPointerGoal = overlayMenuPointer.parent().find("." + targetId);

		// Move the active class to the goal element
		var active = overlay.find(".active");
		active.removeClass("active");
		goal.addClass("active");

		// Find the slide wrapper
		var overlaySlideWrapper = overlay.find(".overlay-slide-wrapper");

		// Get the number of slides and the current slide and append to div.overlay.slide-number
		var overlaySlideCount = overlay.find(".overlay-slide-wrapper .overlay-slide").length;
		var currentSlide = overlaySlideWrapper.children().index(goal) + 1;
		overlay.find(".overlay-slide-number").text(currentSlide + "/" + overlaySlideCount);

		// Get the new scroll position
		var scrollTo = goal.position().left;

		// Get the position of the goal menu element
		var movePositionTo = overlayMenuPointerGoal.position().top;

		// Animate the pointer
		pointerSpeed = Math.round(speed / 4);
		overlayMenuPointer.animate({top: (movePositionTo - 6) + "px"}, pointerSpeed);

		var prevButton = overlay.find(".overlay-prev-button > a");
		var nextButton = overlay.find(".overlay-next-button > a");

		if (currentSlide == 1) { // If moving to first, hide prev button
			prevButton.removeClass("visible").stop().fadeOut("fast"); 
		}
		else if (!prevButton.hasClass("visible")) {
			prevButton.addClass("visible").stop().fadeIn("fast");
		}
		
		if (currentSlide == overlaySlideCount) { // If moving to last, hide next button
			nextButton.removeClass("visible").stop().fadeOut("fast");
		}
		else if (!nextButton.hasClass("visible")) {
			nextButton.addClass("visible").stop().fadeIn("fast");
		}

		// Animate the slide wrapper
		overlaySlideWrapper.animate({left: -scrollTo + "px"}, speed, function() {
			// Remove the animating class
			overlay.removeClass("animating");
		});
	}
}
