var cached_pages = {};

function loadPage(elm, page, e)
{
	if (e)
		e.preventDefault();
	
	$('#container').animate({opacity: 0}, 'fast', function() {
		if (cached_pages[page])
		{
			$('#container')
			.html(cached_pages[page])
			.animate({opacity: 1}, 'slow');
			curr = $('#navbar > ul > li > a > img.active').removeClass('active').get(0);
			if (curr && curr.src.indexOf('_hover.png') != -1)
				curr.src = curr.src.replace('_hover.png', '.png');
			elm = $('> img:not(.active)', elm).addClass('active').get(0);
			if (elm && elm.src.indexOf('_hover.png') == -1)
				elm.src = elm.src.replace('.png', '_hover.png');

			_l = window.location;
			_l.href = _l.protocol + '//' + _l.hostname + _l.pathname + '#' + page;
		}
		else
		{
			$('.loading').fadeIn('slow');
			$.get('ajax.php?page=' + page, function(data) {
				if (!data)
				{
					data = '<h1>Some error has occured, we cannot complete your request</h1>';
				}
				cached_pages[page] = data;
				$('.loading').fadeOut('fast');
				$('#container')
				.html(data)
				.animate({opacity: 1}, 'slow');
				curr = $('#navbar > ul > li > a > img.active').removeClass('active').get(0);
				if (curr && curr.src.indexOf('_hover.png') != -1)
					curr.src = curr.src.replace('_hover.png', '.png');
				elm = $('> img:not(.active)', elm).addClass('active').get(0);
				if (elm && elm.src.indexOf('_hover.png') == -1)
					elm.src = elm.src.replace('.png', '_hover.png');

				_l = window.location;
				_l.href = _l.protocol + '//' + _l.hostname + _l.pathname + '#' + page;
			});
		}
	});
}

$(function() {
	$('#navbar > ul > li > a > img').hover(function() {
		if (!$(this).hasClass("active") && this.src.indexOf('_hover.png') == -1)
			this.src = this.src.replace('.png', '_hover.png');
	}, function() {
		if (!$(this).hasClass("active") && this.src.indexOf('_hover.png') != -1)
			this.src = this.src.replace('_hover.png', '.png');
	});
	
	$('#mnuIndex').click(function(e) {
		loadPage(false, 'index', e);
	});
	$('#mnuProjects').click(function(e) {
		loadPage(this, 'projects', e);
	});
	$('#mnuServices').click(function(e) {
		loadPage(this, 'services', e);
	});
	$('#mnuPortfolios').click(function(e) {
		loadPage(this, 'portfolios', e);
	});
	$('#mnuContact').click(function(e) {
		loadPage(this, 'contact', e);
	});

	var _l = window.location;
	var _dirs = _l.pathname.split('/');
	var _page = _dirs[_dirs.length - 1];
	_dirs[_dirs.length - 1] = '';
	if (_page != "") {
		_l.href = _l.protocol + '//' + _l.hostname + _dirs.join('/') + '#' + _page;
	}
	else if (_l.hash.length > 1)
	{
		loadPage(false, _l.hash.substring(1));
	}
});