var is_loading = false;
var tm_loading = false;
var ct_loading = '';

function ajaxify_link(el) {
	if (is_loading || !el) {
		return false; // cancel quick clicks
	}
	new Request({
		method: 'get', 
		url: el.getProperty('href'),
		onRequest:function() {
			// called when calling: fade out
			if (ek = $$('#submenu a.current')) {
				ek.each(function(ej) {
					ej.removeClass('current');
				});
			}
			el.addClass('current');
			$('subcontent').tween('opacity',0);
			ajaxify_load();
		},
		onComplete:function() {
			// called right before success
			ajaxify_unload();
		},
		onSuccess:function(res) {
			ct_loading = res;
			window.setTimeout('ajaxify_content()',500);
		},
		onFailure:function() {
			$('subcontent').set('text','Uh oh something went wrong, please try again');
			$('subcontent').tween('opacity',1);
		}
	}).send();
}

function ajaxify_content() {
	ct = $('subcontent');
	ct.set('html',ct_loading);
	ct.scrollTo(0,0);
	ct.tween('opacity',1);
	ct_loading = '';
	is_loading = false;
}
function ajaxify_load(t) {
	is_loading = true;
	tm_loading = window.setTimeout('ajaxify_load_div()',1000);
}
function ajaxify_load_div() {
	new Element('div',{'id':'subload'}).inject('global','top');
}
function ajaxify_unload() {
	window.clearTimeout(tm_loading);
	if (el = $('subload')) {
		el.destroy();
	}
}

window.addEvent('domready', function() {
	var flnk = '';
	var url = '';
	if (window.location.hash) {
		url = '/'+window.location.hash.substring(1)+'.html';
	}
	if(lst = $$('#submenu a')) {
		lst.each(function(el) {
			el.addEvent('click', function(e) {
				e.stop();
				ajaxify_link(el);
			});
			if (url && url == el.get('href')) {
				flnk = el;
			} else if (!flnk) {
				flnk = el;
			}
		});	
	}
	
	if (url || $('subcontent').get('text').clean() == '') {
		ajaxify_link(flnk);
	}
});
