$(window).addEvent('domready', function() { AjaxLink.init(); });

AjaxLink = {};
AjaxLink.fx = null;
AjaxLink.loaded = null;
AjaxLink.domain = 'http://colorsalley.com';
AjaxLink.links = null;

AjaxLink.init = function() {
	this.links = $(document.body).getElements('a[rel=ajax]')
	this.links.removeEvent('click', this.catchLinks);
	this.links.addEvent('click', this.catchLinks);
	
	if (!this.loaded) {
		this.loaded = true;
		var href = location.href.replace(this.domain, '');
		if (href.length > 4) {
			if (href.indexOf('#') == -1) {
				$('content').setStyle('display', 'none');
				location.href = href.substr(0, 4) + '#/' + href.substr(4);
			}
			else {
				var a = null;
				for (var i = 0; i < this.links.length; i++)
					if (this.links[i].get('href') == href.replace(/\/#/, '')) {
						a = this.links[i];
						break;
					}
				if (a == null)
					a = new Element('a', { href: href.replace(/\/#/, '') });
				this.processLink(a);
			}
		}
	}
}

AjaxLink.catchLinks = function(event) {
	var a = $(event.target);
	event.stop();
	
	if (a.tagName != 'A') a = a.getParent('a');
	
	AjaxLink.processLink(a);
}

AjaxLink.processLink = function(a) {
	// update browser url
	this.ajaxHref(a.get('href'));
	
	// send request
	new Request.HTML({
		update: 'content',
		url: a.get('href'),
		onRequest: function() {
			$('content').setStyles({ height: $('content').getSize().y, overflow: 'hidden' });
			
			var div = new Element('div');
			div.setStyles({ background: 'url(/images/ajax-loader.gif) no-repeat center', height: 150 });
			$('content').set('html', '');
			$('content').grab(div);
			
			AjaxLink.fx = new Fx.Morph('content');
			AjaxLink.fx.start({ height: 150 })
		},
		onComplete: function() {
			AjaxLink.fx.cancel();
			$('content').setStyles({ height: 'auto' });
		}
	}).send();
}

AjaxLink.ajaxHref = function(href) {
	var tmp = href.split('/');
	var ret = '#';
	for (var i = 2; i < tmp.length; i++)
		ret += '/' + tmp[i];
		
	if (location.href.indexOf('#') == -1)
		location.href += ret;
	else
		location.href = location.href.replace(/#.*/, ret);
}
