
// <![CDATA[
function popupwikihelp() {
var win = window.open('', 'wikitips', 'height=600,width=600');
var doc = win.document;
doc.write('<div id="wikihelp"><p>Bold:&nbsp;&nbsp;__bold text__ (2 "_" before and after the text)</p><p>Italic:&nbsp;&nbsp;//italic text//</p><p>Link:&nbsp;&nbsp;{(ftp|http)://www.myurl.com This is the link text}</p><p>Internal Link:&nbsp;&nbsp;{link pageid Another internal webpage}</p><p>Section Link:&nbsp;&nbsp;{link #woadsectionX Link to a section} (X = section number)</p><p>Document Link:&nbsp;&nbsp;{doclink myfile.pdf My File}</p><p>Email:&nbsp;&nbsp;{myuser@myemail.com}</p><p>Image:&nbsp;&nbsp;{image src alt} (alt is optional)</p><p>Header:&nbsp;&nbsp;== This is a level 2 header (level is number of "=")</p><p>Column Break:&nbsp;&nbsp;| (on own line)</p><p>Right Justified:&nbsp;&nbsp;&gt; This paragraph is right justified</p><p>Centered:&nbsp;&nbsp;^ This paragraph is centered</p><p>Indented:&nbsp;&nbsp;: This paragraph is indented</p><p>Bulleted List:&nbsp;&nbsp;* Bulleted list item</p><p>Numbered List:&nbsp;&nbsp;# Bulleted list item</p><p>Horizontal Line:&nbsp;&nbsp;---- (at least 4 "-")</p></div>');
doc.close();
}
// ]]>


// <![CDATA[
function popupsearchtips() {
var win = window.open('', 'searchtips', 'height=300,width=400');
var doc = win.document;
doc.writeln('<p>A few tips on searching the directory</p>');
doc.writeln('<ul>');
doc.writeln('<li>Searches for <strong>any</strong> of the words listed (boolean OR)</li>');
doc.writeln('<li>"+" before a term will make it a required term: "John +Smith" finds "John Smith" but not "John Doe"</li>');
doc.writeln('<li>"-" before a term will make it required to not be present: "John -Smith" finds "John Doe" but not "John Smith"</li>');
doc.writeln('<li>"*" after a term will match words starting with the term: "cat*" matches "cat" "catalog" "category"</li>');
doc.writeln('</ul>');
doc.close();
return true;
}
// ]]>


// <![CDATA[
function openBrowser() {
field = (arguments[0]) ? escape(arguments[0]) : '';
root = (arguments[1]) ? escape(arguments[1]) : '';
rtype = (arguments[2]) ? arguments[2] : '';
url = (arguments[3]) ? arguments[3] : 'filebrowser.php';
url = url + "?root=" + root + "&rtype=" + rtype + "&field=" + field;
options = "width=350,height=500,status=yes,resizable=yes,scrollbars=yes";
browseWin = window.open(url, "FileBrowser", options);
browseWin.opener = self;
}
// ]]>


function openPageBrowser() {
url = "pagebrowser.php?field=" + arguments[0] + ( (arguments[1]) ? "&append=1" : "") + ( (arguments[2]) ? "&display=" + arguments[2] : "");
options = "width=480,height=350,status=no,resizable=yes,top=300,left=300,scrollbars=yes";
pageBrowseWin = window.open(url, "PageBrowser", options);
pageBrowseWin.opener = self;
}


/**********************************************************************/
/*
	AJAX Connect
	
	*** STANDARD METHOD ***
	
	Call this with:
		ajaxConnect(url, target_field_name[, output_type][, http_method]);
		
	url:
		URL of the file or script you are calling.
		
	target_field_name:
		Field ID to be used for the returned data.
		
	output_type (optional):
		html: Default behavior, assumes the data is in HTML format and
			puts it into the innerHTML of the supplied target field.
			
		custom: Requires a function called ajaxCustom that takes
			the arguments http_request and target. The function will
			be triggered when the content is sucessfully returned,
			and should be used to display the returned data.
			
		function_name: A function name can be passed in as an output type.
			In this case the function will be called in place of
			ajaxHandleContent, and should take http_request and target as
			arguments. This function will need to check for the readyState
			since it will be called for every state change of the
			http_request object.

	http_method (optional):
		GET: default behavior, treats the request as standard HTTP GET.
			Include any parameters in the URL using normal query string
			behavior.
		
		POST: treats the request as a HTTP POST. Include any parameters
			in the URL field using normal query string behavior.
			
	*** REMOTE METHOD USING <SCRIPT>***
	
	Call this with:
		ajaxConnectRemote(url[, script_id]);
		
	url:
		URL of the file or script you are calling.
		
	script_id (optional):
		DOM ID for the <script>. If left out, a default name will be used.
		
	NOTE: this function will require a callback function -- pass that
		to the receiving server in the querystring
*/
/**********************************************************************/

//standard connect, uses XMLHttpRequest
function ajaxConnect(url, target) {
	var http_request = false;
	var output_type = 'html';
	var http_method = 'GET';
	var url_parts;
	if (arguments.length == 3) {
		output_type = arguments[2];
	}
	else if (arguments.length == 4) {
		output_type = arguments[2];
		http_method = arguments[3];
	}
	
	//setup http_request
	if (window.XMLHttpRequest) {
		http_request = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {}
		}
	}
	
	//get the data
	if (!http_request) {
		alert('Cannot create an XMLHttpRequest object');
		return false;
	}
	http_request.onreadystatechange = function() { ajaxHandleContent(http_request, target, output_type); };
	switch (http_method) {
		case 'GET':
			http_request.open('GET', url, true);
			http_request.send(null);
			break;
			
		case 'POST':
			url_parts = url.split('?');
			if (!url_parts[1]) url_parts[1] = '';
			http_request.open('POST', url_parts[0], true);
			http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			http_request.setRequestHeader("Content-length", url_parts[1].length);
			http_request.setRequestHeader("Connection", "close");
			http_request.send(url_parts[1]);
			break;
	}
}

//default function for handling AJAX returns
function ajaxHandleContent(http_request, target, output_type) {
	if ((output_type != 'html') && (output_type != 'custom')) {
		eval(output_type + '(http_request, target);');
		return;
	}
	try {
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				if (output_type == 'html') {
					var text = http_request.responseText;
					document.getElementById(target).innerHTML = text;
				}
				else {
					ajaxCustom(http_request, target);
				}
			}
			else {
				alert('There was a problem with the request.');
			}
		}
	}
	catch(e) {
		alert('Caught Exception: ' + e.description);
	}
}

//remote JSON-type call, creates a new <script> on the fly in the doc <head>
function ajaxConnectRemote (url) {
	var parent = document.getElementsByTagName("head").item(0);
	var id = 'ajaxconnectremotescript';
	if (arguments.length == 2) {
		id = arguments[1];
	}
	var nocache = '&nocache=' + (new Date()).getTime();
	var scriptTag;
	
	//delete the generated <script> if it already exists
	if (document.getElementById(id)) parent.removeChild(document.getElementById(id));
	
	//create the new <script>
	scriptTag = document.createElement("script");
	scriptTag.setAttribute("type", "text/javascript");
	scriptTag.setAttribute("charset", "utf-8");
	scriptTag.setAttribute("src", url + nocache);
	scriptTag.setAttribute("id", id);
	parent.appendChild(scriptTag);
}

//*********************************************************** END AJAX Connect



/**********************************************************************/
/*
	Cascading Select
*/
/**********************************************************************/

//*********************************************************** Public API

//constructor
function cascadeSelect() {
	this.fieldlist;
	this.datalist = new Object();
	this.datalocation = 'local';
}

//cascade function 
cascadeSelect.prototype.cascade = function(field) {
	switch (this.datalocation) {
		case 'local':
			this.cascadeLocal(field);
			break;
	}		
}

//*********************************************************** Class methods

//cascade using a local data concept
cascadeSelect.prototype.cascadeLocal = function(field) {
	var i, level = 0;
	var numlevels = this.fieldlist.length;
	var newopts = this.datalist[field];
	
	//get level number from field list
	for (i = 0; i < numlevels; i++) {
		if (this.fieldlist[i] == field) {
			level = i;
			break;
		}
	}
	
	//clear options from appropriate select(s)
	for (i = level; i < numlevels; i++) {
		this.removeAllChildren(document.getElementById(this.fieldlist[i]));
	}
	
	//add new list of options
	for (i = 0; i < level; i++) {
		newopts = newopts[document.getElementById(this.fieldlist[i]).selectedIndex];
	}
	this.addSelectOptions(document.getElementById(field), newopts);
}

//cascade using a remote AJAX call
cascadeSelect.prototype.cascadeRemote = function(field) {
	var i, level = 0;
	var numlevels = this.fieldlist.length;
	
	//get level number from field list
	for (i = 0; i < numlevels; i++) {
		if (this.fieldlist[i] == field) {
			level = i;
			break;
		}
	}
	
	//clear options from appropriate select(s)
	for (i = level; i < numlevels; i++) {
		this.removeAllChildren(document.getElementById(this.fieldlist[i]));
	}
	
	//add new list of options
	/*TODO*/
}

//delete all children for a given node statement
cascadeSelect.prototype.removeAllChildren = function(node) {
	while (node.hasChildNodes()) node.removeChild(node.lastChild);
}

//add in an array of new options for a select
cascadeSelect.prototype.addSelectOptions = function(select, options) {
	var n, i, obj_option, obj_text, obj_value;
	n = options.length;
	
	for (i = 0; i < n; i++) {
		//handle option that is an array (value, text)
		if (options[i] instanceof Array) {
			obj_value = options[i][0];
			obj_text = options[i][1];
		}
		//others assume value = text
		else {
			obj_value = options[i];
			obj_text = options[i];
		}
		obj_option = document.createElement('option');
		obj_option.appendChild(document.createTextNode(obj_text));
		obj_option.setAttribute("value", obj_value);
		select.appendChild(obj_option);
	}
}

//*********************************************************** END Cascading Select

//*********************************************************** START Other Tools

var woadAjax = new Object();

//show/hide a section
woadAjax.expandDivCurrent;
woadAjax.expandDiv = function(id) {
   //do we hide the more link?
   var hidelink = (arguments.length == 2) ? arguments[1] : 0;

   //clear any open divs if requested
   if (woadAjax.expandDivCurrent) {
      document.getElementById(woadAjax.expandDivCurrent).style.display = 'none';
      document.getElementById(woadAjax.expandDivCurrent).style['z-index'] = -100;
      if (hidelink) document.getElementById(woadAjax.expandDivCurrent + 'morelink').style.display = 'block';
   }
   
   //open new div
   if (woadAjax.expandDivCurrent != id) {
      woadAjax.expandDivCurrent = id;
      document.getElementById(id).style.display = 'block';
      document.getElementById(id).style['z-index'] = 100;
      if (hidelink) document.getElementById(id + 'morelink').style.display = 'none';
   }
   else {
      woadAjax.expandDivCurrent = '';
   }
}

function getCookie(c_name) {
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1) {
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1) c_end = document.cookie.length;
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
	return "";
}

function setCookie(c_name, value, expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

function getQueryString(key) {
	qs = window.location.search.substring(1).split("&");
	for (var i = 0; i < qs.length; i++) {
		keypair = qs[i].split("=");
		if (keypair[0] == key) {
			return keypair[1];
		}
	}
}

//*********************************************************** END Other Tools
/*
The MIT Licence, for code from kryogenix.org

Code downloaded from the Browser Experiments section of kryogenix.org is licenced under the so-called MIT licence. The licence is below.

Copyright (c) 1997-date Stuart Langridge

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Modifications for odd row coloring from http://mathiasbynens.be/archive/2005/09/highlighted-sorttable

Other modifications and change to object-based format by Andrew Frink

######################################

To make a table sortable, the table must have an id specified, and must be of class "sortable"

Example:

	<table width="100%" class="sortable" id="uniqueid">
	
######################################
*/

var SortTables = new Object();
SortTables.sort_column_index;
SortTables.cascade = 1;

SortTables.init = function() {
	// Find all tables with class sortable and make them sortable
	if (!document.getElementsByTagName) return;
	tbls = document.getElementsByTagName("table");
	for (ti = 0; ti < tbls.length; ti++) {
		thisTbl = tbls[ti];
		if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) {
			SortTables.makeSortable(thisTbl);
		}
	}
}

SortTables.makeSortable = function(table) {
    if (table.rows && table.rows.length > 0) {
        var firstRow = table.rows[0];
    }
    if (!firstRow) return;

    // We have a first row: assume it's the header, and make its contents clickable links
    for (var i = 0; i < firstRow.cells.length; i++) {
        var cell = firstRow.cells[i];
        var txt = SortTables.getInnerText(cell);
        var html = '<a href="#" class="sortheader" onclick="SortTables.resortTable(this, '+i+'); return false;">';
        html += txt + '<span class="sortarrow">&nbsp;&nbsp;&nbsp;</span></a>';
        cell.innerHTML = html;
    }
}

SortTables.resortTable = function(lnk, clid) {
    // get the span
    var span;
    for (var ci = 0; ci < lnk.childNodes.length; ci++) {
        if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
    }
    var spantext = SortTables.getInnerText(span);
    var td = lnk.parentNode;
    var table = SortTables.getParent(td, 'TABLE');
    SortTables.sort_column_index = clid || td.cellIndex;
    
    // Work out a type for the column
    if (table.rows.length <= 1) return;
    var itm = SortTables.getInnerText(table.rows[1].cells[SortTables.sort_column_index]);
    var sortfn = SortTables.whichSort(itm);
    
    var firstRow =[];
    var newRows = [];
    for (i = 0; i < table.rows[0].length; i++) { firstRow[i] = table.rows[0][i]; }
    for (j = 1; j < table.rows.length; j++) { newRows[j - 1] = table.rows[j]; }
    
    newRows.sort(sortfn);
    
    if (span.getAttribute("sortdir") == 'down') {
        ARROW = '&nbsp;&nbsp;&uarr;';
        newRows.reverse();
        span.setAttribute('sortdir','up');
    } else {
        ARROW = '&nbsp;&nbsp;&darr;';
        span.setAttribute('sortdir','down');
    }
    
    // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
    // don't do sortbottom rows
    for (i = 0; i < newRows.length; i++) {
    	if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) table.tBodies[0].appendChild(newRows[i]);
    }
    // do sortbottom rows only
    for (i = 0; i < newRows.length; i++) {
    	if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) table.tBodies[0].appendChild(newRows[i]);
    }
    
    // Delete any other arrows there may be showing
    var allspans = document.getElementsByTagName("span");
    for (var ci = 0; ci < allspans.length; ci++) {
        if (allspans[ci].className == 'sortarrow') {
            if (SortTables.getParent(allspans[ci], "table") == SortTables.getParent(lnk, "table")) { // in the same table as us?
                allspans[ci].innerHTML = '&nbsp;&nbsp;&nbsp;';
            }
        }
    }
    
    span.innerHTML = ARROW;
	 
	 //add "oddrow" class to alternating rows
	 SortTables.setRowStyle(table);
}

SortTables.whichSort = function(itm) {
	var sortfn = SortTables.sort_caseinsensitive;
	if (itm.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2}$/)) sortfn = SortTables.sort_date;
	if (itm.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{4}$/)) sortfn = SortTables.sort_date;
	if (itm.match(/^[£$]/)) sortfn = SortTables.sort_currency;
	if (itm.match(/^-{0,1}[\d\.]+$/)) sortfn = SortTables.sort_numeric;
	return sortfn;
}

SortTables.sortNextColumn = function(a,b) {
	if (SortTables.cascade && (a.cells.length > (SortTables.sort_column_index + 1)) && (b.cells.length > (SortTables.sort_column_index + 1))) {
		SortTables.sort_column_index = SortTables.sort_column_index + 1;
		var sortfn = SortTables.whichSort(SortTables.getInnerText(a.cells[SortTables.sort_column_index]));
		var sorted = sortfn(a, b);
		SortTables.sort_column_index = SortTables.sort_column_index - 1;
		return sorted;
	}
	else {
		return 0;
	}
}

SortTables.sort_date = function(a, b) {
	aa = SortTables.getInnerText(a.cells[SortTables.sort_column_index]);
	bb = SortTables.getInnerText(b.cells[SortTables.sort_column_index]);
	dt1 = new Date(aa);
	dt2 = new Date(bb);
	dt1 = dt1.valueOf();
	dt2 = dt2.valueOf();
	if (dt1 == dt2) return SortTables.sortNextColumn(a, b);
	if (dt1 < dt2) return -1;
	return 1;
}

SortTables.sort_currency = function(a, b) { 
	aa = SortTables.getInnerText(a.cells[SortTables.sort_column_index]).replace(/[^0-9.]/g,'');
	bb = SortTables.getInnerText(b.cells[SortTables.sort_column_index]).replace(/[^0-9.]/g,'');
	if (parseFloat(aa) == parseFloat(bb)) return SortTables.sortNextColumn(a, b);
	return parseFloat(aa) - parseFloat(bb);
}

SortTables.sort_numeric = function(a, b) { 
	aa = parseFloat(SortTables.getInnerText(a.cells[SortTables.sort_column_index]));
	if (isNaN(aa)) aa = 0;
	bb = parseFloat(SortTables.getInnerText(b.cells[SortTables.sort_column_index]));
	if (isNaN(bb)) bb = 0;
	if (aa == bb) return SortTables.sortNextColumn(a, b);
	return aa-bb;
}

SortTables.sort_caseinsensitive = function(a, b) {
	aa = SortTables.getInnerText(a.cells[SortTables.sort_column_index]).toLowerCase();
	bb = SortTables.getInnerText(b.cells[SortTables.sort_column_index]).toLowerCase();
	if (aa == bb) return SortTables.sortNextColumn(a, b);
	if (aa < bb) return -1;
	return 1;
}

SortTables.sort_default = function(a, b) {
	aa = SortTables.getInnerText(a.cells[SortTables.sort_column_index]);
	bb = SortTables.getInnerText(b.cells[SortTables.sort_column_index]);
	if (aa == bb) return SortTables.sortNextColumn(a, b);
	if (aa < bb) return -1;
	return 1;
}

SortTables.getInnerText = function(el) {
	if (typeof el == "string") return el;
	if (typeof el == "undefined") { return el };
	if (el.innerText) return el.innerText;	//Not needed but it is faster
	var str = "";
	
	var cs = el.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				str += SortTables.getInnerText(cs[i]);
				break;
			case 3: //TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}

SortTables.getParent = function(el, pTagName) {
	if (el == null) {
		return null;
	}
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase()) {	// Gecko bug, supposed to be uppercase
		return el;
	}
	else {
		return SortTables.getParent(el.parentNode, pTagName);
	}
}

//recolors the table rows using "oddrow class"
SortTables.setRowStyle = function(table) {
	var trs = table.getElementsByTagName('tr');
	for (var j = 1; j < trs.length; j++) {
		trs[j].className = (j % 2 == 0 ? 'oddrow' : '');
	}
}

window.onload = SortTables.init;

//user summary AJAX wrapper
function get_user_summary(form, empfield) {
	f = document.getElementById(form);
	if (f[empfield].value) {
		ajaxConnect('http://www.drooartz.com/index.php?request=' + f[empfield].value, empfield + 'display');
	}
}
