/******************************************************************************\

 Common.js

  Description:    Common functions for various purposes

  Functions:      - OpenTree(name)
                  - GetWindowHeight()
                  - GetWindowWidth()
                  - SetCenter()

  Date:           2005-03-10
  Company:        InterShift
  Author:         Tom Erwich

  Version:      
  Date:        
  Author:        
  Changed        

\******************************************************************************/
function addEvent(obj, evType, fn){
	if(obj.addEventListener){
		obj.addEventListener(evType, fn, false); 
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent('on'+evType, fn);
		return r;
	} else {
		return false;
	}
}


if (!document.getElementById)
    document.getElementById = function() { return null; }

var timer;
/******************************************************************************\

  Function OpenTree()

  Description:    Retrieves the height of the client's browser window
  Parameters:     - o:    Object on which is clicked
                  - tree: Tree to open
  Returns:        boolean false
  Uses function:  none

  Date:           2005-03-10
  Author:         Tom Erwich

\******************************************************************************/
function OpenTree(o,tree) {
	var cls = '';
	var el = document.getElementById (tree);
	if (el && el.className) {
		el.className = (el.className == 'mnuBody') ? 'mnuBodyOpen' : 'mnuBody';
	}
	if (o && o.className) {
		o.className = (o.className=='mnuTtlOpen')?'mnuTtl':'mnuTtlOpen';
	}
	return false;
}


/******************************************************************************\

  Function GetWindowHeight()

  Description:    Retrieves the height of the client's browser window
  Parameters:      none
  Returns:      number (windowHeight)
  Uses function:    none

  Date:        2005-03-10
  Author:        Tom Erwich

\******************************************************************************/
function GetWindowHeight() {
  var windowHeight=0;
  if (typeof(window.innerHeight)=='number') {
    windowHeight=window.innerHeight;
  } else {
    if (document.documentElement&&
      document.documentElement.clientHeight) {
        windowHeight=
          document.documentElement.clientHeight;
    } else {
      if (document.body&&document.body.clientHeight) {
        windowHeight=document.body.clientHeight;
      }
    }
  }
  return windowHeight;
}


/******************************************************************************\

  Function GetWindowWidth()

  Description:    Retrieves the width of the client's browser window
  Parameters:      none
  Returns:      number (windowWidth)
  Uses function:    none

  Date:        2005-03-10
  Author:        Tom Erwich

\******************************************************************************/
function GetWindowWidth() {
  var windowWidth=0;
  if (typeof(window.innerWidth)=='number') {
    windowWidth=window.innerWidth;
  } else {
    if (document.documentElement&&
      document.documentElement.clientWidth) {
        windowWidth=document.documentElement.clientWidth;
    } else {
      if (document.body&&document.body.clientWidth) {
        windowWidth=document.body.clientWidth;
      }
    }
  }
  return windowWidth;
}


/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function SetCenter(ElementId) {
  if (document.getElementById) {
    var windowHeight=GetWindowHeight();
    var windowWidth  =GetWindowWidth();
    if (windowHeight>0 && windowWidth>0) {
      var is = document.getElementById(ElementId);
      var isH = is.offsetHeight;
      var isW = is.offsetWidth;
      is.style.position  = 'relative';
      is.style.top    = (windowHeight/2 - isH) + 'px';
      is.style.left    = (windowWidth/2 - isW/2) + 'px';
    }
  }
}


/******************************************************************************\

  Function hasClass()

  Description:    Checks if an object has a class and returns the class name
  Parameters:      - obj (object):  object
  Returns:        String|false
  Uses functions:    

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function hasClass(obj) {
	var result = false;
	if (obj.getAttributeNode("class") != null) {
		result = obj.getAttributeNode("class").value;
	}
	return result;
}   


/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function stripe_init() {
  if(!document.getElementsByTagName) return;
	var tbls	= document.getElementsByTagName("table");
	for(var i=0;i<tbls.length;i++) {
		thisTbl	= tbls[i];
		if((thisTbl.getAttribute("stripe")||thisTbl.getAttribute("v:stripe")) && thisTbl.id) {
			stripe(thisTbl.id);
		}
	}
}


/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function fstripe_init() {
  if(!document.getElementsByTagName) return;
	var tbls	= document.getElementsByTagName("table");
	for(var i=0;i<tbls.length;i++) {
		thisTbl	= tbls[i];
		if(thisTbl.getAttribute("fstripe") && thisTbl.id) {
			fstripe(thisTbl.id);
		}
	}
}


/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function stripe(id) {
	var even		= false;
	var evenColor	= arguments[1] ? arguments[1] : "#fff";
	var oddColor	= arguments[2] ? arguments[2] : "#ffdfb3";


	var table = document.getElementById(id);
	if (! table) { return; }

	var tbodies = table.getElementsByTagName("tbody");

	for (var h = 0; h < tbodies.length; h++) {
		var trs = tbodies[h].getElementsByTagName("tr");
		for (var i = 0; i < trs.length; i++) {
			if (! hasClass(trs[i]) && ! trs[i].style.backgroundColor) {
				var tds = trs[i].getElementsByTagName("td");
				for (var j = 0; j < tds.length; j++) {
					var mytd = tds[j];
					if (! hasClass(mytd) &&	! mytd.style.backgroundColor) {
							mytd.style.backgroundColor = even ? evenColor : oddColor;
					}
				}
			}
		even =  ! even;
		}
	}
}


/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function fstripe(id) {
	var even		= false;
	var evenColor	= arguments[1] ? arguments[1] : "#fff";
	var oddColor	= arguments[2] ? arguments[2] : "#ffdfb3";


	var table = document.getElementById(id);
	if (! table) { return; }

	var tbodies = table.getElementsByTagName("tbody");

	for (var h = 0; h < tbodies.length; h++) {
		var trs = tbodies[h].getElementsByTagName("tr");
		for (var i = 0; i < trs.length; i++) {
			if (! trs[i].style.backgroundColor) {
				var tds = trs[i].getElementsByTagName("td");
				for (var j = 0; j < tds.length; j++) {
					var mytd = tds[j];
					if (mytd.className != 'wk') {
							mytd.style.backgroundColor = even ? evenColor : oddColor;
					}
				}
			}
		even =  ! even;
		}
	}
}

var nw;


/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function mnw(url,w,h) {
	w		= (w == null)?500:w;
	h		= (h == null)?400:h;
	var wl	= (screen.width-w)/2;
	var wt	= (screen.height-h)/2;

	if((!nw)||(nw.closed)) {
		nw	= window.open(url,"popup","width="+ w +",height="+ h +",left="+ wl +",top="+ wt +",resizable=yes,toolbar=no,status=no,statusbar=no,menubar=no,copyhistory=no,scrollbars=auto,location=no");
		if(!nw.opener) {
			nw.opener	= window;
		}
		nw.focus();
	} else {
		nw.location	= 'about:blank';
		nw.location	= url;
		nw.resizeTo(w,h);
		nw.moveTo(wl,wt);
		nw.focus();
	}
}


/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function hide(aLyr) {
  var lyr = document.getElementById(aLyr);
  if(!lyr) { return; }

  if(!lyr.stickIt) {
	  clearTimeout(timer);
	  timer = setTimeout("hideLayer('"+ aLyr +"')",200);
  }
}

function stick(lyrid) {
  var lyr = document.getElementById(lyrid);
  if(!lyr) { return; }
  //alert(lyr.stickIt);
  if(lyr.stickIt == true) {
    lyr.stickIt = false;
  } else {
    lyr.stickIt = true;
  }
  //alert(lyr.stickIt);
}

/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function alt(lyr,text,e) {
	var x,y;
	var div	= document.getElementById(lyr);
	clearTimeout(timer);

	if(!div || !div.style)	{ return; }
	if(!e)		{ e = window.event; }
	x			= 100;
	y			= 100;
  //alert(x +' x'+ y);
	if(e.pageX && e.pageY) {
		x		= e.pageX;
		y		= e.pageY;
	} else if(e.clientX && e.clientY) {
		x		= e.clientX + document.body.scrollLeft;
		y		= e.clientY + document.body.scrollTop;
	}
  //alert(x +' x '+ y);
	div.innerHTML = text;
	div.style.top	= y +'px';
	div.style.left	= x +'px';
  
	timer = setTimeout("showLayer('"+ lyr +"')",300);

}


/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function hideLayer(aLyr) {
	var div	= document.getElementById(aLyr);

	if(!div || !div.style) { return; }
	clearTimeout(timer);
	div.style.visibility	= 'hidden';
	div.style.display	= 'none';
}


/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function showLayer(lyr) {
	//alert(lyr);
	
	var div = document.getElementById(lyr);

	if(!div) { return; }

	div.style.visibility = 'visible';
	div.style.display	= 'block';
  //alert(div.style.top +' - '+ div.style.left);
}


/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function showhide(lyr) {
	var div = document.getElementById(lyr);

	if(!div) { return; }
	if(!div.style.visibility || div.style.visibility == 'hidden') {
		showLayer(lyr);
	} else {
		hideLayer(lyr);
	}
}


/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function highlight_init() {
  if(!document.getElementsByTagName) return;
	var tbls	= document.getElementsByTagName("table");
	for(var i=0;i<tbls.length;i++) {
		thisTbl	= tbls[i];
		if(thisTbl.getAttribute("highlight") && thisTbl.id) {
			highlight(thisTbl.id);
		}
	}
}


/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function highlight(id) {
  var overColor = arguments[3] ? arguments[3] : "#FFA526";

  var table = document.getElementById(id);
  if (! table) { return; }
  
  var tbodies = table.getElementsByTagName("tbody");
  
  for (var h = 0; h < tbodies.length; h++) {
	var trs = tbodies[h].getElementsByTagName("tr");

	for (var i = 0; i < trs.length; i++) {
      if (! trs[i].style.backgroundColor) {
		var mytr  = trs[i];
		//mytr.overColor = overColor;
        mytr.onmouseover = function(evt) {
          removeTdClassName(this);
          //this.bgColor = this.overColor; 
        };
        mytr.onmouseout  = function(evt) {
          setTdClassName(this);
          //this.bgColor = "";
        };
	  }
	}
  }
}


/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function setTdClassName(tr) {
	var tds = tr.getElementsByTagName("td");
	for(var j =0;j < tds.length ; j++)
	{
		var mytd = tds[j];
		//var s = new String(mytd.className);
		//s = s.replace(/Over/g,"",s);
		//mytd.className = s;
		mytd.style.backgroundColor = mytd.tempcolor;
		mytd.style.color = mytd.temptext;
	}
}


/******************************************************************************\

  Function SetCenter()

  Description:    Sets the given element in center of the screen
  Parameters:      - ElementId (String): Element to center
  Returns:      nothing
  Uses functions:    - GetWindowWidth
            - GetWindowHeight

  Date:        2005-03-10
  Author:        Tom Erwich
  
\******************************************************************************/
function removeTdClassName(tr) {
  var alerted = false;
  var tds = tr.getElementsByTagName("td");
  for(var j=0;j<tds.length;j++) {
	var mytd = tds[j];
	mytd.tempcolor	= mytd.style.backgroundColor;
	mytd.temptext = mytd.style.color;
	mytd.style.backgroundColor = "#FFA526";
	mytd.style.color = "#fff";
	//mytd.className = mytd.className + 'Over';
  }
}	

/* Modification of sorttable.js
 * http://www.kryogenix.org/code/browser/sorttable/
 * Original code by Stuart Langridge, November 2003
 * Modified by Andy Edmonds, December 2003
 *  Added alternateRowColors to color alternating rows
 * Modified by caspar.dk, November 2004
 *  Added cookie-memory to remember most recent sorting
 *  Released at http://netfactory.dk/technology/markup/javascript/
 * Modified by Tom Erwich, August 2005
 *  Removed alternateRowColors
 *  Added 'sortable' as attribute in table tag in stead of part of class name
 */

var SORT_COLUMN_INDEX;

function sortables_init() {
  if(!document.getElementsByTagName) return;
	var tbls	= document.getElementsByTagName("table");
	for(var i=0;i<tbls.length;i++) {
		thisTbl	= tbls[i];
		if(thisTbl.getAttribute("sortable") && thisTbl.id) {
			ts_makeSortable(thisTbl);
		}
	}
}

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

  for(var i=0;i<firstRow.cells.length;i++) {
    var cell  = firstRow.cells[i];
    var txt   = ts_getInnerText(cell);

    if(cell.getAttribute("nosort")=="nosort") {
      // non sortable header
    } else {
      if(table.getAttribute("fstripe")) {
        funcs = "fstripe('"+ table.id +"');";
      } else {
        funcs = "";
      }
      cell.innerHTML = '<a href="#" class="sortheader" onclick="ts_resortTable(this);'+ funcs +';return false;">'+ txt +'</a>';
    }
  }
}

function ts_getInnerText(el) {
  if (typeof el == "string" || typeof el == "undefined") { 
    s1 = new String(el);
    el = s1.replace(/,/g,"");
    return el;
  };
  if (el.innerText) {
    s1 = new String(el.innerText);
    el = s1.replace(/,/g,"");
    return el;
  }
  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 += ts_getInnerText(cs[i]);
        break;
      case 3:	//TEXT_NODE
        str += cs[i].nodeValue;
        break;
    }
  }
  s1 = new String(str);
  el = s1.replace(/,/g,"");
  return el;
}

function ts_resortTable(lnk) {
  var td = lnk.parentNode;
  var column = td.cellIndex;
  var table = getParent(td,'TABLE');

  // Work out a type for the column
  if (table.rows.length <= 1) return;
  var itm = ts_getInnerText(table.rows[1].cells[column]);

  var s1 = new String(itm);
  itm = s1.replace(/,/g,"");

  var sortfn = ts_sort_caseinsensitive;
  if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) sortfn = ts_sort_date;
  if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = ts_sort_date;
  if (itm.match(/^[£$€]/)) sortfn = ts_sort_currency;
  if (itm.match(/^[\d\.]+$/)) sortfn = ts_sort_numeric;
  SORT_COLUMN_INDEX = column;
  var firstRow = new Array();
  var newRows = new Array();
  var lngth = table.rows[0].length;
  for (var i=0;i<lngth;i++) { firstRow[i] = table.rows[0][i]; }
  for (var j=1;j<table.rows.length;j++) { newRows[j-1] = table.rows[j]; }

  newRows.sort(sortfn);

  if(lnk.getAttribute("sortdir") && lnk.getAttribute("sortdir") == 'down') {
    newRows.reverse();
    lnk.setAttribute('sortdir','up');
  } else {
    lnk.setAttribute('sortdir','down');
  }
  
  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]);
  }
  for (i=0;i<newRows.length;i++) { 
    if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) table.tBodies[0].appendChild(newRows[i]);
  }
}


function getParent(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 getParent(el.parentNode, pTagName);
}

function ts_sort_date(a,b) {
  var aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
  var bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
  var dt1, dt2, yr;
  if (aa.length == 10) {
    dt1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
  } else {
    yr = aa.substr(6,2);
    if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
    dt1 = yr+aa.substr(3,2)+aa.substr(0,2);
  }
  if (bb.length == 10) {
    dt2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
  } else {
    yr = bb.substr(6,2);
    if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
    dt2 = yr+bb.substr(3,2)+bb.substr(0,2);
  }
  if (dt1==dt2) return 0;
  if (dt1<dt2) return -1;
  return 1;
}

function ts_sort_currency(a,b) {
  var aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
  var bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
  return parseFloat(aa) - parseFloat(bb);
}

function ts_sort_numeric(a,b) { 
  var aa = parseFloat(ts_getInnerText(a.cells[SORT_COLUMN_INDEX]));
  var bb = parseFloat(ts_getInnerText(b.cells[SORT_COLUMN_INDEX]));
	
  if (isNaN(aa)) aa = 0;
  if (isNaN(bb)) bb = 0;
	
  return aa-bb;
}

function ts_sort_caseinsensitive(a,b) {
  var aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
  var bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();

  var s1 = new String(aa);
  var s2 = new String(bb);

  aa = s1.replace(/,/g,"");
  bb = s2.replace(/,/g,"");

  if (!isNaN(aa) && !isNaN(bb)) {
    return aa-bb;
  }

  if (aa==bb) return 0;
  if (aa<bb) return -1;
  return 1;
}

function ts_sort_default(a,b) {
  var aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
  var bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);

  if (aa==bb) return 0;
  if (aa<bb) return -1;
  return 1;
}

/*addEvent(window, "load", stripe_init);
addEvent(window, "load", sortables_init);
addEvent(window, "load", fstripe_init);
addEvent(window, "load", highlight_init);*/
