/*--------------------------------------------------|
| dTree 2.05 | www.destroydrop.com/javascript/tree/ |
|---------------------------------------------------|
| Copyright (c) 2002-2003 Geir Landrö               |
|                                                   |
| This script can be used freely as long as all     |
| copyright messages are intact.                    |
|                                                   |
| Updated: 17.04.2003                               |
|--------------------------------------------------*/

// Node object
function Node(id, pid, node_status, input_id, can_select, is_active, name) {
	this.id = id;
	this.pid = pid;
  this.node_status = (node_status==1)?true:false;    //true - iezimets; false - nav iezimets
  this.input_id = input_id;                          //input elementa ID
  this.can_select = can_select                       //Vai objektam ir checkboxis
  this.is_active = is_active;                        //Vai checkboxs ir aktivs
	this.name = name;
	this._io = false;
	this._last = false;        //true - node is last;
	this._hc = false;          //true - is header; false - is child
	this._hc_status = 0;       //0 - nav virsotnei neviens berns iezimets , 1 - vismaz viens berns virsotnei ir iezimets, 2 - visi berni ir iezimeti
};

// Tree object
function dTree(objName) {
	this.config = {
		useCookies			: true,
		useSelected     : true
	}

	this.icon = {
		join				: 'images/join.gif',
		joinBottom	: 'images/joinbottom.gif',
		plus				: 'images/plus.gif',
		plusBottom	: 'images/plusbottom.gif',
		minus				: 'images/minus.gif',
		minusBottom	: 'images/minusbottom.gif',
		plusTop     : 'images/plus_top.gif',
		minusTop    : 'images/minus_top.gif',
		check0      : 'images/checkbox_0.gif',
		check1      : 'images/checkbox_1.gif',
		check2      : 'images/checkbox_2.gif',
		spacer      : 'images/spacer.gif'

	};

	this.obj = objName;
	this.aNodes = [];
	this.aIndent = [];
	this.root = new Node(-1);
	this.selectedNode = null;
	this.selectedFound = false;
	this.completed = false;
	this.selectedN = false;
};

// Adds a new node to the node array
dTree.prototype.add = function(id, pid, node_status, input_id, can_select, is_active, name) {
	this.aNodes[this.aNodes.length] = new Node(id, pid, node_status, input_id, can_select, is_active, name);
};

// Open/close all nodes
dTree.prototype.openAll = function() {
	this.oAll(true);
};

dTree.prototype.closeAll = function() {
	this.oAll(false);
};

// Outputs the tree to the page
dTree.prototype.toString = function() {
	var str = '<div class="dtree">\n';
	if (document.getElementById) {
		if (this.config.useCookies) this.selectedNode = this.getSelected();
//alert('Selected node: ' + this.selectedNode);
		str += this.addNode(this.root);
    str += '<a href="javascript:' + this.obj + '.openAll();"><img src="'+ this.icon.plusTop +'" width="18" height="18" border="0"></a>';
    str += '<a href="javascript:' + this.obj + '.closeAll();"><img src="'+ this.icon.minusTop +'" width="18" height="18" border="0"></a>';
	} else str += 'Browser not supported.';
	str += '</div>';
	if (!this.selectedFound) this.selectedNode = null;
	this.completed = true;
//	alert(str);
	return str;
};

// Creates the tree structure
dTree.prototype.addNode = function(pNode) {
	var str = '';
	var n=0;
	for (n; n<this.aNodes.length; n++) {
		if (this.aNodes[n].pid == pNode.id) {
			var cn = this.aNodes[n];
			this.setCS(cn);
/*alert('Has childs: ' + ((cn._hc)?'True':'False') + '; ' +
      'Is Open: ' + ((cn._io)?'True':'False') + '; ' +
      'Use Cookies: ' + ((this.config.useCookies)?'True':'False') + '; ');*/
			if (cn._hc && !cn._io && this.config.useCookies) {cn._io = this.isOpen(cn.id);};
			if (cn.id == this.selectedNode && !this.selectedFound) {
					this.selectedNode = n;
					this.selectedFound = true;
			}
			str += this.node(cn, n);
		}
	}
	return str;
};

// Creates the node icon, text
dTree.prototype.node = function(node, nodeId) {
	var str = '<div class="dTreeNode">' + this.indent(node, nodeId);

  //Legend name
  if (node.pid == this.root.id) {
    str += node.name + '<br>';
    str += '<a href="javascript:' + this.obj + '.openAll();"><img src="'+ this.icon.plusTop +'" width="18" height="18" border="0"></a>';
    str += '<a href="javascript:' + this.obj + '.closeAll();"><img src="'+ this.icon.minusTop +'" width="18" height="18" border="0"></a>';
  }

  //Legend node
	if (node._hc && node.pid != this.root.id) {
		str += '<a href="javascript: ' + this.obj + '.c(' + nodeId + ');">';
    if (node._hc_status==0)
       str += '<img id="c' + this.obj + nodeId + '" src="'+ this.icon.check0 +'">';
    else if (node._hc_status==1)
       str += '<img id="c' + this.obj + nodeId + '" src="'+ this.icon.check1 +'">';
    else str += '<img id="c' + this.obj + nodeId + '" src="'+ this.icon.check2 +'">';

    str += '</a>';
    str += '<IMG SRC="'+ this.icon.spacer +'" WIDTH=3>';

		str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');" class="txt_tree_title" classX="txt_white_bold_11">';
    str += node.name;
    str += '</a>';
	}
	else if (node.pid != this.root.id) //Legend children
    str += node.name;
	str += '</div>';

  //Legend node
	if (node._hc) {
		str += '<div id="d' + this.obj + nodeId + '" class="clip" style="display:' + ((this.root.id == node.pid || node._io) ? 'block' : 'none') + ';">';
		str += this.addNode(node);
		str += '</div>';
	}

	this.aIndent.pop();
	return str;
};

// Adds the empty and line icons
dTree.prototype.indent = function(node, nodeId) {
	var str = '';
	if (this.root.id != node.pid) {
		(node._last) ? this.aIndent.push(0) : this.aIndent.push(1);
		if (node._hc) {
			str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');"><img id="j' + this.obj + nodeId + '" src="';
      str += ( (node._io) ? ((node._last) ? this.icon.minusBottom : this.icon.minus) : ((node._last) ? this.icon.plusBottom : this.icon.plus ) );
			str += '" alt="" /></a>';
		} else str += '<img src="' + ( (node._last) ? this.icon.joinBottom : this.icon.join ) + '" alt="" />';
	}
	return str;
};

// Checks if a node has any children and if it is the last sibling
dTree.prototype.setCS = function(node) {
	var lastId;
	var checkTrueCnt=0, checkFalseCnt=0;
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n].pid == node.id) node._hc = true;
		if (this.aNodes[n].pid == node.pid) lastId = this.aNodes[n].id;
		if (node.pid == 0)
      if (this.aNodes[n].pid == node.id)
         (this.aNodes[n].node_status)?checkTrueCnt++:checkFalseCnt++;
	}
  //Nosaka kads virsotnei ir keksis
  if (node.pid == 0) {
     if ((checkFalseCnt > 0) && (checkTrueCnt > 0)) node._hc_status = 1;
     else if ((checkFalseCnt == 0)&&(checkTrueCnt > 0)) node._hc_status = 2;
     else node._hc_status = 0;
  }

	if (lastId==node.id) node._last = true;
};

// Returns the selected node
dTree.prototype.getSelected = function() {
	var sn = this.getCookie('cs' + this.obj);
	return (sn) ? sn : null;
};

// Check virsotnei
dTree.prototype.cc = function(id, pid) {
	var cn;
	var tn;
	var checkTrueCnt=0, checkFalseCnt=0;
	var str = '';
	var ind =0;

	for (var n=0; n<this.aNodes.length; n++) {
    if (this.aNodes[n].id == id && this.aNodes[n].pid == pid && (this.aNodes[n].can_select) && (this.aNodes[n].is_active)) {
       tn = this.aNodes[n];
       tn.node_status = !tn.node_status;
    }
    if (this.aNodes[n].id == pid && this.aNodes[n].pid ==0)
       ind = n;
    if (this.aNodes[n].pid == pid && (this.aNodes[n].can_select) && (this.aNodes[n].is_active)) {
      (this.aNodes[n].node_status)?checkTrueCnt++:checkFalseCnt++;
    }
  }

  cn = this.aNodes[ind];
  var dDiv	= document.getElementById('c' + this.obj + ind);

  if ((checkFalseCnt > 0) && (checkTrueCnt > 0)) {
   cn._hc_status = 1;
   str = this.icon.check1;
  }
  else if ((checkFalseCnt == 0)&&(checkTrueCnt > 0)) {
   cn._hc_status = 2;
   str = this.icon.check2;
  }
  else {
   cn._hc_status = 0;
   str = this.icon.check0;
  }

  dDiv.src = str;

//alert('Trues: ' + checkTrueCnt + '; Falses: ' + checkFalseCnt);
	if (this.config.useCookies) this.updateCookie();
}

// Maina virsotnei statusu
dTree.prototype.c = function(id) {
	var cn = this.aNodes[id];
	var str = '';
	var strInput = '';
	var checkTrueCnt=0, checkFalseCnt=0;

  cDiv	= document.getElementById('c' + this.obj + id);
//alert('Trues: ' + checkTrueCnt + '; Falses: ' + checkFalseCnt);

	for (var n=0; n<this.aNodes.length; n++) {
		if ((this.aNodes[n].pid != 0) && (this.aNodes[n].pid == cn.id) && (this.aNodes[n].can_select) && (this.aNodes[n].is_active)) {
      if (cn._hc_status == 0 || cn._hc_status == 1) {
        strInput = 'CHECKED';
        this.aNodes[n].node_status = true;
      }
      else {
        strInput = '';
        this.aNodes[n].node_status = false;
      }

      iDiv = document.getElementById(this.aNodes[n].input_id);
      iDiv.checked = strInput;
    }
		if (cn.pid == 0 && (this.aNodes[n].can_select) && (this.aNodes[n].is_active))
      if (this.aNodes[n].pid == cn.id)
         (this.aNodes[n].node_status)?checkTrueCnt++:checkFalseCnt++;
  }
//alert('Trues: ' + checkTrueCnt + '; Falses: ' + checkFalseCnt);

  if (cn.pid == 0) {
     if ((checkFalseCnt > 0) && (checkTrueCnt > 0)) {
       cn._hc_status = 1;
       str = this.icon.check1;
     }
     else if ((checkFalseCnt == 0)&&(checkTrueCnt > 0)) {
       cn._hc_status = 2;
       str = this.icon.check2;
     }
     else {
       cn._hc_status = 0;
       str = this.icon.check0;
     }
  }

  cDiv.src = str;

	if (this.config.useCookies) this.updateCookie();

};

// Toggle Open or close
dTree.prototype.o = function(id) {
	var cn = this.aNodes[id];
	this.nodeStatus(!cn._io, id, cn._last);
	cn._io = !cn._io;
	if (this.config.useCookies) this.updateCookie();
};

// Open or close all nodes
dTree.prototype.oAll = function(status) {
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n]._hc && this.aNodes[n].pid != this.root.id) {
			this.nodeStatus(status, n, this.aNodes[n]._last)
			this.aNodes[n]._io = status;
		}
	}
	if (this.config.useCookies) this.updateCookie();
};

// Change the status of a node(open or closed)
dTree.prototype.nodeStatus = function(status, id, bottom) {
	eDiv	= document.getElementById('d' + this.obj + id);
	eJoin	= document.getElementById('j' + this.obj + id);
	eJoin.src =
	(status)?((bottom)?this.icon.minusBottom:this.icon.minus):((bottom)?this.icon.plusBottom:this.icon.plus);

	eDiv.style.display = (status) ? 'block': 'none';
};

// [Cookie] Clears a cookie
dTree.prototype.clearCookie = function() {
	var now = new Date();
	var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
	this.setCookie('co'+this.obj, 'cookieValue', yesterday);
	this.setCookie('cs'+this.obj, 'cookieValue', yesterday);
};

// [Cookie] Sets value in a cookie
dTree.prototype.setCookie = function(cookieName, cookieValue, expires, path, domain, secure) {
	document.cookie =
		escape(cookieName) + '=' + escape(cookieValue)
		+ (expires ? '; expires=' + expires.toGMTString() : '')
		+ (path ? '; path=' + path : '')
		+ (domain ? '; domain=' + domain : '')
		+ (secure ? '; secure' : '');
};

// [Cookie] Gets a value from a cookie
dTree.prototype.getCookie = function(cookieName) {
	var cookieValue = '';
	var posName = document.cookie.indexOf(escape(cookieName) + '=');
	if (posName != -1) {
		var posValue = posName + (escape(cookieName) + '=').length;
		var endPos = document.cookie.indexOf(';', posValue);
		if (endPos != -1) cookieValue = unescape(document.cookie.substring(posValue, endPos));
		else cookieValue = unescape(document.cookie.substring(posValue));
	}
	return (cookieValue);
};

// [Cookie] Returns ids of open nodes as a string
dTree.prototype.updateCookie = function() {
	var str = '';
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n]._io && this.aNodes[n].pid != this.root.id) {
			if (str) str += '.';
			str += this.aNodes[n].id;
		}
	}
	this.setCookie('co' + this.obj, str);
//alert('updateCookie: co' + this.obj + ':' + str);
};

// [Cookie] Checks if a node id is in a cookie
dTree.prototype.isOpen = function(id) {
	var aOpen = this.getCookie('co' + this.obj).split('.');
	for (var n=0; n<aOpen.length; n++)
		if (aOpen[n] == id) return true;
	return false;
};

// If Push and pop is not implemented by the browser
if (!Array.prototype.push) {
	Array.prototype.push = function array_push() {
		for(var i=0;i<arguments.length;i++)
			this[this.length]=arguments[i];
		return this.length;
	}
};
if (!Array.prototype.pop) {
	Array.prototype.pop = function array_pop() {
		lastElement = this[this.length-1];
		this.length = Math.max(this.length-1,0);
		return lastElement;
	}
};

