/* MAIN App CLASS!!!!!!*/
jQuery.easing.def = "easeInOutQuint";

function App(args){
		
	$.nav = $("nav");
	$.main = $("#main");
	$.mainBackground = $("#mainBackground");
	$.mainBackgroundImg = $("#mainBackgroundImg");
	$.mainContent = $("#mainContent");
	$.touch = $(window).width() < 750 ? true : false;
	if (!$.browser.msie){
		var canvas = document.getElementById("backer");
		var context = canvas.getContext("2d");
		$.ctx = context;
	}
	
	this.navArray = [];
	this.workArray = [];
	this.imageWidth = 1000;
	this.current = 0;
	this.currentImage = 0;
	this.direction = 0;
	this.bgType = "triangles";
	this.bgColour = "#2E2D4D";
	this.portfolioPage = false;
	this.imageLoaded = false;
	this.str = "";
	this.drawMountains = 0;
	this.navManager = {};
	this.totalSeen = [];
	this.inactivityDetector = {};
	this.url = "";
		
	this.init(args);
}

App.prototype = {
	
	init:function(args){
		
		this.subUrl = args.subUrl;
		this.portfolioPage = args.portfolioPage;

		for(i = 0; i< $('ul.mainNav a').length; i++){
			var navUrl = $('ul.mainNav a').eq(i).attr('href');
			this.navArray.push(navUrl);
			this.totalSeen.push(navUrl);
			
			var selectText = $('ul.mainNav a div').eq(i).html();
			var index = selectText.indexOf("<", 0);
			var text = selectText.substr(0, index);
			var selectValue = "<option value = '" + navUrl + "'>" + text +"</option>"
			$("#selectNav").append(selectValue);
		}
		
		$('#selectNav').change(jQuery.proxy(this, "selectChanged"));
		
		for(i = 0; i< $('.what').length; i++){
			this.workArray.push($('.what').eq(i).attr('href').split(".html").join(""));
		}
		
		this.navManager = new NavManager(this);
		
		this.inactivityDetector = new InactivityDetector(this);
				
		$("a.changePage").click(jQuery.proxy(this, "navigateToPage"));
		$('.pager, .topPager').click(jQuery.proxy(this, "changePageDirection"));
		$(document).keyup(jQuery.proxy(this, "keyboardUp"));
		$(document).keydown(jQuery.proxy(this, "keyboardDown"));
		
		$.address.change(jQuery.proxy(this, "addressChanged"));
	
		$(window).resize(jQuery.proxy(this, "windowResized"));
		
		$.mainBackgroundImg.bind('load', jQuery.proxy(this, "backgroundLoaded"));
		
		this.navManager.toggle();
	
	},
	
	addressChanged: function(event){
		
		
		// determine true URL and affect navigation
		this.url = $.address.value().split("/").join("")  + ' #mainContent';
		
		if(this.url == " #mainContent") this.url = this.subUrl + '.html #mainContent';
		this.current = Math.max(0, jQuery.inArray(this.url.split(' #mainContent').join(""), this.navArray));
		
		$('#selectNav option').eq(this.current + 1).attr('selected', 'selected');

		
		this.navManager.update(this.current);
								
		// choosing where to animate
		var target = $.mainContent.offset().left - 300;
		if(this.direction == 0) target = 0;
		if(this.direction == -1) target = $.mainContent.offset().left + 300;
		//$("#backer").stop().animate({opacity:0}, 400);
		Animate($("#backer"), {opacity:0}, null, 400);
		this.navManager.close();
		Shadowbox.close();
				
		// fluff - the progress bar :)
		if(this.totalSeen.length > 0){
			var ref = jQuery.inArray(this.url.split(' #mainContent').join(""), this.totalSeen);;
			if(ref > -1) this.totalSeen.splice(ref, 1);
		}
		
		$("#baseJourney").stop().animate({width: Utils.getJourneyWidth(this.navArray.length - this.totalSeen.length - 1, this.navArray.length - 1)}, 400, "easeOutBack");
		
		/* START MAIN PAGE LOAD / RESET */
		Animate($.mainContent, {left:target, opacity:0}, jQuery.proxy(this, "offScreen"), 500, $.easeIn);
					
	},
	
	offScreen: function(){
		var that = this;
		$("#loading").show();
		$('html,body').stop().animate({'scrollTop': 0}, 400, 'easeInOutQuad');
		$("#main").load(this.url, function(text){
			
			// reset global maincontent variable to reduce lookups
			$.mainContent = $("#mainContent");
							
			that.bgType = $.mainContent.attr('data-background_shape_type');
			that.bgColour = $.mainContent.attr('data-background_colour') ? $.mainContent.attr('data-background_colour') : "#EFEFEF";
			that.portfolioPage = $.mainContent.hasClass('portfolioPage') ? true : false;
			
			that.pageLoaded();
			
		});
	},
	
	backgroundLoaded: function(event){
		$.mainBackground.stop().animate({opacity: 1});
		this.imageLoaded = true;
		this.resizeElements();
	},
	
	windowResized: function(event){
		setTimeout(jQuery.proxy(this, "resizeElements"), 200);
	},
	
	changePageDirection: function(event){
		var dir = parseInt(($(event.currentTarget).attr('data-direction')));
		this.changePage(dir);
		event.preventDefault();
		return false;
	},
	
	navigateToPage: function(event){
		this.direction = 0;
		var url = $(event.currentTarget).attr("href");
		$.address.value(url);
		event.preventDefault();
		return false;
	},
	
	selectChanged: function(event){
		this.direction = 0;
		var url = $(event.currentTarget).attr("value");
		$.address.value(url);
		event.preventDefault();
		return false;
	},
	
	keyboardUp: function(event){
		switch(event.keyCode){
			case 39:
				this.changePage(1);
				break;
			case 37:
				this.changePage(-1);
				break;
			case 190:
				this.changeImage(1);
				break;
			case 188:
				this.changeImage(-1);
				break;	
			case 82:
				this.randomWork();
				break;
			case 73:
				var target = $("#imageCopy").offset().top - 70;
				$('html,body').stop().animate({'scrollTop': target+'px'}, 500, 'easeInOutExpo');
				break;
			case 220:
				$('html,body').stop().animate({'scrollTop': '0px'}, 500, 'easeInOutExpo');
				this.navManager.toggle();
				break;
		}
		$("#next").trigger("mouseout");
		$("#previous").trigger("mouseout");
		//alert(String.fromCharCode(event.keyCode))
		this.str += String.fromCharCode(event.keyCode);
		
		if (Utils.stringEndsWith(this.str, "CX")) {
			this.bgType = "curveLine";
			this.resizeElements();
		} else if(Utils.stringEndsWith(this.str, "BX")){
			this.bgType = "burstLines";
			this.resizeElements();
		} else if(Utils.stringEndsWith(this.str, "BALLS")){
			this.bgType = "balls";
			this.resizeElements();
		} else if(Utils.stringEndsWith(this.str, "BLOCK")){
			this.bgType = "texturedLine";
			this.resizeElements();
		} else if(Utils.stringEndsWith(this.str, "OLD")){
			$.address.value("old");	
		} else if(Utils.stringEndsWith(this.str, "APP")){
			$.address.value("stitch");	
		} else if(Utils.stringEndsWith(this.str, "EURO")){
			$.address.value("eurosport");	
		} else if(Utils.stringEndsWith(this.str, "IAAF")){
			$.address.value("iaaf");	
		}
			
	},
	
	keyboardDown: function(event){
		switch(event.keyCode){
			case 39:
				$("#next").trigger("mouseover");
				break;
			case 37:
				$("#previous").trigger("mouseover");
				break;
		}
	},

	pageLoaded: function(){
		
		$("p#currentNumber").html("<span>" + (this.current + 1) + "</span>/" + this.navArray.length);
		
		$.address.title("f-90 - Peter Wright " + this.navArray[this.current].split("_").join(" "));
		$("#loading").hide();

		var target = $.mainContent.offset().left + 500;//$(window).width() + $.mainContent.outerWidth();
		if(this.direction == 0) target = 0;
		if(this.direction == -1) target = $.mainContent.offset().left - 500;//-$.mainContent.outerWidth();
		$.mainContent.css({left:target, opacity:0});
		this.reset();
		this.resizeElements();
		
		if($.mainContent.attr("data-background_image") && $.mainContent.attr("data-background_image") != $.mainBackgroundImg.attr('src')) $.mainBackground.css({opacity:0});
		Animate($.mainContent, {left:0, opacity:1}, jQuery.proxy(this, "bringItBack"), 1000, $.easeOut);
		
	},
	
	bringItBack: function(){

		Animate($("#backer"), {opacity:1}, null, 1200);
		if($.mainContent.attr("data-background_image") && $.mainContent.attr("data-background_image") != $.mainBackgroundImg.attr('src')){
			this.imageLoaded = false;
			
			$.mainBackgroundImg.attr('src', $.mainContent.attr("data-background_image"));
			if($.mainContent.attr("data-background_overlay")){
				$("#mainBackgroundTexture").css("background-image", "url(" + $.mainContent.attr("data-background_overlay") +")");
			} else {
				$("#mainBackgroundTexture").css("background-image", "url(images/background_pattern_lt.gif)");
			}
			
		}
		
	},
	
	switchImage: function (target){
		var slides = $('.imageSlide');
		if(target == this.currentImage) return;
		if(target > this.currentImage){
			slides.eq(target).css({left:this.imageWidth});
			slides.eq(this.currentImage).stop().animate({left: -this.imageWidth}, 400, 'easeInOutExpo');
		} else {
			slides.eq(target).css({left: -this.imageWidth});
			slides.eq(this.currentImage).stop().animate({left: this.imageWidth}, 400, 'easeInOutExpo');
		}
		this.currentImage = target;
		slides.eq(this.currentImage).stop().animate({left: 0}, 400, 'easeInOutExpo');
		this.changeSub(target);
	},
	
	changeSub: function(target){
		$("#nextImage, #previousImage").show();
		if(target == 0) $("#previousImage").hide();
		if(target == $('.imageSlide').length - 1) $("#nextImage").hide();
		var numbers = $('#imageSub ul li');
		numbers.removeClass('activeSub');
		numbers.eq(target).addClass('activeSub');
		var image = $(".imageSlide").eq(target);
		$("#imageTitle").html($(image).attr("title"));
		$("#imageHolder").css({height: $('.imageSlide').eq(this.currentImage).height()});
	},
	
	changeImage: function(direction){
		var target = Math.max(0, Math.min(this.currentImage + direction, $('.imageSlide').length - 1));
		if(target == this.currentImage) return;
		this.switchImage(target);
	},
	
	reset: function(){
				
		if(this.portfolioPage) this.makeNumbers();
		
		$("a.innerPageChange").click(jQuery.proxy(this, "navigateToPage"));
		
		$('#homeContent li').hover(function(event){
			Animate($('.homeCircleInner', this), {left:0}, null, 400);
			Animate($(this), {backgroundColor:"#FF8E3E"}, null, 500);
		}, function(event){
			var lt = $.touch? -130 : -150;
			Animate($('.homeCircleInner', this), {left:lt}, null, 700);
			Animate($(this), {backgroundColor:$(this).attr("data-background_colour")}, null, 400);
		});
		
		$('#homeContent li').click(function(event){
			$.address.value($('a', this).attr('href'));
			event.preventDefault();
			return false;
		});
		
		$('.circleButton').hover(function(event){
			Animate($('.circleButtonInner', this), {left:0}, null, 400);
			Animate($(this), {backgroundColor:"#FF8E3E"}, null, 500);
		}, function(event){
			Animate($('.circleButtonInner', this), {left:-100}, null, 700);
			Animate($(this), {backgroundColor:$(this).attr("data-background_colour")}, null, 400);
		});
		
		$('.linkOut').click(function(event){
			window.open($('a', this).attr('href'), "_blank");
		});
		
		$('.shadowboxer').click(function(event){
			Shadowbox.open(sBox);
			event.preventDefault();
		});
		
		sBox = [];
		$('a.shadowbox').each(function(){
			var obj = {
				player: 'swf',
				content: $(this).attr("href"),
				height: $(this).attr("height"),
    			width: $(this).attr("width")
			}
			sBox.push(obj);
		});
				
	},
	
	makeNumbers: function (){
		this.currentImage = 0;
		var container = $('#imageHolder');
		
		$('#imageHolder').click(jQuery.proxy(this, "changeImageDirection"));
		
		$('.imageSlide').each(function(){
			$('#imageSub ul').append('<li></li>');
		});

		$('#imageSub').css({width: 17 * $('.imageSlide').length});

		$('#imageSub ul li').click(jQuery.proxy(this, "switchImageSub"));
				
		this.changeSub(0);
		
	},
	
	switchImageSub: function(event){
		if($(event.currentTarget).hasClass('activeSub')) return;
		var target = $('li', $(event.currentTarget).parent()).index(event.currentTarget);
		this.switchImage(target);
		event.preventDefault();
	},
	
	changeImageDirection: function(event){
		var half = Utils.getHalf($(event.currentTarget), event);
		this.changeImage(half);
	},
	
	resizeElements: function(){
		$.touch = $(window).width() < 750 ? true : false;
		if(this.portfolioPage){
			this.imageWidth = $('#imageHolder').width();
			$('.imageSlide').css({left: this.imageWidth});
			$('.imageSlide').eq(this.currentImage).css({left: 0});
			$("#imageHolder").css({height: $('.imageSlide').eq(0).height()});
		} else {
			if($.mainContent.height() < $(window).height() - 80 && !$.touch){
				$.mainContent.css({top:Math.max(70, $(window).height() / 2 - $.mainContent.height() / 2)});
			} else {
				if(!$.touch) $.mainContent.css({top:70});
			}
		}
		if(this.imageLoaded) Utils.maxscreen($.mainBackground,  $.mainBackgroundImg);
		if(!$.browser.msie) this.draw();
		//if(this.navManager.navOpen) $("#nav").css({'top': Math.max(20, $(window).height()/2 + this.navManager.navY / 2)});
		$("#baseJourney").css({width: Utils.getJourneyWidth(this.navArray.length - this.totalSeen.length - 1, this.navArray.length - 1)});

	},
	
	changePage: function(dir){
		var ref = this.current + dir;
		this.direction = dir;
		if(ref > this.navArray.length - 1) ref = 0;
		if(ref < 0) ref = this.navArray.length - 1;
		$.address.value(this.navArray[ref]);
	},
	
	randomWork: function(){
		var url = this.navArray[0];
		if(this.workArray.length > 0){
			var ref = Utils.randRange(0, this.workArray.length);
			url = this.workArray[ref];
			this.workArray.splice(ref, 1);
		}
		$.address.value(url);
	},
	
	draw: function () {
		
		$.ctx.clearRect (0, 0, $(window).width(), $(window).height());
		$.ctx.canvas.width  = $(window).width();
		$.ctx.canvas.height = $(window).height();
		
		$(window).unbind('mousemove');
		
		clearInterval(this.drawMountains);
		
		var total;
		
		var yt = $(window).height()/2;
		
		switch(this.bgType){
			
			case "none":
				break;
				
			case "balls":
				balls = [];
				var radius = 200;
				total = Math.round(window.innerWidth / radius) + 3;
				for(var i = 0; i<total; i++){
					var col = "rgba(255, 255, 255," + Utils.getAlpha(i, total, radius/2) + ")";
					var ball = new Ball(radius, i*radius - radius, yt, col, i+1, 100, 1);
					balls.push(ball);
				}
				this.drawMountains = setInterval(jQuery.proxy(this, "bounce"), 1000/60);
				break;
				
			case "texturedLine":
				slab = {a:0, angle:0};
				this.drawMountains = setInterval(jQuery.proxy(this, "slabber"), 1000/60);
				break;
				
			case "circles":
				var radius = 190;
				
				total = Math.round(window.innerWidth / radius) + 1;
				for(var i = 0; i< total; i++){
					var col = "rgba(255, 255, 255," + Utils.getAlpha(i, total, radius/2) + ")";
					var ball = new Ball(radius, i*radius, yt, col, null, null, null);
					ball.create();
				}
				break;
				
			case "curveLine":
				pointArray = [];
				total = 20;
				for(var i = 0; i < total; i++){
					curvePoint = new CurvePoint(($(window).width() / total) * i, $(window).height()/2, 70);
					pointArray.push(curvePoint);	
				}
				curvePoint = new CurvePoint($(window).width(), $(window).height()/2, 70);
				pointArray.push(curvePoint);
				this.drawMountains = setInterval(jQuery.proxy(this, "sine"), 1000/60);
				
				$(window).mousemove(function(event){
					var percentage = event.pageX / $(window).width();
					for(var i = 0; i < total; i++){
						var innerPercentage = (i+1) / total;
						pointArray[i].range = Math.abs(innerPercentage - percentage) * 100;	
					}
				});
				
				$(window).mousemove();
				break;
				
			case "chunk":
				
				var grad = $.ctx.createLinearGradient(0, 0, 0, $(window).height());
				grad.addColorStop(0, "rgba(255, 255, 255, 0)");
				grad.addColorStop(0.5, "rgba(255, 255, 255, 0.5)");
				grad.addColorStop(1, "rgba(255, 255, 255, 0)");
				$.ctx.fillStyle = grad;
				$.ctx.beginPath();
				$.ctx.moveTo(0, Math.max(200, $(window).height() - 300));
				$.ctx.lineTo(0, $(window).height()+100);
				$.ctx.lineTo($(window).width(),20);
				$.ctx.lineTo($(window).width(),-20);
				$.ctx.lineTo(0, Math.max(200, $(window).height() - $(window).height() / 2));
				$.ctx.fill();	
				break;
				
			case "line":
				
				$.ctx.lineWidth = 1;
				$.ctx.strokeStyle = "rgba(255, 255, 255, 0.2)";
				$.ctx.beginPath();
				$.ctx.moveTo(0, Math.max(200, $(window).height() - 200));
				$.ctx.lineTo($(window).width(),40);
				$.ctx.stroke();
				break;
				
			case "burstLines":
				$(window).mousemove(function(event){
					$.ctx.lineWidth = 1;
					$.ctx.strokeStyle = "rgba(255, 255, 255, 0.4)";
					$.ctx.beginPath();
					$.ctx.moveTo($(window).width() / 2, $(window).height() / 2);
					$.ctx.lineTo(event.pageX, event.pageY);
					$.ctx.stroke();
				});
				break;
				
			case "triangles":
			
				var wT = 500;
				
				total = Math.round(window.innerWidth / wT * 2) + 1;
				for(var i = 0; i< total; i++){
					$.ctx.fillStyle = "rgba(255, 255, 255," + Utils.getAlpha(i, total, wT/2) + ")";
					$.ctx.beginPath();
					var offset = wT / 2 * i;
					$.ctx.moveTo(offset + -wT/2,yt);
					$.ctx.lineTo(offset + wT/2,yt);
					$.ctx.lineTo(offset + 0,yt-wT * 0.75);
					$.ctx.lineTo(offset + -wT/2,yt);
					$.ctx.fill();	
				}
				break;
				
			case "diamonds":
			
				var wT = 400;
				
				total = Math.round(window.innerWidth / wT * 2) + 1
				for(var i = 0; i< total; i++){
					$.ctx.fillStyle = "rgba(255, 255, 255," + Utils.getAlpha(i, total, wT/2) + ")";
					$.ctx.beginPath();
					var offset = wT / 2 * i;
					$.ctx.moveTo(offset + -wT/2,yt);
					$.ctx.lineTo(offset + 0,yt+wT * 0.58);
					$.ctx.lineTo(offset + wT/2,yt);
					$.ctx.lineTo(offset + 0,yt-wT * 0.58);
					$.ctx.lineTo(offset + -wT/2,yt);
					$.ctx.fill();	
				}
				break;
				
			case "arrows":
			
				var wT = 300;
				
				total = Math.round(window.innerWidth / wT * 2) + 1
				for(var i = 0; i< total; i++){
					$.ctx.fillStyle = "rgba(255, 255, 255," + Utils.getAlpha(i, total, wT/2) + ")";
					$.ctx.beginPath();
					var offset = wT / 2 * i;
					$.ctx.moveTo(offset + -wT/2,yt + wT * 0.75);
					$.ctx.lineTo(offset + wT/2,yt);
					$.ctx.lineTo(offset + -wT/2,yt-wT * 0.75);
					$.ctx.lineTo(offset + -wT/2,yt + wT * 0.75);
					$.ctx.fill();	
				}
				break;
			
		}
		
	},
	
	sine: function (){
		
		$.ctx.clearRect (0, 0, $(window).width(), $(window).height());
		
		$.ctx.strokeStyle = "rgba(255, 255, 255, 0.4)";
		$.ctx.lineWidth = (20);
		$.ctx.beginPath();
		
		$.ctx.moveTo(pointArray[0].x, pointArray[0].y);
		
		for(var i = 0; i<pointArray.length;i++){
				
				var a = pointArray[i].startpoint+(Math.sin(pointArray[i].angle)*pointArray[i].range);
				pointArray[i].angle += pointArray[i].inc;
				pointArray[i].y = a;
				var midpoint = {};
				if(i<pointArray.length-1){
					midpoint.x = (pointArray[i+1].x+pointArray[i].x)/2;
					midpoint.y = (pointArray[i+1].y+pointArray[i].y)/2;
				} 
				$.ctx.quadraticCurveTo(pointArray[i].x, pointArray[i].y, midpoint.x, midpoint.y);
			}
		
		$.ctx.lineTo(pointArray[pointArray.length-1].x, pointArray[pointArray.length-1].y)
		$.ctx.stroke();
		
		
	},
	
	bounce: function (){
		
		$.ctx.clearRect(0, 0, $(window).width(), $(window).height());
		
		totalWidth = balls.length * balls[0].radius;
		
		var top		= balls[0];
		var base	= balls[balls.length-1];
		
		for(var i = 0; i<balls.length; i++){
			balls[i].update();
			if (base.x > totalWidth-base.radius) {
				var ball = balls.pop();
				// moves clips from last to first
				balls.unshift(ball);
				base.x = top.x-base.radius;
			}
		
			if(i > 0) balls[i].x = balls[i-1].x + balls[i-1].radius;
				
		}
					
		balls[0].move();
	},
	
	slabber: function (){
		
		$.ctx.clearRect(0, 0, $(window).width(), $(window).height());
		
		slab.a = (Math.sin(slab.angle));
		slab.angle += 0.05;
		
		slab.a = (slab.a + 1) / 2;
		
		var grad = $.ctx.createLinearGradient(0, 0, slab.a * $(window).width(), $(window).height());
		grad.addColorStop(0, "rgba(255, 255, 255, 0)");
		grad.addColorStop(slab.a, "rgba(255, 255, 255, 0.5)");
		grad.addColorStop(1, "rgba(255, 255, 255, 0.8)");
		$.ctx.fillStyle = grad;
		$.ctx.beginPath();
		$.ctx.moveTo(0, Math.max(200, $(window).height() - 300));
		$.ctx.lineTo(0, $(window).height()+100);
		$.ctx.lineTo($(window).width(),20);
		$.ctx.lineTo($(window).width(),-20);
		$.ctx.lineTo(0, Math.max(200, $(window).height() - $(window).height() / 2));
		$.ctx.fill();
	}

}

function CurvePoint(xT, yT, rangeT){
	this.x			= xT;
	this.y			= yT;
	this.startpoint	= yT;
	this.range		= - Math.random()*10*((rangeT/10));
	this.angle		= Math.random();
	this.inc		= Math.random()*0.2;
}

function Ball(rad, xt, yt, col, index, range, xInc){
			
	this.radius = rad;
	this.x = xt;
	this.y = yt;
	this.sy = yt;
	this.angle = index;
	this.range = range//index * 20;
	this.inc = 0.05// + (index / 100);
	this.xInc = xInc;
	this.a = 0;
	
	this.col = col;
	
	this.update = function(){
		this.a = this.sy + (Math.sin(this.angle)*this.range);
		this.angle += this.inc;
		this.y = this.a;
		this.create();
	}
	
	this.move = function(){
		this.x += this.xInc;
	}
	
	this.create = function(){
		$.ctx.fillStyle = this.col;
		$.ctx.beginPath();
		$.ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
		$.ctx.closePath();
		$.ctx.fill();	
	}
}

Globals = {
	MIN_WIDTH:750,
	MIN_HEIGHT:370,
	MAX_WIDTH:1200,
	MAX_HEIGHT:675,
	SUB_WIDTH:300,
	SUB_HEIGHT:230,
	IMAGE_WIDTH: 16,
	IMAGE_HEIGHT: 9
}

/* NavManager CLASS!!!!!!*/

function NavManager(parent){
	
	this.navOpen = true;
	this.parent = parent;
	
	this.init();
}

NavManager.prototype = {

	init:function(args){
		
		$("#navTab").hover(jQuery.proxy(this, "goingToClose"), jQuery.proxy(this, "notGoingToClose"));
		$("ul.mainNav li a").hover(jQuery.proxy(this, "mainOver"), jQuery.proxy(this, "mainOut"));
		$("#next").hover(jQuery.proxy(this, "nextOver"), jQuery.proxy(this, "nextOut"));
		$("#previous").hover(jQuery.proxy(this, "previousOver"), jQuery.proxy(this, "previousOut"));
		
		$("#navTab, #overall").click(jQuery.proxy(this, "toggle"));
				
	},
	mainOver: function(event){
		if($(event.currentTarget).hasClass("downNav")) return;
		Animate($("div", $(event.currentTarget)), {opacity: 1}, null, 400, $.easeInOut);
	},
	mainOut: function(event){
		if($(event.currentTarget).hasClass("downNav")) return;
		Animate($("div", $(event.currentTarget)), {opacity: 0}, null, 500, $.easeInOut);
	},
	nextOver: function(event){
		if($.touch) return;
		this.setInUse(true);
		Animate($(event.currentTarget), {right: 0, backgroundColor:"#FF8E3E"}, null, 300);
		Animate($("#innerNext"), {left: 0}, null, 500);
	},
	nextOut: function(event){
		if($.touch) return;
		this.setInUse(false);
		Animate($(event.currentTarget), {right: -50, backgroundColor:"#53C7E0"}, null, 800);
		Animate($("#innerNext"), {left: -130}, null, 500);
	},
	previousOver: function(event){
		if($.touch) return;
		this.setInUse(true);
		Animate($(event.currentTarget), {left: 0, backgroundColor:"#FF8E3E"}, null, 300);
		Animate($("#innerPrevious"), {right: 0}, null, 500);
	},
	previousOut: function(event){
		if($.touch) return;
		this.setInUse(false);
		Animate($(event.currentTarget), {left: -50, backgroundColor:"#53C7E0"}, null, 800);
		Animate($("#innerPrevious"), {right: -130}, null, 500);
	},
	setInUse: function(inactive){
		this.parent.inactivityDetector.setInUse(inactive);
	},
	toggle: function(event){
		if(!this.navOpen){
			this.open();
		} else {
			this.close();
		}
		event.preventDefault();
		return false;
	},
	open:function(event){
		if(this.navOpen) return;
		$.nav.slideToggle(500);
		$("#navTab p").html("Close").addClass('closeNav');
		if(!$.touch) Animate($("#navTab"), {top: -30}, null, 300);
		Animate($("#navTab"), {backgroundColor:"#242424"}, null, 300);
		$("#navTabArrow").attr('src', "images/top_arrow_reverse.png")
		this.navOpen = true;
	},
	goingToClose:function(event){
		this.setInUse(true);
		if(!$("#navTab p").hasClass('closeNav')) Animate($("#navTab"), {backgroundColor:"#FF8E3E"}, null, 300);
		Animate($("#navTab"), {top: 0}, null, 300);
		Animate($("#innerNavTab"), {top: 0}, null, 500);
	},
	notGoingToClose:function(event){
		this.setInUse(false);
		if(!$("#navTab p").hasClass('closeNav')) Animate($("#navTab"), {backgroundColor:"#53C7E0"}, null, 800);
		Animate($("#navTab"), {top: -20}, null, 800);
		Animate($("#innerNavTab"), {top: -70}, null, 500);
	},
	close:function(event){
		if(!this.navOpen) return;
		$.nav.slideToggle(500);
		$("#navTab p").html("Menu").removeClass('closeNav');
		$("#navTab").trigger("mouseout");
		$("#navTabArrow").attr('src', "images/top_arrow.png")
		this.navOpen = false;
	},
	update:function(index){
		$('nav li a').eq(index).trigger("mouseover");
		$('nav li a').removeClass("current downNav").eq(index).addClass("seen current downNav");
		$('nav li a').trigger("mouseout");	
	}
}

/* InactivityDetector CLASS!!!!!!*/

function InactivityDetector(parent){
	
	this.asleep = false;
	this.sleepTimer = 0;
	this.inUse = false;
	this.parent = parent;
	
	this.init();	
}

InactivityDetector.prototype = {
	
	init: function(args){
		if(!$.touch) $(document).mousemove(jQuery.proxy(this, "awake"));
	},
	
	awake: function(){
		if(!this.inUse){
			clearTimeout(this.sleepTimer);
			this.sleepTimer = setTimeout(jQuery.proxy(this, "sleep"), 5000);
		}
		if(this.asleep){
			$("#next, #previous, #navTab").stop().animate({opacity: 1});
			this.asleep = false;	
		}
	},
	
	sleep: function(){
		if(this.inUse) return;
		this.asleep = true;	
		$("#next, #previous, #navTab").stop().animate({opacity: 0}, 2000);
	},
	
	setInUse: function(value){
		this.inUse = value;
		if(this.inUse){
			clearTimeout(this.sleepTimer);
			this.awake();
		}
	}
	
}

/**/

Utils = {

	trackHover: function (element){
		$(element).mousemove(function(e){
			if((Utils.getHalf($(this), e) == 1)){
				$("#nextImage").trigger("mouseover");
				//$("#previousImage").trigger("mouseout");
			} else {
				//$("#nextImage").trigger("mouseout");
				$("#previousImage").trigger("mouseover");
			}
		});
	},
	
	getHalf: function (element, e){
		var half = 1;
		var x = e.pageX - $(element).offset().left;
		if(x < $(element).width()/2) half = -1;
		return half;
	},
	
	getImage: function (activeImage, parentElement, half){
		var index = $('img', parentElement).index($(activeImage));
		var image = $(activeImage).prev('.fader').length ? index - 1 : $('img', parentElement).length-1;
		if(half) image = $(activeImage).next('.fader').length ? index + 1 : 0;
		return image;
	},
	
	getJourneyWidth: function (target, length){
		var journeyPercentage = target / length;
		return journeyPercentage * ($("#innerNav").width()-60);
	},

	maxscreen: function(imageHolder, image){
		var imageRatio = $(image).width() / $(image).height();
		var wt = $(window).width();
		var ht = wt / imageRatio;
	
		if(ht < $(window).height()){
			ht = $(window).height();
			wt = ht * imageRatio;
		}
		$(image).css({top: 0, width: wt, height:ht});
	},
	
	randRange: function (start, end) {
		return Math.floor(start+(Math.random()*(end-start)));
	},
	
	stringEndsWith: function (str, substr) {
		return str.substr(0 - substr.length) == substr;
	},
	
	degreesToRadians: function (degrees){
		return degrees * Math.PI / 180;
	},
	
	getAlpha: function(i, total, wT){
		var alpha = 0.2;
		return alpha;
	},
	
	trace: function(str){
		$("#trace").append(str + "<br/>");	
	}

}

function Animate(object, cssProperties, callback, ms, easing) {
	Stop(object);
	if (!ms) ms = 500;
	if(!easing) easing = $.easeInOut;

	if (Modernizr.csstransitions) {
		object.css($.vP+"transition", "all "+ms+"ms " + easing);
		object.css(cssProperties);

		if ($.isFunction(callback)) {
			object.one($.transitionEnd,function(){
				//object.unbind($.transitionEnd);
				callback();
			});
		}

	} else {
		if ($.isFunction(callback)) {		
			object.stop().animate(cssProperties, ms, callback);
		} else {
			object.stop().animate(cssProperties, ms);			
		}
	}
}

function Stop(object){
	object.unbind($.transitionEnd);
}

$.vP = "";
$.easeInOut = "cubic-bezier(1.000, 0.000, 0.000, 1.000)";
$.easeOut = "cubic-bezier(0.230, 1.000, 0.320, 1.000)";
$.easeIn = "cubic-bezier(0.755, 0.050, 0.855, 0.060)";
$.transitionEnd = "transitionEnd";
if ($.browser.webkit) {
	$.vP = "-webkit-";
	$.transitionEnd = "webkitTransitionEnd";
} else if ($.browser.msie) {
	$.vP = "-ms-";
	$.transitionEnd = "msTransitionEnd";	
} else if ($.browser.mozilla) {
	$.vP = "-moz-";
	$.transitionEnd = "transitionend";
} else if ($.browser.opera) {
	$.vP = "-o-";
	$.transitionEnd = "oTransitionEnd";
}
