function getInternetExplorerVersion() {
	var rv = -1; // Return value assumes failure.
	if (navigator.appName == 'Microsoft Internet Explorer') {
		var ua = navigator.userAgent;
		var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
			rv = parseFloat( RegExp.$1 );
	}
	return rv;
}

var browser_is_IE = getInternetExplorerVersion() > -1;

function preload(arg) {
	var preload1 = function(path) {
		var img = $("<img src='" + path + "' />")
			.hide()
			.load(function() {img.remove();});
		$("body").append(img);
		return img;
	}

	if (arg instanceof Array) {
		var i = 0;
		var next = function() {
			if (i < arg.length) {
				preload1(arg[i]).load(next);
				i++;
			}
		}
		next();
	} else {
		preload1(arg);
	}
}

function scripted_paging(context) {
	$("div.page", context)
		.parent()
		.each(function() {
				var pages = $("div.page", this);
				var first = pages
					.first()
					.addClass("active");
				pages
					.slice(1)
					.addClass("inactive")
					.css("height", first.height())
					.append("<a class='page_prev'>&lt; " + texts[lang]["page_prev"] + "</a>")
					.children("a.page_prev")
					.click(function() {
							var page = $(this)
								.parent()
								.removeClass("active")
								.addClass("inactive")
								.prev("div.page")
								.removeClass("inactive")
								.addClass("active")
							page
								.animate({marginLeft: -10, opacity: 0}, 0)
								.animate({marginLeft: 0, opacity: 1}, 500);
							if (browser_is_IE) { //IE fix
								$("*", page)
									.animate({opacity: 0}, 0)
									.animate({opacity: 1}, slide_duration);
							}
						});
				pages
					.slice(0, -1)
					.append("<a class='page_next'>" + texts[lang]["page_next"] + " &gt;</a>")
					.children("a.page_next")
					.click(function() {
							var page = $(this)
								.parent()
								.removeClass("active")
								.addClass("inactive")
								.next("div.page")
								.removeClass("inactive")
								.addClass("active")
							page
								.animate({marginLeft: 10, opacity: 0}, 0)
								.animate({marginLeft: 0, opacity: 1}, 500);
							if (browser_is_IE) { //IE fix
								$("*", page)
									.animate({opacity: 0}, 0)
									.animate({opacity: 1}, slide_duration);
							}
						});
						
				$(this).css("overflow", "visible");
			});
}

function transform_imagepath(path, type) {
	var prefix = "";
	switch (type) {
	case 0: prefix = "t_"; break;
	case 1: prefix = "s_"; break;
	}
	path = path.split("/");
	path[path.length - 1] = prefix + path[path.length - 1];
	return path.join("/");
}

function Photo(container, path) {
	var center = function() {
		wrapper
			.css("top", (container.height() - wrapper.height()) / 2)
			.css("left", (container.width() - wrapper.width()) / 2);
	}
	var updateDimensions = function() {
		if (natWidth / natHeight >= container.width() / container.height()) {
			var x = Math.min(natWidth, container.width());
			image
				.css("width", x)
				.css("height", (x / natWidth) * natHeight);
		} else {
			var x = Math.min(natHeight, container.height());
			image
				.css("width", (x / natHeight) * natWidth)
				.css("height", x);
		}
		wrapper.css("width", image.width());
		wrapper.css("height", image.height());
		center();
	}
	
	var wrapper = $("<div>")
		.addClass("photo_wrapper")
		.hide()
		.data("logic", this);
	container.append(wrapper);
	
	center();
	$(window).bind("resize", center);
	
	var natWidth = 1;
	var natHeight = 1;
	var image = $("<img>")
		.hide()
		.attr("src", path);
	wrapper.append(image);

	var t = setInterval(function() {
			if (image.width() > 100 && image.height() > 100) {
				natWidth = image.width();
				natHeight = image.height();
				clearInterval(t);
				updateDimensions();
				$(window)
					.unbind("resize", center)
					.bind("resize", updateDimensions);
				image.show();
			}
		}, 10);
		
	this.get_wrapper = function() {
		return wrapper;
	}
	
	this.get_image = function() {
		return image;
	}
	
	this.destroy = function() {
		clearInterval(t);
		$(window)
			.unbind("resize", center)
			.unbind("resize", updateDimensions);
		wrapper.remove();
	}
}

function PhotoViewer(arg1, arg2) {
	var viewer = $("\
		<div id='photo_viewer'>\
			<span class='background click_area'></span>\
			<div class='boundaries'></div>\
		</div>");
	$("body").append(viewer);
	
	var arrowKeyHandlerRef = null;
	
	var close = function() {
		$("*", viewer).unbind("click");
		$(document).unbind('keydown', escKeyHandler);
		if (arrowKeyHandlerRef != null) {
			$(document).unbind('keydown', arrowKeyHandlerRef);
		}
		
		if ($("div.photo_wrapper", viewer).length == 0) {
			viewer.remove();
		} else {
			$("div.photo_wrapper", viewer)
				.stop(true, false)
				.fadeOut(500, function() {
						$(this).data("logic").destroy();
						$(this).remove();
						if ($("div.photo_wrapper", viewer).length == 0) {
							viewer.remove();
						}
					});
			if (browser_is_IE) { //IE fix
				$("div.photo_wrapper>div.caption, div.photo_wrapper>div.page_no", viewer)
					.fadeOut(500);
			}
		}
	}
	
	var escKeyHandler = function(e) {
		if (e.keyCode == 27) {
			close();
		}
	}
	
	var control_close = $("<a class='close'></a>")
		.bind("click", close);
	viewer.append(control_close);
	$("#photo_viewer>span.click_area, #photo_viewer>div.boundaries>span.click_area")
		.bind("click", close);
	$(document).bind("keydown", escKeyHandler);

	if (arg1 instanceof Array && arg1.length > 1) {
	
		var inc = function(ix) {
			return (ix + 1) % arg1.length;
		}
		var dec = function(ix) {
			return (ix - 1 < 0) ? (arg1.length - 1) : (ix - 1);
		}
	
		var next = function() {
			index = inc(index);
			var temp = index;
			$("div.photo_wrapper", viewer).data("logic").destroy();
			create_photo("slideLeft").load(function() {
					preload(arg1[inc(temp)].path);
				});
		}
		
		var prev = function() {
			index = dec(index);
			var temp = index;
			$("div.photo_wrapper", viewer).data("logic").destroy();
			create_photo("slideRight").load(function() {
					preload(arg1[dec(temp)].path);
				});
		}
		
		var create_photo = function(effect) {
			var new_photo = new Photo($("div.boundaries", viewer), arg1[index].path);
		
			new_photo.get_wrapper()
				.append("\
					<span class='click_area'></span>"
					+ ((typeof arg1[index].caption != "undefined") ? ("<div class='caption'>" + arg1[index].caption[lang] + "</div>") : "") +
					"<div class='page_no'>" + (index + 1) + "/" + arg1.length + "</div>\
					");
			new_photo.get_wrapper()
				.bind("click", next);
			
			if (effect == "fadeIn") {
				new_photo.get_wrapper()
					.fadeIn(500);
			} else if (effect == "slideLeft") {
				new_photo.get_wrapper()
					.animate({marginLeft: "10"}, 0)
					.animate({marginLeft: "0", opacity: "show"}, 500);
			} else if (effect == "slideRight") {
				new_photo.get_wrapper()
					.animate({marginLeft: "-10"}, 0)
					.animate({marginLeft: "0", opacity: "show"}, 500);
			}
			if (browser_is_IE) { //IE fix
				$("div.caption, div.page_no", new_photo.get_wrapper())
					.hide()
					.fadeIn(500);
			}
			
			return new_photo.get_image();
		}
		
		var arrowKeyHandler = function(e) {
			switch(e.keyCode) {
			case 37:
				prev();
				break;
			case 39:
				next();
			}
		}
		
		arrowKeyHandlerRef = arrowKeyHandler;
		$(document).bind("keydown", arrowKeyHandler);
		
		var control_next = $("<a class='next'></a>")
			.bind("click", next);
		var control_prev = $("<a class='prev'></a>")
			.bind("click", prev);
		viewer.append(control_next, control_prev);
		
		var index = arg2;
		var temp = index;
		
		create_photo("fadeIn").load(function() {
				preload(arg1[inc(temp)].path);
				preload(arg1[dec(temp)].path);
			});
		
	} else {
		var img_data = (arg1 instanceof Array) ? arg1[0] : arg1;
	
		var new_photo = new Photo($("div.boundaries", viewer), img_data.path);
	
		new_photo.get_wrapper()
			.append(((typeof img_data.caption != "undefined") ? ("<div class='caption'>" + img_data.caption[lang] + "</div>") : ""));
		
		new_photo.get_wrapper()
			.fadeIn(500);
		if (browser_is_IE) { //IE fix
			$("div.caption, div.page_no", new_photo.get_wrapper())
				.hide()
				.fadeIn(500);
		}
	}
}

function Slideshow(element, data, period) {
	var slideshow_id = 0;
	var slideshow_i = 0;
	
	var slide = function(transition) {
		var i = slideshow_i;
		
		var prev_slide = $("div.slide.cur", element).removeClass("cur");
		var new_slide = $("<div class='slide cur'></div>");
		
		var img = $("<img style='visibility: hidden; position: absolute' src='" + transform_imagepath(data[i].path, 1) + "' />")
			.load(function() {
					$(this)
						.css("top", ($(this).parent().height() - $(this).height()) / 2)
						.css("left", ($(this).parent().width() - $(this).width()) / 2)
						.css("visibility", "visible");
					
					if (transition) {
						prev_slide.children("img").fadeOut(1000, function() {
								$(this).remove();
							});
					} else {
						prev_slide.remove();
						img.show();
					}
					
					preload(transform_imagepath(data[(i + 1) % data.length].path, 1));
				});
		new_slide.append(img);
		element.prepend(new_slide);
	}
	
	var next = function() {
		slideshow_i = (slideshow_i + 1) % data.length;
		slide(true);
	}
	
	var prev = function() {
		slideshow_i = (slideshow_i == 0) ? (data.length - 1) : (slideshow_i - 1);
		slide(true);
	}
	
	this.reset = function() {
		this.stop();
		slideshow_i = 0;
		slide(false);
	}
	
	this.next = function() {
		this.stop();
		next();
	}
	
	this.prev = function() {
		this.stop();
		prev();
	}
	
	this.autoplay = function() {
		var playnext = function(id) {
			setTimeout(function() {
						if (slideshow_id == id) {
							next();
							playnext(id);
						}
					}, period);
		}
		
		slideshow_id++;
		playnext(slideshow_id);
	}
	
	this.stop = function() {
		slideshow_id++;
	}
	
	var caption = $("\
			<div class='caption'>\
				<span class='background'></span>\
				<span class='text'>" + element.attr("title") + "</span>\
			</div>");
	
	element
		.removeAttr("title")
		.append(caption);
	
	caption
		.css("left", (caption.parent().width() - caption.outerWidth()) / 2)
		.css("top", (caption.parent().height() - caption.outerHeight()) / 2);
		
	element.click(function() {
			new PhotoViewer(data[slideshow_i]);
		});
	
	
	this.reset();
	this.autoplay();
}

var Portfolio = {
	activate : function(item) {
		$("#portfolio_project .title").html(item.title);
		$("#portfolio_project p").html(item.details[lang]);

		var perc = 100 / item.images.length;
		
		for (var i = 0; i < item.images.length; i++) {
			var thumb = $("\
				<div class='thumb_wrapper loading' style='width: " + perc + "%'>\
					<a></a>\
				</div>");
			$("a", thumb)
				.data("index", i)
				.click(function() {
						new PhotoViewer(item.images, $(this).data("index"));
						return false;
					});

			var img = $("<img>")
				.css("position", "absolute")
				.hide()
				.load(function() {
						$(this)
							.css("top", ($(this).parent().height() - $(this).height()) / 2)
							.css("left", ($(this).parent().width() - $(this).width()) / 2)
							.show();
						$(this)
							.parent()
							.removeClass("loading");
					})
				.attr("src", transform_imagepath(item.images[i].path, 0));
			$("a", thumb)
				.append(img)
				.append("<span class='active'></span>");
			$("#portfolio_images").append(thumb);
		}
		
		$("#slideshow").data("logic").stop();
		$("#portfolio_listing, #slideshow").hide();
		$("#portfolio_project").show();
		
		$("#portfolio_project p").css("height", $("#portfolio_project .back").offset().top - $("#portfolio_project p").offset().top);
		
		$("#portfolio div.content>*")
			.animate({marginTop: slide_distance, opacity: 0}, 0)
			.animate({marginTop: 0, opacity: 1}, slide_duration);
		if (browser_is_IE) { //IE fix
			$("#portfolio_project *, #portfolio_images>div.thumb_wrapper, #portfolio_images>div.thumb_wrapper *")
				.animate({opacity: 0}, 0)
				.animate({opacity: 1}, slide_duration);
		}
	},
	
	reset : function() {
		$("#slideshow").data("logic").reset();
		$("#slideshow").data("logic").autoplay();
		$("#portfolio_images>div.thumb_wrapper").remove();
		$("#portfolio_project").hide();
		$("#portfolio_listing, #slideshow").show();
		$("#portfolio div.content>*")
			.animate({marginTop: -slide_distance, opacity: 0}, 0)
			.animate({marginTop: 0, opacity: 1}, slide_duration);
		if (browser_is_IE) { //IE fix
			$("#portfolio_listing h3, #portfolio_listing table, #slideshow *")
				.animate({opacity: 0}, 0)
				.animate({opacity: 1}, slide_duration);
		}
	},
	
	init : function() {		
		$("body").append(
			$("\
				<div id='portfolio_title'>\
					<img />\
					<span></span>\
				</div>").hide());
		
		var x_size = 2;
		var y_size = 4;
		
		var pages = new Array;
		var page = null;
		var row = null;
		var index = 0; //to make the order vertical, not horizontal

		for (var i = 0; index != portfolio_data.length - 1; i++) {
			if ((i % (x_size * y_size)) == 0) {
				page = $("\
					<div class='page'>\
						<table></table>\
					</div>")
					.data("index", pages.length);
				$("#portfolio_listing").append(page);
				pages.push(page);
				index = i;
			} else if (i % x_size == 0) {
				index = index - y_size + x_size - 1;
			} else {
				index = index + y_size;
			}
			
			if (i % x_size == 0) {
				row = $("<tr>");
				$("table", page).append(row);
			}

			var item = null;
			if (index < portfolio_data.length) {
				item = $("\
						<td class='item'>\
							<span class='year'>" + portfolio_data[index].year + "</span>\
							<a class='title'>" + portfolio_data[index].title + "</a>\
						</td>\
					");
				$("a", item)
					.data("data", portfolio_data[index])
					.click(function() {
							Portfolio.activate($(this).data("data"));
						})
					.hover(function() {
							$("#portfolio_title")
								.stop(true, false)
								.hide();
							$("#portfolio_title>img").attr("src", $(this).data("data").thumb);
							$("#portfolio_title>span").html($(this).data("data").description[lang]);
							$("#portfolio_title")
								.css("top", $(this).offset().top - (($("#portfolio_title").outerHeight() - $(this).height()) / 2))
								.css("left", $(this).offset().left + $(this).outerWidth() + 5)
								.fadeTo(0, 0)
								.animate({left: "+=5", opacity: 1}, 200);
						}, function() {
							$("#portfolio_title")
								.stop(true, false)
								.animate({left: "+=5", opacity: "hide"}, 200);
						});
			} else {
				item = $("<td class='item'></td>");
			}
			row.append(item);
		}
		
		scripted_paging("#portfolio_listing");
		
		$("#slideshow").data("logic", new Slideshow($("#slideshow"), slideshow_data, slideshow_period));
		
		{ //preload individual project thumbnails
			var strip = new Array();
			for (var i = 0; i < portfolio_data.length; i++) {
				strip.push(portfolio_data[i].thumb);
			}
			preload(strip);
		}
	}
}

var current_section = null;

$(document).ready(function() {
		$("body").css("overflow", "hidden");

		scripted_paging("body");
		
		current_section = $("#home");
		$(window).resize(function() {
				if (current_section != null)
					$.scrollTo({top: 0, left: current_section.offset().left}, {duration: 0});
			});
			
		{ //initialize decoration
			$("body").prepend("\
					<span id='decor_wall1'></span>\
					<span id='decor_wall2'></span>\
					<span id='decor_tag'></span>\
					<span id='decor_tagline1'></span>\
					<span id='decor_tagline2'></span>\
					<span id='decor_tagline3'></span>\
				");
			$(window).resize(function() {
					var h = $("#mainline").height();
					$("#decor_wall1")
						.css("left", $("#portfolio>div.position").offset().left + 100)
						.width(h / 3 * 2)
						.height($("#mainline").offset().top);
					$("#decor_wall2")
						.width(h / 3 * 2)
						.css("left", $("#contact>div.position").offset().left + $("#contact>div.position").width() - $("#decor_wall2").width() - 60)
						.height($("#decor_wall1").height());
					var bottom = $("#mainline").offset().top + $("#mainline").height();
					var left = $("#decor_wall1").offset().left + $("#decor_wall1").width();
					var right = $("#decor_wall2").offset().left;
					$("#decor_tag")
						.html(Math.round((right - left) / 10) * 10)
						.css("left", left + (right - left) / 2 - $("#decor_tag").width() / 2)
						.css("top", bottom + 100);
					var top = bottom + 50;
					var inner_bottom = $("#decor_tag").offset().top + $("#decor_tag").height();
					bottom = inner_bottom + $("#decor_tagline3").height();
					$("#decor_tagline1")
						.css("left", left - $("#decor_tagline1").width())
						.css("top", top)
						.css("height", bottom - top + 80);
					$("#decor_tagline2")
						.css("left", right)
						.css("top", top)
						.css("height", bottom - top + 80);
					$("#decor_tagline3")
						.css("top", inner_bottom)
						.width($("#mainline").width());
				});
		}
		$(window).resize();
		
		{ //scripted navigation
			$("div.nav a").each(function() { //animated scroll
				$(this)
					.data("link", $(this).attr("href"))
					.removeAttr("href")
					.click(function() {
							$.scrollTo({top: 0, left: $($(this).data("link")).offset().left}, {
									duration: 500,
									easing: "swing"
								});
						});
				});
			
			//scripted title tag
			$("body").append($("<div>")
				.attr("id", "nav_title")
				.fadeTo(0, 0));
			$("div.nav>ol>li>a").each(function() {
					$(this)
						.data("title", $(this).attr("title"))
						.attr("title", "")
						.hover(function() {
								$("#nav_title")
									.hide()
									.html($(this).data("title"))
									.css("top", $(this).offset().top - $("#nav_title").outerHeight())
									.css("left", $(this).offset().left + ($(this).width() - $("#nav_title").outerWidth()) / 2)
									.stop(true, false)
									.fadeTo(0, 0)
									.animate({top: "-=5", opacity: 1}, 200);
							}, function() {
								$("#nav_title")
									.stop(true, false)
									.animate({top: "-=5", opacity: "hide"}, 200);
							});
				});
		}
		
		
		Portfolio.init();
			
		$("#portfolio div.content>div.right").height($("#portfolio div.content>div.right").height());
		$("#portfolio div.content>div.left").height($("#portfolio div.content>div.right").height());
		$("#contact div.content>div.right").height($("#contact div.content>div.right").height());
		$("#contact div.content>div.left").height($("#contact div.content>div.right").height());
		
		$("#mainline")
			.removeClass("padding")
			.css("height", $("#mainline").height());
		$("div.section>div.position").each(function() {
				var nav_h = $(this).children("div.nav").outerHeight();
				if ($(this).parent().attr("id") == "home") nav_h = nav_h / 3; 
				$(this)
					.children("div.content")
					.css("padding-top", ($(this).outerHeight() - nav_h - $(this).children("div.content").outerHeight()) / 2);
			});
		$("#slideshow").css("top", ($("#slideshow").parent().height() - $("#slideshow").outerHeight()) / 2);
		$("#map").css("top", ($("#map").parent().height() - $("#map").outerHeight()) / 2);
		
		$("#portfolio_project .back, #portfolio_project h4>a").click(function() {Portfolio.reset();});
		
		
		
		
		var caption = $("\
				<div class='caption'>\
					<span class='background'></span>\
					<span class='text'>" + $("#map").attr("title") + "</span>\
				</div>");
		$("#map")
			.removeAttr("title")
			.append(caption);
		caption
			.css("left", (caption.parent().width() - caption.outerWidth()) / 2)
			.css("top", (caption.parent().height() - caption.outerHeight()) / 2);
			
		$("#mainline>div.section").data("visible", false);
		$(window).scroll(function() {
				var sections = $("#mainline>div.section");
				var center = $(window).scrollLeft() + $(window).width() / 2;
				var min = sections.eq(0);
				var min_d = Math.abs(min.offset().left + min.outerWidth() / 2 - center);
				for (var i = 1; i < sections.length; i++) {
					var cur = sections.eq(i);
					var d = Math.abs(cur.offset().left + cur.outerWidth() / 2 - center);
					if (d < min_d) {
						min = cur;
						min_d = d;
					}
				}
				current_section = min;
		
				sections.each(function() {
						var elem = $(this).children("div.position");
						if (elem.offset().left < $(window).scrollLeft() + $(window).width() && elem.offset().left + elem.outerWidth() > $(window).scrollLeft()) {
							if (! $(this).data("visible")) {
								$(this).data("visible", true);
							}
						} else {
							if ($(this).data("visible")) {
								$(this).data("visible", false);
								
								$("div.page", this)
									.parent()
									.each(function() {
											var pages = $("div.page", this);
											var first = pages
												.first()
												.removeClass("inactive")
												.addClass("active");
											pages
												.slice(1)
												.removeClass("active")
												.addClass("inactive");
										});
								
								if ($(this).attr("id") == "portfolio") {
									Portfolio.reset();
								}
							}
						}
					});
			});
	});
