if (!window.console) {
	console = {};
}
console.log = console.log || function(){};
console.error = console.error || function(){};
console.warn = console.warn || function(){};
console.info = console.info || function(){};

$.gohai = $.gohai || {};

$.gohai.backend = function() {
	return function(param, func) {
		// make sure parameters are json encoded
		// otherwise we would get complaints from the php parser for empty 
		// strings, arrays and thelike
		for (p in param) {
			param[p] = JSON.stringify(param[p]);
		}
		$.post($.gohai.base_url+'json.php', param, function(data) {
			if (data === null) {
				if (typeof func == 'function') {
					func({ '#error': true, '#data':'There was a problem communicating with the server' });
				}
			} else if (typeof func == 'function') {
				func(data);
			}
		}, 'json');
	};
}();

$(document).ready(function() {
	$('.nav_item').bind('click', function(e) {
		var name = $(this).attr('id');
		if (name.substr(0, 9) == 'nav_item_') {
			name = name.substr(9);
			// check if there is a matching submenu
			if ($('#nav_submenu_'+name).length) {
				// hide any visible submenu
				$('.nav_submenu_active').each(function() {
					$(this).removeClass('nav_submenu_active');
					$(this).hide(200);
				});
				$('#nav_submenu_'+name).each(function() {
					$(this).show(200);
					$(this).addClass('nav_submenu_active');
				});
			}
		}
		if ($(e.target).is('a')) {
			var target = $(e.target).attr('href');
			if (target && target.substr(0, $.gohai.base_url.length) == $.gohai.base_url) {
				// try to get content via ajax call
				$.gohai.backend({ method: 'gohai.get_content', name: target.substr($.gohai.base_url.length) }, function(data) {
					if (!data['#error']) {
						$('#content').html(data['#data']);
					}
				});
				return false;
			} else if (target == '#') {
				return false;
			}
		}
	});
	
	if ($.gohai.base_url.length < location.href.length) {
		// expand submenu
		$('.nav_item').children('a').each(function() {
			if ($(this).attr('href') == location.href) {
				$(this).parents('.nav_submenu').each(function() {
					$(this).show();
					$(this).addClass('nav_submenu_active');
				});
				return;
			}
		});
	}
});

