$(document).ready(function() {

	// UI options
	var tabOptions = {fx:{height: "toggle", duration: "fast"}};

	// main menu
	$('#main').tabs(tabOptions).bind('tabsselect', function() {
		propertyBoxHide();
	});

	// sub-menus (for diagram and text)
	$('#document-diagram, #document-text').tabs(tabOptions).addClass('ui-tabs-vertical ui-helper-clearfix').bind('tabsselect',function(event, ui) {
		propertyBoxHide();
	});
	
	// sub-menus shown vertically
	$('#document-diagram li,#document-text li').removeClass('ui-corner-top').addClass('ui-corner-left');

	// map area click handler
	$('map area').click(function() {
		var href = this.href;
		var hash = href.indexOf('#');
		if (hash < 0) {
			return true; // follow external link
		};
		var id = href.slice(hash + 1);
		if (id.indexOf('diagram-') == 0) {
			return diagramMenuSelect(href)
		} else {
			return propertyBoxShow(id, 0);
		};
	});
	
	// diagram menu selection
	var $diagramPage = $('#document-diagram');
	var $diagramMenu = $('#document-diagram ul li a');
	function diagramMenuSelect(href) {
		/// there should be a way of doing this without looping in jQuery ///
		var tabNr = -1;
		for (i = 0; i < $diagramMenu.length; i++) {
			if ($diagramMenu[i] == href) {
				$diagramPage.tabs('select', i);
				return false;
			};					
		};
		return true;
	};
	
	// property box
	$('<div id="properties-dialog" class="dialog">'
		+ '<div id="properties" class="properties-content"></div></div>')
		.appendTo('body');
	var $properties = $('#properties');
	var $propertyBox = $('#properties-dialog').dialog( {
		autoOpen: false,
		show: 'blind',
		hide: 'blind',
		width: 600,
		minHeight: 200
	});
	function propertyBoxShow(id, tab) {
		var $contentDivs = $('#' + id + ' div');
		var titleDiv = $contentDivs[0];
		// loop needed because IE has 1 child here, FF and GC 3...
		/// there should be a way of doing this without looping in jQuery ///
		for (i = 0; i < titleDiv.childNodes.length; i++) {
			var child = titleDiv.childNodes[i];
			if (child.innerHTML) {
				$properties.html($contentDivs[1].innerHTML);						
				$propertyBox.dialog('option', 'title', child.innerHTML); 
			};
		};
		$propertyBox.dialog('open').tabs(tabOptions).tabs('select', tab);
		//commentId = id;
		//$comment.text('   ');
		return false;	
	};
	function propertyBoxHide() {
		if ($propertyBox.dialog('isOpen')) {
			$propertyBox.dialog('close');
		};
	};

});
