//    ***********
//    SITE.INC.JS
//    ***********
//    Our Javascript Functions!

var xmlHttp;

//       ********
function postData(caction,cid,commentText,url)
//       ********
//       Post our data via HTTP
{
   xmlHttp=GetXmlHttpObject();
   if (xmlHttp==null)
   {
      alert ("Browser does not support HTTP Request");
      return;
   }
   postStr="cid="+cid+"&text="+commentText+"&action="+caction;
   xmlHttp.onreadystatechange=stateChanged;
   xmlHttp.open("POST",url,true);
   xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   xmlHttp.setRequestHeader("Content-length", postStr.length);
   xmlHttp.setRequestHeader("Connection", "close");
   xmlHttp.send(postStr);
   document.getElementById("txtResponse").innerHTML="Updating...";
}

//       ********
function getData(caction,url,idspace)
//       ********
//       Post our data via HTTP
{
   xmlHttp=GetXmlHttpObject();
   if (xmlHttp==null)
   {
      alert ("Browser does not support HTTP Request");
      return;
   }
   postStr="action="+caction;
   xmlHttp.onreadystatechange=getStateChanged;
   xmlHttp.open("POST",url,true);
   xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   xmlHttp.setRequestHeader("Content-length", postStr.length);
   xmlHttp.setRequestHeader("Connection", "close");
   xmlHttp.send(postStr);
   document.getElementById(idspace).innerHTML="Loading...";
}

//       ************
function stateChanged()
//       ************
//       let us know when our HTTP Request is complete
{
   if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
   {
      document.getElementById("txtResponse").innerHTML=xmlHttp.responseText;
      editing = false;
   }
}

//       ************
function getStateChanged(idspace)
//       ************
//       let us know when our HTTP Request is complete
{
   if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
   {
      document.getElementById("file_tree").innerHTML=xmlHttp.responseText;
	  convertTrees();
      editing = false;
   }
}


//       ****************
function GetXmlHttpObject()
//       ****************
//       Retrieve our HTTP request.
{
   var objXMLHttp=null;
   if (window.XMLHttpRequest)
   {
      objXMLHttp=new XMLHttpRequest();
   }
   else if (window.ActiveXObject)
   {
      objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
      return objXMLHttp;
   }

   var editing  = false;

   if (document.getElementById && document.createElement)
   {
      var butt = document.createElement('BUTTON');
      var buttext = document.createTextNode('Edit!');
      butt.appendChild(buttext);
      butt.onclick = saveEdit;
      var editpostbutt = document.createElement('BUTTON');
      var editpostbuttext = document.createTextNode('Edit!');
      editpostbutt.setAttribute('id','f_button');
      editpostbutt.appendChild(editpostbuttext);
      editpostbutt.onclick = saveEditPost;
      var subjectbutt = document.createElement('BUTTON');
      var subjectbuttext = document.createTextNode('Edit!');
      subjectbutt.setAttribute('id','f_button');
      subjectbutt.appendChild(subjectbuttext);
      subjectbutt.onclick = saveEditSubject;
   }

//       *******
function catchIt(e)
//       *******
//       catch our clicks
{
   if (editing) return;
   if (!document.getElementById || !document.createElement) return;
   if (!e) var obj = window.event.srcElement
      else var obj = e.target;
   while (obj.nodeType != 1)
   {
      obj = obj.parentNode;
   }
   if (obj.tagName == 'TEXTAREA' || obj.tagName == 'A') return;
   while (obj.nodeName != 'DIV' && obj.nodeName != 'HTML')
   {
      obj = obj.parentNode;
   }
   if (obj.nodeName == 'HTML') return;
   if (!obj.getAttribute('id')) return;
   var grabbedID = obj.getAttribute('id');
      // if (!grabbedID.match('editable_content') || !grabbedID.) return;
	  
   if (grabbedID.match('editable_content'))
   {
   var commentID = grabbedID.substr(16); // grab our number from this.
   var x = obj.innerHTML;
   var y = document.createElement('TEXTAREA');
      y.setAttribute('cols','80');
      y.setAttribute('id',commentID);
      y.setAttribute('rows','8');
      y.setAttribute('wrap','soft');
      y.style.whiteSpace = 'pre';
   // this will put the button below the textarea, but needs to be removed....
   var yBR = document.createElement('SPAN');
      yBR.setAttribute('id','remove_me');
      yBR.innerHTML = '<br />Useable tags: <b>&lt;b&gt;&lt;/b&gt;</b>, <i>&lt;i&gt;&lt;/i&gt;</i>, &lt;pre&gt;&lt;/pre&gt;, &lt;a href=\'http://link.here\'&gt;&lt;/a&gt;<br />';
   var z = obj.parentNode;
      z.insertBefore(y,obj);
      z.insertBefore(yBR,obj);
      z.insertBefore(butt,obj);
      z.removeChild(obj);
   // ok, this next part took FOREVER to sort out.
   // y.value takes <br>'s (and <br />'s -- even thought I don't tell it to... ? ah well..)
   // it takes them and replaces <br>\n (a line break) and turns it into just a line break.
   // but in IE, the textareas don't recognise linebreaks from the source for some reason
   // so a second command is needed to replace the <br> as if there was no \n after it
   // so <br> is replaced by \r, which isn't used by FF or Opera, but is by IE for some reason
   // so this is almost browser-specific code, without really being such. 'Cause without that,
   // FF/Opera would have double line breaks, or IE would have no line breaks. Both unacceptable.
   // I hope this is all that ever has to be done to fix this!
   y.value = x.replace(/<br>\n/gi, '\r\n');
   y.value = x.replace(/<br>/gi, '\r');
   y.focus();
   editing = true;
   }
   //  EDIT POSTS on FORUM
   //  *******************
   if (grabbedID.match('editable_postbody'))
   {
   var postID = grabbedID.substr(17); // grab our number from this.
   var x = obj.innerHTML;
   var y = document.createElement('TEXTAREA');
      y.setAttribute('cols','90');
      y.setAttribute('alt',postID);
      y.setAttribute('rows','10');
      y.setAttribute('wrap','soft');
      y.setAttribute('id','edit_fpost');	
      y.style.whiteSpace = 'pre';
   // this will put the button below the textarea, but needs to be removed....
   var yBR = document.createElement('SPAN');
      yBR.setAttribute('id','remove_me');
      yBR.innerHTML = '<br />Some text here<br />';
   var z = obj.parentNode;
      z.insertBefore(y,obj);
      z.insertBefore(yBR,obj);
      z.insertBefore(editpostbutt,obj);
      z.removeChild(obj);
   // ok, this next part took FOREVER to sort out.
   // y.value takes <br>'s (and <br />'s -- even thought I don't tell it to... ? ah well..)
   // it takes them and replaces <br>\n (a line break) and turns it into just a line break.
   // but in IE, the textareas don't recognise linebreaks from the source for some reason
   // so a second command is needed to replace the <br> as if there was no \n after it
   // so <br> is replaced by \r, which isn't used by FF or Opera, but is by IE for some reason
   // so this is almost browser-specific code, without really being such. 'Cause without that,
   // FF/Opera would have double line breaks, or IE would have no line breaks. Both unacceptable.
   // I hope this is all that ever has to be done to fix this!
   y.value = x.replace(/<br>\n/gi, '\r\n');
   y.value = x.replace(/<br>/gi, '\r');
   y.focus();
   editing = true;
   }
   // EDITING SUBJECTS in FORUMS
   // **************************
      if (grabbedID.match('editable_subject'))
   {
   var postID = grabbedID.substr(16); // grab our number from this.
   var x = obj.innerHTML;
   var y = document.createElement('INPUT');
      y.setAttribute('type','text');
      y.setAttribute('alt',postID);
      y.setAttribute('size','95');
      y.setAttribute('maxlength', '150');
      y.setAttribute('id','edit_fsub');
      y.style.fontSize = '10pt';
   var z = obj.parentNode;
      z.insertBefore(y,obj);
      z.insertBefore(subjectbutt,obj);
      z.removeChild(obj);
   // ok, this next part took FOREVER to sort out.
   // y.value takes <br>'s (and <br />'s -- even thought I don't tell it to... ? ah well..)
   // it takes them and replaces <br>\n (a line break) and turns it into just a line break.
   // but in IE, the textareas don't recognise linebreaks from the source for some reason
   // so a second command is needed to replace the <br> as if there was no \n after it
   // so <br> is replaced by \r, which isn't used by FF or Opera, but is by IE for some reason
   // so this is almost browser-specific code, without really being such. 'Cause without that,
   // FF/Opera would have double line breaks, or IE would have no line breaks. Both unacceptable.
   // I hope this is all that ever has to be done to fix this! - Rob
   y.value = x;
   y.focus();
   editing = true;
   }
   // ####
   if (grabbedID.match('file_tree_space_content'))
   {
   getData('file_tree_content','ajax.php','file_tree');
   document.getElementById("file_tree_space_content").innerHTML='';   
   }
   // ####
   if (grabbedID.match('file_tree_space_forum'))
   {
   getData('file_tree_forum','ajax.php','file_tree');
   document.getElementById("file_tree_space_forum").innerHTML='';   
   }

   // QUICK SEARCH
   // *********************
      if (grabbedID.match('quick_search'))
   {

	var y = document.getElementById('search_q');

	if(y.style.display == 'block')
	{
		y.style.display = 'none';
		return;
	}	
		

		
	y.style.display = 'block';
   	//var z = document.getElementsById('subject');
 
	document.search_form.query_string.focus();

   }

   // ADDING FLAG POSTS
   // *********************
      if (grabbedID.match('add_flag'))
   {

	var y = document.getElementById('flag_hide');

	if(y.style.display == 'block')
	{
		y.style.display = 'none';
		return;
	}	
		

		
	y.style.display = 'block';
   	//var z = document.getElementsById('subject');
 
	document.flag_form.flag_to.focus();

   }

   // ADDING QUICK NT POSTS
   // *********************
      if (grabbedID.match('add_quicknt'))
   {

	var y = document.getElementById('quick_nt');

	if(y.style.display == 'block')
	{
		y.style.display = 'none';
		return;
	}	
		

		
	y.style.display = 'block';

	document.qp_form.subject.focus();

   }

   // ADDING QUICK NT POSTS
   // *********************
      if (grabbedID.match('qp_cancel'))
   {
   var y = document.getElementById('quick_nt');
	y.style.display = 'none';
   }

}


//       ********
function saveEdit()
//       ********
//       save our edited comments
{
   var area = document.getElementsByTagName('TEXTAREA')[0];
   var commentText = area.value;
         commentTextBrowser = commentText.replace(/\n/gi,'<br />\n');
   var commentID = area.getAttribute('id');
   var y = document.createElement('DIV');
      y.setAttribute('className','editable_content'); // for IE...
      y.setAttribute('class','editable_content');
      y.setAttribute('id','editable_content'+commentID);
      y.innerHTML = commentTextBrowser;
   var notify = document.createElement('DIV');
      notify.setAttribute('id','txtResponse');
      notify.setAttribute('class','edited_content');
      notify.setAttribute('className','edited_content');
   var z = area.parentNode;
      z.insertBefore(notify,area)
      z.insertBefore(y,area);
      z.removeChild(area);
      z.removeChild(document.getElementsByTagName('button')[0]);
      // removes our BR tag
      z.removeChild(document.getElementById('remove_me'));
   postData('updatecomment', commentID, encodeURIComponent(commentText), 'ajax_update.php');
}

//       ********
function saveEditPost()
//       ********
//       save our edited comments
{
   var area = document.getElementById('edit_fpost');
   var commentText = area.value;
         commentTextBrowser = commentText.replace(/\n/gi,'<br />\n');
   var commentID = area.getAttribute('alt');
   var y = document.createElement('DIV');
      y.setAttribute('className','editable_content'); // for IE...
      y.setAttribute('class','editable_content');
      y.setAttribute('id','editable_postbody'+commentID);
      y.innerHTML = commentTextBrowser;
   var notify = document.createElement('DIV');
      notify.setAttribute('id','txtResponse');
      notify.setAttribute('class','edited_content');
      notify.setAttribute('className','edited_content');
   var z = area.parentNode;
      z.insertBefore(notify,area)
      z.insertBefore(y,area);
      z.removeChild(area);
      z.removeChild(document.getElementById('f_button'));
      // removes our BR tag
      z.removeChild(document.getElementById('remove_me'));
   postData('updatepostbody', commentID, encodeURIComponent(commentText), 'ajax_update.php');
}

//       ********
function saveEditSubject()
//       ********
//       save our edited comments
{
   var area = document.getElementById('edit_fsub');
   var commentText = area.value;
   var commentID = area.getAttribute('alt');
   var y = document.createElement('DIV');
      y.setAttribute('className','editable_content'); // for IE...
      y.setAttribute('class','editable_content');
      y.setAttribute('id','editable_subject'+commentID);
      y.innerHTML = commentText;
   var notify = document.createElement('DIV');
      notify.setAttribute('id','txtResponse');
      notify.setAttribute('class','edited_content');
      notify.setAttribute('className','edited_content');
   var z = area.parentNode;
      z.insertBefore(notify,area)
      z.insertBefore(y,area);
      z.removeChild(area);
      z.removeChild(document.getElementById('f_button'));
      // removes our BR tag
   postData('updatepostsubject', commentID, encodeURIComponent(commentText), 'ajax_update.php');
}


function InsertText(input, insTexte)
{

startTag = '';
endTag = '';

     if (input.createTextRange)
     {
      var text;
      input.focus(input.caretPos);
      input.caretPos = document.selection.createRange().duplicate();
      if(input.caretPos.text.length>0)
      {
       input.caretPos.text = startTag + input.caretPos.text + endTag;
      }
      else
      {
       input.caretPos.text = startTag + " " + insTexte + " " + endTag;
      }
     }
     else input.value += startTag + insTexte + endTag;
}


document.onclick = catchIt;
//window.onload=show;

//       ****
function show(id)
//       ****
//       show our menu item
{
   var d = document.getElementById(id);
   for (var i = 1; i<=10; i++)
   {
      if (document.getElementById('smenu'+i))
      {
         document.getElementById('smenu'+i).style.display='none';
      }
   }
   if (d)
   {
      d.style.display='block';
   }
}


//       ****
function hide(id)
//       ****
//       hide our menu item.
{
   var d = document.getElementById(id);
   for (var i = 1; i<=10; i++)
   {
      if (document.getElementById('smenu'+i))
      {
         document.getElementById('smenu'+i).style.display='none';
      }
   }
   if (d)
   {
      d.style.display='none';
   }
}


function InsertImage(id, imgname, gall, formname)
{

		if(formname == 'editor')
		{
		var oEditor = FCKeditorAPI.GetInstance(id) ;
		}
		else
		{
		var x = document.getElementById(id);
		
		}
		
	var editor = document.getElementById(formname);	
			
	if (editor.float_i[1].checked)
	{
		var styleAdd = 'float:left; padding:'+editor.pad_i.value+'px;';
	}
	if (editor.float_i[1].checked)
	{
		var styleAdd = 'float:right; padding:'+editor.pad_i.value+'px;';
	}
	if (editor.float_i[0].checked)
	{
		var styleAdd = 'padding:'+editor.pad_i.value+'px;';
	}
	
	if (formname == 'editor')	
	{
		oEditor.InsertHtml('<img src=\''+gall+imgname+'\' style=\''+styleAdd+'\' />') ;
	}
	else
	{
		InsertText(x,'<img src=\''+gall+imgname+'\' style=\''+styleAdd+'\' />');
	}
}


// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.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 my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

// HISTORY
// ------------------------------------------------------------------
// December 9, 2003: Added script to the Javascript Toolbox
// December 10, 2003: Added the preProcessTrees variable to allow user
//      to turn off automatic conversion of UL's onLoad
// March 1, 2004: Changed it so if a <li> has a class already attached
//      to it, that class won't be erased when initialized. This allows
//      you to set the state of the tree when painting the page simply
//      by setting some <li>'s class name as being "liOpen" (see example)
/*
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)
*/

// 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,true); 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) {
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	expandCollapseList(ul,nodeOpenClass);
}

// Fully collapses a tree with a given ID
function 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) {
	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) {
	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","mktree");
	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) {
	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") {
					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 = 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
				item.className = nodeBulletClass;
				s.onclick = function () { return false; }
			}
			s.appendChild(document.createTextNode(t));
			item.insertBefore(s,item.firstChild);
		}
	}
}


