$(document).ready(function() {
	UmericSite.init();
});







var UmericSite = function() {
	var footer;
	var maincontent;
	var visor;
	var splashes = ["assets/splash/splash1.jpg", "assets/splash/splash2.jpg", "assets/splash/splash3.jpg", "assets/splash/splash4.jpg", "assets/splash/splash5.jpg", "assets/splash/splash6.jpg", "assets/splash/splash7.jpg", "assets/splash/splash8.jpg", "assets/splash/splash9.jpg", "assets/splash/splash10.jpg", "assets/splash/splash11.jpg", "assets/splash/splash12.jpg"];
	var targetSplash = 0;
	var path;
	var hash;
	var cache_home = "";

	var section = "home";

	var intervalID;
	
	function init() {
		//pre locate objects
		footer = $("#footer");
		maincontent = $("#maincontent");
		visor = $("#visor");
		cache_home = maincontent.html();
		path = window.location.pathname;
		if(path == "/update.php") {
			path = "/";
		}

		//handle anchor clicks
		$('a').live("click", onClickAnchorTag);

		//ready fullscreen background
		FullOn.init("#wallpaper", "RATIO_FILL", splashes);

		//handle resize events
		$(window).resize(resize);
		resize();

		hash = getHash();
		if(hash  != "" && hash != "/" && hash != "#/") {
			handleHref(hash);
		}
		
		
		intervalID = setInterval(UmericSite.hashCheck, 200);
	
	}

	
	function hashCheck() {
		var tmp = getHash();
		if(hash != tmp) {
			hash = tmp;
			handleHref(hash);	
		}
	}
	

	function getHash() {
		var hash = "";
		if(location.hash.length > 1) {
			hash = location.hash.substr(1);
		}
		return hash;
	}
	

	

	function resize() {
		//height first to take scrollbars into account
		var windowHeight = $(window).height();
		var contentHeight = Math.max(maincontent.height() + 120, windowHeight);
		visor.height(contentHeight);

		var windowWidth = $(window).width();
		visor.width(windowWidth);

		FullOn.resize(windowWidth, contentHeight);
		footer.css("top", (contentHeight - 60)+"px");
	}

	



/*

 * GLOBAL HANDLERS ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

 */

	function onClickAnchorTag() {
		var a = $(this); //this refers to the clicked anchor tag

		//check to see if its a project link
		var href = a.attr("href");

		if(href == undefined || href.indexOf('http://') > -1 || href.indexOf('mailto:') > -1 || href.indexOf('https://') > -1) {
			//external link
			return true;
		}

		//are we in a deeper section?
		if(path != "/" && path != "") {
			window.location.href = "/#"+href;
			return false;
		}
		//internal link
		return handleHref(href);
	}

	function handleHref(href) {
		pageTracker._trackPageview(href);
		location.hash = href;
		hash = href;
		if(href.indexOf('/project') > -1 || href.indexOf('/spotlight') > -1) {
			loadProject(href);
		}else{
			loadContent(href);
		}
		return false;
	}


	function showVisor() {
		visor.show();
		FullOn.hideFlash();
	}

	

	function hideVisor() {
		FullOn.showFlash();
		visor.hide();
	}

	

	function isHome() {
		return section == "home";
	}

	

/*
 * PROJECT ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 */



	function loadProject(href) {
		showVisor();
		maincontent.hide();
		showLoading();
		section = "project";
		$.getJSON("/api/content/get/?path="+escape(href), onLoadProject);
	}

	

	function onLoadProject(o) {
		hideLoading();
		if(o.error == "0") {
			maincontent.html(o.html);
			maincontent.show();
			buildViewport();
			resize();

		}else{
			alert(o.message);
		}
	}
	

	function buildViewport() {
		var vp = $("#viewport");
		vp.empty();
		var src = $("#videoSources span.source").each(function(n) {
			vp.append(getVideoSource($(this).html()));
		});
		var imgs = $("#imageSources span.source").each(function(n) {
			vp.append(getImageSource($(this).html()));
		});
	}
	
	function getVideoSource(source) {
		if(source == null) {
			return "";
		}
		
		if(source.indexOf("vimeo") > -1) {
			var data = source.split(",");
			if(data.length >= 2) {
				var id = data[0].substr(source.lastIndexOf("/")+1);
				var url = "http://vimeo.com/moogaloop.swf?clip_id="+id+"&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=ccfaff&amp;fullscreen=1";
				var x = new Array();
				var w = parseInt(data[1]);
				var h = parseInt(data[2]);
				var bgcolor = "#000000";
				w = w == 0 ? 681 : w;
				h = h == 0 ? 380 : h;
				
				x.push('<div class="videoEntry"><object width="'+w+'" height="'+h+'">');
					x.push('<param name="allowfullscreen" value="true" />');
					x.push('<param name="allowscriptaccess" value="always" />');
					x.push('<param name="movie" value="'+url+'" />');
					x.push('<param name="bgcolor" value="'+bgcolor+'" />');
					x.push('<embed src="'+url+'" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+w+'" height="'+h+'" bgcolor="'+bgcolor+'"></embed>');
				x.push('</object></div>');
				
				return x.join('');
			}
		}
		
		return "";
	}
	
	function getImageSource(src) {
		if(src == null) {
			return "";
		}

		
		var data = src.split(",");
		var w = parseInt(data[1]);
		var h = parseInt(data[2]);
		w = w == 0 ? 681 : w;
		h = h == 0 ? 380 : h;
		if(data.length >= 2) {
			return "<img src='"+data[0]+"' width='"+w+"' height='"+h+"' border='0' />";
		}
		
		return "";
	}

	
	
	
/*
 * CONTENT ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 */
	
	function loadContent(href) {
		scrollTo(0,0);
		if(href == "/" || href == "") {
			hideVisor();
			maincontent.empty();
			maincontent.html(cache_home);
			resize();
			section = "home";
		}else{
			$.getJSON("/api/content/get/?path="+escape(href), onLoadContent);
			showLoading();
			showVisor();
			maincontent.empty();
			section = "nothome";
		}
	}
	
	function onLoadContent(o) {
		hideLoading();
		if(o.error == "0") {
			maincontent.html(o.html);
			handleForms();
			resize();
		}else{
			alert(o.message);
		}
	}
	

	
/*
 * FORMS ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 */
	
	function handleForms() {
		//quick hack
		$("#maincontent form").submit(handleForm);
		$("#maincontent form a.formaction").click(handleFormSubmit);
	}
	
	
	function handleFormSubmit() {
		var a = $(this);
		a.parents("form").submit();
		return false;
	}
	
	function handleForm() {
		var f = $(this);
		var id = f.attr("id");
		switch(id) {
			case "formnewsletter" : handleNewsLetter();	break;
			default:
				alert("Unknown form");
		}
		return false;
	}
	
	function handleNewsLetter() {
		var email = $("#newsletteremail").val();
		if(validateEmail(email)) {
			showLoading();
			$.getJSON("/api/mailinglist/?go=SUBMIT&opt=in&email="+escape(email), onHandleNewsLetter);
		}else{
			alert("invalid email address");
		}
	}
	
	function onHandleNewsLetter(o) {
		hideLoading();
		if(o.error == "0") {
			$("#formnewsletter").hide();
			$("#newslettermsg").html("THANK YOU!");
		}else{
			alert(o.message);
		}
	}
	
/*
 * TOOLS ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 */
	/*
	 * Unscrambles a scrambled string, mainly used for emails
	 */
	function unscramble(s) {
		var result = "";
		for(var i = s.length - 1; i >= 0; i--) {
			var c = s.substr(i,1);
			if(c != "-") result += c; 
		}
		return result;
	}
	
	function validateEmail(email) {
	   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	   if(reg.test(email) == false) {
	      return false;
	   }
	   return true;
	}

	
	
	function showLoading() {
		visor.find("div.loading").show();
	}
	
	function hideLoading() {
		visor.find("div.loading").hide();
	}
	
	return {
		init: init,
		unscramble: unscramble,
		validateEmail: validateEmail,
		hashCheck : hashCheck
	}
}();



/* 
 * FullOn v0.1
 * A fullscreen filling / stretching background manager
 */

FullOn = function() {

	/*
	 * possible filltypes:
	 * RATIO_FILL 	stretches the image to fit the entire area keeping aspect ratio
	 */
	
	//dom elements
	var frame;
	var frameFlash;


	var flashLoaded = false;
	
	
	function init(id, filltype, wallpapers) {
		this.filltype = filltype;
		frame = $(id);
		
		
		var flashvars = new Object();
		for(var i = 0; i < wallpapers.length; i++) {
			flashvars["wallpaper"+i] = wallpapers[i];
		}
		swfobject.embedSWF("fullon.swf", "fullonflash", "100%", "100%", "10.0.0", "expressInstall.swf", flashvars, {wmode:"opaque", bgcolor: "#000000"});
		frameFlash = $("#fullonflash"); 
	}
	

	
	function resize(w, h) {
		frameWidth = w;
		frameHeight = h;
		frame.height(h);
		frameFlash.height(h);
		
		var windowWidth = $(window).width();
		frame.width(windowWidth);
		frameFlash.width(windowWidth);

	}
	
	function showFlash() {
		frameFlash.show();
		if(fmr("fullonflash").startRotation != undefined) {
			fmr("fullonflash").startRotation();
		}
	}
	
	function hideFlash() {
		frameFlash.hide();
		if(fmr("fullonflash").stopRotation != undefined) {
			fmr("fullonflash").stopRotation();
		}
	}
	
		
	function show() {
		frame.show();
	}
	
	function hide() {
		frame.hide();
	}
	
	function flashLoaded() {
		flashLoaded = true;
	}
	
	function fmr(movieName) {
		if (document.embeds && document.embeds[movieName]){
			return document.embeds[movieName]; 
		} else if (window.document[movieName]) {
			return window.document[movieName];
		} else {
			return document.getElementById(movieName);
		}
	}

	
	return {
		init: init,
		resize: resize,
		show: show,
		hide: hide,
		flashLoaded: flashLoaded,
		showFlash: showFlash,
		hideFlash: hideFlash
	}
}();