var strElemIDPrefix = 'structure_';
var structureTreeRoot = false;

function createTreeNode(nodeID,parentNode,pictureURL,nodePictureWidth,nodePictureHeight,nodeText,nodeTextAlign,nodeLinkURL,nodeChildSpacing,nodeChildIndent,showNodeChildren){
	
	var treeNode = {
		id : nodeID,
		parent : parentNode,
		picture : pictureURL,
		pictureWidth : nodePictureWidth,
		pictureHeight : nodePictureHeight,
		openLinkOnPictureClick : false,
		depth : (parentNode ? parentNode.depth + 1 : 0),
		text : nodeText,
		textAlign : nodeTextAlign,
		linkURL : nodeLinkURL,
		childSpacing : nodeChildSpacing,
		childIndent : nodeChildIndent,
		showChildren : showNodeChildren,
		childrenRetrieved : false,
		onlyVisibleChild : null,
		collapsedSpacing : 60,
		line : "/g/struktuur_joon.png",
		oneChildVisiblePicture : pictureURL,
		oneChildVisiblePictureWidth : nodePictureWidth,
		oneChildVisiblePictureHeight : nodePictureHeight,
		onlyChildPicture : pictureURL,
		onlyChildPictureWidth : nodePictureWidth,
		onlyChildPictureHeight : nodePictureHeight,
		arrowPicture : "/g/arrow2_right.gif",
		selectedArrowPicture : "/g/arrow3_right.gif",
		closedPicture : pictureURL,
		notes : nodeText,
		alwaysOpen : false,
		x : 0,
		y : 0,
		children : new Array() 
	};
	
	if(parentNode){
		parentNode.children.push(treeNode);
	}
	
	return treeNode;
}

function toggleNodeChildren(treeNode){
	treeNode.showChildren = treeNode.alwaysOpen || !treeNode.showChildren;
}

function setShowNodeChildren(treeNode, show, recursive){
	treeNode.showChildren = treeNode.alwaysOpen || show;
	if(recursive && treeNode.children.length > 0){
		for(var i=0; i<treeNode.children.length; i++)
			setShowNodeChildren(treeNode.children[i],show,recursive);
	}
}

function showAllChildren(treeNode, recursive){
	treeNode.onlyVisibleChild = null;
	if(recursive && treeNode.children.length > 0){
		for(var i=0; i<treeNode.children.length; i++)
			showAllChildren(treeNode.children[i],recursive);
	}
}

function findStructureNodeByID (node, nodeID){
	if(!node) return null;
	if(node.id == nodeID) return node;
	
	var child;
	if(node.children.length > 0){
		for(var i=0; i<node.children.length; i++){
			if(child = findStructureNodeByID(node.children[i], nodeID))
				return child;
		}
	}
	return null;
}

var structureMenuTimeoutID = 0;
var lastStructureNodeID = 0;

function structureNodeHover(node){
	if(!node) return;
	
	if(node.parent){
		if(node.parent.children.length > 0){
			for(var i=0; i<node.parent.children.length; i++){
				setShowNodeChildren(node.parent.children[i], false, false);
			}
		}
		if(node.parent.parent){
			node.parent.parent.onlyVisibleChild = node.parent;
		}
	}
	
	if(node.onlyVisibleChild){
		//node.onlyVisibleChild = null;
		showAllChildren(node,true);
		for(var i = 0; i < node.children.length; i++){
			for(var j = 0; j < node.children[i].children.length; j++){
				node.children[i].children[j].showChildren = false;
			}
		}
	}
	
	setShowNodeChildren(node, true, false);
	
	if(/*node.children.length == 0 &&*/ !node.childrenRetrieved){
		if(structureMenuTimeoutID)
			window.clearTimeout(structureMenuTimeoutID);
		lastStructureNodeID = node.id;
		structureMenuTimeoutID = window.setTimeout(
			function(){
				structureMenuTimeoutID = 0;
				lastStructureNodeID = 0;
				fetchStructureMenu(structureTreeRoot.id,node.id);
			},500);
		
		//fetchStructureMenu(structureTreeRoot.id,node.id);
	}else{
		refreshStructureTree();
	} 
}


function structureNodeClick(rootNode, nodeID){
}

function refreshStructureTree(){
	var targetDiv = document.getElementById('structureview');
	if(!targetDiv)
		return;
		
	while (targetDiv.hasChildNodes()) targetDiv.removeChild(targetDiv.firstChild);
	
	drawTree(structureTreeRoot,targetDiv,false, 20, 100); 
}

/*function calculateTreeLayout(node, x, yMin, ancestorX, ancestorY){
	if(node.showChildren && node.children.length){
		
		//var yFirst = Math.max(y - (node.children.length - 1) * node.childSpacing / 2 , yMin + node.children[0].pictureHeight / 2);
		var yLast = yMin;
		for(i=0; i<node.children.length; i++){
			yLast = calculateTreeLayout(node.children[i],x+node.childIndent, yLast, ancestorX, ancestorY);
		}
		node.x = x;
		node.y = Math.min(ancestorY, (node.children[0].x + node.children[node.children.length-1])/2);
	}else{
		node.x = x;
		node.y = yMin;
	}
	return y0 + node.childSpacing;
}*/

function findBottomLevelHeight(node){
	if(!node.showChildren || !node.children.length){
		if(node.parent)
			return node.parent.childSpacing;
		else
			return 0;
	}else{
		var height = 0;
		for(i=0; i<node.children.length; i++){
			height += findBottomLevelHeight(node.children[i]);
		}
		return height;
	}
}

function drawTree(treeRoot, targetElement, showRoot, x, y){
	var node = treeRoot;
	var elem;
	
	node.x = x; node.y = y;
	
	if(showRoot){
		if(node.onlyVisibleChild){
			elem = createPictureElement(node, node.oneChildVisiblePicture, x - node.oneChildVisiblePictureWidth/2, y - node.oneChildVisiblePictureHeight/2);
		}else if((node.parent && node.parent.onlyVisibleChild == node) || (node.parent == structureTreeRoot && !node.onlyVisibleChild)){
			elem = createPictureElement(node, node.onlyChildPicture, x - node.onlyChildPictureWidth/2, y - node.onlyChildPictureHeight/2);
		}else{
			elem = createPictureElement(node, node.picture, x - node.pictureWidth/2, y - node.pictureHeight/2);
		}
		targetElement.appendChild(elem);
	}

	if(node.depth > 1 && (!node.parent || node.parent.onlyVisibleChild != node)){
		targetElement.appendChild(createLineElement(node.parent.line,x-node.parent.childIndent*0.2,y,x-node.pictureWidth / 2,y));
	}
	
	var x0 = x;
	var y0 = y;
	
	
	if((node.children.length > 0) && node.showChildren){
		if(node.onlyVisibleChild){
			x0 = x; y0 = y;	
			if(showRoot){
				y0 += node.collapsedSpacing;
				targetElement.appendChild(createLineElement(node.line,x,y+node.pictureHeight/2,x,y+node.collapsedSpacing-node.onlyVisibleChild.pictureHeight/2));
			}
			drawTree(node.onlyVisibleChild, targetElement, true, x0, y0);
		}else{
			x0 = x + node.childIndent;
			y0 = Math.max(y - (node.children.length - 1) * node.childSpacing / 2 , node.children[0].pictureHeight / 2);
		
			if(showRoot){
				targetElement.appendChild(createLineElement(node.line,
					x+node.pictureWidth / 2, 
					y, 
					x+node.childIndent * 0.8, 
					y
				));
			}
			var yMax = y0;
			for(var i = 0; i < node.children.length; i++){
				//drawTree(node.children[i], targetElement, true, x0, y0 + i * node.childSpacing);
				
				//if(i) yMax += findBottomLevelHeight(node.children[i]) / 2;
				drawTree(node.children[i], targetElement, true, x0, yMax);
				if(node.children[i].showChildren && node.children[i].children.length){
					yMax = node.children[i].children[node.children[i].children.length-1].y + node.children[i].childSpacing;
				}
				
				yMax += node.childSpacing;
				//yMax += findBottomLevelHeight(node.children[i]) / 2;
				
			}
			if(showRoot && node.children.length){
				var lineElement = createLineElement(node.line,
					x + node.childIndent * 0.8,
					node.children[0].y,
					x + node.childIndent * 0.8,
					node.children[node.children.length-1].y
				);
				if(lineElement)
					targetElement.appendChild(lineElement);
			}
		}
	}
	
	var height = parseInt(targetElement.style.height);
	if(!height)
		height = 0
	targetElement.style.height = Math.max(height,y0 + node.pictureHeight + 40)+'px'; 
	
	if(showRoot){
		if(node.text != ""){
			var elem;
			if(node.textAlign == "right"){
				elem = createTextElement(node, x + node.pictureWidth / 2 + 3, y - node.pictureHeight / 2, "left", "top");
			}else if(node.textAlign == "bottom"){
				elem = createTextElement(node, x - node.pictureWidth / 2, y + node.pictureHeight / 2 + 3, "left", "top");
			}else if(node.textAlign == "bottom-center"){
				elem = createTextElement(node, x - node.pictureWidth / 2, y + node.pictureHeight / 2 + 3, "left", "top");
				//elem = createTextElement(node, x, y + node.pictureHeight / 2 + 3, "center", "top");
			}
			targetElement.appendChild(elem);
		}
	}
	
}

function showNodeTooltip(node){

}

function createTextElement(node, x, y, xPos, yPos){
	if(node.linkURL != ''){
		var img = document.createElement("img");
		img.src = node.arrowPicture;
		img.style.padding = "0px 0px 0px 2px";
		
		var a = document.createElement("a");
		a.href = node.linkURL;
		a.onmouseover = function() { showNodeTooltip(node);};
	}else{
		var a = document.createElement("span");
	}
	a.appendChild(document.createTextNode(node.text));
	if(img) a.appendChild(img);
	
	a.style.position="relative";
	
	var left = x;
	var top = y;
	
	a.style.background = 'white';
	a.style.zIndex = 10;
	a.style.padding = "2px 2px 2px 2px";
	
	//a.style.fontSize = "12px";
	//a.style.color = "#000000";
	//a.style.textDecoration = "none";
	
	/*switch(xPos){
		case "left": break;
		case "center": left -= a.offsetWidth / 2; break;
		case "right": left -= a.offsetWidth; break;
	}
	
	switch(yPos){
		case "top": break;
		case "center": top -= a.offsetHeight / 2; break;
		case "bottom": top -= a.offsetHeight; break;
	}*/
	
	a.style.left = left + 'px';
	a.style.top = top + 'px';
	
	var div = document.createElement("div");
	div.style.position = "absolute";
		
	div.appendChild(a);
	return div;
}

function stopEventPropagation(e){
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation(); 
}

function createPictureElement(node, pictureName, x, y){
	var div = document.createElement("div");
	div.style.position = "absolute";
	var img = document.createElement("img");
	img.src = pictureName;
	img.id = node.id;
	img.style.position="relative";
	img.style.left = x + 'px';
	img.style.top = y + 'px';
	
	img.title = node.notes;
	
	img.onmouseover = function() { showNodeTooltip(node);};
	
	if(!node.alwaysOpen){
		
		if(node.openLinkOnPictureClick){
			/*img.onclick = function(e) {
				//stopEventPropagation(e); 
				document.location.href = node.linkURL; };*/
		}else{
			img.style.cursor = "pointer";
			img.onclick = function(e) { 
				//stopEventPropagation(e);
				structureNodeHover(node); };
			
			if(!node.showChildren || node.onlyVisibleChild){
				var img2 = document.createElement("img");
				img2.src = node.arrowPicture;
				img2.style.left = x + 'px';
				img2.style.top = y - node.pictureHeight / 2 + 3.5 + 'px';
				img2.style.position="relative";
				img2.zIndex = 200;
				img2.style.padding = "0px 0px 0px 2px";
				
				img.onmouseover = function(){
					img2.src = node.selectedArrowPicture;
				};
				img.onmouseout = function(){
					img2.src = node.arrowPicture;
				};
			}
		}
	}
	
	div.appendChild(img);
	if(img2) div.appendChild(img2);
	return div;
}

function createLineElement(lineURL, x0, y0, x1, y1){	
	var div = document.createElement("div");
	div.style.position = "absolute";
	var img = document.createElement("img");
	
	if(x0 == x1 && y0 != y1){ // vertikaaljoon
		img.src = lineURL;
		img.style.left = (x0 - 1) + 'px';
		img.style.top = Math.min(y0,y1) + 'px';
		img.style.height = Math.abs(y1-y0) + 'px';
		img.style.width = 2 + 'px';
	}else if(y0 == y1 && x0 != x1){ // horisontaaljoon
		img.src = lineURL;
		img.style.left = Math.min(x0,x1) + 'px';
		img.style.top = (y0 - 1) + 'px';
		img.style.height = 2 + 'px';
		img.style.width = Math.abs(x1-x0) + 'px';
	}else{
		return null;
	}
	
	img.style.position="relative";
	div.appendChild(img);
	return div;
}

function findDeepestVisibleNode(node){
	var deepest = node;
	if(node.showChildren && node.children.length){
		for(i=0; i<node.children.length; i++){
			var tmpnode = findDeepestVisibleNode(node.children[i]);
			if(tmpnode.depth > deepest.depth)
				deepest = tmpnode;
		}
	}
	return deepest;
}

function reorganizeTree(){
	var node = findDeepestVisibleNode(structureTreeRoot);
	if(node && node.parent && node.parent.showChildren && node.parent.parent && node.parent.parent.showChildren){
		node = node.parent.parent;
		while(node.parent && (node.parent != structureTreeRoot)){
			if(node.parent.showChildren){
				node.parent.showChildren = false;
				node.parent.onlyVisibleChild = node;
			}
			node = node.parent;
		}
	}
}

function createStructNodes(nodeXML, rootNode){
	var node = null;
	if(nodeXML){
		var id = parseInt(nodeXML.attributes.getNamedItem('id').value);
		var parentID = parseInt(nodeXML.attributes.getNamedItem('parentID').value);
		var level = parseInt(nodeXML.attributes.getNamedItem('level').value);
		var text = nodeXML.attributes.getNamedItem('description').value;
		var notes = nodeXML.attributes.getNamedItem('notes').value;
		var pictureFile = nodeXML.attributes.getNamedItem('pictureFile').value;
		var pictureWidth = parseInt(nodeXML.attributes.getNamedItem('pictureWidth').value);
		var pictureHeight = parseInt(nodeXML.attributes.getNamedItem('pictureHeight').value);
		var linkURL = nodeXML.attributes.getNamedItem('linkURL').value;
		var hasChildren = parseInt(nodeXML.attributes.getNamedItem('hasChildren').value);
		var lineFile = nodeXML.attributes.getNamedItem('lineFile').value;
		var oneChildVisiblePictureFile = nodeXML.attributes.getNamedItem('oneChildVisiblePictureFile').value;
		var pageRoot = nodeXML.attributes.getNamedItem('pageRoot').value;
		var alwaysOpen = parseInt(nodeXML.attributes.getNamedItem('alwaysOpen').value);
		
		if(rootNode == structureTreeRoot){
			if(!(rootNode = findStructureNodeByID(rootNode, parentID)))
				rootNode = structureTreeRoot;
		}
		
		var childNode;
		if(rootNode){
			var node = findStructureNodeByID(rootNode, id);
			if(!node){
				var childIndent = new Array();
				childIndent[0] = 100;
				childIndent[1] = 170;
				childIndent[2] = 220;
				childIndent[3] = 220;
				childIndent[4] = 220;
				childIndent[5] = 220;
				childIndent[6] = 220;
			
				var node = createTreeNode(id, rootNode,  pictureFile, pictureWidth, pictureHeight, text, "bottom", linkURL, 50, childIndent[rootNode.depth], true);
				node.openLinkOnPictureClick = hasChildren ? false : true;
				
				node.line = lineFile;
				if(oneChildVisiblePictureFile)
					node.oneChildVisiblePicture = oneChildVisiblePictureFile;
				else
					node.oneChildVisiblePicture = pageRoot+'/g/struktuur_v2ike_mummu_hall.png';
				if(!pageRoot){
					pageRoot = '';
				}
				
				node.arrowPicture = pageRoot + "/g/arrow2_right.gif";
				node.selectedArrowPicture = pageRoot + "/g/arrow3_right.gif";
				//node.onlyChildPicture = pageRoot+'/g/struktuur_suur_mummu_oranz.png';
				node.onlyChildPicture = pictureFile;
				
				node.notes = notes;
				if(alwaysOpen){
					node.alwaysOpen = true;
					node.showChildren = true;
				}else{
					node.alwaysOpen = false;
				}
				
				node.notes = notes;
			}
			if(nodeXML.childNodes.length > 0){
				for(var i=0; i<nodeXML.childNodes.length; i++){
					if(nodeXML.childNodes[i].tagName == 'structElement'){
						childNode = createStructNodes(nodeXML.childNodes[i], node);
					}
				}
			}
		}
	}
	return node;
}

function assureNodeVisibility(nodeID){
	var node = findStructureNodeByID(structureTreeRoot, nodeID);
	//var show = node.showChildren;
	
	setShowNodeChildren(structureTreeRoot,false,true);
	structureTreeRoot.showChildren = true;
	//node.showChildren = show;
	node.showChildren = (node.children.length > 0);
	
	var tmpNode = node;
	if(tmpNode && tmpNode.parent){
		while(tmpNode.parent){
			tmpNode.parent.showChildren = true;
			tmpNode = tmpNode.parent;
		}
	}
	
	//if(node && node.parent && node.parent.showChildren){
		//if((!node.children.length || !node.showChildren) && node.parent.parent && node.parent.parent.showChildren) 
		//	node = node.parent.parent;
		//else
		//	node = node.parent;
		
		node.onlyVisibleChild = null;
		
		while(node.parent && (node.parent != structureTreeRoot)){
			if(node.parent.showChildren){
				node.parent.onlyVisibleChild = node;
			}
			node = node.parent;
		}
	//}
}

function updateStructureMenu(objXML, rootID, structID){
	if(objXML && objXML != null) {
		if(!structureTreeRoot)
			structureTreeRoot = createTreeNode(rootID, null, "", 0, 0, "", "", "", 50, 0, true);
		var node;
		
		var xmlRoot = objXML.getElementsByTagName('structureData');
		if(xmlRoot.length > 0){
			if(xmlRoot[0].childNodes.length > 0){
				for(var i=0; i<xmlRoot[0].childNodes.length; i++){
					if(xmlRoot[0].childNodes[i].tagName == 'structElement'){
						createStructNodes(xmlRoot[0].childNodes[i], structureTreeRoot);
					}
				}
			}
		}
		assureNodeVisibility(structID);
		refreshStructureTree();
		//reorganizeTree();
		refreshStructureTree();
	}
}


function fetchStructureMenu(rootID, structID){
	
	ajax = new getAjax();
	
	ajax.open("POST", 'StructureXMLProxy', true);
	ajax.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
	ajax.setRequestHeader("Content-Encoding", 'UTF-8');
	ajax.send('action=getStructure&struct_id=' + structID + '&root_id=' + rootID);
	
	ajax.onreadystatechange = function() {
		if (ajax.readyState == 4 && ajax.status == 200) {
			//alert(ajax.responseText);
			//alert(ajax.responseXML);
			updateStructureMenu(ajax.responseXML, rootID, structID);
		}
	}
}