$(function () { x.init(); });

var x = {
	PROJECTS: 'projects',
	DOTS: [[[65,0],[65,27], [65,81],[65,108],[11,54,1],[38,54]],
		   [[26,8],[26,100],[50,32],[50,78], [71,54,1]]],
	SPEED_IN: 'slow',
	SPEED_OUT: 'medium',
	BKGD_IN: 2000,
	BKGD_OUT: 1000,
	SPEED_FLASH: 500,
	SPEED_GLOW: 4000,
	PHOTO_W: 506,
	PAGE_H: 424,
	PHOTO_SCRIM: 0.5,
	PAGE_SCRIM: 0.5,
	SLIDESHOW_PAUSE: 3000,
	startImage: null,
	IMAGES: {},
	activeState: {},
	catMap: {},
	busy: false,
	firstProject: true,
	slideShow: null,
	debug: null,
	DEBUG: false,
	
	init: function()
	{
		x.debug = $('#debug');
		x.slideShow = {};
		
		// roll-over on main menu <li> items
		$('#header li').each(function() {
			$(this).bind('mouseover', function() { $(this).addClass('hover'); });
			$(this).bind('mouseout', function() { $(this).removeClass('hover'); });
		});
		
		// click action on main menu
		$('#header li a').each(function() {
			x.setSegments(this);
			if (!(this.page == x.PROJECTS && this.cat == '' & this.proj == ''))
			{
				$(this).bind('click', function() { x.setState(x.makePath(this)); });
			}
		});
		
		$('ul#project-list a').livequery(function() {
			x.setSegments(this);
			$(this).bind('click', function() { x.setState(x.makePath(this)); });
		});
		
		// add scroll bars
		$('.scrolling').livequery(function() {
			$(this).jScrollPane({'scrollbarWidth': 11});
		});
		
		// project dots
		$('#dots').livequery(function() {
			$(this).children('span').each(function(){
				var i = 0;
				var dotContainer = this;
				var dir = ($(this).hasClass('dir-0') ? -1 : 1);
				var href = $(this).children('a').attr('href');
				this.href = href;
				var dotIndex = (dir == -1 ? 0 : 1);
				$(this).children('a').remove();
				x.shuffle($(x.DOTS[dotIndex])).each(function(){
					var dot = document.createElement('a');
					$(dot)
						.css('left', this[0] + 'px')
						.css('top', this[1] + 'px')
						.css('opacity', 0)
						.appendTo(dotContainer)
						.bind('click', function() { x.setState(x.makePath(this), this); x.stopFlashing(); })
						.hover(function() { $(this).stop().removeClass('glowing').css('opacity', 1); }, function() { $(this).removeClass('in').addClass('out').addClass('glowing'); });
					if (this[2])
					{
						$(dot).addClass('always-on');
					}
					dot.href = href;
					dot._dir = dir;
					x.setSegments(dot);
					setTimeout(function() { x.glow(dot); }, i++ * 1600);
				});
			});
			//if (x.firstProject)
			//{
				x.flashDot();
			//}
			x.updateDotState();
		});

		// flashing dots
		$('#dots a.flashing.in').livequery(function() {
			$(this).animate({'opacity': 1}, x.SPEED_FLASH, function() { $(this).removeClass('in'); $(this).addClass('out'); });
		});
		
		$('#dots a.flashing.out').livequery(function() {
			$(this).animate({'opacity': 0}, x.SPEED_FLASH, function() { $(this).removeClass('out'); $(this).addClass('in'); });
		});
		
		// glowing dots
		$('#dots a.glowing.in:not(.flashing)').livequery(function() {
			$(this).animate({'opacity': 1}, x.SPEED_GLOW, 'easeInCubic', function() { $(this).removeClass('in'); $(this).addClass('out'); });
		});
		
		$('#dots a.glowing.out:not(.flashing)').livequery(function() {
			$(this).animate({'opacity': 0}, x.SPEED_GLOW, 'easeOutCubic', function() { $(this).removeClass('out'); $(this).addClass('in'); });
		});
		
		// prepare to replace background image
		$('#page').addClass('script').css('opacity', 0);
		$('img.bkgd').hide();
		
		// set interval to check for new hash
		setInterval('x.checkState()', 100);
		x.checkState();
	},
	
	setState: function(path, a)
	{
		if (!a && x.activeState.path && path == x.activeState.path) { return; } // no change
		if (x.busy) { return; } // cancel

		if (x.slideShow.active)
		{
			clearTimeout(x.slideShow.interval);
			x.slideShow.interval = null;
			x.slideShow.active = false;
		}
		
		var prevPage = x.activeState.page;
		var prevCat = x.activeState.cat;
		var prevProj = x.activeState.proj;
		var prevPhoto = x.activeState.photo;

		// update x.activeState
		x.setSegments(x.activeState, path);

		// special case: if choosing project categories from a page other than projects, don't load new page (until a project is selected)
		if (x.activeState.page == x.PROJECTS && prevPage != x.PROJECTS && prevPage && x.activeState.proj == '' && prevPage)
		{
			x.activeState.page = prevPage;
		}
		
		// check for page change
		if ((x.activeState.page != prevPage && x.activeState.page != x.PROJECTS) || !x.activeState.cat || !prevPage)
		{
			x.showPage();
		}
		
		if (!x.activeState.path || !x.activeState.cat)
		{
			// hide cat container
			$('#cat').css('opacity', 0);
		}
		
		var noBack = (a && a._dir == -1 && prevPhoto < 2);
		var noNext = (a && a._dir ==  1 && $('#photo-number').hasClass('last'));
		var doShowPhoto = false;
		
		if (a)
		{
			if (noBack || noNext)
			{
				x.activeState.photo = prevPhoto;
			} else
			{
				x.activeState.photo = prevPhoto + a._dir;
			}
			x.updateState();
			doShowPhoto = (x.activeState.photo != prevPhoto);
		} else
		{
			doShowPhoto = true;
		}
		
		// unset previous state
		if (x.activeState.path)
		{
			$('#header ul li#m-' + prevPage).removeClass('selected');
			if (prevCat)
			{
				$('#header ul ul li#p' + x.catMap[prevCat]).removeClass('selected');
				if (prevProj && prevProj != x.activeState.proj)
				{
					$('a#project-' + prevProj).removeClass('selected');
				}
			}
		}
		
		if (x.activeState.path)
		{
			location.hash = x.activeState.path;

			// page: set background-position of main menu item
			$('#header ul li#m-' + x.activeState.page).addClass('selected');
			
			if (x.activeState.cat)
			{
				if (x.activeState.cat != prevCat)
				{
					$('#header ul ul li#p' + x.catMap[x.activeState.cat]).addClass('selected');
					
					// load the project category
					x.showCat();
				} else
				if (x.activeState.proj != prevProj)
				{
					x.showProject();
				}
				
				if (doShowPhoto)
				{
					x.showPhoto();
				}
			}
		}
		
		document.title = 'Iconstrux - ' + x.toDocTitle(path);
	},
	
	updateState: function()
	{
		x.activeState.path = x.makePath();
	},
	
	showPage: function(onComplete)
	{
		x.busy = true;
		$('#page').animate({'opacity': 0}, x.SPEED_OUT).load('_page.php', { 'page': x.activeState.page, 'cat': x.activeState.cat, 'proj': x.activeState.proj }, function() { x.onShowPage(); if (onComplete) { onComplete(); } } );
	},
	
	onShowPage: function()
	{
		// init state
		$('#photo-loading').hide().css('background-color', '#4D4D4D');
		//$('#page-loading').hide().css('background-color', '#4D4D4D');
		$('#photo-number').css('opacity', 0.7);
		
		// also load page text
		if (x.activeState.page != x.PROJECTS)
		{
			$('#cat').load('_text.php', { 'page': x.activeState.page }, x.onShowCat);
		}
		
		$('img.bkgd').each(function() { x.replaceImage(this); });
	},
	
	showPhoto: function()
	{
		if (!(x.activeState.photo > 0)) { return; }
		
		x.busy = true;
		$('#photo-loading').css('width', 0).css('opacity', x.PHOTO_SCRIM).show().animate({'width': x.PHOTO_W}, x.SPEED_IN);
		$('#photo').animate({'opacity': 0}, x.SPEED_OUT).load('_project-photo.php', { 'proj': x.activeState.proj, 'photo': x.activeState.photo }, x.onShowPhoto);
	},
	
	onShowPhoto: function(result)
	{
		x.updateDotState();
		
		var src = $('#project-photo').attr('src');
		var loader = new Image();
		$(loader).load(function ()
		{
			x.onLoadProjectPhoto();
		})
		.attr('src', src);
	},
	
	updateDotState: function()
	{
		var noBack = !(x.activeState.photo > 1);
		var noNext = $('#photo-number').hasClass('last');
		
		if (noBack)
		{
			$('#dots .dir-0').fadeOut();
		} else
		{
			$('#dots .dir-0').fadeIn();
		}
		if (noNext)
		{
			$('#dots .dir-1').fadeOut();
		} else
		{
			$('#dots .dir-1').fadeIn();
		}
	},
	
	onLoadProjectPhoto: function()
	{
		$('#photo-loading').animate({'opacity': 0}, x.SPEED_OUT, function() { $(this).hide(); } );
		$('#photo').stop().css('opacity', 0).animate({'opacity': 1}, x.SPEED_IN, function() { x.busy = false; });
	},
	
	showCat: function()
	{
		x.busy = true;
		$('#cat').animate({'opacity': 0}, x.SPEED_OUT).load('_project-category.php', { 'cat': x.activeState.cat }, x.onShowCat);
	},
	
	onShowCat: function()
	{
		if ($('#cat .scrolling').length > 0)
		{
			$('#cat').stop().css('opacity', 0).animate({'opacity': 1}, x.SPEED_IN, function() { x.busy = false; });
		}
		if (x.activeState.page == x.PROJECTS)
		{
			x.showProject();
		}
	},
	
	showProject: function() 
	{
		if (x.activeState.proj)
		{
			x.busy = true;
			$('a#project-' + x.activeState.proj).addClass('selected');
			$('#project').animate({'opacity': 0}, x.SPEED_OUT).load('_project.php', { 'proj': x.activeState.proj }, x.onShowProject);
			x.showPage(x.showPhoto);
		}
	},
	
	onShowProject: function()
	{
		$('#project').stop().css('opacity', 0).animate({'opacity': 1}, x.SPEED_IN, function() { x.busy = false; });
	},
	
	setSegments: function(a, path)
	{
		if (!path && a.href) 
		{ 
			path = a.href; 
			x.voidHref(a); 
		}
		
		// extract segments (page, cat, proj) from path
		segments = path.match('(' + x.BASE + '_\/)?\/?([^/]*)\/?([^/]*)\/?([^/]*)\/?([^/]*)');
		
		a.page  = segments[2] ? segments[2] : ''; // page
		a.cat   = segments[3] ? segments[3] : ''; // cat
		a.proj  = segments[4] ? segments[4] : ''; // proj
		a.photo = segments[5] ? parseInt(segments[5]) : 0; // photo
		
		a.path = x.makePath(a);
	},
	
	checkState: function()
	{
		var path = x.normalizeHash(location.hash);
		if (!x.activeState || path != x.activeState.path)
		{
			x.setState(path);
		}
	},
	
	normalizeHash: function(hash)
	{
		if (hash.charAt(0) == '#')
		{
			return hash.substr(1);
		} else
		{
			return hash;
		}
	},
	
	toDocTitle: function(str)
	{
		return str.replace(/-|\+/g, ' ').replace(/\//g, ' - ').replace(/\b[a-z]/g, cnvrt);
        function cnvrt() {
            return arguments[0].toUpperCase();
        }
	},
	
	makePath: function(a)
	{
		if (!a) { a = x.activeState; }
		return a.page ? a.page + (a.cat ? '/' + a.cat + (a.proj ? '/' + a.proj  + (a.photo ? '/' + a.photo : ''): '') : '') : '';
	},
	
	voidHref: function(a)
	{
		// only do it once
		a._href = a.href;
		a.href = 'javascript:void(0);';
	},
	
	replaceImage: function(img)
	{
		// img with id="_foo" replaces background image of id="foo"
		$(img).remove();
		
		// wrap our new image in jQuery, then:
		x.busy = true;
		x.slideShow.index = x.startImage;
		var onComplete;
		if (x.IMAGES[x.activeState.page] > 1)
		{
			x.slideShow.active = true;
			onComplete = x.onBkgdImage;
		}
		x.loadImage(img.src, img.id.substr(1), onComplete);
	},
	
	onBkgdImage: function()
	{
		//$('#page-loading').animate({'opacity': 0}, x.SPEED_OUT, function() { $(this).hide(); } );
		if (!x.slideShow.active) { return; }
		x.slideShow.interval = setTimeout('x.loadNextSlide()', x.SLIDESHOW_PAUSE);
	},
	
	loadNextSlide: function()
	{
		if (x.slideShow.index >= x.IMAGES[x.activeState.page])
		{
			x.slideShow.index = 1;
		} else
		{
			x.slideShow.index++;
		}
		
		//$('#page-loading').css('width', 0).css('opacity', x.PAGE_SCRIM).show().animate({'width': $(document).width()}, x.SPEED_IN);
		$('#page').stop().css('opacity', 1).animate({ 'opacity': 0}, x.BKGD_OUT, function() { x.loadImage(x.BASE + 'img/' + x.activeState.page + '/' + x.slideShow.index + '.jpg', 'page', x.onBkgdImage); });
	},
	
	loadImage: function(src, id, onComplete)
	{
		if (!onComplete) { onComplete = function() {}; }
		
		var loader = new Image();
		$(loader).load(function ()
		{
			$('#'+id)
				.css('background-image', "url(\""+src+"\")")
				//.stop()
				.css('opacity', 0)
				.animate({ 'opacity': 1 }, x.BKGD_IN, null, function() { x.busy = false; onComplete(); } );
			$(this).remove();
		})
		.attr('src', src);
	},
	
	stopFlashing: function()
	{
		$('#dots a.flashing').each(function() {
			$(this).removeClass('flashing');
		});
		x.firstProject = false;
	},
	
	flashDot: function()
	{
		var dots = $('#dots span.dir-1 a.always-on');
		var dot = dots[0]; // dots[Math.floor(Math.random() * dots.length)];
		$(dot).addClass('flashing in');
	},
	
	glow: function(dot)
	{
		$(dot).addClass('glowing in');
	},
	
	shuffle: function(arr)
	{
		for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
		return arr;
	},
	
	trace: function(msg)
	{
		if (!x.DEBUG) return;
		x.debug.append(msg + '; ');
	}
}
	
var mailto = function()
{
	var a, b, c, d, id;
	a = mailto.arguments;
	var id = a[0];
	var b = a[1];
	var c = "";
	for (var i=0; i<10; i++)
	{
		var d = b.indexOf(i) + 2;
		c += a[d];
	}
	$('#' + id).html(c);
}