String.prototype.ucfirst = function()
{
	return this.substr(0, 1).toUpperCase() + this.substr(1);
};

if (!Array.indexOf)
{
	Array.prototype.indexOf = function(obj)
	{
		for (var i = 0, c = this.length; i < c; i += 1)
		{
			if (this[i] == obj)
				return i;
		}
		return -1;
	}
}

var onSectionLoad = [];

// TODO: Move this?
onSectionLoad.push
(
	function()
	{
		if ($("#body .nieuws_pagina_tekst").length)
		{
			var container = $("<div />");
			var inner = $("<div />");
			
			container.append(inner).addClass("section" ).css({margin: "0px 30px", height: "300px", width: "570px", position: "relative", overflow: "hidden", top: "80px"});
			inner.css({position: "relative", left: "0px", width: "1000000px"});
			$("#body .section").css("float", "left").wrapAll(container);
							
			var prev = $("<a><img src=\"" + URI_BASE + "/graphics/shoppingtour_prev.png\" /></a>").addClass("prev").click(function()
			{
				var inner = $("#body>div>div");
				if (inner.position().left >= 0)
					return;
				inner.animate({"left": "+=570"});
			});
			var next = $("<a><img src=\"" + URI_BASE + "/graphics/shoppingtour_next.png\" /></a>").addClass("next").click(function()
			{
				var inner = $("#body>div>div");
				if (Math.ceil(inner.position().left / -570) >= (inner.children().length - 1))
					return;
				inner.animate({"left": "-=570"});
			});
			
			$("#body").append(prev).append(next);
		}
		else
		{
			$("#body .prev, #body .next").remove();
		}	
	}
);

onSectionLoad.push
(
	function()
	{
		$("#body .cycle").length && $("#body .cycle").cycle();
	}
);

$(function()
{
	$("#body .cycle").length && $("#body .cycle").cycle();

	$("#menu_handle, #body_handle").disableSelection();
	$("#sticker, #popup").disableSelection().draggable();
	$("#menu").draggable({handle: "#menu_handle"});
	$("#body").draggable({handle: "#body_handle"});
	
	$(window).resize(function()
	{
		if ($(document).width() > 3000)
			return;
			
		// center menu, body and sticker overlay on the page
		var width = 900, height = 550, gap = 20;
		var left = ($(document).width() - width) / 2;
		var top = ($(document).height() - height) / 2;
		
		// sticker is horizontally centered in menu
		var stickerLeftOffset = ($("#menu").width() - $("#sticker").width()) / 2;

		$("#menu").css({left: left, top: top});
		$("#body").css({left: left + $("#menu").width() + gap, top: top});
		$("#sticker").css({left: left + stickerLeftOffset, top: top + 275});
	});
	// trigger resize handler
	$(window).resize();
		
	// initialize menu
	$("#menu li ul").css({display: "none"});
	$("#menu .menu_a, #sticker a, #welkom_text a").click(function()
	{
		var a = $(this), li = null;
		
		RemoveSlideshow();
		$("#body").show();
		$("#omgeving").remove();
		$("#impressie").remove();
		
		if (a.parents("#menu").length)
		{
			// link is in menu, get associated list item
			li = a.closest("li");
		}
		else
		{
			// link not in menu, find link with same href in menu, get that li
			$("#menu a").each(function()
			{
				if ($(this).attr("href") == a.attr("href"))
				{
					li = $(this).closest("li");
					return false;
				}
			});
		}
		
		if (li != null)
		{
			if (li.hasClass("main") && li.find("ul") && !li.find("ul").is(":visible"))
			{
				// if this is a top-level menu-item, and it has children which are 
				// not visible, hide all other sub menus, and show this one
				$("#menu li ul").slideUp();
				li.find("ul").slideDown();
			}

			if (a.hasClass("nolink"))
			{
				a = li.find("ul a:first");
				li = a.closest("li");
			}

			// mark this menu item as active
			$("#menu .active").removeClass("active");
			li.addClass("active");
		}
		
		$.getJSON(SplicePath(a.attr("href")), {}, function(data)
		{
			if ($("#body").data("pageData"))
				$("#body h2").removeClass("page_" + $("#body").data("pageData").id);
				
			// remove all sections of the previous page, add the new data
			$("#body .section").remove();
			$("#body").append(data.html).data("pageData", data);
			
			$("#body .section").each(function(i)
			{
				$(this).data("section", data.sections[i]);
			});
			
			document.title = "Coriocenter - " + data.title;
			$("#body h2").text(data.title).addClass("page_" + data.id);
			if (data.subtitle)
				$("#body h2").append($("<span/>").text(data.subtitle));
			
			// change the page background
			$("#back img").attr("src", data.background);
			$("#body").css("background-image", "url('" + (data.bodyBackground || URI_BASE + "/graphics/Content_bg.png") + "')");
			$("#body").removeClass().addClass(data.bodyClass);
			
			for (var i = 0; i < onSectionLoad.length; i += 1)
				onSectionLoad[i]();
		});
		
		return false;
	});
	
	// intialize admin functionality
	$.fn.editSection = function()
	{
		var pageData = $("#body").data("pageData");
		if (USER == null)
			return;

		if (GROUPS.indexOf(pageData.group) < 0)
		{
			alert("Unable to edit this section. Only members of the " + pageData.group + " group can edit this page.");
			return;
		}

		if (this.is(".html, .script, .shopfoto"))
		{
			var section = this;
			var form = this.overlayElement("div");
			var input = $("<textarea />").val(section.data("section").content);
			var linkTemplate = $("<a href=\"#\">&nbsp;</a>");
			form
				.append(linkTemplate.clone().actionLink("image").click
				(
					function() 
					{ 
						section.imagePopup(form); 
						return false; 
					}
				))
				.append(linkTemplate.clone().actionLink("bold").click
				(
					function()
					{
						section.makeBold(form);
						return false;
					}
				))
				.append(linkTemplate.clone().actionLink("italic").click
				(
					function()
					{
						section.makeItalic(form);
						return false;
					}
				))
				.append(linkTemplate.clone().actionLink("link").click
				(
					function()
					{
						section.makeLink(form);
						return false;
					}
				))
				.append(linkTemplate.clone().actionLink("save").click
				(
					function()
					{
						section.saveSection(form); 
						return false; 
					}
				))
				.append(linkTemplate.clone().actionLink("close").click
				(
					function() 
					{ 
						form.remove(); 
						section.show(); 
						return false; 
					}
				));

			form.append(input);
			input.width(form.width() - 12).height(form.innerHeight() - linkTemplate.outerHeight(true) - 12);
			
			if (form.height() < 250)
			{
				form.animate({height: 250}, "fast", function()
				{
					input.height(form.innerHeight() - linkTemplate.outerHeight(true) - 12);
				});
			}
		}
		else
		{
			// alert("Unable to edit this section");
		}
	};
	
	$.fn.saveSection = function(form)
	{
		var section = this;
		var content = $(form).find("textarea").val();
				
		$.ajax({
			url: SplicePath(URI_BASE + "/" + this.attr("title").replace("_", "/")), 
			type: "POST",
			data: {content: content}, 
			dataType: "json",
			success: function(data)
			{
				if (data.error)
					alert(data.error);

				section.show();
				section.disableSelection();
				section.replaceWith(data.html);
				
				form.remove();
				
				for (var i = 0; i < onSectionLoad.length; i += 1)
					onSectionLoad[i]();				
			}
		});
	};
	
	$.fn.actionLink = function(type)
	{
		return this.each(function()
		{
			$(this).addClass("action").addClass(type).attr("title", STRINGS[type.ucfirst()] || type.ucfirst());
		});
	}
	
	$.fn.editHeader = function()
	{
		if (USER == null)
			return;
		
		var header = this;
		var form = this.overlayElement("div");
		var input = $("<input />").attr("type", "text").addClass("header").val(this.text());
		var save = $("<a href=\"#\">&nbsp;</a>").actionLink("save").click(function(e) { header.saveHeader(form); return false; });
		var close = $("<a href=\"#\">&nbsp;</a>").actionLink("close").click(function(e) { form.remove(); header.show(); return false; });

		form.find("a").css({marginTop: "7px"});
		form.append(input).append(save).append(close);
	};
	
	$.fn.saveHeader = function(form)
	{
		var header = this, newTitle = form.find("input").val();
		var url = $("#menu .active a").attr("href") || window.location.pathname;
		
		$.ajax({
			url: SplicePath(url), 
			type: "POST",
			data: {title: newTitle}, 
			success: function(data)
			{
				if (data.error)
					alert(data.error);
				else
					header.text(newTitle);
				form.remove();
				header.show();
			}
		});
	};
	
	$.fn.imagePopup = function(form)
	{
		$.getJSON(SplicePath(URI_BASE + "/image"), {}, function(data)
		{
			$("#popup .section").remove();
			
			var list = $("<ul />").addClass("section").addClass("imagePopup");
			for (var i = 0; i < data.length; i += 1)
			{
				var img = $("<img />").data(data[i]).attr("src", data[i].url).click(function(e)
				{
					var url = $(this).data().url;
					
					form.find("textarea").replaceSelection("<img src=\"" + url + "\" />");
					
					$("#popup").hide();
				});
				
				var li = $("<li />").append(img);
				list.append(li);
			}
			
			$("#popup").append(list);
			$("#popup").append("<p class=\"section clear\"><a class=\"notpopup\" href=\"/image/add\">Toevoegen</a></p>");
			$("#popup h2").text(STRINGS["Insert Image"] || "");
			
			$("#popup").show();
			$("#popup").css($("#body").offset());
		});
	};
	
	$.fn.makeBold = function(form)
	{
		var t = form.find("textarea");
		t.replaceSelection("<strong>" + t.getSelection() + "</strong>");
	};
	$.fn.makeItalic = function(form)
	{
		var t = form.find("textarea");
		t.replaceSelection("<em>" + t.getSelection() + "</em>");
	};
	$.fn.makeLink = function(form)
	{
		var t = form.find("textarea");
		t.replaceSelection("<a href=\"" + t.getSelection() + "\">" + t.getSelection() + "</a>");
	};

	$.fn.replaceSelection = function(text)
	{
		return this.each(function()
		{
			if (document.selection)
			{
				this.focus();
				var sel = document.selection.createRange();
				sel.text = text;
				this.focus();
			}
			else if (this.selectionStart || this.selectionStart == "0")
			{
				var startPos = this.selectionStart;
				var endPos = this.selectionEnd;
				var scrollTop = this.scrollTop;
				this.value = this.value.substr(0, startPos) + text + this.value.substr(endPos);
				this.focus();
				this.selectionStart = startPos;
				this.selectionEnd = startPos + text.length;
				this.scrollTop = scrollTop;
			}
			else
			{
				this.value += text;
				this.focus();
			}
		});
	};

	$.fn.getSelection = function()
	{
		var textArea = this[0];
		if (document.selection)
		{
			textArea.focus();
			return document.selection.createRange().text;
		}
		else if (textArea.selectionStart || textArea.selectionStart == "0")
		{
			var start = textArea.selectionStart, length = textArea.selectionEnd - start;
			return textArea.value.substr(start, length);
		}
		else
		{
			return "";
		}
	};

	$.fn.overlayElement = function(type)
	{
		var elem = $("<" + type + " />");
		elem.addClass("overlay").width(this.outerWidth()).height(this.outerHeight());
		
		var props = ["marginTop", "marginRight", "marginBottom", "marginLeft", "clear", "float", "position", "left", "top"]
		for (var i = 0; i < props.length; i += 1)
			elem.css(props[i], this.css(props[i]));
		
		this.hide().after(elem);
		return elem;
	};
	
	$("#body .section").live("dblclick", function(e)
	{
		$(this).editSection();
	});
	
	$("#body").append($("<div id=\"actions\" />").hide());
	
	$("#body h2, #body .section").live("mouseenter", function(e)
	{
		var section = $(this);
		
		if (USER == null)
			return;
		
		var actions = $("#actions").empty();
		actions.mouseenter();
		
		if (section.is("h2"))
		{
			actions.append($("<a href=\"#\">&nbsp;</a>").addClass("edit").click(function()
			{
				actions.hide();
				section.editHeader();
				return false;
			}));
		}
		else if (section.hasClass("html") || section.hasClass("colorlist"))
		{
			actions.append($("<a href=\"#\">&nbsp;</a>").addClass("edit").click(function()
			{
				actions.hide();
				section.editSection();
				return false;
			}));
		}
		else
		{
			return;
		}
		
		actions.css({width: actions.children().length * 26});
		actions.show();
		actions.position({my: "left top", at: "left top", of: section});
		
	});
	$("#body h2, #body .section").live("mouseleave", function(e)
	{
		$("#actions").mouseleave();
	});
	$("#actions").mouseenter(function(e)
	{
		clearTimeout(window._actionTimeout);
	});
	$("#actions").mouseleave(function(e)
	{
		clearTimeout(window._actionTimeout);
		window._actionTimeout = setTimeout(function() { $("#actions").fadeOut(); }, 500);
	});
	
	$("#closePopup").click(function(e)
	{
		$("#popup").hide();
		return false;
	});
	
	$(".popup").live("click", function(e)
	{
		var a = $(this);

		$.getJSON(SplicePath(a.attr("href")), {}, function(data)
		{
			$("#popup .section").remove();
			$("#popup").append(data.html);
			
			$("#popup .section").each(function(i)
			{
				$(this).data("section", data.sections[i]);
			});
			
			$("#popup .cycle").length && $("#popup .cycle").cycle();
			
			$("#popup h2").text(data.title);
			
			$("#popup").show();
			$("#popup").css($("#body").offset());
		});
		
		return false;
	});
	
	$("#wiezitwaar_lijst a").live("click", function(e)
	{
		var a = $(this);
		var id = a.attr("href").split("#")[1];
		
		$("#wiezitwaar img").each(function()
		{
			if ($(this).attr("alt") == id)
				$(this).show();
			else
				$(this).hide();
		});
		
		return false;
	});
	
	$("#shop_lijst a").live("click", function(e)
	{
		var a = $(this);
		var id = a.attr("href").split("#")[1];

		$("#shop img").each(function()
		{
			var img = $(this);
			if (img.attr("src").indexOf(id + ".png") > 0)
			{
				img.show();
				img.attr("href", a.attr("href").split("#")[0]);
				img.addClass("popup");
			}
			else
			{
				img.hide();
				img.removeClass("popup");
			}
		});
		
		if ($("#shop img:visible").length != 1)
			console.debug($("#shop img:visible"));
		
		return false;
	});
	
	$("#shoppingtour_prev").live("click", function()
	{
		if ($("#shoppingtour_winkels div").position().left >= 0)
			return;
		
		shoppingTourIndex -= 1;
		$("#shoppingtour_winkels div").animate({"left": "+=260px"}, "slow", ShoppingTourUpdateLayer);
	});
	
	$("#shoppingtour_next").live("click", function()
	{
		var sum = 0;
		for (var i = 0; i < shoppingtour.length; i += 1)
			sum += shoppingtour[i].width;
	
		if (shoppingTourIndex + 1 >= sum)
			return;
	
		shoppingTourIndex += 1;
		$("#shoppingtour_winkels div").animate({"left": "-=260px"}, "slow", ShoppingTourUpdateLayer);
	});	
});

// This function places /json/ in front of the handler name, so that the
// PHP handler knows it has to pass back JSON instead of just HTML
function SplicePath(path)
{
	if (path.substr(0, URI_BASE.length) != URI_BASE)
		return path;
	return URI_BASE + "/json" + path.substr(URI_BASE.length);
}

function StartSlideshow()
{
	$("#body h2").hide();
	$("#body").addClass("slideshow");
	
	var img = new Image();
	img.onload = function()
	{
		$("#body").data("slideshow", {loaded: 0, started: false});
		for (var i = 0; i < elementen.length + 4; i += 1)
		{
			var img = $("<img />").attr("src", elementen[i % elementen.length]).load(SlideshowImageLoaded);
			$("#slideshow_elementen").append(img);
		}
	
		for (var i = 0; i < produkten.length + 4; i += 1)
		{
			var img = $("<img />").attr("src", produkten[i % produkten.length]).load(SlideshowImageLoaded);
			$("#slideshow_produkten").append(img);
		}
	};
	img.src = URI_BASE + "graphics/Slide_bg.jpg";
}

function SlideshowImageLoaded()
{
	var data = $("#body").data("slideshow");
	data.loaded += 1;
	if (data.loaded >= elementen.length + produkten.length && !data.started)
	{
		data.started = true;
		StartSlideshow2();
	}
}

function StartSlideshow2()
{
	var data = $("#body").data("slideshow");

	$("#slideshow_wrapper>img").hide();
	$("#slideshow_wrapper>div").show();
	
	data.bgTimeout = window.setInterval(function()
	{
		var width = 665, num = 5;
		var pos = parseInt($("#body").css("backgroundPosition").split(" ")[0]) - width;
		$("#body").animate({"backgroundPosition" : pos + " 0px"}, "slow", function()
		{
			if ((pos % (width * num)) == 0)
				$("#body").css("backgroundPosition", "0px 0px");
		});
	}, 4000);

	data.eTimeout = window.setInterval(function()
	{
		var width = 250, num = elementen.length;
		var div = $("#slideshow_elementen");
		
		div.animate({"left" : "-=" + width}, function()
		{
			if (div.position().left <= (-1 * width * num))
				div.css("left", 0);
		});
	}, 4000);

	data.pTimeout = window.setInterval(function()
	{
		var width = 250, num = produkten.length;
		var div = $("#slideshow_produkten");
		
		div.animate({"left" : "-=" + width}, function()
		{
			if (div.position().left <= (-1 * width * num))
				div.css("left", 0);
		});
	}, 2000);
}

function RemoveSlideshow()
{
	$("#body h2").show();
	$("#body").removeClass("slideshow").css("backgroundPosition", "0px 0px");
	$("#slideshow_wrapper, #slideshow_text").remove();
	
	var data = $("#body").data("slideshow");
	if (data && data.bgTimeout)
		window.clearInterval(data.bgTimeout);
	if (data && data.eTimeout)
		window.clearInterval(data.eTimeout);
	if (data && data.pTimeout)
		window.clearInterval(data.pTimeout);
}

function StartOmgeving()
{
	var num = 12, cols = 6;
	
	var control = $("<div id=\"omgeving\" />").draggable();
	$("#body").hide();
	$("body").append(control);

	for (var i = 0; i < num; i += 1)
	{
		var x = 15 + (i % cols) * 30, y = 10 + Math.floor(i / cols) * 27;
		var a = $("<a href=\"#\">&nbsp;</a>").css({backgroundPosition: "-" + x + "px -" + y + "px"});
		a.data("url", URI_BASE + "/graphics/omgeving/" + (i + 1) + ".jpg");
		a.click(function(){ $("#back img").attr("src", $(this).data("url")); });
		control.append(a);
	}

	var gap = 50;
	var left = $("#menu").offset().left + $("#menu").width() + gap;
	var top = $("#menu").offset().top + gap;
	control.css({left: left, top: top});
}

function StartImpressie()
{
	var num = 12, cols = 6;
	
	var control = $("<div id=\"impressie\" />").draggable();
	$("#body").hide();
	$("body").append(control);

	for (var i = 0; i < num; i += 1)
	{
		var x = 15 + (i % cols) * 30, y = 10 + Math.floor(i / cols) * 27;
		var a = $("<a href=\"#\">&nbsp;</a>").css({backgroundPosition: "-" + x + "px -" + y + "px"});
		a.data("url", URI_BASE + "/graphics/foto_impressies/" + (i + 1) + ".jpg");
		a.click(function(){ $("#back img").attr("src", $(this).data("url")); });
		control.append(a);
	}

	var gap = 50;
	var left = $("#menu").offset().left + $("#menu").width() + gap;
	var top = $("#menu").offset().top + gap;
	control.css({left: left, top: top});
}

var shoppingTourIndex = 0;
function ShoppingTourUpdateLayer()
{
	var sum = 0;
	for (var i = 0; i < shoppingtour.length; i += 1)
	{
		if (shoppingTourIndex >= sum && shoppingTourIndex <= sum + shoppingtour[i].width)
		{
			$("#shoppingtour").css("background-image", "url('" + shoppingtour[i].map + "')");
			return;
		}
		
		sum += shoppingtour[i].width;
	}
}


