var SMTHandler = {
	idCounter : 0,
	idPrefix  : "smt-object-",
	all       : {},
	behavior  : null,
	selected  : null,
	onSelect  : null, /* should be part of tree, not handler */
	getId     : function() { return this.idPrefix + this.idCounter++; },
	toggle    : function (oItem) { this.all[oItem.id.replace('-plus','')].toggle(); },
	select    : function (oItem) { this.all[oItem.id.replace('-icon','')].select(); },
	focus     : function (oItem) { this.all[oItem.id.replace('-anchor','')].focus(); },
	blur      : function (oItem) { this.all[oItem.id.replace('-anchor','')].blur(); },
	keydown   : function (oItem, e) { return this.all[oItem.id].keydown(e.keyCode); },
	cookies   : new SMTCookie(),
	insertHTMLBeforeEnd	:	function (oElement, sHTML) {
		if (oElement.insertAdjacentHTML != null) {
			oElement.insertAdjacentHTML("BeforeEnd", sHTML)
			return;
		}
		var df;	
		var r = oElement.ownerDocument.createRange();
		r.selectNodeContents(oElement);
		r.collapse(false);
		df = r.createContextualFragment(sHTML);
		oElement.appendChild(df);
	}
};

function SMTCookie() {
	if (document.cookie.length) { this.cookies = ' ' + document.cookie; }
	//alert(this.cookies)
}

SMTCookie.prototype.setCookie = function (key, value) {
	document.cookie = key + "=" + escape(value) + ";path=/";
}

SMTCookie.prototype.getCookie = function (key) {
	if (this.cookies) {
		var start = this.cookies.indexOf(' ' + key + '=');
		if (start == -1) { return null; }
		var end = this.cookies.indexOf(";", start);
		if (end == -1) { end = this.cookies.length; }
		end -= start;
		var cookie = this.cookies.substr(start,end);
		return unescape(cookie.substr(cookie.indexOf('=') + 1, cookie.length - cookie.indexOf('=') + 1));
	}
	else { return null; }
}

function SMTAbstractNode(sText, sAction) {
	this.childNodes  = [];
	this.id     = SMTHandler.getId();
	this.text   = sText || SMTConfig.defaultText;
	this.action = sAction || SMTConfig.defaultAction;
	this._last  = false;
	SMTHandler.all[this.id] = this;
}

SMTAbstractNode.prototype.add = function (node, bNoIdent) {
	node.parentNode = this;
	this.childNodes[this.childNodes.length] = node;
	var root = this;
	if (this.childNodes.length >=2) {
		this.childNodes[this.childNodes.length -2]._last = false;
	}
	while (root.parentNode) { root = root.parentNode; }
	if (root.rendered) {
		if (this.childNodes.length >= 2) {
			document.getElementById(this.childNodes[this.childNodes.length -2].id + '-plus').src = ((this.childNodes[this.childNodes.length -2].folder)?((this.childNodes[this.childNodes.length -2].open)?SMTConfig.tMinusIcon:SMTConfig.tPlusIcon):SMTConfig.tIcon);
			if (this.childNodes[this.childNodes.length -2].folder) {
				this.childNodes[this.childNodes.length -2].plusIcon = SMTConfig.tPlusIcon;
				this.childNodes[this.childNodes.length -2].minusIcon = SMTConfig.tMinusIcon;
			}
			this.childNodes[this.childNodes.length -2]._last = false;
		}
		this._last = true;
		var foo = this;
		while (foo.parentNode) {
			for (var i = 0; i < foo.parentNode.childNodes.length; i++) {
				if (foo.id == foo.parentNode.childNodes[i].id) { break; }
			}
			if (++i == foo.parentNode.childNodes.length) { foo.parentNode._last = true; }
			else { foo.parentNode._last = false; }
			foo = foo.parentNode;
		}
		SMTHandler.insertHTMLBeforeEnd(document.getElementById(this.id + '-cont'), node.toString());
		if ((!this.folder) && (!this.openIcon)) {
			this.icon = SMTConfig.folderIcon;
			this.openIcon = SMTConfig.openFolderIcon;
		}
		if (!this.folder) { this.folder = true; this.collapse(true); }
		if (!bNoIdent) { this.indent(); }
	}
	return node;
}

SMTAbstractNode.prototype.toggle = function() {
	if (this.folder) {
		if (this.open) { this.collapse(); }
		else { this.expand(); }
}	}

SMTAbstractNode.prototype.select = function() {
	document.getElementById(this.id + '-anchor').focus();
}

SMTAbstractNode.prototype.deSelect = function() {
	document.getElementById(this.id + '-anchor').className = '';
	SMTHandler.selected = null;
}

SMTAbstractNode.prototype.focus = function() {
	if ((SMTHandler.selected) && (SMTHandler.selected != this)) { SMTHandler.selected.deSelect(); }
	SMTHandler.selected = this;
	if ((this.openIcon) && (SMTHandler.behavior != 'classic')) { document.getElementById(this.id + '-icon').src = this.openIcon; }
	document.getElementById(this.id + '-anchor').className = 'selected';
	document.getElementById(this.id + '-anchor').focus();
	if (SMTHandler.onSelect) { SMTHandler.onSelect(this); }
}

SMTAbstractNode.prototype.blur = function() {
	if ((this.openIcon) && (SMTHandler.behavior != 'classic')) { document.getElementById(this.id + '-icon').src = this.icon; }
	document.getElementById(this.id + '-anchor').className = 'selected-inactive';
}

SMTAbstractNode.prototype.doExpand = function() {
	if (SMTHandler.behavior == 'classic') { document.getElementById(this.id + '-icon').src = this.openIcon; }
	if (this.childNodes.length) {  document.getElementById(this.id + '-cont').style.display = 'block'; }
	this.open = true;
	SMTHandler.cookies.setCookie(this.id.substr(11,this.id.length - 11), '1');
}

SMTAbstractNode.prototype.doCollapse = function() {
	if (SMTHandler.behavior == 'classic') { document.getElementById(this.id + '-icon').src = this.icon; }
	if (this.childNodes.length) { document.getElementById(this.id + '-cont').style.display = 'none'; }
	this.open = false;
	SMTHandler.cookies.setCookie(this.id.substr(11,this.id.length - 11), '0');
}

SMTAbstractNode.prototype.expandAll = function() {
	this.expandChildren();
	if ((this.folder) && (!this.open)) { this.expand(); }
}

SMTAbstractNode.prototype.expandChildren = function() {
	for (var i = 0; i < this.childNodes.length; i++) {
		this.childNodes[i].expandAll();
} }

SMTAbstractNode.prototype.collapseAll = function() {
	this.collapseChildren();
	if ((this.folder) && (this.open)) { this.collapse(true); }
}

SMTAbstractNode.prototype.collapseChildren = function() {
	for (var i = 0; i < this.childNodes.length; i++) {
		this.childNodes[i].collapseAll();
} }

SMTAbstractNode.prototype.indent = function(lvl, del, last, level) {

	if (lvl == null) { lvl = -2; }
	var state = 0;
	for (var i = this.childNodes.length - 1; i >= 0 ; i--) {
		state = this.childNodes[i].indent(lvl + 1, del, last, level);
		if (state) { return; }
	}
	if (del) {
		if ((level >= this._level) && (document.getElementById(this.id + '-plus'))) {
			if (this.folder) {
				document.getElementById(this.id + '-plus').src = (this.open)?SMTConfig.lMinusIcon:SMTConfig.lPlusIcon;
				this.plusIcon = SMTConfig.lPlusIcon;
				this.minusIcon = SMTConfig.lMinusIcon;
			}
			else { document.getElementById(this.id + '-plus').src = SMTConfig.lIcon; }
			return 1;
	}	}
	var foo = document.getElementById(this.id + '-indent-' + lvl);
	if (foo) {
		if ((del) && (last)) { foo._last = true; }
		if (foo._last) { foo.src =  SMTConfig.blankIcon; }
		else { foo.src =  SMTConfig.iIcon; }
	}
	return 0;
}


function SMT(sText, sAction, sBehavior, sIcon, sOpenIcon) {
	this.base = SMTAbstractNode;
	this.base(sText, sAction);
	this.icon      = sIcon || SMTConfig.rootIcon;
	this.openIcon  = sOpenIcon || SMTConfig.openRootIcon;
	this.open      = (SMTHandler.cookies.getCookie(this.id.substr(11,this.id.length - 11)) == '0')?false:true;
	this.folder    = true;
	this.rendered  = false;
	this.onSelect  = null;
	if (!SMTHandler.behavior) {  SMTHandler.behavior = sBehavior || SMTConfig.defaultBehavior; }
}

SMT.prototype = new SMTAbstractNode;

SMT.prototype.setBehavior = function (sBehavior) {
	SMTHandler.behavior =  sBehavior;
};

SMT.prototype.getBehavior = function (sBehavior) {
	return SMTHandler.behavior;
};

SMT.prototype.getSelected = function() {
	if (SMTHandler.selected) { return SMTHandler.selected; }
	else { return null; }
}

SMT.prototype.remove = function() { }

SMT.prototype.expand = function() {
	this.doExpand();
}

SMT.prototype.collapse = function(b) {
	if (!b) { this.focus(); }
	this.doCollapse();
}

SMT.prototype.getFirst = function() {
	return null;
}

SMT.prototype.getLast = function() {
	return null;
}

SMT.prototype.getNextSibling = function() {
	return null;
}

SMT.prototype.getPreviousSibling = function() {
	return null;
}

SMT.prototype.keydown = function(key) {
	if (key == 39) {
		if (!this.open) { this.expand(); }
		else if (this.childNodes.length) { this.childNodes[0].select(); }
		return false;
	}
	if (key == 37) { this.collapse(); return false; }
	if ((key == 40) && (this.open) && (this.childNodes.length)) { this.childNodes[0].select(); return false; }
	return true;
}

SMT.prototype.toString = function() {
	var str = "<div id=\"" + this.id + "\" ondblclick=\"SMTHandler.toggle(this);\" class=\"smt-item\" onkeydown=\"return SMTHandler.keydown(this, event)\">";
	str += "<img id=\"" + this.id + "-icon\" class=\"smt-icon\" src=\"" + ((SMTHandler.behavior == 'classic' && this.open)?this.openIcon:this.icon) + "\" onclick=\"SMTHandler.select(this);\"><a href=\"" + this.action + "\" id=\"" + this.id + "-anchor\" onfocus=\"SMTHandler.focus(this);\" onblur=\"SMTHandler.blur(this);\">" + this.text + "</a></div>";
	str += "<div id=\"" + this.id + "-cont\" class=\"smt-container\" style=\"display: " + ((this.open)?'block':'none') + ";\">";
	for (var i = 0; i < this.childNodes.length; i++) {
		str += this.childNodes[i].toString(i, this.childNodes.length);
	}
	str += "</div>";
	this.rendered = true;
	return str;
};

function SMTItem(sText, sAction, eParent, sIcon, sOpenIcon) {
	this.base = SMTAbstractNode;
	this.base(sText, sAction);
	this.open = (SMTHandler.cookies.getCookie(this.id.substr(11,this.id.length - 11)) == '1')?true:false;
	if (sIcon) { this.icon = sIcon; }
	if (sOpenIcon) { this.openIcon = sOpenIcon; }
	if (eParent) { eParent.add(this); }
}

SMTItem.prototype = new SMTAbstractNode;

SMTItem.prototype.remove = function() {
	var iconSrc = document.getElementById(this.id + '-plus').src;
	var parentNode = this.parentNode;
	var prevSibling = this.getPreviousSibling(true);
	var nextSibling = this.getNextSibling(true);
	var folder = this.parentNode.folder;
	var last = ((nextSibling) && (nextSibling.parentNode) && (nextSibling.parentNode.id == parentNode.id))?false:true;
	this.getPreviousSibling().focus();
	this._remove();
	if (parentNode.childNodes.length == 0) {
		parentNode.folder = false;
		parentNode.open = false;
	}
	if (!nextSibling) { parentNode.indent(null, true, last, this._level); }
	if ((prevSibling == parentNode) && !(parentNode.childNodes.length)) {
		prevSibling.folder = false;
		prevSibling.open = false;
		iconSrc = document.getElementById(prevSibling.id + '-plus').src;
		iconSrc = iconSrc.replace('minus', '').replace('plus', '');
		document.getElementById(prevSibling.id + '-plus').src = iconSrc;
		document.getElementById(prevSibling.id + '-icon').src = SMTConfig.fileIcon;
	}
	if (document.getElementById(prevSibling.id + '-plus')) {
		if (parentNode == prevSibling.parentNode) {
			iconSrc = iconSrc.replace('minus', '').replace('plus', '');
			document.getElementById(prevSibling.id + '-plus').src = iconSrc;
}	}	}

SMTItem.prototype._remove = function() {
	for (var i = this.childNodes.length - 1; i >= 0; i--) {
		this.childNodes[i]._remove();
 	}
	for (var i = 0; i < this.parentNode.childNodes.length; i++) {
		if (this == this.parentNode.childNodes[i]) {
			for (var j = i; j < this.parentNode.childNodes.length; j++) {
				this.parentNode.childNodes[j] = this.parentNode.childNodes[j+1];
			}
			this.parentNode.childNodes.length -= 1;
			if (i + 1 == this.parentNode.childNodes.length) { this.parentNode._last = true; }
			break;
	}	}
	SMTHandler.all[this.id] = null;
	if (document.getElementById(this.id)) {
		var tmp = document.getElementById(this.id);
		tmp.parentNode.removeChild(tmp);
	}
}

SMTItem.prototype.expand = function() {
	this.doExpand();
	document.getElementById(this.id + '-plus').src = this.minusIcon;
}

SMTItem.prototype.collapse = function(b) {
	if (!b) { this.focus(); }
	this.doCollapse();
	document.getElementById(this.id + '-plus').src = this.plusIcon;
}

SMTItem.prototype.getFirst = function() {
	return this.childNodes[0];
}

SMTItem.prototype.getLast = function() {
	if (this.childNodes[this.childNodes.length - 1].open) { return this.childNodes[this.childNodes.length - 1].getLast(); }
	else { return this.childNodes[this.childNodes.length - 1]; }
}

SMTItem.prototype.getNextSibling = function() {
	for (var i = 0; i < this.parentNode.childNodes.length; i++) {
		if (this == this.parentNode.childNodes[i]) { break; }
	}
	if (++i == this.parentNode.childNodes.length) { return this.parentNode.getNextSibling(); }
	else { return this.parentNode.childNodes[i]; }
}

SMTItem.prototype.getPreviousSibling = function(b) {
	for (var i = 0; i < this.parentNode.childNodes.length; i++) {
		if (this == this.parentNode.childNodes[i]) { break; }
	}
	if (i == 0) { return this.parentNode; }
	else {
		if ((this.parentNode.childNodes[--i].open) || (b && this.parentNode.childNodes[i].folder)) { return this.parentNode.childNodes[i].getLast(); }
		else { return this.parentNode.childNodes[i]; }
} }

SMTItem.prototype.keydown = function(key) {
	if ((key == 39) && (this.folder)) {
		if (!this.open) { this.expand(); }
		else { this.getFirst().select(); }
		return false;
	}
	else if (key == 37) {
		if (this.open) { this.collapse(); }
		else { this.parentNode.select(); }
		return false;
	}
	else if (key == 40) {
		if (this.open) { this.getFirst().select(); }
		else {
			var sib = this.getNextSibling();
			if (sib) { sib.select(); }
		}
		return false;
	}
	else if (key == 38) { this.getPreviousSibling().select(); return false; }
	return true;
}

SMTItem.prototype.toString = function (nItem, nItemCount) {
	var foo = this.parentNode;
	var indent = '';
	if (nItem + 1 == nItemCount) { this.parentNode._last = true; }
	var i = 0;
	while (foo.parentNode) {
		foo = foo.parentNode;
		indent = "<img id=\"" + this.id + "-indent-" + i + "\" src=\"" + ((foo._last)?SMTConfig.blankIcon:SMTConfig.iIcon) + "\">" + indent;
		i++;
	}
	this._level = i;
	if (this.childNodes.length) { this.folder = 1; }
	else { this.open = false; }
	if ((this.folder) || (SMTHandler.behavior != 'classic')) {
		if (!this.icon) { this.icon = SMTConfig.folderIcon; }
		if (!this.openIcon) { this.openIcon = SMTConfig.openFolderIcon; }
	}
	else if (!this.icon) { this.icon = SMTConfig.fileIcon; }
	var label = this.text.replace(/</g, '&lt;').replace(/>/g, '&gt;');
	var str = "<div id=\"" + this.id + "\" ondblclick=\"SMTHandler.toggle(this);\" class=\"smt-item\" onkeydown=\"return SMTHandler.keydown(this, event)\">";
	str += indent;
	str += "<img id=\"" + this.id + "-plus\" src=\"" + ((this.folder)?((this.open)?((this.parentNode._last)?SMTConfig.lMinusIcon:SMTConfig.tMinusIcon):((this.parentNode._last)?SMTConfig.lPlusIcon:SMTConfig.tPlusIcon)):((this.parentNode._last)?SMTConfig.lIcon:SMTConfig.tIcon)) + "\" onclick=\"SMTHandler.toggle(this);\">"
	str += "<img id=\"" + this.id + "-icon\" class=\"smt-icon\" src=\"" + ((SMTHandler.behavior == 'classic' && this.open)?this.openIcon:this.icon) + "\" onclick=\"SMTHandler.select(this);\"><a href=\"" + this.action + "\" id=\"" + this.id + "-anchor\" onfocus=\"SMTHandler.focus(this);\" onblur=\"SMTHandler.blur(this);\">" + label + "</a></div>";
	str += "<div id=\"" + this.id + "-cont\" class=\"smt-container\" style=\"display: " + ((this.open)?'block':'none') + ";\">";
	for (var i = 0; i < this.childNodes.length; i++) {
		str += this.childNodes[i].toString(i,this.childNodes.length);
	}
	str += "</div>";
	this.plusIcon = ((this.parentNode._last)?SMTConfig.lPlusIcon:SMTConfig.tPlusIcon);
	this.minusIcon = ((this.parentNode._last)?SMTConfig.lMinusIcon:SMTConfig.tMinusIcon);
	return str;
}
