var Website = {

	currentPage: "home",
	currentPageVar: false,
	interfaceVisible: true,
	items: [],
	currentItem: null,
	objectIDs: [],
	
	isiPad: function() {
		return (navigator.platform.indexOf("iPad") != -1);	
	},

	menu: {
		openItem: null,
		closeTimeout: null,
		init: function() {

			$("ul.filters > li").each(function(){
				var li = $(this);

				if (Website.isiPad()) {

					li.find(".header").each(function(){
						var element = $(this);
						element.bind("click", function(element){
							return function() {
								Website.menu.toggle(element);
							}
						}(li));
					});

				} else {

					li.find(".header, li a, li span").each(function(){
						var element = $(this);
						element.bind("mouseenter", function(element){
							return function() {
								Website.menu.open(element);
							}
						}(li));
					});

					li.find("li a, li span").each(function(){
						var element = $(this);
						element.bind("mouseleave", function(element){
							return function() {
								Website.menu.close(element, this);
							}
						}(li));
					});

				}
			});

		},
		toggle: function(element) {
			if (element.attr("open") == "no") {
				this.open(element);
			} else {
				this.close(element);
			}
		},
		open: function(element) {
			clearTimeout(this.closeTimeout);
			if (element.attr("open") == "no") {
				if (this.openItem) {
					this.actuallyClose(this.openItem);
				}
				element.attr("open", "yes");
				element.find("> ul, > ul ul").show();
				this.openItem = element;
			}
		},
		close: function(element, origin) {
			if (element.attr("open") == "yes") {
				this.closeTimeout = setTimeout(function() {
					Website.menu.actuallyClose(element);
				}, 350);
			}
		},
		actuallyClose: function(element) {
			element.attr("open", "no");
			element.find("> ul").hide();
		}
	},
	
	mySelection: {

		items: [],

		add: function() {
			$.ajax({
				cache: false,
				dataType: "json",
				error: function(xhr, status, error) { alert("error"); },
				success: function(data, status, xhr) {
					if (data.status == "success") {
						// alert("success");
					} else if (data.status == "double") {
						alert("Je hebt dit item al toegevoegd aan je selectie.");
					} else {
						alert("Kan dit item nu niet toevoegen aan je selectie. Probeer het nog eens.");
					}
					Website.mySelection.items = data.items;
					Website.mySelection.update();
				},
				url: "my-selection/add/"+Website.currentItem+"/"
			});
			
		},

		remove: function() {
			
		},
		
		update: function() {
			$("#my-list .view").text("Mijn selectie ["+Website.mySelection.items.length+"]");
			$("#my-list .add").text("+ Voeg toe");
			for (var i = 0; i < Website.mySelection.items.length; i++) {
				if (parseInt(Website.mySelection.items[i]) == Website.currentItem) {
					$("#my-list .add").text("Toegevoegd!");
				}
			}
		}

	},

	init: function() {
		
		$("#navigation").append($("<div/>").attr("id", "tags").append("<ul/>"));
		$("#navigation").append($("<div/>").attr("id", "note").append("<p/>").append("<h2/>").append("<a class='inverted-tag'/>"));
		$("#navigation").append($("<div/>").attr("id", "project").append("<h2/>").append("<p><a></a></p>"));
		$("#background, #note, #tags").hide();

		Website.bg.init();
		Website.resize();
		
		if (this.currentPage == "tag") {
			setTimeout(function(){
				Website.toggleInfo();
			}, 1000);
		}
		
		$(window).resize(function(){ Website.resize(); });
		this.mySelection.update();
		this.menu.init();
		$(document).keydown(function(event){ Website.keypress(event); });
		
	},
	
	keypress: function(e) {
		switch (e.which) {
			case 37: // left
			this.bg.previous();
			e.preventDefault();
			break;
			case 39: // right
			this.bg.next();
			e.preventDefault();
			break;
		}
	},

	setCurrentPage: function(page) {
		this.currentPage = page;
	},

	setCurrentPageVar: function(v) {
		this.currentPageVar = v;
	},

	addData: function(item) {
		if (item.id) {
			Website.items.push(item);
			Website.objectIDs.push(item.id);
		}
	},

	bg: {
		container: null,
		itemsToLoad: null,
		firstImage: 0,
		autoLoadStatus: null,
		autoLoadInterval: null,
		init: function() {
			this.container = $("#background ul");
			if (this.container.length) {
				this.showThumbs();
				for (var i = 0; i < Website.items.length; i++) {
					var item = Website.items[i];
					var li = $("<li/>").attr("id", "background-"+item.id).data("id", item.id).data("src", item.background.src).data("ratio", item.background.ratio).addClass("not-loaded");
					if (i == 0) this.firstImage = item.id;
					this.container.append(li);
				}

				this.autoLoadStatus = "idle";
				this.autoLoadInterval = setInterval(function(){
					Website.bg.handleInterval();
				},20);
				$("#background").show();
				
			}
		},
		handleInterval: function() {
			if (this.autoLoadStatus == "idle") {
				this.loadImage();
			} else if (this.autoLoadStatus == "done") {
				clearInterval(this.autoLoadInterval);
			}
		},
		loadImage: function() {
			var li = $("#background ul li.not-loaded:first");
			if (li.length) {
				this.autoLoadStatus = "loading";
				var img = $("<img/>").attr("ratio", li.data("ratio"));
				img.bind("load", function(){

					var id = $(this).parent().data("id");
					$("#background-"+id).removeClass("not-loaded");
					Website.bg.enableThumb(id);
					if (Website.bg.firstImage == id) Website.bg.show(id);
					
					Website.bg.autoLoadStatus = "idle";

				}).bind("error", function(){
				
					alert("Image ("+$(this).parent().data("id")+") could not be loaded...");

				});
				var timestamp = new Date();
				timestamp = timestamp.getTime();
				img.attr("src", li.data("src")+"?="+timestamp);
				li.append(img);
			} else {
				Website.bg.autoLoadStatus = "done";
			}
		},
		enableThumb: function(id) {
			$("#thumb-"+id).removeClass("thumb-disabled");
			$("#thumb-"+id+" img").css("opacity", 1);
		},
		resize: function() {
			
		},
		next: function(id) {
			var position = Website.getCurrentPosition();
			if (position !== false) {
				if (position < Website.objectIDs.length - 1) {
					this.show(Website.objectIDs[position + 1]);
				}
			}
		},
		previous: function(id) {
			var position = Website.getCurrentPosition();
			if (position !== false) {
				if (position) {
					this.show(Website.objectIDs[position - 1]);
				}
			}
		},
		show: function(id) {
			var element = $("#background-"+id);
			if (element.length == 1) {

				if (!element.hasClass("not-loaded")) {
					
					$("#background li").hide().removeClass("current");
					$("#background-"+id).show().addClass("current");
					$("#thumbs li").removeClass("current");
					$("#thumb-"+id).addClass("current");
					
					Website.positionBackground();
					
					// show details
					var item = Website.getItem(id);

					if (item.project) {
						$("#note").show();
						$("#note p").html(item.note.text);
						$("#note h2").text(item.project.name);
						$("#note a.inverted-tag").text("naar project").attr("href", item.project.url);
						$("#note a.inverted-tag").css("visibility", item.project.linkVisible ? "visible" : "hidden");
					}

					$("#tags ul").empty();
					if (item.tags) {
						var tag;
						for (var i = 0; i < item.tags.length; i++) {
							tag = item.tags[i];
							var li = $("<li/>").html("<a href='"+tag.url+"#"+item.id+"'>"+tag.name+"</a>").attr("top", tag.top).attr("left", tag.left);
							$("#tags ul").append(li);
							if (Website.currentPage == "tag" && Website.currentPageVar == tag.id) {
								$(".tag-info p").text(tag.description);
							}
							Website.positionTag(li);
						}
					}
					$("#tags").show();

					Website.currentItem = item.id;

					// fix previous and next
					var position = Website.getCurrentPosition();
					if (position !== false) {
						if (position) {
							$("#previous").show();
						} else {
							$("#previous").hide();
						}
						if (position < Website.objectIDs.length - 1) {
							$("#next").show();
						} else {
							$("#next").hide();
						}
					}

					// hide items again when interface is closed
					if (!Website.interfaceVisible) {
						$("#note, #tags").hide();
					}
					
				}
				
			}
		},
		showThumbs: function() {
			if (Website.items.length) {
				var thumbs = $("#thumbs");
				var ul = $("<ul/>");
				var li, img, item, a, span;
				var totalWidth = 0;
				thumbs.append(ul);
				for (var i = 0; i < Website.items.length; i++) {
					item = Website.items[i];
					li = $("<li/>").attr("id", "thumb-"+item.id).addClass("thumb-disabled");
					a = $("<a/>").attr("href", "javascript:Website.bg.show("+item.id+");");
					img = $("<img/>").attr("src", item.background.thumb);
					span = $("<span/>").css("width", Math.ceil(item.background.ratio * 48));
					a.append(img).append(span);
					li.append(a);
					ul.append(li);
					totalWidth += Math.ceil(item.background.ratio * 48);
				}
				thumbs.css({
					"margin-left": -(totalWidth / 2),
					"width": totalWidth
				});
				$(".thumb-disabled img").css("opacity", .3);
			}
		}
	},

	positionBackground: function() {

		if (this.items.length) {
			var w = $(window);
			var windowWidth = w.width();
			var windowHeight = w.height();
			var windowRatio = windowWidth / windowHeight;
			var backgroundImage = $("#background .current img");
			var backgroundImageRatio = backgroundImage.attr("ratio");

			// backgroundImage
			if (windowRatio > backgroundImageRatio) {
				backgroundImage.css("width", windowWidth).css("height", (windowWidth / backgroundImageRatio));
				backgroundImage.css("margin-top", -((windowWidth / backgroundImageRatio) - windowHeight) / 2).css("margin-left", 0);
			} else {
				backgroundImage.css("height", windowHeight).css("width", (windowHeight * backgroundImageRatio));
				backgroundImage.css("margin-left", -((windowHeight * backgroundImageRatio) - windowWidth) / 2).css("margin-top", 0);
			}
		}
		
	},

	getCurrentPosition: function() {
		for (var i = 0; i < Website.objectIDs.length; i++) {
			if (Website.objectIDs[i] == Website.currentItem) {
				return i;
			}
		}
		return false;
	},

	getItem: function(id) {
		if (id == "first") {
			var item = Website.items[0];
			return item;
		} else {
			for (var i = 0; i < Website.items.length; i++) {
				if (Website.items[i].id == id) {
					return Website.items[i];
				}
			}
		}
		return false;
	},

	toggleInterface: function() {
		if (Website.interfaceVisible) {
			$("#filters, #pages, #tags li, #note, #information, #info, #info-close").fadeOut(250);
			$("#toggler a").attr("class", "maximize");
			$("#topbar").animate({
				width:150
			},250);
			Website.interfaceVisible = false;
		} else {
			$("#filters, #pages, #tags li, #note, #information, #info, #info-close").fadeIn(250);
			$("#toggler a").attr("class", "");
			$("#topbar").animate({
				width:$(window).width() - 80
			},250);
			Website.interfaceVisible = true;
		}
	},

	resize: function() {
	
		this.positionBackground();
		
		// interface
		if (Website.interfaceVisible) {
			$("#topbar").css("width", $(window).width() - 80);
		}
		
		// infoPage
		var info = $("#info");
		if (info.length) {
			var infoImageContainer = info.find(".image");
			var infoImage = infoImageContainer.find("img");
			var cw = infoImageContainer.width();
			var ch = infoImageContainer.height();
			var cr = cw / ch;
			var ir = infoImage.attr("ratio");
			if (cr > ir) {
				infoImage.css("width", cw).css("height", cw / ir);
				infoImage.css("margin-left", 0).css("margin-top", -((cw / ir) - ch) / 2);
			} else {
				infoImage.css("height", ch).css("width", ch * ir);
				infoImage.css("margin-top", 0).css("margin-left", -((ch * ir) - cw) / 2);
			}
		}
		
		// tags
		$("#tags li").each(function(){
			Website.positionTag($(this));
		});
		
	},
	
	showMap: function(id) {
		$(".maps .links li").each(function(){
			var element = $(this);
			if (element.attr("id") == "map-link-"+id) {
				element.addClass("current");
			} else {
				element.removeClass("current");
			}
		});
		$(".maps .images li").each(function(){
			var element = $(this);
			if (element.attr("id") == "map-image-"+id) {
				element.addClass("current");
			} else {
				element.removeClass("current");
			}
		});
	},
	
	toggleProjectInfo: function() {
		$("#info.project-info").toggle();
		$("#info-close").toggle();
	},
	
	positionTag: function(tag) {

		var w = $(window);
		var windowWidth = w.width();
		var windowHeight = w.height();
		var windowRatio = windowWidth / windowHeight;
		var backgroundImage = $("#background .current img");
		var backgroundImageRatio = backgroundImage.attr("ratio");

		var left = parseInt(tag.attr("left"), 10);
		var top = parseInt(tag.attr("top"), 10);
		
		var leftValue = Math.round(backgroundImage.width() * (left / 100));
		var topValue = Math.round(backgroundImage.height() * (top / 100));
		
		if (windowRatio > backgroundImageRatio) {
			tag.css("left", leftValue);
			tag.css("top", topValue - ((backgroundImage.height() - windowHeight) / 2));
		} else {
			tag.css("top", topValue);
			tag.css("left", leftValue - ((backgroundImage.width() - windowWidth) / 2));
		}
	},

	infoOpen: false,
	infoButtonOriginalWidth: false,
	toggleInfo: function() {
		if (this.infoOpen) {
			$(".tag-info > a").animate({
				opacity: 1
			}, 250);
			$(".tag-info div").slideUp(250, function(){
				$(this).parent().animate({
					width: Website.infoButtonOriginalWidth
				}, 250);
			});
			this.infoOpen = false;
		} else {
			if (!this.infoButtonOriginalWidth) {
				this.infoButtonOriginalWidth = $(".tag-info").width();
			}
			$(".tag-info > a").animate({
				opacity: 0
			}, 250);
			$(".tag-info").animate({
				width: 200
			}, 250, function() {
				$(this).find("div").slideDown(250);
			});
			this.infoOpen = true;
		}
	}
	
};
