/*--------------------------------------------------|
| 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                               |
|-------------------------------------------------- |
| Modified by Ktf, 20/04/2006                       |
|--------------------------------------------------*/

// Node object
function Node(id, pid, name, icon, iconOpen) {
	this.id = id;
	this.pid = pid;
	this.name = name;
	this.icon = icon;
	this.iconOpen = iconOpen;
	this._io = false;
	this._is = false;
	this._ls = false;
	this._hc = false;
	this._ai = 0;
	this._p;
};

// Tree object
function dTree(objName) {
	this.icon = {
		root: '/faq_online/img/base.gif',
		folder: '/faq_online/img/folder.gif',
		folderOpen: '/faq_online/img/folderopen.gif',
		node: '/faq_online/img/page.gif',
		plus: '/faq_online/img/plus.gif',
		minus: '/faq_online/img/minus.gif'
	};
	this.obj = objName;
	this.aNodes = [];
	this.aIndent = [];
	this.root = new Node(-1);
	this.selectedNode = null;
	this.selectedFound = false;
	this.completed = false;
	this.formproc = null;
};

// history vars
var h = new Array(1);
var hx = 0;

// Adds a new node to the node array
dTree.prototype.add = function(id, pid, dir, name) {
	var icon = ( dir ) ? ( (pid != -1) ? this.icon.folder : this.icon.root ) : this.icon.node;
	var iconOpen = ( dir ) ? ( (pid != -1) ? this.icon.folderOpen : this.icon.root ) : this.icon.node;
	this.aNodes[this.aNodes.length] = new Node(id, pid, name, icon, iconOpen);
};

// Outputs the tree to the page
dTree.prototype.toString = function() {
	var str = '<div style="MARGIN: 5 5" onSelectStart="return false;">\n';
	str += this.addNode(this.root);
	str += '</div>';
	if (!this.selectedFound) this.selectedNode = null;
	this.completed = true;
	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];
			cn._p = pNode;
			cn._ai = n;
			this.setCS(cn);
			if (cn.id == this.selectedNode && !this.selectedFound) {
				cn._is = true;
				this.selectedNode = n;
				this.selectedFound = true;
			}
			str += this.node(cn, n);
			if (cn._ls) break;
		}
	}
	return str;
};

// Creates the node icon, url and text
dTree.prototype.node = function(node, nodeId) {
	var str = '<div class="node" style="cursor: pointer; cursor: hand; margin-left: ' + 15*(this.aIndent.length + ((node._hc) ? 0 : 1)) + 'px;" ';
	if (node._hc && node.pid != this.root.id) str += 'onclick="javascript: ' + this.obj + '.o(' + nodeId + ');" ';
	str += '>' + this.indent(node, nodeId);
	if (!node.icon) node.icon = (this.root.id == node.pid) ? this.icon.root : ((node._hc) ? this.icon.folder : this.icon.node);
	if (!node.iconOpen) node.iconOpen = (node._hc) ? this.icon.folderOpen : this.icon.node;
	if (this.root.id == node.pid) {
		node.icon = this.icon.root;
		node.iconOpen = this.icon.root;
	}
	str += '<img id="i' + this.obj + nodeId + '" src="' + ((node._io) ? node.iconOpen : node.icon) + '" alt="" />';
	str += '<a id="s' + this.obj + nodeId + '" class="' + (node._is ? 'nodeSel' : 'node')  + '" href="faq_online.php';
	if (node.id != 0) str += '?n=' + node.id;
	str += '" title="' + node.name + '" onclick="javascript: ' + this.obj + '.openNode(' + node.id + '); return false;">';
	str += node.name + '</a>';
	str += '</div>';
	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 expand/collapse icons
dTree.prototype.indent = function(node, nodeId) {
	var str = '';
	if (this.root.id != node.pid) {
		(node._ls) ? this.aIndent.push(0) : this.aIndent.push(1);
		if (node._hc) {
			str += '<img id="j' + this.obj + nodeId + '" width=9 height=9 hspace=3 alt="" border=1 src="';
			str += (node._io) ? this.icon.minus : this.icon.plus;
			str += '" />';
		}
	}
	return str;
};

// Checks if a node has any children and if it is the last sibling
dTree.prototype.setCS = function(node) {
	var lastId;
	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 (lastId==node.id) node._ls = true;
};

// Highlights the selected node
dTree.prototype.s = function(id) {
	var cn = this.aNodes[id];
	if (this.selectedNode != id) {
	         if (this.selectedNode || this.selectedNode==0) {
	                  eOld = item_byid("s" + this.obj + this.selectedNode);
	                  eOld.className = "node";
	         }
	         eNew = item_byid("s" + this.obj + id);
	         eNew.className = "nodeSel";
	         this.selectedNode = id;
	}
};

// Toggle Open or close
dTree.prototype.o = function(id) {
	var cn = this.aNodes[id];
	this.nodeStatus(!cn._io, id, cn._ls);
	cn._io = !cn._io;
	this.closeLevel(cn);
};

// Opens the tree to a specific node
dTree.prototype.openTo = function(nId, bSelect, bFirst) {
	if (!bFirst) {
		for (var n=0; n<this.aNodes.length; n++) {
			if (this.aNodes[n].id == nId) {
				nId=n;
				break;
			}
		}
	}
	var cn=this.aNodes[nId];
	if (cn.pid==this.root.id || !cn._p) {
		if (!bFirst) this.s(cn._ai);
		return;
	}
	cn._io = true;
	cn._is = bSelect;
	if (this.completed && cn._hc) this.nodeStatus(true, cn._ai, cn._ls);
	if (this.completed && bSelect) this.s(cn._ai);
	else if (bSelect) this._sn=cn._ai;
	this.openTo(cn._p._ai, false, true);
};

// Closes all nodes on the same level as certain node
dTree.prototype.closeLevel = function(node) {
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n].pid == node.pid && this.aNodes[n].id != node.id && this.aNodes[n]._hc) {
			this.nodeStatus(false, n, this.aNodes[n]._ls);
			this.aNodes[n]._io = false;
			this.closeAllChildren(this.aNodes[n]);
		}
	}
};

// Closes all children of a node
dTree.prototype.closeAllChildren = function(node) {
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n].pid == node.id && this.aNodes[n]._hc) {
			if (this.aNodes[n]._io) this.nodeStatus(false, n, this.aNodes[n]._ls);
			this.aNodes[n]._io = false;
			this.closeAllChildren(this.aNodes[n]);
		}
	}
};

// Change the status of a node(open or closed)
dTree.prototype.nodeStatus = function(status, id, bottom) {
	eDiv      = item_byid('d' + this.obj + id);
	eIcon     = item_byid('i' + this.obj + id);
	eIcon.src = (status) ? this.aNodes[id].iconOpen : this.aNodes[id].icon;
	eJoin     = item_byid('j' + this.obj + id);
	eJoin.src = (status)?this.icon.minus:this.icon.plus;
	eDiv.style.display = (status) ? 'block': 'none';
};

// Get node by id
dTree.prototype.nodeById = function(nId) {
	node = null;
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n].id == nId) {
			node = n;
			break;
		}
	}
	return node;
};

// Change the status of a node(open or closed)
dTree.prototype.openNode = function(id) {
	this.openNodeWithComments(id, false);
};

// Change the status of a node(open or closed)
dTree.prototype.openNodeWithComments = function(_id, comments, _caching) {	if (_caching == undefined) _caching = true;	this.internal_open(_id, comments, _caching);
	if ( h[hx] != _id ) {
		h.length = ++hx+1;
		h[hx] = _id;
         }
};

dTree.prototype.internal_open = function(_id, comments, _caching) {
	this.openTo(_id, true);
	nId = this.nodeById(_id);
	var node = this.aNodes[nId]
	if (_id!=0 && node._hc) this.o(nId);
	var req = new JsHttpRequest();
	req.onreadystatechange = function() {
		if ( req.readyState == 4) {
			item_byid('faqbody').innerHTML = req.responseJS.text;
			if ( comments ) toggle_div('c');
		}
	}
	req.caching = _caching;
	item_byid('title').innerHTML = node.name;
	item_byid('faqbody').innerHTML =
	'<table class="bodyline" border="0" width="96%" cellpadding="2" cellspacing="1" align="center">' +
	'<tr><td class="row1" valign="middle" height="44"><span class="gen">Идет загрузка данных.<br>' +
	'Это может занять некоторое время.</span></td></tr></table><br>';
	req.open('GET', 'faq_online/faq_load.php', true);
	req.send({ mode: 'id', id: _id});
	item_byid('bread_crumbs').innerHTML = this.get_bread_crumbs();
};

// Exec server request
dTree.prototype.out_rq = function(loc_id, msg, method, caching, clearcache, content, outid) {
	var req = new JsHttpRequest();
	if ( method == 'GET' ) {
		rqfile = 'faq_load.php';
	} else {
		rqfile = 'faq_post.php';
	}
	if ( clearcache ) {
		req.open('GET', 'faq_online/faq_load.php', true);
		req.clearcache({ mode: 'id', id: loc_id });
	}
	req.caching = caching;
	req.open(method, 'faq_online/' + rqfile, true);
	req.onreadystatechange = function() {
		if ( req.readyState == 4) item_byid(outid).innerHTML = req.responseJS.text;
	};
	item_byid(outid).innerHTML =
	'<table class="bodyline" border="0" width="96%" cellpadding="2" cellspacing="1" align="center">' +
	'<tr><td class="row1" valign="middle" height="44"><span class="gen">'+ msg +'<br>' +
	'Это может занять некоторое время.</span></td></tr></table><br>';
	req.send(content);
};

dTree.prototype.rq = function(loc_id, msg, method, caching, clearcache, content) {
	this.out_rq(loc_id, msg, method, caching, clearcache, content, 'faqbody');
};

// Reload tree
dTree.prototype.reload = function(_id){
	this.aNodes = [];
	this.selectedNode = null;
	item_byid('tree').innerHTML=
		'<table class="bodyline" border="0" width="96%" cellpadding="4" cellspacing="1" align="center">' +
		'<tr><td class="row1" valign="middle" height="44"><span class="gen">Обновление дерева навигации.<br>' +
		'Это может занять некоторое время.</span></td></tr></table>';

	var req = new JsHttpRequest();
	req.caching = false;
	req.method = 'script';
	req.open('GET', 'faq_online/faq_tree.php', true);
	req.onreadystatechange = function() {
		if ( req.readyState == 4) {			item_byid('tree').innerHTML = '';
			item_byid('faqbody').innerHTML = req.responseJS.text;
			eval(req.responseJS.tree);
		}
	};
	req.send({ mode: 'id', id: _id});
};

// Refresh tree
dTree.prototype.refresh = function(){
	_id = 0;
	var node = this.aNodes[this.selectedNode];
	if ( node ) _id = node.id;
	this.reload(_id);
};

// Renew item content
dTree.prototype.renew = function(){
	_id = 0;
	var node = this.aNodes[this.selectedNode];
	if ( node ) _id = node.id;

    var req = new JsHttpRequest();
	req.open('GET', 'faq_online/faq_load.php', true);
	req.clearcache({ mode: 'id', id: _id });
	req.caching = true;
	req.onreadystatechange = function() {
		if ( req.readyState == 4) item_byid('faqbody').innerHTML = req.responseJS.text;
	};
	item_byid('faqbody').innerHTML =
		'<table class="bodyline" border="0" width="96%" cellpadding="2" cellspacing="1" align="center">' +
		'<tr><td class="row1" valign="middle" height="44"><span class="gen">Выполняется обновление содержимого.<br>' +
		'Это может занять некоторое время.</span></td></tr></table><br>';
	req.send({ mode: 'id', id: _id });
};

// Generate bread crumbs
dTree.prototype.get_bread_crumbs = function(){
	bc = '';
	node = this.aNodes[this.selectedNode];
	while ( node ) {
		if ( bc != '') bc = ' :: ' + bc;
		bc = '<a onclick="javascript: hook_click(\''+ node.id +'\'); return false;" href="faq_online.php' +
		( node.id != 0 ? '?n=' + node.id : '') + '" class="faq_ref" title="' + node.name + '">' + node.name + '</a>' + bc;
		if ( node._p == this.root) break;
		node = node._p;
	}
	return bc;
};

dTree.prototype.go_back = function() {
  if (hx > 0) this.internal_open(h[--hx], false, true);
};

dTree.prototype.go_next = function() {
  if (hx < h.length-1) this.internal_open(h[++hx], false, true);
};

dTree.prototype.get_link = function(){
  var link = '[url="http://forum.chertenok.ru/faq_online.php"]FAQ Online[/url]';
  node = this.aNodes[this.selectedNode];
  if (node.id != 0) link = '[faq=' + node.id + ']' + node.name + '[/faq]';
  window.prompt('BB-код для вставки в тело сообщения:', link);
};

// 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;
	}
};

// Other global functions

/*-------------------------------------------------------------------------*/
// Get item by id
/*-------------------------------------------------------------------------*/
function item_byid(id)
{
	itm = null;
	if (document.getElementById) {
		// this is the way the standards work
		itm = document.getElementById(id);
	}
	else if (document.all) {
		// this is the way old msie versions work
		itm = document.all[id];
	}
	else if (document.layers) {
		// this is the way nn4 works
		itm = document.layers[id];
	}
	return itm;
};

/*-------------------------------------------------------------------------*/
// Show/hide toggle div
/*-------------------------------------------------------------------------*/
function toggle_div(whichLayer)
{
	if (!item_byid(whichLayer)) return;
	var style2 = item_byid(whichLayer).style;
	style2.display = style2.display?"":"none";
};

/*-------------------------------------------------------------------------*/
// Generate BBCode toolbar
/*-------------------------------------------------------------------------*/
document.write('<scr'+'ipt id="bbscript"></scr'+'ipt>');

function dynamicLoad(dynid, jsFileName){
	var getData = jsFileName;

	if( document.all ){
		if( navigator.userAgent.indexOf("Win")!=-1 ){
			//--for document.all && Win
			eval(document.all(dynid)).src = getData;
		} else if( navigator.userAgent.indexOf("Mac")!=-1 ){
			//--for document.all && Mac
			document.body.insertAdjacentHTML('BeforeEnd','<scr'+'ipt src="'+getData+'"><scr'+'ipt/>');
		}
	} else if( document.getElementById ) {
		//--for w3c-dom  without document.all
		var cnode =document.getElementById(dynid);
		var nnode = document.createElement('script');
		nnode.src = getData;
		nnode.id  = dynid;
		cnode.parentNode.replaceChild(nnode,cnode);
	}
};

function generate_toolbar(id) {
	syntax = new Array('', 'default', 'asm', 'c', 'cpp', 'csharp', 'css', 'delphi', 'html', 'javascript', 'oracle8', 'pascal', 'perl', 'php', 'python', 'sql', 'vb', 'vbnet', 'vfp', 'xml');
	syntaxnames = new Array('Вставить код...', 'Без подсветки', 'Asm', 'c', 'cpp', 'c#', 'css', 'Delphi', 'HTML', 'JavaScript', 'Oracle 8', 'Pascal', 'Perl', 'PHP', 'Python', 'SQL', 'VB', 'VB.NET', 'Visual FoxPro', 'xml');

	dynamicLoad("bbscript", "faq_online/bbcode.js");

	var bar = item_byid(id + '_bar');

	code = '<table border=0 cellspacing=0 cellpadding=1>\n';
	code += '<tr align=center valign=middle class=genmed>\n';
	code += '<td><input type=button class=button accesskey="b" id="'+id+'_bb0" value="B" style="font-weight:bold; width:25px" onClick="bbstyle(\'' + id + '\',0)"></td>\n';
	code += '<td><input type=button class=button accesskey="i" id="'+id+'_bb2" value="i" style="font-style:italic; width:25px" onClick="bbstyle(\'' + id + '\',2)"></td>\n';
	code += '<td><input type=button class=button accesskey="u" id="'+id+'_bb4" value="u" style="text-decoration: underline; width:25px" onClick="bbstyle(\'' + id + '\',4)"></td>\n';
	code += '<td><input type=button class=button accesskey="q" id="'+id+'_bb6" value="Quote" style="width:45px" onClick="bbstyle(\'' + id + '\',6)"></td>\n';

	code += '<td><select id="'+id+'_syntax" onChange="syntaxstyle(\'' + id + '\',item_byid(\''+id+'_syntax\').options[item_byid(\''+id+'_syntax\').selectedIndex].value);this.selectedIndex=0;">\n';
	for (i = 0; i < syntax.length; i++) {
		code += '<option value="' + syntax[i] + '" class="genmed">' + syntaxnames[i] + '</option>\n';
	}
	code += '</select></td>\n';
	code += '<td><input type=button class=button accesskey="l" id="'+id+'_bb10" value="List" style="width:35px" onClick="bbstyle(\'' + id + '\',10)"></td>\n';
	code += '<td><input type=button class=button accesskey="f" id="'+id+'_bb12" value="FAQ" style="width:40px" onClick="bbstyle(\'' + id + '\',12)"></td>\n';
	code += '<td><input type=button class=button accesskey="h" value="HR" style="width:30px" onClick="emoticon(\'' + id + '\',\'[HR]\')"></td>\n';
	code += '<td><input type=button class=button accesskey="p" id="'+id+'_bb14" value="Img" style="width:35px" onClick="bbstyle(\'' + id + '\',14)"></td>\n';
	code += '<td><input type=button class=button accesskey="w" id="'+id+'_bb16" value="URL" style="text-decoration: underline; width:40px" onClick="bbstyle(\'' + id + '\',16)"></td>\n';
	code += '</tr></table>';

	bar.innerHTML = code;
};

function emoticon(id, text) {
	var txtarea = item_byid(id);
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
	} else {
		txtarea.value  += text;
	}
	txtarea.focus();
};

function quoteSelection(id) {
	theSelection = false;
	// Get text selection
	if (document.getSelection) {
		theSelection = document.getSelection()
         }
	else if (document.selection) {
		theSelection = document.selection.createRange().text;
	}

	if (theSelection) {
		// Add tags around selection
		emoticon(id, '[quote]' + theSelection + '[/quote]\n');
		theSelection = '';
		return;
	} else {
		alert('Выделите текст на странице и попробуйте еще раз');
	}
};

// Insert at Claret position. Code from
// http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
function storeCaret(textEl) {
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
};

