/******************************************************************************
* kwdKeywordTreeSelect.js
*******************************************************************************
Controle de selection de mots-cle
*******************************************************************************
*                                                                             *
* Copyright 2000-2002								                          *
*                                                                             *
******************************************************************************/
var allKeywordTreeSelects = new Array();
var currentKeywordTreeSelect = null;
var currentDragKeywordTreeSelect = null;


function KeywordTreeSelect(name, data)
{
	this.name = name;
	this.id = name.substr(1);
	this.data = new Array();
	this.separator = ",";
	var ancestors = new Array();
	for(var i=0;i<data.length;i++) {
		var record = data[i].split(":");
		var key = record[0];
		var start = parseInt(record[1], 10);
		var width = parseInt(record[2], 10);
		var label = record[3];
		var synonyms = record[4];
		for(var j=0; j<ancestors.length;j++) {
			var ancestor = this.data[ancestors[j]];
			if(ancestor[1] + ancestor[2] < i) {
				break;
			}
		}
		ancestors.length = j;
		var parent = null;
		if(ancestors.length > 0) {
			parent = ancestors[ancestors.length -1];
		}
		this.data[i] = new Array(key, start, width, label, synonyms, ancestors.length, parent);
		if(width > 0) {
			ancestors[ancestors.length] = i;
		}
	}
	this.tbody = document.getElementById("TT" + name);
	this.open = new Array();
	allKeywordTreeSelects[name] = this;
}

KeywordTreeSelect.prototype.showEntry = function(record, open)
{
	var parentRecord = this.data[record[6]];
	if(parentRecord != null) this.showEntry(parentRecord, true);
	tr = record[7];
	if(tr == null) return alert("no entry");
	tr.style.display = document.all ? "block": "table-row";
	if(open) {
		this.toggleFolder(record[1], false, record);
	}
}

KeywordTreeSelect.prototype.initState = function(state, gids)
{
	var hits = new Array();
	for(var name in state) {
		name = objStringUtils.normalizeString(name);
		var n = name;
		if(name.substr(name.length-1) != "*") {
			n = n + ",";
		} else {
			n = n.substr(0, n.length-1);
		}
		if(name.substr(0,1) != "*") {
			n = "," + n;
		} else {
			n = n.substr(1);
		}
		for(var i=0;i<this.data.length;i++) {
			var record = this.data[i];
			var synonyms = "," + record[4] + ",";
			if(synonyms.indexOf(n) >= 0) {
				hits[i] = 1;
			}
		}
	}
	for(var i=0;i<this.data.length;i++) {
		var record = this.data[i];
		if(gids[record[0]] == 1) {
			hits[i] = 1;
		}
	}
	// close and reset tree
	for(var i=0;i<this.data.length;i++) {
		var record = this.data[i];
		var tr = record[7];
		if(tr == null) continue;
		var img = record[8];
		var input = record[9];
		input.checked = false;
		input.disabled = false;
		if(record[2] > 0) {
			img.src = "./iso_icons/dynlib_plus.gif";
		}
		if(record[5] > 0) {
			tr.style.display = "none";
		}
	}
	if(this.data.length > 2) {
		var firstRecord = this.data[0];
		if(firstRecord[2] +  1 ==  this.data.length) {
			var secondRecord = this.data[1];
			this.showEntry(secondRecord, false);
		}
	}
	for(var i=0;i<hits.length;i++) {
		if(hits[i] != 1) continue;
		var record = this.data[i];
		this.showEntry(record, false);
		var input = record[9];
		if(input != null) {
			input.checked = true;
		}
		var end = i + record[2];
		i++;
		while(i<=end) {
			var r = this.data[i];
			var input = r[9];
			if(input != null) {
				input.checked = true;
				input.disabled = true;
			}
			i++;
		}
		i--;
	}
	this.updateState();
}

KeywordTreeSelect.prototype.start = function(inPopup)
{
	this._inPopup = inPopup;
	var input, div;
	if(this._inPopup) {
		this._currentId = window.opener.kwdCurrentId;
		input = this.popupField = window.opener.document.getElementById(this._currentId);
		div = this.popupText = window.opener.document.getElementById(this._currentId + "_t");
	} else {
		input = this.popupField = document.getElementById("ctrl" + this.id);
		div = this.popupText = document.getElementById("ctrl" + this.id + "_t");
		if(input == null) {
			input = this.popupField = document.getElementById(this.id);
			div = this.popupText = document.getElementById(this.id + "_t");
		}
	}
	var gids = new Object();
	var labels = "";

	for(var i=0;i<this.data.length;i++) {
		var record = this.data[i];
		this.createRow(record, null);
		var width = parseInt(record[2],10);
		i += width;
	}
	if(div != null) {
		var fields = input.value.split(" ");
		for(var i=0;i<fields.length;i++) {
			gids[fields[i]] = 1;
		}
		for(var i=0;i<this.data.length;i++) {
			var record = this.data[i];
			if(gids[record[0]] == null) continue;
			if(labels != "") labels += ", ";
			labels += record[3];
		}
		div.innerHTML = labels;
	}
	if(this._inPopup) {
		this.initState(new Array(), gids);
	}
}

KeywordTreeSelect.prototype.createRow = function(record, trPivot, checked)
{
	var rank = record[1];
	var empty = record[2] == 0;
	var label, icon, category;
	var key = record[0];
	var label = record[3];
	var depth = record[5];
	var tr = document.createElement("tr");
	record[7] = tr;
	tr.setAttribute("RANK", "" + rank);
	tr.height = 16;
	if(trPivot != null) {
		var sibling = this.tbody.insertBefore(tr, trPivot);
	} else {
		this.tbody.appendChild(tr);
	}
	var className = "fontFamilyStandardText fontSizeNormal backgroundColorTableCell fontColorTableCell keywordTableCell";
	var open = false;
	var visible = true;
	if(!visible) open = false;
	this.open[key] = open;
	if(!visible) tr.style.display = "none";
	var td = document.createElement("td");
	td.className = className;
	td.width = 1;
	var disabled = (checked  == true)? " checked=\"checked'\" disabled=\"disabled\"":"";

	td.innerHTML = '<input' + disabled + ' value="' + key + '" type="checkbox" style="width:25px" onclick="' + this.name + '.checkboxClick(this,' + rank + ')"/>';
	var input = td.firstChild;
	tr.appendChild(td);
	var td = document.createElement("td");
	tr.appendChild(td);
	td.className = className + " ";
	td.align = "left";
	td.vAlign = "top";
	//td.width = column.width;
	td.noWrap = true;
	var spacer = document.createElement("img");
	spacer.style.width = 16 * depth;
	spacer.src = "./iso_icons/empty.gif";
	spacer.style.height = 1;
	td.appendChild(spacer);

	var container = td;
	if(!empty) {
		var a = document.createElement("a");
		a.href = "javascript:" + this.name + ".plusMinusClick(" + rank + ")";
		td.appendChild(a);	
		container = a;
	}
	var img = document.createElement("img");
	if(empty) {
		img.src = "./iso_icons/empty.gif";
	} else {
		if(open) {
			img.src = "./iso_icons/dynlib_minus.gif";
		} else {
			img.src = "./iso_icons/dynlib_plus.gif";
		}
	}
	img.height = 16;
	img.width = 16;
	img.border = 0;
	img.id = "I" + key + "_" + this.name;
	record[8] = img;
	record[9] = input;
	container.appendChild(img);	
	if(icon != null && icon != "") {
		var img = document.createElement("img");
		img.src = icon;
		img.height = 16;
		img.width = 16;
		img.align = "absbottom";
		td.appendChild(img);	
	}
	var span = document.createElement("span");
	td.appendChild(span);
	span.innerHTML = "\240\240" + label;
	return tr;
}

KeywordTreeSelect.prototype.plusMinusClick = function(rank)
{
	var record = this.data[rank];
	var key = record[0];
	var id = "R" + key;
	var tr = record[7];
	var img = document.getElementById("I" + key + "_" + this.name);
	if(tr == null || img == null) {
		return;
	}
	var depth = record[5];
	var path = img.src;
	var pos = path.lastIndexOf("/");
	var filename = path.substr(pos+1);
	var close;
	close = filename != "dynlib_plus.gif";
	this.toggleFolder(rank, close, record);
}

KeywordTreeSelect.prototype.toggleFolder = function(rank, close, record)
{
	var key = record[0];
	var start = record[1];
	var end = start + record[2];
	var tr = record[7];
	var img = record[8];
	var input = record[9];
	var checked = input.checked;
	var display = "none";
	if(close) {
		img.src = "./iso_icons/dynlib_plus.gif";
	} else {
		if(document.all == null) display = "table-row";
		else display = "block";
		img.src = "./iso_icons/dynlib_minus.gif";
	}
	var next = tr.nextSibling;
	for(var i=start+1;i<=end;i++) {
		r = this.data[i];
		if(r == null) break;
		if(close) {
			childTr = r[7];
			if(childTr != null) {
				childTr.style.display = display;
				// closing the icons
				var icon = r[8].src;
				icon = icon.substr(icon.length -9);
				if(icon != "empty.gif") {
					r[8].src = "./iso_icons/dynlib_plus.gif";
				}
			}
		} else {
			var childTr = r[7];
			if(r[6] != rank) continue;
			if(childTr == null) {
				this.createRow(r, next, checked);
			} else {
				childTr.style.display = display;
			}
		}
	}
}

KeywordTreeSelect.prototype.oncheckboxclick = function(ev)
{
	ev || (ev = window.event);
	var self = keywordGetInstance(ev);
	var el = keywordGetElement(ev);
	return self.checkboxClick(el);
}

KeywordTreeSelect.prototype.checkboxClick = function(input)
{
	var tr = input.parentNode.parentNode;
	var rank = tr.getAttribute("RANK").split(".");
	record = this.data[rank];
	var start = record[1];
	var end = start + record[2];
	var checked = input.checked;
	for(var i=start+1;i<=end;i++) {
		var r = this.data[i];
		if(r == null) break;
		var childInput = r[9];
		if(childInput == null) continue;
		childInput.checked = checked;
		childInput.disabled = checked;
	}
	this.updateState();
}

KeywordTreeSelect.prototype.updateState = function()
{
	var res = "";
	var gids = "";
	var done = new Array();
	for(var i=0;i < this.data.length;i++) {
		var record = this.data[i];
		var input = record[9];
		if(input == null || !input.checked) continue;
		if(gids == "") gids = record[0];
		else gids += " " + record[0];	
		if(done[record[3]] == null) {
			if(res == "") res = record[3];
			else res += ", " + record[3];
			done[record[3]] = 1;
		}
		i += record[2];
	}
	this.stateString = res;
	this.gidString = gids;
}

KeywordTreeSelect.prototype.disableInputs = function()
{
	for(var i=0;i < this.data.length;i++) {
		var record = this.data[i];
		var input = record[9];
		if(input == null) continue;
		input.disabled = true;
	}
}

KeywordTreeSelect.prototype.validatePopup = function()
{
	if(this._inPopup) {
		if(this.gidString == null) this.gidString = "";
		if(this.stateString == null) this.stateString = "";
		window.opener.kwdCommitPopup(this._currentId, this.gidString, this.stateString);
		window.close();
	} else {
		if(this.popupField != null) {
			if(this.popupText != null) {
				this.popupText.innerHTML = this.stateString;
				this.popupField.value = this.gidString;
			} else {
				this.popupField.value = this.stateString;
			}
		}
		this.cancelPopup();
	}
}

KeywordTreeSelect.prototype.cancelPopup = function()
{
	var div = document.getElementById("POPUP_"+this.name);
	if(div == null) return;
	div.style.display = "none";
	this.isPopupShown = false;
	this.hidden = true;
	this.hideShowCovered();
	this.removeEvent(this.titleElement, "mousedown", this._dragStart);
	//this.removeEvent(this.popupElement, "blur", this.onblur);
	//this.removeEvent(this.popupElement, "focus", this.onfocus);
	this.disableInputs();
}
KeywordTreeSelect.prototype.showPopup = function(field)
{
	var div = document.getElementById("POPUP_"+this.name);
	if(div == null) return;
	var ev = window.event;
	this.popupElement = div;
	var position = this.getAbsolutePos(field);
	div.style.left = position.x + "px";
	var bodyHeigh; // (see http://www.quirksmode.org/js/winprop.html)
	if (self.innerHeight)
		bodyHeigh = self.innerHeight;	// netscape
	else if (document.documentElement && document.documentElement.clientHeight)
		bodyHeigh = document.documentElement.clientHeight;	// DOCTYPE
	else if (document.body)
		bodyHeigh = document.body.clientHeight;	// IE without DOCTYPE
	var top = document.body.scrollTop + bodyHeigh/2 - 174;
	if (top < 0) top = 0;
	div.style.top = top;
	div.style.display = "block";
	this.isPopupShown = true;
	if (field != null) {
		var valueSet = new Object();
		var hitSet = new Object();
		if(this.popupText == null) {
			var value = field.value;
			this.stateString = value;
			var values = value.split(this.separator);
			for(var i=0;i<values.length;i++) {
				var value = unescape(values[i]);
				value = value.replace(/^ +/, "").replace(/ +$/, "");
				valueSet[value] = 1;
			}
		} else {
			this.stateString = this.popupText.innerHTML;
			var gids = field.value.split(" ");
			for(var i=0;i<gids.length;i++) {
				hitSet[gids[i]] = 1;
			}
		}
		this.initState(valueSet, hitSet);
	}
	this.titleElement = document.getElementById("TITLE_"+this.name);
	//this.consoleDump(this.titleElement.tagName);
	this.addEvent(this.titleElement, "mousedown", this._dragStart);
	//this.addEvent(this.popupElement, "blur", this.onblur);
	//this.addEvent(this.popupElement, "focus", this.onfocus);
	//this.addEvent(this.popupElement, "onclick", this.onclick);
	//this.popupElement.focus();
	this.hidden = false;
	this.hideShowCovered();

}

KeywordTreeSelect.prototype.getAbsolutePos = function(el) {
	var SL = 0, ST = 0;
	var is_div = /^div$/i.test(el.tagName);
	if (is_div && el.scrollLeft)
		SL = el.scrollLeft;
	if (is_div && el.scrollTop)
		ST = el.scrollTop;
	var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
	if (el.offsetParent) {
		var tmp = this.getAbsolutePos(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
}

KeywordTreeSelect.prototype.hideShowCovered = function () 
{
	if(document.all == null) return;
	function getVisib(obj){
		var value = obj.style.visibility;
		if (!value) {
			if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { // Gecko, W3C
				value = document.defaultView.
						getComputedStyle(obj, "").getPropertyValue("visibility");
			} else if (obj.currentStyle) { // IE
				value = obj.currentStyle.visibility;
			} else
				value = '';
		}
		return value;
	};

	var tags = new Array("applet", "iframe", "select");
	var el = document.getElementById("POPUP_"+this.name);

	var p = this.getAbsolutePos(el);
	var EX1 = p.x;
	var EX2 = el.offsetWidth + EX1;
	var EY1 = p.y;
	var EY2 = el.offsetHeight + EY1;

	for (var k = tags.length; k > 0; ) {
		var ar = document.getElementsByTagName(tags[--k]);
		var cc = null;

		for (var i = ar.length; i > 0;) {
			cc = ar[--i];

			p = this.getAbsolutePos(cc);
			var CX1 = p.x;
			var CX2 = cc.offsetWidth + CX1;
			var CY1 = p.y;
			var CY2 = cc.offsetHeight + CY1;

			if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
				if (!cc.__msh_save_visibility) {
					cc.__msh_save_visibility = getVisib(cc);
				}
				cc.style.visibility = cc.__msh_save_visibility;
			} else {
				if (!cc.__msh_save_visibility) {
					cc.__msh_save_visibility = getVisib(cc);
				}
				cc.style.visibility = "hidden";
			}
		}
	}
}

function keywordGetElement(ev) 
{
	if (document.all != null) {
		return window.event.srcElement;
	} else {
		return ev.currentTarget;
	}
}

function getKeywordTreeSelectInstance(element) 
{
	while(element != null) {
		var id = element.id + "";
		if(id.substr(0,6) == "POPUP_") {
			var name = id.substr(6);
			var instance = allKeywordTreeSelects[name];
			if(instance != null) return instance;
		}
		element = element.parentNode;
	}
}

function keywordHideTreeTableWindow()
{
	if(currentKeywordTreeSelect == null) return;
	currentKeywordTreeSelect.cancelTimer = null;
	//currentKeywordTreeSelect.cancelPopup();
	currentKeywordTreeSelect = null;
}
function keywordGetInstance(ev) 
{
	return getKeywordTreeSelectInstance(keywordGetElement(ev));
}

KeywordTreeSelect.prototype.onblur = function (ev) 
{
	ev || (ev = window.event);
	var self = keywordGetInstance(ev);
	if(self == null) return;
	currentKeywordTreeSelect = self;
	self.cancelTimer = setTimeout("keywordHideTreeTableWindow()", 10);
}

KeywordTreeSelect.prototype.onfocus = function (ev) 
{
	ev || (ev = window.event);
	var el = keywordGetElement(ev);
	var self = keywordGetInstance(ev);
	if(self == null) return;
	if(currentKeywordTreeSelect == self && self.cancelTimer != null) {
		clearTimeout(self.cancelTimer);
		currentKeywordTreeSelect = null;
	}
}

KeywordTreeSelect.prototype.onclick = function (ev) 
{
	ev || (ev = window.event);
	var el = keywordGetElement(ev);
	el.focus();
}

KeywordTreeSelect.prototype._dragStart = function (ev) 
{
	ev || (ev = window.event);
	var self = keywordGetInstance(ev);
	if(self == null) return alert("no self");
	currentDragKeywordTreeSelect = self;
	with(self) {
		if (self.dragging) {
			return;
		}
		self.dragging = true;
		var posX;
		var posY;
		if (document.all != null) {
			posY = window.event.clientY + document.body.scrollTop;
			posX = window.event.clientX + document.body.scrollLeft;
		} else {
			posY = ev.clientY + window.scrollY;
			posX = ev.clientX + window.scrollX;
		}
		var st = self.popupElement.style;
		self.xOffs = posX - parseInt(st.left);
		self.yOffs = posY - parseInt(st.top);
		addEvent(document, "mousemove", calDragIt);
		addEvent(document, "mouseover", stopEvent);
		addEvent(document, "mouseup", calDragEnd);
	}
}

KeywordTreeSelect.prototype.calDragIt = function (ev) 
{
	ev || (ev = window.event);
	var self = currentDragKeywordTreeSelect;
	if(self == null) return;
	with(self) {
		var posX;
		var posY;
		if (document.all != null) {
			posY = window.event.clientY + document.body.scrollTop;
			posX = window.event.clientX + document.body.scrollLeft;
		} else {
			posX = ev.pageX;
			posY = ev.pageY;
		}
		hideShowCovered();
		var st = popupElement.style;
		st.left = (posX - self.xOffs) + "px";
		st.top = (posY - self.yOffs) + "px";
		return stopEvent(ev);
	}
};

KeywordTreeSelect.prototype.stopEvent = function(ev) {
	ev || (ev = window.event);
	if (document.all != null) {
		ev.cancelBubble = true;
		ev.returnValue = false;
	} else {
		ev.preventDefault();
		ev.stopPropagation();
	}
	return false;
};


KeywordTreeSelect.prototype.calDragEnd = function (ev) {
	ev || (ev = window.event);
	var self = currentDragKeywordTreeSelect;
	if(self == null) return;
	with(self) {
		self.dragging = false;

		removeEvent(document, "mousemove", calDragIt);
		removeEvent(document, "mouseover", stopEvent);
		removeEvent(document, "mouseup", calDragEnd);
		self.hideShowCovered();
	}
	currentDragKeywordTreeSelect = null;
};

KeywordTreeSelect.prototype.addEvent = function(el, evname, func) {
	if (el.attachEvent) { // IE
		el.attachEvent("on" + evname, func);
	} else if (el.addEventListener) { // Gecko / W3C
		el.addEventListener(evname, func, true);
	} else {
		el["on" + evname] = func;
	}
};

KeywordTreeSelect.prototype.removeEvent = function(el, evname, func) {
	if (el.detachEvent) { // IE
		el.detachEvent("on" + evname, func);
	} else if (el.removeEventListener) { // Gecko / W3C
		el.removeEventListener(evname, func, true);
	} else {
		el["on" + evname] = null;
	}
};

var kwdCurrentId;
function kwdCommitPopup(id, value, text)
{
	var input = document.getElementById(id);
	var textDiv = document.getElementById(id + "_t");
	if(input != null) input.value = value;
	if(textDiv != null) textDiv.innerHTML = text;
}

function kwdShowPopup(popupLink, id, rootId, oidAsKey)
{
	var url = popupLink;
	var needQM = true;
	if(rootId != null && rootId != "") {
		url += "?rootId=" + escape(rootId);
		needQM = false;
	}
	if(oidAsKey == true) {
		url += (needQM?"?":"&") + "oidAsKey=true";
	}
	kwdCurrentId = id;
	var width = "320";
	var height = "330";
	var leftPos = (screen.availWidth - width) / 2;
	var topPos = (screen.availHeight - height) / 2;
	var options = 'width=' + width + ',height=' + height + ',left=' + leftPos + ',top=' + topPos;
	var win = window.open(url, "_blank", options);
	if (win==null)
		alert(objThesaurus.translate("odfCheckPopupBlocker"));
	else
		win.focus();
}