var loc;
var getPage = function(anchor, instant) {
	url = anchor.getProperty('href');
	newloc = url.substr(1);
	if ($(newloc).get('html') != '&nbsp;') {
		showPage(newloc, instant);
		window.location.hash = '!' + url.substr(1);
		loc = newloc;
	} else {
		new Request({
			'url': url,
			'method': 'get',
			'link': 'cancel',
			'onRequest': function() {
				$('loading').fade('show');
			},
			'onSuccess': function(txt) {
				$(newloc).empty();
				$(newloc).set('html', txt);
			},
			'onFailure': function(res) {
				$(newloc).set('html', res.responseText);
			},
			'onComplete': function() {
				showPage(newloc, instant);
				window.location.hash = '!' + url.substr(1);
				if (newloc == 'contact') {
					Asset.javascript('/scripts/validate.js');
				}
				$('loading').fade('hide');
				loc = newloc;
			}
		}).send();
	}
	$('header').getElements('ul a.active').removeClass('active');
	anchor.addClass('active');
};
var showPage = function(id, instant) {
	var mod = 0 - $('content').getChildren('div').indexOf($(id));
	if (instant) {
		$('content').setStyle('left', mod*900);
	} else {
		$('content').set('tween', {'duration': 500, 'transition': Fx.Transitions.Sine.easeOut}).tween('left', mod*900);
	}
	if (id == 'home') {
		document.title = 'Home - Tim Wienk .nl';
	} else if (id == 'whoiam') {
		document.title = 'Who I Am - Tim Wienk .nl';
	} else if (id == 'whatido') {
		document.title = 'What I Do - Tim Wienk .nl';
	} else if (id == 'contact') {
		document.title = 'Contact - Tim Wienk .nl';
	} else {
		document.title = 'Tim Wienk .nl';
	}
}
window.addEvent('domready', function() {
	if (loc = $('container').getElement('div.content').getProperty('id')) {
		if (loc != 'home') {
			new Element('div', {'id': 'home', 'class': 'content', 'html': '&nbsp;'}).inject(loc, 'before');
		}
		if (loc != 'whoiam') {
			new Element('div', {'id': 'whoiam', 'class': 'content', 'html': '&nbsp;'}).inject('home', 'after');
		}
		if (loc != 'whatido') {
			new Element('div', {'id': 'whatido', 'class': 'content', 'html': '&nbsp;'}).inject('whoiam', 'after');
		}
		if (loc != 'contact') {
			new Element('div', {'id': 'contact', 'class': 'content', 'html': '&nbsp;'}).inject('whatido', 'after');
		}
		new Element('div', {'id': 'loading', 'html': '<img src="/skin/loading.gif" alt="Loading..." /><br />Loading...'}).inject('container', 'bottom');
		$('loading').fade('hide');
	}
	$('header').getElements('ul a').addEvent('click', function(e) {
		if (e) e.stop();
		getPage(this);
	});
	if (window.location.hash) {
		if (['home','whoiam','whatido','contact'].indexOf(window.location.hash.substr(2)) > -1) {
			$('header').getElements('ul a').each(function(anchor) {
				if (anchor.getProperty('href') == '/'+window.location.hash.substr(2)) {
					getPage(anchor, true);
				}
			});
		}
	} else {
		showPage('home', true);
	}
});
