addEvent(window, "load", sortables_init);
addEvent(window, "load", setvisible);
addEvent(window, "load", setResolutionCookie);

//doTheClock();

function setResolutionCookie() {
 var today = new Date();
 var the_date = new Date("December 31, 2023");
 var the_cookie_date = the_date.toGMTString();

 var width = 0;
 var height = 0;

 if (window.innerWidth) {
	 width = window.innerWidth;
 } else if (document.documentElement.clientWidth) {
		width = document.documentElement.clientWidth;
 }

 if (window.innerHeight) {
	 height = window.innerHeight;
 } else if (document.documentElement.clientHeight) {
		height = document.documentElement.clientHeight;
 }

 var the_cookie = "users_resolution="+ width +"x"+ height;
 var the_cookie = the_cookie + ";expires=" + the_cookie_date;
 var the_cookie = the_cookie + ";path=/";
 document.cookie=the_cookie
}

function getpathtoxml() {
  try {
    var realSelf = document.getElementById("REAL_SELF")
    var rc = realSelf.title;
  } catch (err) {
    var rc = '/';
  }

  return(rc);
}

/* StopEvent From Moo tools http://codingforums.com/showthread.php?t=85775 */
function stopEvent(e) {
    if (e.stopPropagation) e.stopPropagation();
    else e.cancelBubble = true;

    if (e.preventDefault) e.preventDefault();
    else e.returnValue = false;
}


function setvisible() {
  var previewData = document.getElementById("previewdata");

  if (previewData != undefined) {
    previewData.setAttribute("class", "invisible");
  }

  var mainData = document.getElementById("maindata");
  if (mainData != undefined) {
    mainData.setAttribute("class", "main");
  }
}

function jumpToAnchor(anchor) {
  window.location.hash=anchor;

  return false;
}

function setDateField(fieldname)
{
  daysInMonth = { 1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31 };

  if (document.getElementById(fieldname + '-day').value > daysInMonth[document.getElementById(fieldname + '-month').value]) {
    document.getElementById(fieldname + '-day').value = daysInMonth[document.getElementById(fieldname + '-month').value];
  }

  var year = document.getElementById(fieldname + '-year').value;
  if (isNaN(year)) {
    alert ("Year must be numeric!");
  }

  document.getElementById(fieldname).value = document.getElementById(fieldname + '-year').value + '-' + document.getElementById(fieldname + '-month').value + '-' + document.getElementById(fieldname + '-day').value;

  //alert(document.getElementById(fieldname).value);
}

//Find the parent tag with the name specified
function getParent(el, pTagName) {
  //Check to see if the immediate parent is the tag name we are looking for.

  alert ("GET PARENT CALLED");

  if (el == null) {
    debug("el was null!");
    return null;
  } else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())  // Gecko bug, supposed to be uppercase
  {
    return el;
  }
  else
  {
    //If not go up another level by Recursing
    return getParent(el.parentNode, pTagName);
  }
}

function getChildByTagNameAndClass(theElement, tagName, theClass) {
  var loop;
  var theChild;

  children = theElement.getElementsByTagName(tagName);
  for (loop=0;loop<children.length;loop++) {
    theChild = children[loop];
    if ((' '+theChild.className+' ').indexOf(theClass) != -1) {
      return theChild;
    }
  }
}


/**
 * This debug function displays plain-text debugging messages in a
 * special box at the end of a document.  It is a useful alternative
 * to using alert() to display debugging messages.
 **/
function debug(msg, severity) {
    // If we haven't already created a box within which to display
    // our debugging messages, then do so now.  Note that to avoid
    // using another global variable, we store the box node as a property
    // of this function.

    //var userName = document.getElementById("username"). innerHTML;
    userName = 'admin';

    if ((userName == "admin") || (severity > 0)) {
      if (!debug.box) {
          // Create a new <div> element
          debug.box = document.createElement("span");
          // Specify what it looks like using CSS style attributes
          debug.box.setAttribute("class","debugbox");

          // And append our new <div> element to the end of the document
          document.body.appendChild(debug.box);

          // Now add a title to our <div>.  Note that the innerHTML property is
          // used to parse a fragment of HTML and insert it into the document.
          // innerHTML is not part of the W3C DOM standard, but it is supported
          // by Netscape 6 and Internet Explorer 4 and later.  We can avoid 
          // the use of innerHTML by explicitly creating the <h1> element,
          // setting its style attribute, adding a Text node to it, and 
          // inserting it into the document, but this is a nice shortcut
          debug.box.innerHTML =
              "<h1 style='text-align:center'>Debugging Output</h1>";
      }

      // When we get here, debug.box refers to a <div> element into which
      // we can insert our debugging message.
      // First, create a <p> node to hold the message
      var p = document.createElement("p");
      // Now create a text node containing the message, and add it to the <p>
      p.appendChild(document.createTextNode(msg));
      // And append the <p> node to the <div> that holds the debugging output
      debug.box.appendChild(p);
  }
}

var SORT_COLUMN_INDEX;

function sortables_init(startPoint) {
    // Find all tables with class sortable and make them sortable
    //Make sure elements exist

    if (!document.getElementsByTagName) return;

    if(!startPoint) {
      tbls = startPoint.getElementsByTagName("table");
    } else {
      tbls = document.getElementsByTagName("table");
    }

    //Go through all the tables
    for (ti=0;ti<tbls.length;ti++) {
        thisTbl = tbls[ti];
        //For all tables that are marked as sortable and have an id run ts_makeSortable on it.
        if (((' '+thisTbl.className+' ').indexOf("sortableOLD") != -1) && (thisTbl.id)) {
            //initTable(thisTbl.id);
            if(!thisTbl.sortInit) {
              ts_makeSortable(thisTbl);
              thisTbl.sortInit = 1;
            }
        }
    }
}

function clearAllArrows() {
  spans = document.getElementsByTagName("span");
  //Go through all the tables
  for (span=0;span<spans.length;span++) {
    thisSpan = spans[span];
    //For all tables that are marked as sortable and have an id run ts_makeSortable on it.
    if ((' '+thisSpan.className+' ').indexOf("sortarrow") != -1) {
        thisSpan.innerHTML = "   ";
    }
  }
}

function ts_makeSortable(table) {
    //If the table has rows and the number of rows is great than 0 read the value of it.
    if (table.rows && table.rows.length > 0) {
        var firstRow = table.rows[0];
    }
    //If there is no first row, exit.
    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 = ts_getInnerText(cell);
        var txt = cell.innerHTML;
        // old if if(cell.getAttribute("sorted"));
        if (txt) {
          if (((' '+cell.className+' ').indexOf("sorted") != -1)) {
            cell.innerHTML = '<a href="http://" class="sortheader" onclick="ts_resortTable(this);return false;">' + txt + '<span sortdir="down" class="sortarrow"> &#8595; </span></a>';
          } else {
            if (cell.innerHTML != "&nbsp;") {
              cell.innerHTML = '<a href="http://" class="sortheader" onclick="ts_resortTable(this);return false;">' + txt + '<span class="sortarrow"></span></a>';
            }
          }
        }
    }
}

function ts_getInnerText(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 += ts_getInnerText(cs[i]);
        break;
      case 3: //TEXT_NODE
        str += cs[i].nodeValue;
        break;
    }
  }
  return str;
}

function ts_resortTable(lnk) {
  if (!ts_resortTable.link) {
    if (!ts_resortTable.box) {
      ts_resortTable.box = document.createElement("div");
      document.body.appendChild(ts_resortTable.box);
    }

    windowwidth = window.innerWidth;
    windowheight = window.innerHeight;
    displaywidth = 400;
    displayheight = 80;
    displayleft = (windowwidth / 2) - (displaywidth / 2);
    displaytop = (windowheight / 2)  - (displayheight / 2);

    ts_resortTable.box.setAttribute("style","display: block; position: fixed; top: " + displaytop + "px; left: " + displayleft + "px; width: " + displaywidth + "px;height: " + displayheight + "px; padding: 5px; margin: 10px; z-index: 100; color: black; border-style: solid; border-color: #41478e; border-width: 5px; background: #5864ff; font: 24px Verdana, sans-serif; text-align: center;");

    ts_resortTable.box.innerHTML = "Please wait.  Sorting table";

    ts_resortTable.link = lnk;

    window.setTimeout(ts_resortTable_work, 100);
  }
}

function ts_resortTable_work() {
  var percentdone;

  debug("Sorting...");
  if (!ts_resortTable_work.active) {
    ts_resortTable_work.active = true;
    ts_resortTable.phase0 = false;
    ts_resortTable.phase1 = false;
    ts_resortTable.phase2 = false;
    var i = 0;
    var thiscount = 0;
    var lnk = ts_resortTable.link;
    var span;
    var sorttype = "case insensitive";
    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 = ts_getInnerText(span);
    var td = lnk.parentNode;
    var column = td.cellIndex;
    ts_resortTable_work.table = getParent(td,'TABLE');

    // Work out a type for the column
    if (ts_resortTable_work.table.rows.length <= 1) return;


    sortfn = ts_sort_caseinsensitive;
    var itm = ts_resortTable_work.table.rows[1].cells[column].innerHTML;
    if (itm.match(/input/i)) { 
      sorttype = "Input Sort";
      sortfn = ts_sort_input;
    }

    itm = ts_getInnerText(ts_resortTable_work.table.rows[1].cells[column]).replace(/,/g,"");

    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) { 
      sortfn = ts_sort_date;
      sorttype = "Date Sort";
    }
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) { 
      sortfn = ts_sort_date;
      sorttype = "Date Sort";
    }

    if (itm.match(/^[£$]/)) { 
      sortfn = ts_sort_currency;
      sorttype = "Currency Sort";
    }

    if (itm.match(/^[\d\.]+$/)) {
      sortfn = ts_sort_numeric;
      sorttype = "Numeric Sort";
    }

    ts_resortTable_work.sortfn = sortfn;

    SORT_COLUMN_INDEX = column;
    /* var firstRow = new Array(); */
    ts_resortTable_work.newRows = new Array();

    // Clear all Arrows and previous up/down attributes.
    var allspans = document.getElementsByTagName("span");
    for (var ci=0;ci<allspans.length;ci++) {
        if (allspans[ci] != span) {
          allspans[ci].setAttribute('sortdir',"");
        }
        if (allspans[ci].className == 'sortarrow') {
            if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us?
                //allspans[ci].innerHTML = '&nbsp;&nbsp;&nbsp;';
            }
        }
    }

    ts_resortTable_work.reverseonly = false;
    if (span.getAttribute("sortdir") == 'down') {
        ARROW = ' &#8593; ';
        span.setAttribute('sortdir','up');
        ts_resortTable_work.sortdir = "up";
        ts_resortTable_work.reverseonly = true;
    } else {
        ARROW = ' &#8595; ';

        if (span.getAttribute("sortdir") == 'up') {
          ts_resortTable_work.reverseonly = true;
        }

        span.setAttribute('sortdir','down');
        ts_resortTable_work.sortdir = "down";
    }

    with (ts_resortTable_work) {
      /* for (i=0;i < ts_resortTable_work.table.rows[0].length;i++) {
        firstRow[i] = ts_resortTable_work.table.rows[0][i]; 
        debug('TEST');
      } */
      for (j=1;j < table.rows.length;j++) { 
        //newRows[j-1] = table.rows[j]; 
        //if (((' '+cell.className+' ').indexOf("sorted") != -1)) {
        if ((' '+table.rows[j].className.indexOf("data")) != -1) {
        //if (table.rows[j].getAttribute("class") == 'data') {
          newRows.push(table.rows[j]); 
        }
      }
    }

    clearAllArrows();
    span.innerHTML = ARROW;

    ts_resortTable_work.i = 0;
    ts_resortTable_work.j = 0;
    ts_resortTable.box.innerHTML = "Please Wait, Sorting...<br />" + sorttype;
    window.setTimeout(ts_resortTable_work, 10);
    return;
  }

  if (!ts_resortTable.phase0) {
    ts_resortTable.phase0 = true;

    if(ts_resortTable_work.reverseonly) {
      ts_resortTable_work.newRows.reverse();
    } else {
      if (ts_resortTable_work.newRows.length >= 1000) alert("Warning.  Because this table is so large you may need to hit 'continue' when your browser warns you that this process it taking too long.");
      ts_resortTable_work.newRows.sort(ts_resortTable_work.sortfn);
    }

    window.setTimeout(ts_resortTable_work, 10);

    return;
  }

  var thiscount = 0;
  if (!ts_resortTable.phase1) {
    while (ts_resortTable_work.i < ts_resortTable_work.newRows.length) {
      i = ts_resortTable_work.i;
      ts_resortTable_work.table.tBodies[0].appendChild(ts_resortTable_work.newRows[i]);

      ts_resortTable_work.i++;
      thiscount++;

      if (thiscount > 100) {
        window.setTimeout(ts_resortTable_work, 10);
        percentdone = i / ts_resortTable_work.newRows.length;
        percentdone = percentdone * 100;
        ts_resortTable.box.innerHTML = "Please Wait, Sorting...<br />" + Math.round(percentdone) + " percent done";
        return;
      }
    }
  }

  ts_resortTable_work.active = false;

  ts_resortTable.box.innerHTML = "complete";
  ts_resortTable.box.setAttribute("style","display: none;");
  ts_resortTable.link = 0;
}

//Find the parent tag with the name specified
function getParent(el, pTagName) {
  //Check to see if the immediate parent is the tag name we are looking for.
  if (el == null) return null;
  else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())  // Gecko bug, supposed to be uppercase
    return el;
  else
    //If not go up another level by Recursing
    return getParent(el.parentNode, pTagName);
}

function ts_sort_date(a,b) {
    // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    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) { 
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    return parseFloat(aa) - parseFloat(bb);
}

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

function ts_sort_numeric(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).replace(/,/g,"");
    aa = aa.replace(/\((.+)\)/,"-$1");
    aa = parseFloat(aa);
    if (isNaN(aa)) aa = 0;
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).replace(/,/g,""); 
    bb = bb.replace(/\((.+)\)/,"-$1");
    bb = parseFloat(bb);
    if (isNaN(bb)) bb = 0;
    //debug(aa+" - " +bb);
    return aa-bb;
}

function ts_sort_input(a,b) { 
    var aa = a.getElementsByTagName("input")[0].getAttribute("value");
    var bb = b.getElementsByTagName("input")[0].getAttribute("value");

    //var aaa = parseFloat(aa.cells[SORT_COLUMN_INDEX].innerHTML.replace(",",""));
    if (isNaN(aa)) aa = 0;
    //var bbb = parseFloat(b.cells[SORT_COLUMN_INDEX].innerHTML.replace(",","")); 
    if (isNaN(bb)) bb = 0;
    return aa-bb;
}

function ts_sort_caseinsensitive(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}

function ts_sort_default(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}

function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}



//============================================================
//Script:     Dynamic Title Bar Date-Time Clock
//
//Functions:  Shows the date and time dynamically in the
//            browser title bar in IE4 and later and NS6.
//            (Older browsers show the date and time in the
//            status bar.)
//            
//Browsers:   IE4 and later & NS6 Shows date-time in title bar
//            (Other browsers show date-time in status bar)
//
//Author:     etLux - after Microsoft
//============================================================
//
//INSTRUCTIONS:
//
//This is a simple one.  Just paste the following script into
//the <head> ... </head> of your page.  There are no
//other set-ups needed.
//
//<script language="JavaScript">
//<!--

// ==========================
// (C) 2000 by CodeLifter.com
// http://www.codelifter.com
// Free for all users, but leave in this  header

function doTheClock() {
   window.setTimeout( "doTheClock()", 1000 );
   t = new Date();
   if(theClock = document.getElementById('currentTime')){
      var theDate = dateFormat(t, "shortTime") + "<span>" + dateFormat(t, "default") + "</span>";

      //theDate = theDate.replace(/\s+/g, "&nbsp;");
      theClock.innerHTML = theDate;
   }
}


/*
  Date Format 1.1
  (c) 2007 Steven Levithan <stevenlevithan.com>
  MIT license
  With code by Scott Trenda (Z and o flags, and enhanced brevity)
*/

/*** dateFormat
  Accepts a date, a mask, or a date and a mask.
  Returns a formatted version of the given date.
  The date defaults to the current date/time.
  The mask defaults ``"ddd mmm d yyyy HH:MM:ss"``.
*/
var dateFormat = function () {
  var token        = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloZ]|"[^"]*"|'[^']*'/g,
    timezone     = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
    timezoneClip = /[^-+\dA-Z]/g,
    pad = function (value, length) {
      value = String(value);
      length = parseInt(length) || 2;
      while (value.length < length)
        value = "0" + value;
      return value;
    };

  // Regexes and supporting functions are cached through closure
  return function (date, mask) {
    // Treat the first argument as a mask if it doesn't contain any numbers
    if (
      arguments.length == 1 &&
      (typeof date == "string" || date instanceof String) &&
      !/\d/.test(date)
    ) {
      mask = date;
      date = undefined;
    }

    date = date ? new Date(date) : new Date();
    if (isNaN(date))
      throw "invalid date";

    var dF = dateFormat;
    mask   = String(dF.masks[mask] || mask || dF.masks["default"]);

    var d = date.getDate(),
      D = date.getDay(),
      m = date.getMonth(),
      y = date.getFullYear(),
      H = date.getHours(),
      M = date.getMinutes(),
      s = date.getSeconds(),
      L = date.getMilliseconds(),
      o = date.getTimezoneOffset(),
      flags = {
        d:    d,
        dd:   pad(d),
        ddd:  dF.i18n.dayNames[D],
        dddd: dF.i18n.dayNames[D + 7],
        m:    m + 1,
        mm:   pad(m + 1),
        mmm:  dF.i18n.monthNames[m],
        mmmm: dF.i18n.monthNames[m + 12],
        yy:   String(y).slice(2),
        yyyy: y,
        h:    H % 12 || 12,
        hh:   pad(H % 12 || 12),
        H:    H,
        HH:   pad(H),
        M:    M,
        MM:   pad(M),
        s:    s,
        ss:   pad(s),
        l:    pad(L, 3),
        L:    pad(L > 99 ? Math.round(L / 10) : L),
        t:    H < 12 ? "a"  : "p",
        tt:   H < 12 ? "am" : "pm",
        T:    H < 12 ? "A"  : "P",
        TT:   H < 12 ? "AM" : "PM",
        Z:    (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
        o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
      };

    return mask.replace(token, function ($0) {
      return ($0 in flags) ? flags[$0] : $0.slice(1, $0.length - 1);
    });
  };
}();

// Some common format strings
dateFormat.masks = {
  "default":       "ddd mmm d yyyy HH:MM:ss",
  shortDate:       "m/d/yy",
  mediumDate:      "mmm d, yyyy",
  longDate:        "mmmm d, yyyy",
  fullDate:        "dddd, mmmm d, yyyy",
  shortTime:       "h:MM TT",
  mediumTime:      "h:MM:ss TT",
  longTime:        "h:MM:ss TT Z",
  isoDate:         "yyyy-mm-dd",
  isoTime:         "HH:MM:ss",
  isoDateTime:     "yyyy-mm-dd'T'HH:MM:ss",
  isoFullDateTime: "yyyy-mm-dd'T'HH:MM:ss.lo"
};

// Internationalization strings
dateFormat.i18n = {
  dayNames: [
    "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
    "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
  ],
  monthNames: [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
  ]
};

// For convenience...
Date.prototype.format = function (mask) {
  return dateFormat(this, mask);
}
