var pages = {"": 0, "home": 0, "about": 1, "products":2, "ingredients":3, "journal":4, "contact":5};

var emailReg = /[a-z0-9\!\#\$\%\&\'\*\+\/=\?\^\_`\{\|\}\~\-]+(?:\.[a-z0-9\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;

var ingredients = {
	larginine: null,
	cedarwood: null,
	vitamin_e_acetate: ["moisturiser", "shampoo"],
	organic_borage_oil: ["moisturiser"],
	armoise: null,
	shea_butter: ["moisturiser", "shampoo"],
	willow_bark_extract: null,
	eucalyptus: null,
	uv_absorbers: ["moisturiser"],
	caffeine: ["moisturiser", "shampoo"],
	spinach_extract: ["facewash"],
	black_pepper: null,
	green_tea_extract: ["facewash"],
	aloe_vera: null,
	sunflower: ["moisturiser"],
	tinosan_sdc: ["deodorant"],
	tea_tree: ["showergel"],
	guaiacwood: null,
	juniper: null,
	panthenol: ["shampoo"],
	rosemary: null,
	pineneedle: null,
	lime: null,
	marjoram: null,
	lavandin: null,
	thyme: null
};

var $loader = $('<div id="loader" class="active"></div>'), $contentBg, $contentBgImg;
/*var $loading = $('<div id="loader_emblem"></div>');
$loader.append($loading);
*/

$.fn.reverse = Array.prototype.reverse;

//methods

function bringToFront($dialog) {
	var maxZ = 0;
			
	$(".dialog:visible").not($dialog).each(function() {
		maxZ = Math.max(maxZ, $(this).css("z-index"));
	});
	
	$dialog.css({zIndex: (maxZ+1)});
}

function showDialog($dialogs, x, y, ignoreZ) {
	//get all current position for all currently visible dialogs
	var positions = {}, maxZ = 0;

	$(".dialog:visible").each(function() {
		maxZ = Math.max(maxZ, $(this).css("z-index"));

		var pos = $(this).position();
		positions[JSON.stringify({left: pos.left, top: pos.top })] = null;
	});
	
	$dialogs.each(function() {
		var $dialog = $(this);
		
		if ($dialog.is(":visible")) {
			//bring the dialog to the front
			bringToFront($dialog);
			return false;
		}
		
		$dialog.css({display: "block", visibility: "hidden"});
		
		//keep stepping the x and y position until we no longer have a clash
		if (typeof x == "number" && typeof y == "number") {
			var newX = x, newY = y;
		} else {
			var newX = $dialog.position().left;
			var newY = $dialog.position().top;
		}

		while (positions.hasOwnProperty(JSON.stringify({left: newX, top: newY}))) {
			newX += 15;
			newY += 15;
		}
		
		if (!ignoreZ) {
			$dialog.css({ zIndex: maxZ+1 });
		}
		
		//set the z-index of this window to once 
		$dialog.css({
			display: "none",
			visibility: "visible",
			left: newX,
			top: newY
		}).fadeIn("fast");
	});
}

function chopFileExt(str, func) {
	var matches = str.match(/(.*).(gif|png|jpg)$/);
	
	if (matches.length>2) {
		func(matches[1], matches[2]);
	}
}

function getPageName(url) {
	if (typeof url !== "string") {
		url = window.location.pathname;
	}
	
	var bits = url.match(/\/?([^\/]*)\.([^\/\.]+)$/);
	
	if (bits!==null && bits.length>2) {
		return bits[1];
	} else {
		return "";
	}
}

function initDialog($dialogs) {
	$dialogs.each(function() {
		var $dialog = $(this);
		var mouseInit = null;
		
		$(this).data({origZ: $(this).css("z-index")});
		
		$(this).bind("mousedown", function(e) {
			//bring this dialog to the front
			bringToFront($(this));
			mouseInit = { left: e.pageX, top: e.pageY };
			
			return false;
		});
		
		$(this).find(".dialog_controls, .dialog_content").mousedown(function(e) {
			e.stopPropagation();
			//return false;
		});
		
		if (this.addEventListener) {
			$(this).find(".dialog_controls, .dialog_content").each(function() {
				this.addEventListener("touchstart", function(e) {
					return false;
				}, false);
			});
		
			this.addEventListener("touchstart", function(e) {
				if (e.touches.length==1) {
					var touch = e.touches[0];
			
					if (touch) {
						bringToFront($(this));
						mouseInit = { left: touch.pageX, top: touch.pageY };
					}
				}
			}, false);
		
			this.addEventListener("touchmove", function(e) {
				if (e.touches.length==1) {
					e.preventDefault();
				
					var touch = e.touches[0];
			
					if (touch) {
						moveDialog(touch.pageX, touch.pageY);
					}
			
					return false;
				}
			}, false);
		
			this.addEventListener("touchend", function(e) {
				stopDrag();
			}, false);
		
			this.addEventListener("touchcancel", function(e) {
				stopDrag();
			}, false);
		}
		
		function stopDrag() {
			mouseInit = null;
		}
		
		function moveDialog(mouseX, mouseY) {
			if (mouseInit!==null) {
				//determine the new position
				var newLeft = $dialog.position().left + mouseX - mouseInit.left;
				var newTop = $dialog.position().top + mouseY - mouseInit.top;
				
				//contain dialog boxes to their parents
				newLeft = Math.max(0, Math.min(newLeft, $dialog.parent().innerWidth()-$dialog.outerWidth()));
				newTop = Math.max(0, Math.min(newTop, $dialog.parent().innerHeight()-$dialog.outerHeight()));
				
				$dialog.css({ left: newLeft, top: newTop });
				mouseInit = { left: mouseX, top: mouseY };
			}
		}
		
		$("body").bind("mouseup", function(e) {
			stopDrag();
		}).bind("mousemove", function(e) {
			moveDialog(e.pageX, e.pageY);
		});
		
		$dialog.find(".control_minimize").click(function() {
			$dialog.toggleClass("minimize");
			$dialog.find('.dialog_title').fadeToggle();
			
			if ($dialog.hasClass("minimize")) {
				$dialog.data("origHeight", $dialog.height());
				$dialog.animate({height: $dialog.find(".dialog_controls").height() + 3});
			} else {
				$dialog.animate({height: $dialog.data("origHeight")});
			}
		});
		
		$dialog.find(".control_close").click(function() {
			$dialog.fadeOut("fast");
		});
	});
}

function makeScrollBars($div) {
	if (navigator.userAgent.match(/(iPad|iPhone)/i) == null) {
		$div.each(function() {
			var $scrollArea = $(this);
			$scrollArea.addClass("custom_scroller");
		
			//wrap the element
			var $scrollWrap = $('<div class="custom_scroll_wrap"></div>');
			$scrollWrap.attr("tabIndex", "0");
			$scrollArea.wrap($scrollWrap);
		
			//insert the simple scroller
			var $scrollBar = $('<div class="custom_scroll_bar"><div class="scroll_bar_top"></div><div class="scroll_bar_bottom"></div></div>');
			$scrollArea.after($scrollBar);
			
			//game starto
			var scrollHeight, scrollAreaHeight;
			
			prepareScroll();
			
			//allow the bar to be dragged
			var barScroll;
			$scrollBar.mousedown(function(e) {
				barScroll = {top: e.clientY };
				
				return false;
			});
		
			$("body").mousemove(function(e) {
				if (barScroll) {
					//move the scrollbar vertically (limit the size)
					var newTop = $scrollBar.position().top + (e.clientY - barScroll.top);
					
					newTop = Math.max(Math.min(newTop, scrollAreaHeight-$scrollBar.height()), 0);
					$scrollBar.css({top: newTop});
					scrollContent();
					
					barScroll = {top: e.clientY};
				}
			}).mouseup(function(e) {
				barScroll = null;
			});
		
			//allow the mouse wheel to scroll though
			$scrollArea.mousewheel(function(e, delta, deltaX, deltaY) {
				var dir = deltaY>0 ? 1: -1;
				
				$scrollArea.scrollTop($scrollArea.scrollTop()-30*dir);
				positionBar();
				
				return false;
			});
			
			$scrollArea.data({
				prepareScroll: prepareScroll,
				scrollContent: scrollContent,
				determineScrollHeight: determineScrollHeight,
				sizeBar: sizeBar,
				positionBar: positionBar
			});
			
			function prepareScroll() {
				determineScrollAreaHeight();
				determineScrollHeight();
				sizeBar();
				positionBar();
			}
			
			function scrollContent() {
				//use the position of the scrollbar as a guide to scroll the content
				var newScrollTop = $scrollBar.position().top / (scrollAreaHeight - $scrollBar.height()) * (scrollHeight - scrollAreaHeight);
				
				$scrollArea.scrollTop(newScrollTop);
			}
		
			function determineScrollHeight() {
				//scrollHeight = $scrollArea.children().last;
				//we should not rely on the dom position to determine contents size
				//we could wrap another element around the content except we will have bug issues
				//so we will set the scrolltop, then read it of
				/*var oldScrollTop = $scrollArea.scrollTop();
			
				$scrollArea.scrollTop(9999999999);
				var maxScroll = $scrollArea.scrollTop();
				$scrollArea.scrollTop(oldScrollTop);
				
				scrollHeight = maxScroll + scrollAreaHeight;
				*/
				scrollHeight = 0;
				$scrollArea.children().each(function() {
					var marginTop = parseInt($(this).css("margin-top"));
					var marginBottom = parseInt($(this).css("margin-bottom"));
					
					if (isNaN(marginTop)) marginTop = 0;
					if (isNaN(marginBottom)) marginBottom = 0;
					
					scrollHeight = Math.max($(this).position().top + $(this).height() + marginTop + marginBottom, scrollHeight);
				});
			}
		
			function determineScrollAreaHeight() {
				scrollAreaHeight = parseInt($scrollArea.height());
			}
		
			function sizeBar() {
				$scrollBar.css({height: (scrollAreaHeight / scrollHeight) * scrollAreaHeight });
			}
		
			function positionBar() {
				/*if($('body').attr('id') == 'page_about') {
					$scrollBar.css('top', 'auto');
					var value = $scrollArea.scrollTop() * (scrollHeight + scrollAreaHeight) / (scrollAreaHeight + $scrollBar.height());
					if(value == 0 || value < 65)
						value = '65px';
						
					$scrollBar.css({top: value});
				} else {*/
				
				$scrollBar.css({top: $scrollArea.scrollTop() / (scrollHeight - scrollAreaHeight) * (scrollAreaHeight - $scrollBar.height()) });
				//}
			}
		});
	}
}

//pages
function preparePage() {
	$contentBg = $("#content_bg");
	$contentBgImg = $contentBg.find("img");
	
	resizeBackground();
	
	//load the negative background when the page has loaded
	if ($("body").attr("id")=="page_home" || $("body").attr("id")=="page_contact") {
		chopFileExt($contentBgImg.attr("src"), function(name, ext) {
			//only for home and contact page
			var invBg = new Image();
			invBg.alt = "";
			invBg.src = name + "_inv." + ext;
			
			invBg.onload = function() {
				resizeBackground();
			};
			
			$contentBg.prepend(invBg);
		});
	}
	
	//prevent image dragging in firefox
	$("img").mousedown(function(e) {
		e.preventDefault();
	});
	
	//prevent selection on ie
	/*$("body").mousedown(function(e) {
		return false;
	});*/
	
	//fix ie link unfocus
	$("a").mouseup(function(e) {
		$(this).blur();
	});
	
	//custom scrollers (non-mobile devices only)
	makeScrollBars($(".custom_scroller"));
	
	//based on the current page, load the relevant function
	var currPageName = $("body").attr("id").substring(5);
	
	switch(currPageName) {
		case "": case "home":
			break;
		case "about":
			prepareAbout();
			break;
		case "products":
			prepareProducts();
			break;
		case "ingredients":
			prepareIngredients();
			break;
		case "journal":
			prepareJournal();
			break;
		case "contact":
			prepareContact();
			break;
	}
}

function prepareAbout() {
	$("#content_text").click(function() {
		var $aboutDialog = $(".about_dialog");
		
		var startX = ($("#content").width()-$aboutDialog.width()) /2.0;
		var startY = ($("#content").height()-$aboutDialog.height()) /2.0;
		
		showDialog($aboutDialog, startX, startY);
		$aboutDialog.find(".dialog_content").data("prepareScroll")();
	});
}

function prepareProducts() {
	//grab the positions of all of the thumbs and make them absolute for the animation (smoother transitions)
	var $thumbs = $(".product_thumb");
	$thumbs.reverse().each(function() {
		$(this).css({
			position: "absolute",
			display: "block",
			left: $(this).position().left,
			bottom: 0
		});
	});
	
	//products tabs
	$thumbs.click(function() {
		//animate to line the selected thumbnail
		$thumbs = $(".product_thumb");
		var i = $(this).index(".product_thumb");
		
		if (i<2) {
			//animate left and fade some elements
			var diff = 2-i, $lastThumbs = $("");
			for (j=(i+3); j<5; j++) {
				$lastThumbs = $lastThumbs.add($(".product_thumb:eq(" + (j) + ")"));
			}
			
			var $remainingThumbs = $thumbs.not($lastThumbs);
			
			$lastThumbs.reverse().each(function(k) {
				$(this).parent().prepend($(this));
				$(this).fadeOut(250, function() {
					$(this).css({left: (diff-k-1)*150}).fadeIn(250);
				});
			});
			
			showProductInfo($(".product_thumb:eq(2)").attr("id"));
			
			$remainingThumbs.animate({
				left: "+=" + (150*diff) + "px"
			}, 500);
		} else if (i>2) {
			//animate right and fade some elements
			var diff=i-2, $lastThumbs = $("");
			for (j=0; j<diff; j++) {
				$lastThumbs = $lastThumbs.add($(".product_thumb:eq(" + (j) + ")"));
			}
			
			var $remainingThumbs = $thumbs.not($lastThumbs);
			
			$lastThumbs.each(function(k) {
				$(this).parent().append($(this));
				$(this).fadeOut(250, function() {
					$(this).css({left: 600 - (diff-k-1)*150}).fadeIn(250);
				});
			});
			
			showProductInfo($(".product_thumb:eq(2)").attr("id"));
			
			$remainingThumbs.animate({
				left: "-=" + (150*diff) + "px"
			}, 500);
		}
	});
	
	function showProductInfo(id) {
		var $currInfo = $(".product_info:visible");
		var $newInfo = $("#" + id + "_info");
		
		if (!$currInfo.is($newInfo)) {
			$currInfo.fadeOut("fast", function() {
				$newInfo.fadeIn("fast");
				$newInfo.find(".custom_scroller").each(function() {
					if (typeof $(this).data("prepareScroll") == "function") {
						$(this).scrollTop(0);
						$(this).data("prepareScroll")();
					}
				});
			});
		}
	}
	
	var animating = false;
	
	//allow the left and right arrows to scroll through the products
	$("#move_product_left").click(function() {
		if (animating) {
			return false;
		}
		
		animating = true;
		
		//slide the last four products to the left
		$thumbs = $(".product_thumb");
		var $firstThumb = $thumbs.first();
		var $remainingThumbs = $thumbs.not($firstThumb);
		
		//fade the first product out and send it to the back
		$firstThumb.parent().append($firstThumb);
		$firstThumb.fadeOut(250, function() {
			$(this).css({left: 600}).fadeIn(250);
		});
		
		showProductInfo($(".product_thumb:eq(2)").attr("id"));
		
		$remainingThumbs.animate({
			left: "-=150px"
		}, 500);
		
		window.setTimeout(function() {
			animating = false;
		}, 1000);
	});
	
	$("#move_product_right").click(function() {
		if (animating) {
			return false;
		}
		
		animating = true;
		
		//slide the last four products to the left
		$thumbs = $(".product_thumb");
		var $lastThumb = $thumbs.last();
		var $remainingThumbs = $thumbs.not($lastThumb);
		
		//fade the first product out and send it to the back
		$lastThumb.parent().prepend($lastThumb);
		$lastThumb.fadeOut(250, function() {
			$(this).css({left: 0}).fadeIn(250);
		});
		
		showProductInfo($(".product_thumb:eq(2)").attr("id"));
		
		$remainingThumbs.animate({
			left: "+=150px"
		});
		
		window.setTimeout(function() {
			animating = false;
		}, 1000);
	});
}

function prepareJournal() {
	var selectedIndex = 0;
	
	//journal image box
	$("#close_info_box").click(function() {
		$("#image_info_box").fadeOut("fast");
	});
	
	$("#overlay, #close_overlay").click(function() {
		$("#overlay").fadeOut("fast");
	});
	
	//when a thumbnail is clicked, load the large version of the image in a new box
	$(".image_info .image_image").click(function() {
		//based on the index of this image, decide whether or not to display a left and right button
		selectedIndex = $(this).parent(".image_info").index();
		loadImage(selectedIndex);
	});
	
	$("#overlay_snapshot").click(function() {
		return false;
	});
	
	$("#prev_overlay").click(function() {
		selectedIndex--;
		
		if (selectedIndex<=0) {
			selectedIndex = $(".image_info").length-1;
		}
		
		loadImage(selectedIndex);
		
		return false;
	});
	
	$("#next_overlay, #overlay_snapshot").click(function() {
		selectedIndex++;
		
		if (selectedIndex>=$(".image_info").length) {
			selectedIndex = 0;
		}
		
		loadImage(selectedIndex);
		
		return false;
	});
	
	function loadImage(i) {
		var $img = $(".image_info:eq(" + i + ") .image_image img");
		
		//get the related large version of the selected image and load it into our new dialog box
		chopFileExt($img.attr("src"), function(name, ext) {
			var largeImgSrc = name  + "large." + ext;
			
			$("#overlay_image").hide();
			$("#overlay").fadeIn("fast");
			
			var cacheImg = new Image();
			cacheImg.src = largeImgSrc;
			
			cacheImg.onload = function() {
				//use the width and height to center our image box
				$("#overlay_snapshot img").attr("src", largeImgSrc);
				
				//fade in the image
				$("#overlay_image").css({marginTop: -cacheImg.height/2.0 , marginLeft: -cacheImg.width/2.0}).fadeIn("slow");
			}
		});
	}
	
	/*function showHideLeftRight() {
		if (selectedIndex>0) {
			$("#prev_overlay").show();
		} else {
			$("#prev_overlay").hide();
		}
		
		if (selectedIndex<$(".image_info").length-1) {
			$("#next_overlay").show();
		} else {
			$("#next_overlay").hide();
		}
	}*/
	
	//when an image is clicked, the information for the image is loaded and the info box is shown
	$("#journal_images div").click(function() {
		var $targetInfoBox = $("#image_infos .image_info:eq(" + $(this).index() + ")");
		
		var imageWidth = $targetInfoBox.find(".image_image").width();
		var imageHeight = $targetInfoBox.find(".image_image").height();
		
		var widthBit = (imageWidth-$(this).width())/2.0;
		var heightBit = (imageHeight-$(this).height())/2.0;
		
		//no matter what, we need to position the image info box to the selected div
		$("#image_info_box").css({ marginTop: -($("#journal_images").height()/2.0 - $(this).position().top) - heightBit - 15 });
		//$("#image_infos").css({ marginLeft: -($("#journal_images").width()/2.0 - $(this).position().left) + widthBit - $(this).width()/2 });
		
		$("#image_infos").css({ marginLeft: -($("#journal_images").width()/2.0 - $(this).position().left)-215 });
		
		if ($("#image_info_box").is(":visible")) {
			/*$("#image_infos .image_info:visible").fadeOut("fast", function() {
				$targetInfoBox.fadeIn("fast");
			});*/
			$("#image_infos .image_info:visible").hide();
			$targetInfoBox.show();
		
		} else {
			$("#image_infos .image_info").hide();
			$targetInfoBox.show();
			$("#image_info_box").fadeIn("fast");
		}
	});
}

function prepareIngredients() {
	//explictly define the size of the ingredients for IE7
	var $ingredients = $("#ingredients");
	var lastIngredient = $ingredients.find(".ingredient:last-child");
	//var maxLeft = -(lastIngredient.position().left + lastIngredient.width() - $ingredients.width());
	
	//accumulate the widths of all of the ingredients
	var maxLeft = 0;
	$ingredients.find(".ingredient").each(function() {
		maxLeft += $(this).width();
	});
	
	$ingredients.css({width: maxLeft+57});
	
	$(".ingredient").click(function() {
		var $elem = $(this);
		
		//shrink the current selected ingredient
		var $selected = $(".ingredient.selected");
		
		if ($selected.length<1) {
			$selected = $(".ingredient:first-child");
		}
		
		if (!$elem.is($selected)) {
			$selected.removeClass("selected").animate({ width: 57 }, 500);
			$elem.animate({ width: 500 }, 500, function() {
				$(this).addClass("selected");
			});
			
			selectIngredientProducts($elem);
		}
	});
	
	selectIngredientProducts($(".ingredient:first-child"));
	
	function selectIngredientProducts($elem) {
		//ensure the current ingredient is related to a product
		if (!$elem.attr("id")) {
			return false;
		}
		
		var ingredientNameReg = $elem.attr("id").match(/^ingredient_(.*)$/);
		
		if (!ingredientNameReg || ingredientNameReg.length<2) {
			return false;
		}
		
		var ingredientName = ingredientNameReg[1];
		
		if (!ingredients.hasOwnProperty(ingredientName)) {
			return false;
		}
		
		//animate between the products based on whether the ingredient is in the product
		var $activeProducts = $(""), relatedProducts = ingredients[ingredientName];
		
		if (relatedProducts===null) {
			//use null as an alias to all of the products for ease
			$activeProducts = $(".product_thumb");
		} else {
			for (var i=0; i<relatedProducts.length; i++) {
				$activeProducts = $($activeProducts.add($("#product_" + relatedProducts[i])));
			}
		}
		
		$(".product_thumb").not($activeProducts).animate({opacity: 0.5}, 1000);
		$activeProducts.animate({opacity: 1.0}, 1000);
	}
	
	//allow a product to be selected and information about the product to be displayed
	$(".product_thumb").click(function() {
		//show a dialog with the information for the product
		var productIdStr = $(this).attr("id").match(/^product_(.*)$/);
		
		if (productIdStr===false || productIdStr.length<2) {
			return false;
		}
		
		var $relevantDialog = $("#dialog_" + productIdStr[1]);
		
		showDialog($relevantDialog, 40, $("#content").height()-300);
	});
	
	//allow ingredients to be moved using the mouse 
	$ingredients.each(function() {
		var mousemoveTimer = null, $ingredients = $(this), $ingredientParent = $ingredients.parent();
		var MOVE_NONE = 0, MOVE_LEFT = 1, MOVE_RIGHT = 2;
		var rightTollerance = 100, leftTollerance = 100, moveStatus = MOVE_NONE;
		
		$ingredientParent.mousemove(function(e) {
			//if the mouse is close to the corners, then scroll the contents right and left
			var relativeX = e.pageX - $(this).offset().left;
			
			//animate at 60fps
			if (relativeX < leftTollerance) {
				if (mousemoveTimer==null || moveStatus!=MOVE_LEFT) {
					window.clearInterval(mousemoveTimer);
					mousemoveTimer = window.setInterval(moveIngredientsLeft, 30);
					moveStatus = MOVE_LEFT;
				}
			} else if (relativeX>($ingredientParent.innerWidth()-286-rightTollerance)) {
				if (mousemoveTimer==null || moveStatus!=MOVE_RIGHT) {
					window.clearInterval(mousemoveTimer);
					mousemoveTimer = window.setInterval(moveIngredientsRight, 30);
					moveStatus = MOVE_RIGHT;
				}
			} else {
				moveStatus = MOVE_NONE;
				window.clearInterval(mousemoveTimer);
				mousemoveTimer = null;
			}
		}).mouseleave(function() {
			window.clearInterval(mousemoveTimer);
			mousemoveTimer = null;
		});
		
		function moveIngredientsLeft() {
			var newLeft = Math.min(0, $ingredients.position().left+10);
			
			$ingredients.css({
				left: newLeft
			});
		}
		
		function moveIngredientsRight() {
			var newLeft = Math.max($ingredients.position().left-10, -maxLeft+$ingredients.parent().width()-300)
			
			$ingredients.css({ left: newLeft });
		}
	});
}

function makeDialog($content, title) {
	if (title==undefined) {
		title = "";
	}
	
	var $dialog = $('<div class="dialog"></div>');
	var $dialogControls = $('<div class="dialog_controls"></div>');
	var $dialogTitle = $('<div class="dialog_title"></div>');
	var $dialogMinimize = $('<div class="dialog_control control_minimize"></div>');
	var $dialogClose = $('<div class="dialog_control control_close"></div>');
	var $dialogContent = $('<div class="dialog_content"></div>');
	
	var $dialogTitleContent = $("<h3></h3>");
	$dialogTitleContent.text(title);
	$dialogTitle.append($dialogTitleContent);
	
	$dialogControls.append($dialogMinimize, $dialogClose);
	$dialog.append($dialogTitle, $dialogControls, $dialogContent);
	
	if ($content !== undefined) {
		if (typeof $content == "string") {
			$dialogContent.html($content);
		} else {
			$dialogContent.append($content);
		}
	}
	
	initDialog($dialog);
	
	return $dialog;
}

function prepareContact() {
	//show the contact dialog
	$("#contact_form_button").click(function(e) {
		showDialog($("#contact_dialog"), 70, 60);
		return false;
	});
	/*
	//load the google map and place some custom markers
	if (typeof google != "undefined" && typeof google.maps!="undefined") {
		var map = new google.maps.Map(document.getElementById("map_canvas"), {
			zoom: 3,
		    center: new google.maps.LatLng(47.93106634, -35.33203125),
		    mapTypeId: google.maps.MapTypeId.ROADMAP
		});
		
		//america marker
		var usaMarker = new google.maps.Marker({
			position: new google.maps.LatLng(33.397649, -112.003697),
			map: map,
			icon: 'img/marker.png'
		});
		
		//england marker
		var englandMarker = new google.maps.Marker({
			position: new google.maps.LatLng(52.9121206, -1.4567771),
			map: map,
			icon: 'img/marker.png'
		});
	}*/
}

function resizeBackground() {
	// - also, center the background images changing their left positions to match
	$contentBg.find("img").each(function() {
		var wDiff = $(this).width() - $contentBg.width();
		var hDiff = $(this).height() - $contentBg.height();
		
		if (wDiff>hDiff) {
			var newHeight = $contentBg.height();
			var newWidth = newHeight / ($(this).height()/$(this).width());
			var newTop = 0;
			var newLeft = -(newWidth-$contentBg.width())/2.0;
		} else {
			var newWidth = $contentBg.width();
			var newHeight = ($(this).height()/$(this).width()) * newWidth;
			var newTop = -(newHeight-$contentBg.height())/2.0;
			var newLeft = 0;
		}
		
		
		$(this).css({
			width: newWidth,
			height: newHeight,
			//top: newTop,
			left: newLeft
		});
	});
}

/*var loadingAnimator, loadingFrame=0, loadingAnimFrames = 49, loadingAnimFps = 20;

function startAnimation(repeat) {
	loadingAnimator = window.setInterval(function() {
		//animate the background
		if (loadingFrame>=loadingAnimFrames) {
			resetAnimation();
			
			if (repeat!==undefined && !repeat) {
				pauseAnimation();
			}
		}
		
		$loading.css({backgroundPosition: -loadingFrame*($loading.width()) + "px 0px"})
		loadingFrame++;
	}, 1000/loadingAnimFps);
}

function stopAnimation() {
	pauseAnimation();
	resetAnimation();
}

function pauseAnimation() {
	if (loadingAnimator) {
		window.clearInterval(loadingAnimator);
	}
}

function resetAnimation() {
	loadingFrame=0;
	$loading.css({backgroundPosition: "0px 0px"});
}*/

$(document).ready(function() {
	//for the loader, will will use a javascript-animated loading emblem
	/*var loaderImg = new Image();
	
	loaderImg.onload = function() {
		//startAnimation();
		$loading.fadeIn("fast");
	};
	
	loaderImg.src= "img/loading.png";
	*/
	
	//override the privacy policy to open in a new dialog
	$("#privacy_policy_link").click(function(e) {
		$.get($(this).attr("href"), function(data) {
			//create a new dialog and place it in the content
			var $dialog = makeDialog(data, "Privacy Policy");
			$dialog.css({
				width: 500,
				height: 500,
				top: $("#content").height()/2 - 250,
				left: $("#content").width()/2 - 250
			});
			
			$("#content").append($dialog);
			showDialog($dialog);
			makeScrollBars($dialog.find(".dialog_content"));
		});
		
		return false;
	});
	
	//email box
	$("#email_signup_button").click(function(e) {	
		if ($("body").attr("id")=="page_home" || $("body").attr("id")=="page_contact") {
			$contentBgImg.fadeOut("slow");
		}
		
		$("#email_signup_box").fadeIn("slow", function() {
			$("#email_signup_text").focus();
		});
		
		$("#email_signup_box").click(function(e) {
			e.stopPropagation();
		});
		
		$("body").click(function() {
			fadeSignupOut();
		});
		
		return false;
	});
	
	function fadeSignupOut() {
		if ($("body").attr("id")=="page_home" || $("body").attr("id")=="page_contact") {
			$contentBgImg.fadeIn("slow");
		}
		
		$("#email_signup_box").fadeOut("slow");
	}
	
	$("#email_signup_checkbox").click(function() {
		$(this).toggleClass("selected");
	});
	
	$("#email_signup_send").click(function() {
		var email = $("#email_signup_text").val();
		var terms = $("#email_signup_checkbox").hasClass("selected");
		var $details = $('#email_signup_details');
		
		//ensure an email is given and valid and the terms are ticked
		if (!email.match(emailReg)) {
			
			$details.find('p').first().fadeOut(400, function() {
				$(this).removeClass("success").addClass("error").html('<b>Please enter a valid email address.</b>');
			});
			
			$details.find('p').first().fadeIn();
			
			return false;
		}
		
		if (!terms) {
			$details.find('p').first().fadeOut(400, function() {
				$(this).removeClass("success").addClass("error").html('<b>Please check the terms box.</b>');
			});
			
			$details.find('p').first().fadeIn();
			
			return false;
		}
		
		//send the email to the server and see what it thinks
		$.post("scripts/signup_email.php", {email_address: email}, function(e) {
			if (e.result) {
				$details.find('p').first().fadeOut(400, function() {
					$(this).removeClass("error").addClass("success").html('<b>' + e.data + '</b>');
				}).fadeIn();
				
				window.setTimeout(function() {
					fadeSignupOut();
					
					$("#email_signup_text").val("");
					$("#email_signup_details p").removeClass("success error").first().html("Enter your email address above.");
					$("#email_signup_checkbox").removeClass("selected");
				}, 2000);
				
				/*$dialogBox = makeDialog(e.data, 'Email Signup');
				
				$dialogBox.find('.dialog_content').css({
					'top': '34px',
					'overflow': 'visible !important',
					'left': '-15px'	
				});
				
				$dialogBox.css('display', 'none');
				
				$dialogBox.insertAfter('#contact_dialog');
				
				$dialogBox.css({
					'left': '831px',
					'top': '89px',
					'height': '50px',
					'width': '311px'
				});
				
				$dialogBox.fadeIn();
				
				var clearContactDialog = setTimeout(function() {
					$dialogBox.fadeOut();
				}, 2000);
				
				var removeContactDialog = setTimeout(function() {
					$dialogBox.fadeOut();
				}, 2000);*/
				
				//if successful, remove the content with the result
				//alert(e.data);
			} else {
				$details.find('p').first().fadeOut(400, function() {
					$(this).removeClass("success").addClass("error").html('<b>' + e.data + '</b>');
				}).fadeIn();
			}
		});
	});
	
	//TODO: load the correct content based on the hash
	if (window.location.hash.length > 0) {
		loadWholePage();
	}
	
	//watch the url to change and when it does, change the ajax
	var currUrl = window.location.toString();
	window.setInterval(function() {
		if (window.location.toString() != currUrl) {
			loadWholePage();
			currUrl = window.location.toString();
		}
	}, 1000);
	
	//allow the backgrounds to scale according to the miniumum width/height
	window.onresize = resizeBackground;
	
	//override the page links to use ajax
	$("#title a, #main_nav a, #footer_nav a, #next_button a").live("click", function() {
		window.location.hash = getPageName($(this).attr("href"));
		
		var hashMatch = window.location.toString().match(/#(.*)$/);
		if (!hashMatch || hashMatch.length<1) {
			window.location += "#";
		}
		
		return false;
	});
	
	function loadWholePage() {
		//the hash value is actually different of different browsers using .hash (e.g. just '#')
		//so instead manually get the hash
		var hashMatch = window.location.toString().match(/#(.*)$/);
		
		if (hashMatch && hashMatch.length>1) {
			var nextPageNum = hashMatch[1];
		} else {
			//if there is no hash, use the url filename
			var fileMatch = window.location.pathname.match('\/([^\/]*).php');
			
			if (fileMatch && fileMatch.length>1) {
				var nextPageNum = fileMatch[1];
			} else {
				var nextPageNum = "";
			}
		}
		
		//get the current page and check if the target page is before or after the current
		var currPageNum = $("body").attr("id").substring(5);
		
		//handle the home page as an exception
		if (nextPageNum=="") nextPageNum = "home";
		
		if (currPageNum==null || nextPageNum==null || !pages.hasOwnProperty(currPageNum) || !pages.hasOwnProperty(nextPageNum)) {
			return;
		}
		
		//remove the selected menu item and move it along
		$("#main_nav li.selected").removeClass("selected");
		$("#main_nav li#link_" + nextPageNum).addClass("selected");
		
		//slide in the loading screen
		if (pages[nextPageNum]>pages[currPageNum]) {
			//$loader.show();//.css({right: "auto", left: $("#content").width()});
			//$("#content").append($loader);
			//startAnimation();
			
			$loader.addClass("active");
			
			//$loader.animate({left: 0}, 1000, function() {
			window.setTimeout(function() {
				loadNextPage(nextPageNum);
			}, 1000);
			//});
		} else {
			//$loader.show();//.css({left: "auto", right: $("#content").width()});
			//$("#content").append($loader);
			//startAnimation();
			
			$loader.addClass("active");
			
			//$loader.animate({right: 0}, 1000, function() {
			window.setTimeout(function() {
				loadNextPage(nextPageNum);	
			}, 1000);
			//});
		}
		
		function loadNextPage(nextPageNum) {
			var url = nextPageNum + ".php";
			
			if (url=="home.php") url = "./";
			
			//load the next page content and register js events
			$.get(url, {content: true}, function(data) {
				//remove all data from the current content (except the loader)
				$("#content > *:not(#loader)").remove();
				
				//change the body to relate to the new page
				$("body").attr("id", "page_" + nextPageNum);
			
				//insert the new content
				$("#content").prepend(data);
			
				// once the next page has fully loaded, show the page
				//we could attempt to load all of the content individually and then once all has loaded, call the following method
				
				//we will do another trick, we will create an empty document in an iframe, load the content and then 
				/*var newContentLoader = document.createElement("iframe");
				newContentLoader.className = "loader_iframe";
				newContentLoader.src = url;
				document.body.appendChild(newContentLoader);
				*/
				//wait for the new content to load fully until we reveal the page
				var startTime = new Date().getTime();
				
				//this does not work, use a background image instead
				var newBg = $("#content_bg img").get(0);
				
				newBg.onload = function() {
				
				//newContentLoader.contentWindow.onload = function() {
					//$(newContentLoader).remove();
					
					var loadTime = new Date().getTime();
					resizeBackground();
					$("#contact_dialog").hide();
					
					//change the url and add some history so we can go back
					window.setTimeout(function() {
						preparePage();
						initDialog($("#content .dialog"));
						
						//then reveal our loader
						$loader.removeClass('active');
						//$loader.fadeOut("slow");
						//stopAnimation();
					}, Math.max(0, 2000-(loadTime-startTime)));
				}
			});
		}
	}
	
	//give the page content a loader when the page is started
	$("#content").append($loader);
	
	var startTime = new Date().getTime();
	
	$(window).load(function() {
		var loadTime = new Date().getTime();
		resizeBackground();
		$("#contact_dialog").hide();
		
		//ensure that at least 1/2 cycle of the loading is shown (2 seconds)
		window.setTimeout(function() {
			$loader.removeClass("active");
			
			/*window.setTimeout(function() {
				stopAnimation();
			}, 1000);*/
			/*$loader.fadeOut("slow", function() {
				stopAnimation();
				$(this).remove();
			});*/
		}, Math.max(0, 2000-(loadTime-startTime)));
	});
		
	//dialog boxes
	initDialog($(".dialog"));
	preparePage();
});
