function trace(string) {
	document.body.appendChild(document.createTextNode(string));
	document.body.appendChild(document.createElement('br'));
}

String.prototype.preFill = function(str, len) {
	var filledStr = this;
	while(filledStr.length < len) {
		filledStr = str.concat(filledStr);
	}
	while(filledStr.length > len) {
		filledStr = filledStr.substr(1, filledStr.length - 1);
	}
	return filledStr;
}

String.prototype.ltrim = function(char) {
	char = char || ' ';
	var re = new RegExp("^[" + char + "]*");
	return this.replace(re, '');
}

function pageopener(thelink,name){
	window.open(thelink,name,'toolbar=no,status=no,scrollbars=no,location=0,left=100,top=120,menubar=no,directories=no,width=650,height=500');
}

function bigpageopener(thelink,name){
	window.open(thelink,name,'toolbar=no,status=no,scrollbars=yes,location=0,left=100,top=120,menubar=no,directories=no,width=800,height=950');
}

function requestSnapshot(max) {
	var terms="";
	var delim = "";
	for (i = 1;i<=max;i++) {
		terms+=delim+document.getElementById("term"+i).value;
		delim="-";
	}
	window.location="?cat=term&view=snapshot&terms="+terms;
}

function editSession(params,succFunc,failFunc)
{
	try
	{
		//create object for request processing. see ajaxrequest.js
		var requestObject = new Object();
		requestObject.url = 'session.php';
		requestObject.parameters = params;
		if (failFunc)
		{
			requestObject.onFailure = failFunc;
		}
		else
		{
			requestObject.onFailure = function(req) { alert('AJAX_ERROR'); };
		}
		if (succFunc) requestObject.onSuccess = succFunc;

		AjaxRequest.get(requestObject);
		//alert('done');
	}
	catch (ex) { alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); }
}

function saveFilters(prefix,fields)
{
	var index = 0;
	var params = new Object();

	for(var i in fields)
	{

		index++;
		var value = '';
		var element = document.getElementById(fields[i]);

		//default case
		value = element.value;

		//multiple select
		if(element.multiple)
		{
			var value = '';
			var separator = '';
			var theOptions = element.options;

			for (i=0;i<theOptions.length;i++)
			{
				if(theOptions[i].selected)
				{
					value += separator + theOptions[i].value;
					separator = '|SEPR|';
				}
			}
		}

		//radio or checkbox
		if(element.type == 'radio' || element.type == 'checkbox') value = element.checked;

		params[element.id] = value;
	}

	var test = '';
	for(var i in params)
	{
		test += i + ': ' + params[i] + '\n';
	}
	//alert(test);

	params['vprefix'] = prefix;
	params['action'] = 'set';

	succFunc = function () { window.status = index+" filters in name space "+prefix+" saved."; };
	failFunc = function () { window.status = "Filters not saved."; };

	editSession(params,succFunc,failFunc)
}

function loadFilters(prefix,succFunc)
{
	var index = 0;
	var params = new Object();

	params['vprefix'] = prefix;
	params['action'] = 'getns';

	failFunc = function () { window.status = "Filters could not be loaded."; };

	editSession(params,succFunc,failFunc)
}

//===================================================
// allows only numerical values into an input.
// assign to onkeydown.

function onlyNumbers(e ,field)
{
	e = e ? e : window.event;
	var keynum;
	var isDot = false;

	if(window.event) // IE
	{
		if (e.keyCode==190) isDot = true;
		else keynum = e.keyCode;
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		if (e.which==190) isDot = true;
		else keynum = e.which;
	}

	var allowDot = true;
	if (field)
	{
		if (field.value.indexOf('.')>-1 || field.value=="") allowDot=false;
	}

	if (isDot)
	{
		return allowDot;
	}
	else
	{
		if (keynum==8) return true;
		else
		{
			var keychar = String.fromCharCode(keynum);
			return /[0-9]/.test(keychar);
		}
	}
}

function isNumeric(x)
{
	var numbers=".0123456789";
	// is x a String or a character?
	if(x.length>1)
	{
		// remove negative sign
		x=Math.abs(x)+"";
		for(j=0;j<x.length;j++)
		{
			// call isNumeric recursively for each character
			number=isNumeric(x.substring(j,j+1));
			if(!number) return number;
		}
		return number;
	}
	else
	{
		// if x is number return true
		if(numbers.indexOf(x)>=0) return true;
		return false;
	}
}

function pause(millisecond)
{
    var now = new Date();
    var exitTime = now.getTime() + millisecond;

    while(true)
    {
        now = new Date();
        if(now.getTime() > exitTime) return;
    }
}


function activateRadio(whichRadio) {
	document.getElementById(whichRadio).checked=true;
}
/////////////////////////////////////////////////////
// IE skips whitespace element, while Mozilla doesn't.
// That is why it needs this functions here:
function getFirstChild(n)
{
	var x=n.firstChild;
	while (x.nodeType!=1)
	{
		x=x.nextSibling;
	}
	return x;
}

function getNextChild (n) {
	var x=n.nextSibling;
	while (x.nodeType!=1)
	{
		x=x.nextSibling;
	}
	if (!x) return false;
	else return x;
}

function getLastChild (n) {
	var x=n.lastChild;
	while (x.nodeType!=1)
	{
	x=x.previousSibling;
	}
	if (!x) return false;
	else return x;
}

function countChildElementNodes(element) {
	var count=0;
	for(i=0; i<element.childNodes.length; i++) {
		if(element.childNodes[i].nodeType == 1) count++;
	}
	return count;
}
//
///////////////



function isCReportReady()
{
	var selTerm = document.getElementById("selTermID");
	var selCat = document.getElementById("selCatID");
	var selClass = document.getElementById("selClassID");
	if (selTerm.selectedIndex<1) selTerm.selectedIndex=0;
	if (selCat.selectedIndex<1) selCat.selectedIndex=0;
	if (selClass.selectedIndex<1) selClass.selectedIndex=0;
	return true;
}

function isEReportReady() {
	var hiddenField = document.getElementById("CRready");
	var selTerm = document.getElementById("selTermID");
	var selCat = document.getElementById("selCatID");
	if (selTerm.selectedIndex<1) selTerm.selectedIndex=0;
	if (selCat.selectedIndex<1) selCat.selectedIndex=0;
	hiddenField.value=1;
	return true;
}

function isIReportReady() {
	var hiddenField = document.getElementById("CRready");
	var selTerm = document.getElementById("selTermID");
	if (selTerm.selectedIndex<1) selTerm.selectedIndex=0;
	hiddenField.value=1;
	return true;
}

///////////////////////////////////////////////////////////
// functions to manage cookies
function getJSCookie(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 setJSCookie(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 eraseJSCookie(c_name) {
	setJSCookie(c_name,"",-1);
}

function existsJSCookie(c_name)
{
value=getJSCookie(c_name)
if (value!=null && value!="")
  return true;
else
  return false;
}
///////////////////////////////////////////////////////////

// ==========================================================================
// Fuctions to mimic LTrim, RTrim, and Trim...

// Author          Aurélien Tisné	(CS)
// Date            03 avr. 2003 23:11:39
// Last Update     $Date: 2007/08/16 23:17:19 $
// Version         $Revision: 1.20 $
// ==========================================================================

// --------------------------------------------------------------------------
// Remove leading blanks from our string.

// I               str - the string we want to LTrim
// Return          the input string without any leading whitespace

// Date            03 avr. 2003 23:12:13
// Author          Aurélien Tisné	(CS)
// --------------------------------------------------------------------------
function LTrim(str)
{
  var whitespace = new String(" \t\n\r");

  var s = new String(str);

  if (whitespace.indexOf(s.charAt(0)) != -1) {
    // We have a string with leading blank(s)...

    var j=0, i = s.length;

    // Iterate from the far left of string until we
    // don't have any more whitespace...
    while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
    j++;


    // Get the substring from the first non-whitespace
    // character to the end of the string...
    s = s.substring(j, i);
  }

  return s;
}

// --------------------------------------------------------------------------
// Remove trailing blanks from our string.

// I               str - the string we want to RTrim
// Return          the input string without any trailing whitespace

// Date            03 avr. 2003 23:13:50
// Author          Aurélien Tisné	(CS)
// --------------------------------------------------------------------------
function RTrim(str)
{
  // We don't want to trip JUST spaces, but also tabs,
  // line feeds, etc.  Add anything else you want to
  // "trim" here in Whitespace
  var whitespace = new String(" \t\n\r");

  var s = new String(str);

  if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
    // We have a string with trailing blank(s)...

    var i = s.length - 1;       // Get length of string

    // Iterate from the far right of string until we
    // don't have any more whitespace...
    while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
      i--;


    // Get the substring from the front of the string to
    // where the last non-whitespace character is...
    s = s.substring(0, i+1);
  }

  return s;
}


// --------------------------------------------------------------------------
// Remove trailing and leading blanks from our string.

// I               str - the string we want to Trim
// Return          the trimmed input string

// Date            03 avr. 2003 23:15:09
// Author          Aurélien Tisné	(CS)
// --------------------------------------------------------------------------
function Trim(str)
{
  return RTrim(LTrim(str));
}