var Config = {
	SND_PATH:"content/snd/", SND_TYPE:".mp3", IMG_PATH:"content/img/", VID_PATH:"content/vid/", INT_PATH:"content/interface/", DWL_PATH:"content/download/",
	DRAW_PROPS:{x:0,y:0,lineWidth:1,lineCap:"butt",lineJoin:"miter",miterLimit:"10",startAngle:0,endAngle:Math.PI*2},
	MIN_WIDTH:480, MIN_HEIGHT:480,
	COL_BACKGROUND:"", COL_FORGROUND: "#231f20"
}

var shell = {
	page: "", lastAddress:null, lastScrollY:0,

	init: function() {	  
			Stage.init();
			
			if (!shell.checkBrowser()) return false;
			if (Stage.isIPhone) Config.IMG_PATH = "content/tmb";
			Loader.init();
			infoBox.init();
			Scene.init();	
			closeButton.init();
			
			mainMenu.init(); 
			
			window.onresize = shell.onResize; 
			window.scrollTo(0,0); 
						
			setInterval(shell.checkAddressChange,500); shell.checkAddressChange();
	},	
	
	checkBrowser: function() {	
		var $valid = false;
		if (Stage.browserInfo.firefox && Stage.browserInfo.firefox>=3.5) $valid = true;
		if (Stage.browserInfo.msie && Stage.browserInfo.msie>=8) $valid = true;
		if (Stage.browserInfo.opera && Stage.browserInfo.opera>=9) $valid = true;
		if (Stage.browserInfo.chrome && Stage.browserInfo.chrome>=5) $valid = true;
		if (Stage.browserInfo.safari && Stage.browserInfo.safari>=5) $valid = true;
		if (!Stage.isDesktop) $valid = false;
		
		if (!$valid) {
			alert("You have a non-supported browser. You will now be redirected to our old website.");
			document.location="index3.html";
		} 
		return $valid;
	},
	
	imagesLoaded: function() { 
				Scene.draw(shell.page.src); 
				Loader.hide();
	},
	
	setAddress: function($v) { 
		if (document.location.hash != $v) Sounds.stopSound();
		if($v) document.location.hash=$v; shell.lastAddress = document.location.hash; 
		
		var $p;	
		if ($p = shell.getParam("id")) { Stage.track("id_"+$p); }
		else if ($p = shell.getParam("cat")) { Stage.track("cat_"+$p);}
		else if ($p = shell.getParam("s")) { Stage.track("search_"+$p); }	
	},
	
	checkAddressChange: function() { if (shell.lastAddress != document.location.hash) shell.checkAddress(); },

	checkAddress: function() {
		var $p;			
		if ($p = shell.getParam("id")) { shell.load($p); if (!mainMenu.category) { mainMenu.category = shell.getPage($p).cat; mainMenu.updateMenu(); } }
		else if ($p = shell.getParam("cat")) { mainMenu.drawCategory($p); }
		else if ($p = shell.getParam("s")) { mainMenu.globalSearch($p); }
		else mainMenu.drawCategory("about");
	},
	
	load: function($s) {
		shell.lastScrollY = (document.getElementById("overview")) ? document.getElementById("overview").scrollTop : 0; // save scrollvalue

		if ($s) shell.page = shell.getPage($s);
		shell.setAddress("id="+shell.page.id);
		infoBox.hide(); Loader.show();
		shell.loadImage(shell.page.src);
		Scene.clear();
		if (Scene._type != "overview") infoBox.showBox(this.page); else infoBox.hide();
	},
	
	loadCategory: function($s) {
		shell.lastScrollY = 0;
		mainMenu.drawCategory($s);
	},
	
	loadImage: function($s) { 
		shell.page.src = $s;
		Scene._type = "page"; 
		Images.reset(); Images.load($s);
	},
	
	trace: function($t) { if ($t) document.getElementById("statusfield").innerHTML += $t; else document.getElementById("statusfield").innerHTML = "";},
	onResize: function() { Scene.resize(); mainMenu.resize(); infoBox.resize(); Loader.resize(); closeButton.resize(); },
	getPage: function($s) { 
		if (isNaN($s)) {
			for(var i=0;i<Content.pages.length;i++) if (Content.pages[i].id == $s) return Content.pages[i]; 
		} else return Content.pages[$s%Content.pages.length];
	},
	
	getParam: function( $n )
	{
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\#&]"+$n+"=([^&]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( window.location.href );
	  if( results == null )
	    return "";
	  else
	    return results[1];
	}
			
};


// Main Menu
var mainMenu = {
	isOpen:false, sprite:"", scene:"", pos:0, newPos:0, timer:"", isFirstTime:true,
	content:"", menuButton:"", topMenu:"", subMenu:"", footer:"", category:"", scrollbar:"", search:"", header:"", colortheme:"",
	_pages:[], _search:"", searchForm: null, _hero:"", _autohide:true, hinting:0, hintingValue:0,
	
	init: function() {
		this.draw();
		Stage.bind(document,"mousemove",mainMenu.toggleMenu);
		this.initAutohide();
		colorManager.search(Content.colorTheme)
		//colorManager.setColor(colorManager.getColor(Math.floor(Math.random()*4096)));
	},
		
	resize: function() {
		mainMenu.sprite.style.width = "320px"; mainMenu.sprite.style.height = "100%"; 
		mainMenu.sprite.style.background = Config.COL_BACKGROUND;
		//mainMenu.drawPages("");
		Scene.draw();
		mainMenu.menuButton.setTo({top:(Stage.stageHeight()/2-30)+"px"});
	},
	
	draw: function() {
		var $t;
		
		mainMenu.sprite = document.getElementById("mainMenu");		
		// open graphic
		
		this.menuButton = new Sprite("div","menuButton","menubutton",this.sprite);
		this.menuButton.setTo({left:"305px",visibility:"hidden"}); this.menuButton.write("»");
		this.content = new Sprite("div","menuContainer","obj",this.sprite);
		this.header = new Sprite("div","header","menucontent",this.content.elm); // Header
		this.topMenu = new Sprite("div","topMenu","menucontent",this.content.elm); // Top Menu
		this.search = new Sprite("div","search","searchbox",this.content.elm); // Search box
		this.colortheme = new Sprite("div","colortheme","menucontent",this.content.elm); // Color theme
		
		this.footer = new Sprite("div","footer","menucontent",this.content.elm); // Footer
		this.footer.write(Content.footer);
		
		this.header.write("<img src='"+Config.INT_PATH+"tpg_logo.png' style='margin-bottom:6px'/><div class='hr3'></div>");
		
		// Search Menu
		mainMenu.search.write("<form id=\"searchForm\" action='javascript:void(null)' onkeyup=\"javascript:mainMenu.globalSearch(this.searchtext.value)\"><label for=\"searchtext\"><input type=\"text\" id=\"searchtext\" accesskey=\"s\" placeholder=\"Search...\"/></label></form>")
		mainMenu.searchForm = document.getElementById("searchForm");
		
		
		this.updateMenu();
		this.resize();
	},	
	
	updateMenu: function() {
		// Top Menu
		var $v = Content._topmenu;
		var $t = "<h3>";
		
		for (var i=0; i<2; i++) {
			if (mainMenu.category == $v[i].id){
				$t += "<u><a onclick=\"shell.loadCategory('" + $v[i].id + "')\">" + $v[i].name + "</a></u>";
			}
			else {
				$t += "<a class='noUnderline' onclick=\"shell.loadCategory('" + $v[i].id + "')\">" + $v[i].name + "</a>";
			}
			
			if (i < 1) {
				$t+="&nbsp;&nbsp;&#47;&nbsp;&nbsp;";
			}
		}
		
		$t += "</h3><div class='hr2'></div>"
		
		mainMenu.topMenu.write($t);
		
		mainMenu.drawPages("");
	},
	
	resetSearch: function() { mainMenu.searchForm.reset(); mainMenu._search = ""; },
		
	drawCategory: function($w) {
		mainMenu.category = $w;
		mainMenu.resetSearch();
		mainMenu.updateMenu();
		Scene.drawOverview();
	},
	
	globalSearch: function($v) {
		if (!$v || $v.length<3) return;
		$v = $v.toLowerCase();		
		colorManager.search($v);

		var $p = [];
		var $searchProp = ["client","year","type","title","subtitle","tag","cat","date"];
		var $searchWords = $v.split(" ");
		var $hits = 0, $sw;
		
		loop1: for(var i=0;i<Content.pages.length; i++) {
			$hits = 0; $sw = $searchWords.slice(0);
			loop2: for(var j=0;j<$searchProp.length; j++) {
				for(var k=0;k<$sw.length; k++) { if (Content.pages[i][$searchProp[j]] != undefined && Content.pages[i][$searchProp[j]].toLowerCase().indexOf($sw[k].toLowerCase()) !=-1) { $hits++; $sw.splice(k,1); k--; }; }

				if ($hits == $searchWords.length) { $p.push(Content.pages[i]); break loop2; }
			}
		}

		if (!$p.length) return Scene.drawOverview();
		mainMenu._hero = false;		
		mainMenu._pages = $p;
		mainMenu._search = $v;		
		document.location.hash = "s="+mainMenu._search;
		shell.lastScrollY = 0;
		Scene.drawOverview();
	},
	
	
	drawPages: function($v) {		
		if (mainMenu._search.length) return mainMenu.globalSearch();
		mainMenu._pages = [];
		mainMenu._hero = (Content.hero[mainMenu.category]) ? shell.getPage(Content.hero[mainMenu.category]) : "";
		for(i=0;i<Content.pages.length; i++) if (Content.pages[i].cat.indexOf(mainMenu.category) !=-1 && Content.pages[i].visible != "0") mainMenu._pages.push(Content.pages[i]);
	},
	

	toggleMenu: function($v) { if (!Stage.isDesktop) return;
		if ($v== false || $v== true) $v = !$v; 
		else if (mainMenu.isOpen && Stage.mouseX>320) $v = true;
		else if (!mainMenu.isOpen && Stage.mouseX<80) $v = false;
		else if (mainMenu.isFirstTime && Stage.mouseX<320) { mainMenu.isOpen = true; mainMenu.isFirstTime = false; if (mainMenu._autohide) clearInterval(mainMenu.timer); return; } 
		else return;
		
		if ($v != mainMenu.isOpen) return; 
		mainMenu.isOpen = !$v;
		mainMenu.newPos = (mainMenu.isOpen) ? 0:-301;			
		mainMenu.initHinting();
		mainMenu.menuButton.setTo({visibility: (mainMenu.isOpen || mainMenu.sprite.style.visibility == "hidden") ? "hidden" : "visible"});
		clearInterval(mainMenu.timer); mainMenu.timer = setInterval("mainMenu.update()",40);
	},
		
	initAutohide: function() { mainMenu._autohide = true; mainMenu.timer = setInterval("mainMenu.closeMenu()",5000); },
	closeMenu: function() { clearInterval(mainMenu.timer); mainMenu.isOpen = true; mainMenu.toggleMenu(false); mainMenu.isFirstTime = mainMenu._autohide = false; },
	
	update: function() {
		mainMenu.pos += (mainMenu.newPos-mainMenu.pos)*.4;
		if ( Math.abs(mainMenu.pos-mainMenu.newPos)<.5 ) { mainMenu.pos = mainMenu.newPos; clearInterval(mainMenu.timer); }
		mainMenu.setX(mainMenu.pos);
	},
	
	hide: function() { mainMenu.sprite.style.visibility = "hidden"; mainMenu.menuButton.setTo({visibility:"hidden"}); },
	show: function() { mainMenu.sprite.style.visibility = "visible"; mainMenu.menuButton.setTo({visibility:"visible"});  },
	
	initHinting: function() { clearInterval(mainMenu.hinting); mainMenu.hinting = setInterval("mainMenu.startHinting()",12000); mainMenu.setX(mainMenu.pos); },
	startHinting: function() { if (mainMenu.isOpen) return; clearInterval(mainMenu.hinting); mainMenu.hinting = setInterval("mainMenu.updateHinting()",30); mainMenu.hintingValue = 0; },
	updateHinting: function() { mainMenu.setX( (1-Math.cos(mainMenu.hintingValue++*.05*Math.PI))*10 +mainMenu.pos); if (mainMenu.hintingValue>=40) mainMenu.initHinting(); },
	
	setX: function($x) { mainMenu.sprite.style.left = $x + "px"; }
		
};



// Scene
var Scene = {
	sprite:"",
	lastImage:"",
	_type:"",
	content:"",
	current:"",
	
	init: function() { this.sprite = document.getElementById("scene"); },
	
	resize: function() {
		switch(Scene._type) {
			case "overview":
				Scene.sprite.style.left = (Stage.isDesktop) ? "0px" : "320px";
				Scene.content.style.width = (Stage.stageWidth()-20) + "px";
				if (Stage.isDesktop) {
					Scene.content.style.height = Stage.stageHeight() + "px";
				}else {
					Scene.content.style.height = Scene.sprite.offsetHeight + "px";
				}
				break;
				
			case "page":
				if (!this.lastImage) return;

				var $ir = this.lastImage.width/this.lastImage.height;
				var $wr = Stage.stageWidth()/Stage.stageHeight();
		
				if ($ir<$wr && Stage.isDesktop) {
					this.lastImage.width = Stage.stageWidth(); 
					this.lastImage.height = (1/$ir)*Stage.stageWidth();
					this.sprite.style.left = "0px";
				} else {
					this.lastImage.width = $ir*Stage.stageHeight();
					this.lastImage.height = Stage.stageHeight(); 
					this.sprite.style.left = (-($ir*Stage.stageHeight()-Stage.stageWidth())/2) + "px";
				}
				
				if (!Stage.isDesktop) Scene.sprite.style.left = "320px";
				break;
				
			case "video":
				Scene.sprite.style.left = "0px";
				Scene.content.style.width =  (Stage.stageWidth()) + "px";
				Scene.content.style.height = Stage.stageHeight() + "px";
				break;

		}

	},
		
	draw: function ($t) {
		switch(Scene._type) {
			case "overview": Scene.drawOverview(); break;
			case "page": Scene.drawPage($t); break;	
		}
	},
	
	drawOverview: function() { Scene._type = "overview";
		Scene.clear(); 

		if (mainMenu._pages.length == 1 && mainMenu._search=="") return shell.load(mainMenu._pages[0].id);

		if (mainMenu._search) shell.setAddress("s="+mainMenu._search);
		else shell.setAddress("cat="+mainMenu.category);

		
		// Crazy resize algoritm
		var maxWidth = 640, minWidth = 320;
		var $width, $height;
		var $col = Math.max(0,Math.floor((Stage.stageWidth()-20)/maxWidth)-1);
		
		do  {
			$col++; $width = (Stage.stageWidth()-34)/$col; $row = Math.ceil(mainMenu._pages.length/$col);
		} while (($row-1)*($width*0.5625)>Stage.stageHeight() && $width>290 && Stage.stageWidth()>580);
		
		if ($width>maxWidth) { $col++; $row = Math.ceil(mainMenu._pages.length/$col); $width = (Stage.stageWidth()-18)/$col; }
		else if ($width<minWidth) { $col--;}



		if ($row*($width*0.5625)>Stage.stageHeight()) $width = (Stage.stageWidth()-34)/$col;
		else $width = (Stage.stageWidth()-18)/$col;			

		$width = Math.round($width);
		$height = Math.floor($width * 0.5625);
		
		var $t= "<div id='overview'>", $x = 0, $y = 0;

		// HERO
		if (mainMenu._hero && $col>2) {
			var $w = $width*2-1;
			var $h = $height*2-1;

			$t += "<div class='thumb' style='width:" + $w + "px;left:" + ($width) + "px;top:1px'><img src='content/img/" + mainMenu._hero.src + "' width='" + $w + "' height='" + $h + "'/></div>"; 
			$t += Scene.drawLabel(mainMenu._hero,$width,1,$w,$h,$w/2);
		}

		for (var i=0, j=0; i<mainMenu._pages.length; i++) {
			if (mainMenu._pages[i].id == mainMenu._hero.id && $col>2) continue;
			if (mainMenu._hero && $col>2 && (j==1 || j==1+$col) ) j+=2;
			$x = (j%$col) * ($width);
			$y = 1+Math.floor(j/$col)*($height);
			j++;
			
			$t += "<div class='thumb' style='width:" + $width + "px;left:" + $x + "px;top:" + $y + "px'><img src='content/tmb/" + mainMenu._pages[i].src + "' width='" + ($width-1) + "' height='" + ($height-1) + "'/></div>"; 
			$t += Scene.drawLabel(mainMenu._pages[i],$x,$y,$width,$height,$width);
		};
		$t += "</div>";
		Scene.sprite.innerHTML = $t;
		
		Scene.content = document.getElementById("overview");
		if (!Stage.isDesktop) Scene.content.style.overflow = "visible";
		
		if (shell.lastScrollY) document.getElementById("overview").scrollTop = shell.lastScrollY;
		infoBox.hide(); Scene.resize(); Loader.hide(); closeButton.hide(); mainMenu.show();
	},
	
	drawLabel: function($v,$x,$y,$w,$h,$w2) {
		var $ho = ($v.subtitle.length) ?  $v.date.length ? 100 : 85 : $v.date.length ? 80 : 65;
		var $t = "";
		if (mainMenu.category == "about" && !mainMenu._search.length) $t += "<div class='thumbInfo' onclick='shell.load(\"" + $v.id + "\")' style='opacity:1;width:" + $w + "px;height:" + $h + "px;left:" + $x + "px;top:" + $y + "px'>";
		else $t += "<div class='thumbInfo' onclick='shell.load(\"" + $v.id + "\")' onmouseover='this.style.opacity=1' onmouseout='this.style.opacity=0' style='opacity:0;width:" + $w + "px;height:" + $h + "px;left:" + $x + "px;top:" + $y + "px'>";
		$t += "<div class='thumbText' style='background-color:"+Config.COL_BACKGROUND+";width:"+($w2-60)+"px;top:"+($h-$ho)+"px;'>"
		$t += "<H4>" + $v.date + "</H4>";
		$t += "<h7>" + $v.title +"</h7>";
		if ($v.subtitle.length) $t += "<h6>" + $v.subtitle +"</h6>";		
		$t += "<div class='hr2'></div></div></div>";
		return $t;
	},
	
	drawPage: function($s) { Scene._type = "page";
		Scene.clear(); 

		if ($s) this.lastImage = Images.get($s);
		if (!this.lastImage) return;
		if (mainMenu._pages.length>1) {
			this.lastImage.onclick = Scene.drawOverview;
			this.lastImage.style.cursor = "pointer";
			closeButton.show(Scene.drawOverview);
		}
		this.resize(); mainMenu.show();
		this.sprite.appendChild(this.lastImage);
		if (!mainMenu._search.length) mainMenu.toggleMenu(false);

	},
	
	playVideo: function($s) { 
		Scene._type = "video";
		Scene.sprite.innerHTML = "<video controls id='content'><source src=\"" + Config.VID_PATH + $s + ".mp4\"  type='video/mp4; codecs=\"avc1.42E01E, mp4a.40.2\"'><source src=\"" + Config.VID_PATH + $s + ".webm\" type='video/webm; codecs=\"vp8, vorbis\"'><source src=\"" + Config.VID_PATH + $s + ".ogg\"  type='video/ogg; codecs=\"theora, vorbis\"'></video>"
				
		//Scene.sprite.style.background = Config.COL_FORGROUND;
		Scene.content = document.getElementById("content");
		Scene.content.play();
		Scene.resize();
		infoBox.hide(); 
		Loader.hide();
		mainMenu.hide();
		closeButton.show( Scene.stopVideo );
	},
	
	stopVideo: function() { 
		Scene._type = "page";
		closeButton.hide();
		mainMenu.show();
		shell.load();
	},
	
	clear: function() { while(this.sprite.firstChild) this.sprite.removeChild(this.sprite.firstChild); }
	
		
};
