$(function(){

	// page selection tabs
	$('#main').tabs();

	// diagram and text section sub-menus
	$('#document-diagram').tabs();
	$("#document-diagram").tabs().addClass('ui-tabs-vertical ui-helper-clearfix');
	$("#document-diagram li").removeClass('ui-corner-top').addClass('ui-corner-left');
	$('#document-text').tabs();
	$("#document-text").tabs().addClass('ui-tabs-vertical ui-helper-clearfix');
	$("#document-text li").removeClass('ui-corner-top').addClass('ui-corner-left');

	// properties dialog
	$('#properties').dialog({
		autoOpen: false,
		width: 600
	});
	// close properties on any tabsselect
	$('#main').bind('tabsselect',function(event,ui){
		$('#properties').dialog('close');
	});
	$('#document-diagram').bind('tabsselect',function(event,ui){
		$('#properties').dialog('close');
	});
	$('#document-text').bind('tabsselect',function(event,ui){
		$('#properties').dialog('close');
	});

	// map area click handler
	$('map area').click(function(event){
		// get content from href
		var href = this.href;
		var hash = href.indexOf("#");
		if (hash >= 0) { //ignore external links
			var id = href.slice(hash + 1);
			if (id.indexOf("diagram-") != 0) {
				//content selected - find it
				var content = document.getElementById(id);
				if (content) {
					var contentDivs = content.getElementsByTagName('div');
					var titleDiv = contentDivs[0];
					var title = "";
					//loop needed because IE has 1 child here, FF and GC 3...
					for (i=0; i<titleDiv.childNodes.length; i++) {
						var child = titleDiv.childNodes[i];
						if (child.innerHTML) {
							title = child.innerHTML;
						}
					}
					var properties = document.getElementById('properties');
					properties.innerHTML = contentDivs[1].innerHTML;
					// display properties dialog
					$('#properties').dialog('option', 'title', title);
					$('#properties').dialog('open');
					event.preventDefault();	
				}
			} else {
				//diagram selected - find matching tab
				var tabNr = -1;
				var diagram = document.getElementById("document-diagram");
				var ul = diagram.getElementsByTagName("ul")[0];
				var lis = ul.getElementsByTagName("li");
				for (i=0; i<lis.length; i++) {
					var li = lis[i];
					var a = li.getElementsByTagName("a")[0];
					var aId = a.getAttribute("href");
					var aHash = aId.indexOf("#");
					if (aHash >= 0) {
						aId = aId.slice(aHash + 1);
					}
					if (aId == id) {
						tabNr = i;
					}					
				}
				if (tabNr >= 0) {
					//select matching tab
					var $tabs = $('#document-diagram').tabs();
					$tabs.tabs('select',tabNr);
					event.preventDefault();
				}
			}
		}
	});
});
