/*===================================================================
 Author: Matt Kruse
 
 View documentation, examples, and source code at:
     http://www.JavascriptToolbox.com/

 NOTICE: You may use this code for any purpose, commercial or
 private, without any further permission from the author. You may
 remove this notice from your final code if you wish, however it is
 appreciated by the author if at least the web site address is kept.

 This code may NOT be distributed for download from script sites, 
 open source CDs or sites, or any other distribution method. If you
 wish you share this code with others, please direct them to the 
 web site above.
 
 Pleae do not link directly to the .js files on the server above. Copy
 the files to your own server for use with your site or webapp.
 ===================================================================*/
/*
This code is inspired by and extended from Stuart Langridge's aqlist code:
		http://www.kryogenix.org/code/browser/aqlists/
		Stuart Langridge, November 2002
		sil@kryogenix.org
		Inspired by Aaron's labels.js (http://youngpup.net/demos/labels/) 
		and Dave Lindquist's menuDropDown.js (http://www.gazingus.org/dhtml/?id=109)
*/
var varwaittxt;
if(varwaittxt==undefined) {varwaittxt="Please wait..."}
var varexpandtree;
//if(varexpandtree==undefined) {varexpandtree=""}
var varshowtree;

// Automatically attach a listener to the window onload, to convert the trees
addEvent(window,"load",convertTrees);

// Utility function to add an event listener
function addEvent(o,e,f){
	if (o.addEventListener){ o.addEventListener(e,f,false); return true; }
	else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
	else { return false; }
}

// utility function to set a global variable if it is not already set
function setDefault(name,val) {
	if (typeof(window[name])=="undefined" || window[name]==null) {
		window[name]=val;
	}
}

// Full expands a tree with a given ID
function expandTree(treeId) {
//	alert('expandTree_' + treeId)
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	expandCollapseList(ul,nodeOpenClass);
}

// Fully collapses a tree with a given ID
function collapseTree(treeId) {
//	alert('collapseTree_' + treeId)
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	expandCollapseList(ul,nodeClosedClass);
}

// Expands enough nodes to expose an LI with a given ID
function expandToItem(treeId,itemId) {
//	alert('expandToItem_' + treeId + '_' + itemId)
	var ul = document.getElementById(treeId);

	if (ul == null) { return false; }
	var ret = expandCollapseList(ul,nodeOpenClass,itemId);
	if (ret) {
		var o = document.getElementById(itemId);
		if (o.scrollIntoView) {
			o.scrollIntoView(false);
		}
	}
}

// Performs 3 functions:
// a) Expand all nodes
// b) Collapse all nodes
// c) Expand all nodes to reach a certain ID
function expandCollapseList(ul,cName,itemId) {
//	alert('expandCollapseList_' + ul + '_' + cName + '_' + itemId )
	if (!ul.childNodes || ul.childNodes.length==0) { return false; }
	// Iterate LIs
	for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
		var item = ul.childNodes[itemi];
		if (itemId!=null && item.id==itemId) { return true; }
		if (item.nodeName == "LI") {
			// Iterate things in this LI
			var subLists = false;
			for (var sitemi=0;sitemi<item.childNodes.length;sitemi++) {
				var sitem = item.childNodes[sitemi];
				if (sitem.nodeName=="UL") {
					subLists = true;
					var ret = expandCollapseList(sitem,cName,itemId);
					if (itemId!=null && ret) {
						item.className=cName;
						return true;
					}
				}
			}
			if (subLists && itemId==null) {
				item.className = cName;
			}
		}
	}
}

// Search the document for UL elements with the correct CLASS name, then process them
function convertTrees() {
	setDefault("treeClass","nbtree");
	setDefault("nodeClosedClass","liClosed");
	setDefault("nodeOpenClass","liOpen");
	setDefault("nodeBulletClass","liBullet");
	setDefault("nodeLinkClass","bullet");
	setDefault("preProcessTrees",true);
	if (preProcessTrees) {
		if (!document.createElement) { return; } // Without createElement, we can't do anything
		uls = document.getElementsByTagName("ul");
		for (var uli=0;uli<uls.length;uli++) {
			var ul=uls[uli];
			if (ul.nodeName=="UL" && ul.className==treeClass) {
				processList(ul);
			}
		}
	}
}

// Process a UL tag and all its children, to convert to a tree
function processList(ul) {
//		alert('processList_' + ul.id);
if (!ul.childNodes || ul.childNodes.length==0) { return; }
	// Iterate LIs
	for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
		var item = ul.childNodes[itemi];
		if (item.nodeName == "LI") {
			// Iterate things in this LI
			var subLists = false;
			for (var sitemi=0;sitemi<item.childNodes.length;sitemi++) {
				var sitem = item.childNodes[sitemi];
				if (sitem.nodeName=="UL") {
				
					if (sitem.innerHTML =="")
					{
						item.onclick = DelayLoadNode2;
						if (item.captureEvents) item.captureEvents(Event.CLICK);
					}

					subLists = true;
					processList(sitem);
				}
			}
		
			var s= document.createElement("SPAN");
			var t= '\u00A0'; // &nbsp;
			s.className = nodeLinkClass;
			if (subLists) {
			
				// This LI has UL's in it, so it's a +/- node
				if (item.className==null || item.className=="" || item.className.indexOf("cc")>-1) {
					item.className += " " + nodeClosedClass;
				} 
				// If it's just text, make the text work as the link also
				if (item.firstChild.nodeName=="#text") {
					t = t+item.firstChild.nodeValue;
					item.removeChild(item.firstChild);
				}
				s.onclick = function () {
					this.parentNode.className = (this.parentNode.className==nodeOpenClass) ? nodeClosedClass : nodeOpenClass;
					return false;
				}
			}
			else {
				// No sublists, so it's just a bullet node
				if(item.className.indexOf("menu")==-1)	{
					item.className += " " + nodeBulletClass;					
					s.onclick = function () { return false; }
				}
			}
			s.appendChild(document.createTextNode(t));
			item.insertBefore(s,item.firstChild);
		}
	}
}

///
/// Return a XMLHTTPRequest in a browser independent fashion.
///
function GetXMLHttp()
{
    var xmlhttp=false;
    
    window.setTimeout( function() {
			if (waitElement) {waitElement.style.visibility = 'visible';MoveWaitElement();}
			},1);
		
    try 
    {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } 
    catch (e) 
    {
        try 
        {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (E)
        {
            xmlhttp = false;
        }
    }

    // Mozilla then?
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
       xmlhttp = new XMLHttpRequest();
    }
    
    return xmlhttp;
}

///
/// Perform an AJAX style request for the contents 
/// of a node and put the contents
/// into the empty div.
///

function DelayLoadNode2(e)
{
	if (!e) var e = window.event;
	
	var ids = this.id.split("_");
	var treeid = ids[0];
	var item = ids[1];
	var lingua = ids[2];
    var ulchild = document.getElementById(treeid+"_"+item);

	this.onclick = null;
	if (this.releaseEvents)	this.releaseEvents(Event.CLICK)

    // Make sure the node is empty really, and if so fill it
    if (ulchild.innerHTML == "")
    {	
		ulchild.innerHTML="<span class='liWait'>"+varwaittxt+"</span>";
		
		var xmlhttp = GetXMLHttp();
		xmlhttp.open("GET", "js/jstree/ajaxfill.aspx?tree="+treeid+"&id="+item+"&lin="+lingua, true);
		
        xmlhttp.onreadystatechange=function() 
        {
            if (xmlhttp.readyState==4)
            {   // DEBUG: alert(xmlhttp.responseText);
                ulchild.innerHTML = xmlhttp.responseText;
             	processList(ulchild);
                //Toggle(item);
            }
        }
        xmlhttp.send(null)
    }
    
    window.setTimeout( function() {
			if (waitElement) {waitElement.style.visibility = 'hidden';MoveWaitElement();}
			},500);

}


// wait element 
/*CreateWaitElement();
if (window.addEventListener) {
	window.addEventListener('scroll', MoveWaitElement, false);
	window.addEventListener('resize', MoveWaitElement, false);
}
else if (window.attachEvent) {
	window.attachEvent('onscroll', MoveWaitElement);
	window.attachEvent('onresize', MoveWaitElement);
}
var waitElement;
var scrollX, scrollY = -1;
function MoveWaitElement() {
	var scrollYT, scrollXT;
	if (!waitElement)
		CreateWaitElement();
	if (typeof(window.pageYOffset) == "number") { 
		scrollYT = window.pageYOffset; 
		scrollXT = window.pageXOffset; 
	} 
	else if (document.body && document.documentElement && document.documentElement.scrollTop) { 
		scrollYT = document.documentElement.scrollTop; 
		scrollXT = document.body.scrollLeft;
	}
	else if (document.body && typeof(document.body.scrollTop) == "number") { 
		scrollYT = document.body.scrollTop; 
		scrollXT = document.body.scrollLeft; 
	} 
	if (scrollX != scrollXT || scrollY != scrollYT) {
		scrollX = scrollXT;
		scrollY = scrollYT;
		var width = document.body.clientWidth;
		waitElement.style.top = scrollYT + "px";
		waitElement.style.right = -scrollXT +  "px";
	}
}
function CreateWaitElement() {
	var elem = document.getElementById('__AjaxCall_Wait');	
	if (!elem) {		
		elem = document.createElement("div");
		elem.id = '__AjaxCall_Wait';		
		elem.style.position = 'absolute';
		elem.className ='ajaxcallwait';
		elem.innerHTML = varwaittxt;
		elem.style.visibility = 'hidden';
		document.body.insertBefore(elem, document.body.firstChild);		
	}
	waitElement = elem;	
}
// end wait element
*/
function InitializeTree(){

	if(varselid!=undefined && varexpandtree==undefined)
	{
		trees = varselid.split(",")
		setDefault("nodeOpenClass","liOpen");	

		for(i=0;i<trees.length;i++)
			if(trees[i].split("_").length==3){
				expandToItem(trees[i].split("_")[0],trees[i]);
			}
	}
	if(varexpandtree!=undefined)
	{
		trees = varexpandtree.split(",")
		setDefault("nodeOpenClass","liOpen");
		
		for(i=0;i<trees.length;i++)
			expandTree(trees[i]);
	}
	if(varshowtree!=undefined)
	{	
		trees = varshowtree.split(",")
		for(i=0;i<trees.length;i++)
			SwitchTree2(trees[i]);
	}

}

function SwitchTree(elem) {
	var oper = elem.id.split("_");
	Switch(oper[0],oper[1]);
}

function SwitchTree2(operazione) {
	var oper = operazione.split("_");
	Switch(oper[0],oper[1]);
}

function Switch(operazione, idtree) {

if (document.getElementById('treeview_'+ idtree)== undefined)
	return false;

if (operazione=='showtree')
	{
		divtree = document.getElementById('treeview_'+ idtree);
		divtree.style.visibility='visible';
		
		divfram = document.getElementById('treeframe_'+ idtree);
		if (divfram!=undefined)  {divfram.style.visibility='visible';}
		
		divbutt = document.getElementById('treebutton_'+ idtree);
		divbutt.style.visibility='hidden';
	}
	else if (operazione=='closetree')
	{
		divtree = document.getElementById('treeview_'+ idtree);
		divtree.style.visibility='hidden';
		
		divfram = document.getElementById('treeframe_'+ idtree);
		if (divfram!=undefined)  {divfram.style.visibility='hidden';}
		
		divbutt = document.getElementById('treebutton_'+ idtree);
		divbutt.style.visibility='visible';
	}

}

var varselid;
if(varselid!=undefined || varexpandtree!=undefined || varshowtree!=undefined) {addEvent(window,"load",InitializeTree);}

function __selTesto(idobject,argument)	{
	treeid=idobject.split("_");
	idtree = treeid[1];
	idsezi = treeid[2];
	idling = treeid[3];
	idtext = treeid[4];
	
	idnew = idtree + '_' + idsezi + '_' + idling + '_' + idtext;

	selElementById(idnew, idtree);
}

function __selElement(idobject,argument)	{

	treeid=idobject.split("_");
	idtree = treeid[1];
	iditem = treeid[2];
	idling = treeid[3];
	
	idnew = idtree + '_' + iditem + '_' + idling;
	
	selElementById(idnew, idtree);
}
function selElementById(idnew, idtree)
{
	itemA = document.getElementById(idnew);
	linkA = itemA.getElementsByTagName("a")[0];
	
	if(linkA.className!="selected")
	{
		linkA.oldClass=linkA.className;
		linkA.className="selected";
	}
	else
	{
		linkA.className=linkA.oldClass;
		linkA.oldClass='';
	}
	
	for(i=0;i<document.forms[0].elements.length;i++)
	{
		if(document.forms[0].elements[i].type=='hidden' && document.forms[0].elements[i].name.indexOf('treeval_'+idtree)>-1)
		{
			if(document.forms[0].elements[i].value!="")
			{
				itemOLD = document.getElementById(document.forms[0].elements[i].value);
				
				if (itemOLD!=undefined)
				{
					if(itemOLD.id != idnew)
					{	linkOLD = itemOLD.getElementsByTagName("a")[0];
						linkOLD.className=linkOLD.oldClass;
					}
				}
			}
			if (itemA.getElementsByTagName("a")[0].className == "selected")
				document.forms[0].elements[i].value = idnew;
			else
				document.forms[0].elements[i].value = "";
			
			break;
		}
	}
}
