/*
 * Interface builder
 *
 * Copyright 2009 Grant Zanetti
 *
 * Super deep nesting is for wins
 */

var tree;
var about;
var tree_sec = new Array();

$(document).ready(function () {

	$.ajaxSetup({ cache: false });

	$.getJSON('config/tree.json', function(json) {

		tree = json;

		// Outer div
		var od = document.createElement('div');
		od.className = 'outer';

		for (var i = 0; i < tree.length; i++)
		{
			var s = createSection(tree[i]);
			if (tree[i].opt)
				tree_sec[tree[i].opt[0]] = tree[i];
			od.appendChild(s);
		}

		addWindowBars(od);

		document.body.appendChild(od);

		var link = getAlbumFromHref();
		if (link)
			if (tree_sec[link])
				setTimeout(function() { $(tree_sec[link].pd.childNodes[1].firstChild).click(); }, 1000 );
	});

	$.getJSON('config/about.json', function(json) {

		about = json;
	});
});

// --------------------------------------------------------

function createSection(cfg)
{
	// Tree div
	var td = document.createElement('div');
	td.className = 'tree';
	$(td).hide();

	// Word div
	var wd = document.createElement('div');
	wd.className = 'word';

	// Tree image
	var ti = document.createElement('img');
	ti.onload = function() { $(td).fadeIn(); }
	ti.src = cfg.tree_img;
	ti.width = 200;
	ti.height = 200;

	// Word image
	var wi = document.createElement('img');
	wi.src = cfg.word_img;
	wi.width = 200;
	wi.height = 200;
	wi.cfg = cfg;

	td.appendChild(ti);
	wd.appendChild(wi);

	// Positioning div
	var pd = document.createElement('div');
	pd.className = 'cell';

	if (cfg.module == 'gallery')
		$.getJSON('gallery/' + cfg.opt[0] + '/gallery.json', function(json) { cfg.gallery = json; cfg.loaded = true; });

	$(pd).bind('mouseenter', function(e) {
		if (!e.target.cfg.module)
			return;

		var c = $(e.target.parentNode.parentNode).children();
		$(c[0]).fadeTo('slow', 0.4);
		$(c[1]).fadeTo('slow', 1);
	}).bind('mouseleave', function(e) {
		if (!e.target.cfg.module)
			return;

		var c = $(e.target.parentNode.parentNode).children();
		$(c[0]).fadeTo('slow', 1);
		$(c[1]).fadeTo('slow', 0);
	}).bind('click', function(e) {
		if (!e.target.cfg.module)
			return;

		var tl = $(tree[0].pd).offset();

		var o = document.createElement('div');
		o.className = 'overlay';
		$(o).css({
			top: tl.top + 'px',
			left: tl.left + 'px'
		});

		var tp = $(e.target).offset();
		var d = document.createElement('div');
		d.className = 'page';
		$(d).css({
			top: tp.top + 'px',
			left: tp.left + 'px',
			opacity: 0
		});
		d.overlay = o;
		d.origin = e.target.cfg;

		var c = document.createElement('button');
		c.className = 'close';
		c.innerHTML = 'X';

		document.body.appendChild(o);
		document.body.appendChild(d);

		var h = document.createElement('div');

		$(d).animate({ 
		        'min-width': "600px",
		        width: "600px",
		        'min-height': "600px",
		        height: "600px",
		        top: tl.top + "px",
		        left: tl.left + "px",
			opacity: 1
		}, 1500, function() { 
			d.style.opacity = '';
			d.style.filter = '';
			if (cfg.title)
			{
				h.className = 'title';
				h.innerHTML = cfg.title;

				d.appendChild(h);
			}

			d.appendChild(c); 

			switch(cfg.module)
			{
				case 'gallery':
					var b = document.createElement('div');
					b.className = 'blurb';

					var i = document.createElement('div');
					i.className = 'image';

					var t = document.createElement('div');
					t.className = 'thumbs';

					var border = document.createElement('div');
					border.className = 'border';
					t.appendChild(border);

					var up = document.createElement('a');
					up.className = 'prev browse left';
					t.appendChild(up);

					var scrollable = document.createElement('div');
					scrollable.className = 'vertical';
					t.appendChild(scrollable);

					var items = document.createElement('div');
					items.className = 'items';
					scrollable.appendChild(items);

					var down = document.createElement('a');
					down.className = 'next browse right';
					t.appendChild(down);

					var group_con = document.createElement('div');
					group_con.className = 'group_panel';
					$(group_con).hide();

					var gi = document.createElement('div');
					gi.className = 'group_inner';

					group_con.appendChild(gi);

					var con = document.createElement('div');
					con.className = 'group_controls';

					group_con.appendChild(con);

					var artist_con = document.createElement('div');
					artist_con.className = 'artist_panel';

					var ai = document.createElement('div');
					ai.className = 'artist_inner';

					var ah = document.createElement('div');
					ah.className = 'artist_handle';
					pos = $(d).offset().left;
					$(ah).bind('click', function(e) {
						if (ai.clientWidth > 100)
						{
							$(ai).animate({
								left: "0px",
								width: "30px"
							}, 1000);
							$(d).animate({
								left: pos + "px"
							}, 1000);
						}
						else
						{
							$(ai).animate({
								left: "-280px",
								width: "310px"
							}, 1000);
							$(d).animate({
								left: pos + 135 + "px"
							}, 1000);
						}
					});

					var as = document.createElement('div');
					as.className = 'artist_statement';

					ai.appendChild(ah);
					ai.appendChild(as);
					$(ai).hide();

					artist_con.appendChild(ai);

					for (var is = 0; is < cfg.gallery.sets.length; is++)
					{
						for (var l = 0; l < cfg.gallery.sets[is].images.length; l++)
						{
							cfg.gallery.sets[is].images[l]._setIndex = l + 1;

							var div = document.createElement('div');

							var thumb = document.createElement('img');
							$(thumb).hide();

							$(thumb).bind('load', function() { 
								$(this).fadeIn(function() { 
									this.style.opacity = ''; 
									this.style.filter = ''; 
								});
							});

							thumb.src = 'gallery/' + cfg.opt[0] + '/' + cfg.gallery.sets[is].images[l].thumb;

							addThumbClick(d, i, b, cfg, cfg.gallery.sets[is].images[l], div, cfg.gallery.sets[is], group_con, ai);

							div.appendChild(thumb);
							items.appendChild(div);
						}
					}

					d.appendChild(i);
					d.appendChild(t);
					d.appendChild(b);
					d.appendChild(group_con);
					d.appendChild(artist_con);

					img_idx = getImgIdx();

					$(scrollable).scrollable({ 
						vertical: true,  
						size: 5,
						api: true
					}).click(img_idx || 0);

					$(items.childNodes[img_idx || 0]).click();

					break;
				case 'about':
					var outer = document.createElement('div');
					outer.className = 'about';

					var scroller = document.createElement('div');
					scroller.className = 'about_text';

					var img = document.createElement('img');
					img.className = 'about_image';
					img.width = 150;
					img.height = 164;
					img.src = about.image;

					scroller.appendChild(img);
					scroller.innerHTML += about.text;

					outer.appendChild(scroller);

					d.appendChild(outer);

					break;
				case 'contact':
					var label;
					var value;
					var row = new Array();

					var outer = document.createElement('div');
					outer.className = 'contact';

					// ROW 0 -----------------------------------------------
					row[0] = document.createElement('div');
					row[0].className = 'contact_row';

					label = document.createElement('div');
					label.className = 'contact_label';
					label.innerHTML = 'From';

					value = document.createElement('div');
					value.className = 'contact_value';

					var email_from = document.createElement('input');
					email_from.type = 'text';
					$(email_from).addClass('from_empty');
					email_from.value = 'you@youraddress.com';
					$(email_from).bind('focus', function() {
						if (email_from.value == 'you@youraddress.com')
						{
							$(email_from).removeClass('from_empty');
							email_from.value = '';
						}
					}).bind('blur', function() {
						if (!email_from.value)
						{
							$(email_from).addClass('from_empty');
							email_from.value = 'you@youraddress.com';
						}
					});

					value.appendChild(email_from);

					row[0].appendChild(label);
					row[0].appendChild(value);

					// ROW 1 -----------------------------------------------
					row[1] = document.createElement('div');
					row[1].className = 'contact_row';

					label = document.createElement('div');
					label.className = 'contact_label';
					label.innerHTML = 'Subject';

					value = document.createElement('div');
					value.className = 'contact_value';

					var email_subject = document.createElement('input');
					email_subject.type = 'text';

					value.appendChild(email_subject);

					row[1].appendChild(label);
					row[1].appendChild(value);

					// ROW 2 -----------------------------------------------
					row[2] = document.createElement('div');
					row[2].className = 'contact_row';

					label = document.createElement('div');
					label.className = 'contact_label';
					label.innerHTML = 'Body';

					value = document.createElement('div');
					value.className = 'contact_value';

					var email_body = document.createElement('textarea');

					value.appendChild(email_body);

					row[2].appendChild(label);
					row[2].appendChild(value);

					// ROW 3 -----------------------------------------------
					row[3] = document.createElement('div');
					row[3].className = 'contact_row';

					label = document.createElement('div');
					label.className = 'contact_label';
					label.innerHTML = '&nbsp;';

					value = document.createElement('div');
					value.className = 'contact_submit';

					var email_submit = document.createElement('button');
					email_submit.innerHTML = 'Send';
					email_submit.onclick = function() {
						var json = new Object;

						json.from = email_from.value;
						json.subject = email_subject.value;
						json.body = email_body.value;

						if (!json.from.match(/.+@.+\..+/) || json.from == 'you@youraddress.com')
						{
							popup('Invalid email address');
							return;
						}

						if (!json.subject)
						{
							popup('Empty email subject');
							return;
						}

						if (!json.body)
						{
							popup('Empty email body');
							return;
						}

						$.post('email.cgi', json, function(data) {
							if (data.err == 'OK')
							{
								d.innerHTML = '';
								var pos = $(d.origin.pd).offset();
								$(d).animate({ 
								        width: "200px",
								        height: "200px",
								        top: pos.top + "px",
								        left: pos.left + "px",
									opacity: 0
								}, 1500, function() {
									if (this.parentNode)
									{
										this.parentNode.removeChild(this.overlay); 
										this.parentNode.removeChild(this); 
									}
									popup('Sent!');
								});
							}
							else
								popup('Error: ' + data.err);
						}, 'json');
					};

					value.appendChild(email_submit);

					row[3].appendChild(label);
					row[3].appendChild(value);

					for (var i = 0; i < row.length; i++)
						outer.appendChild(row[i]);
					
					d.appendChild(outer);

					break;
				default:
					break;
			}
		});

		$(c).bind('click', function(e) { 
			var cp = c.parentNode;
			cp.innerHTML = '';
			var pos = $(cp.origin.pd).offset();
			$(cp).animate({ 
			        'min-width': "200px",
			        width: "200px",
			        'min-height': "200px",
			        height: "200px",
			        top: pos.top + "px",
			        left: pos.left + "px",
				opacity: 0
			}, 1500, function() {
				if (this.parentNode)
				{
					this.parentNode.removeChild(this.overlay); 
					this.parentNode.removeChild(this); 
				}
			});
		});
	});

	cfg.pd = pd;

	pd.appendChild(td);
	pd.appendChild(wd);

	return(pd);
}

function addThumbClick(d, area, blurb, cfg, entry, thumb, set, gc, ac)
{
	$(thumb).bind('click', function (e) {
		var div = document.createElement('div');
		$(div).css({
			'width': entry.width + 'px',
			'title': entry.title + 'px',
			'position': 'absolute',
			'margin-left': ((area.clientWidth - entry.width) / 2) + 'px',
			'margin-top': ((area.clientHeight - entry.height) / 2) + 'px'
		});
		$(div).hide();

		var img = document.createElement('img');

		div.appendChild(img);
		area.appendChild(div);

		$(img).bind('load', function() { 
			$(div).fadeIn('slow', function() {
				blurb.innerHTML = '<div style="position: relative; float: left;">' + entry.year + ', <i>' + entry.title + '</i> [' + entry.media + ' ' + entry.measurement + ']</div>';
				blurb.firstChild.style.paddingLeft = ((blurb.clientWidth - blurb.firstChild.offsetWidth) / 2) + 'px';
			});

			if (area.childNodes.length > 1)
			{
				$(area.firstChild).fadeOut('slow', function() {
					area.removeChild(area.firstChild);
				}) 
			}

			if (set.images.length > 1)
			{
				var text = set.name.replace(/ /, '&nbsp;') + '&nbsp;-&nbsp;' + entry._setIndex + '&nbsp;of&nbsp;' + set.images.length;
				gc.childNodes[1].innerHTML = text;
				gc.childNodes[1].style.left = ((gc.clientWidth - gc.childNodes[1].clientWidth) / 2) + 'px';
				$(gc).fadeIn();
				gc.childNodes[1].style.left = ((gc.clientWidth - gc.childNodes[1].clientWidth) / 2) + 'px';
			}
			else
			{
				$(gc).fadeOut();
			}

			var statement = entry.statement;
			if (!statement)
				statement = set.statement;

			if (!statement)
			{
				if (ac.clientWidth > 100)
				{
					$(ac).animate({
						left: "0px",
						width: "30px"
					}, 1000);
					$(d).animate({
						left: pos + "px"
					}, 1000, function() { $(ac).fadeOut() });
				}
				else
					$(ac).fadeOut();
			}
			else
			{
				ac.childNodes[1].innerHTML = '<p style="text-align: justify; line-height: 20px;">' + statement + '</p>';
				$(ac).fadeIn();
			}
		});

		img.src = 'gallery/' + cfg.opt[0] + '/' + entry.image;
	});
}

function getGalleryJson(cfg)
{
	var http = new HTTP('gallery/' + cfg.opt[0] + '/gallery.js');
	http.onSuccess(function(json) {
		cfg.gallery = json;
		cfg.loaded = true;
	});
	http.send();
}

function addWindowBars(od)
{
	var d = document.createElement('div');
	$(d).css({ 'clear': 'both' });

	od.appendChild(d);

	d = document.createElement('div');
	$(d).css({
		'position': 'absolute',
		'top': '190px',
		'left': '0px',
		'width': '600px',
		'height': '20px',
		'background-color': '#fff'
	});

	od.appendChild(d);

	d = document.createElement('div');
	$(d).css({
		'position': 'absolute',
		'top': '390px',
		'left': '0px',
		'width': '600px',
		'height': '20px',
		'background-color': '#fff'
	});

	od.appendChild(d);

	var d = document.createElement('div');
	$(d).css({
		'position': 'absolute',
		'left': '190px',
		'top': '0px',
		'height': '600px',
		'width': '20px',
		'background-color': '#fff'
	});

	od.appendChild(d);

	d = document.createElement('div');
	$(d).css({
		'position': 'absolute',
		'left': '390px',
		'top': '0px',
		'height': '600px',
		'width': '20px',
		'background-color': '#fff'
	});

	od.appendChild(d);

	d = document.createElement('div');
	$(d).css({
		'position': 'absolute',
		'left': '0px',
		'bottom': '-20px',
		'background-color': '#fff',
		'font-size': '10px',
		'margin-left': '5px'
	});
	d.innerHTML = "Copyright 2009 Justine Giles"

	od.appendChild(d);

}

function popup(text)
{
	var div = document.createElement('div');
	div.className = 'popup';
	$(div).css({
		'position': 'absolute',
		'left': '-1000px'
	});

	document.body.appendChild(div);

	div.innerHTML = text;

	var top = (($(document.body).innerHeight() - div.clientHeight) / 3) + 'px';
	var left = (($(document.body).innerWidth() - div.clientWidth) / 2) + 'px';

	$(div).hide().css({'top':  top, 'left': left}).fadeIn();

	setTimeout(function() { $(div).fadeOut(function() { document.body.removeChild(div); }) }, 4000);
}

function hrefParts()
{
	var parts = new Array;

	var hash = document.location.href.split(/#/);
	if (hash[1])
		parts = hash[1].split(/:/);

	return(parts);
}


function getImgIdx()
{
	var img_idx = 0;
	
	var p = hrefParts();
	if (p[1])
		img_idx = p[1];

	return(img_idx);
}

function getAlbumFromHref()
{
	var album = null;
	
	var p = hrefParts();
	if (p[0])
		album = p[0];

	return(album);
}


