/**
 * $Header: /home/mpdavig/proj/repository/html/home/work/company/ccib/library/lib/global.js,v 1.14 2009/10/22 04:14:43 mpdavig Exp $
 *
 * Requires MooTools 1.2 or greater
 *
 * COPYRIGHT:
 *
 * This software is Copyright (c) 2006-2010 Marc Davignon
 *                         <mpdavig@users.sourceforge.net>
 *
 * LICENSE:
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of Version 2 of the GNU General Public License as published by the
 * Free Software Foundation.
 */


/**
 * The JavaScript Anthology Pg. 15
 * Allows any number of load event handlers:
 *  addLoadListener(firstFunction);
 *  addLoadListener(secondFunction);
 *  addLoadListener(twentyThirdFunction);
 */
function addLoadListener(fn) {
  if (typeof window.addEventListener != 'undefined') {
    window.addEventListener('load', fn, false);
  } else if (typeof document.addEventListener != 'undefined') {
    document.addEventListener('load', fn, false);
  } else if (typeof window.attachEvent != 'undefined') {
    window.attachEvent('onload', fn);
  } else {
    var oldfn = window.onload;
    if (typeof window.onload != 'function') {
      window.onload = fn;
    } else {
      window.onload = function() {
        oldfn();
        fn();
      };
    }
  }
} // function addLoadListener(fn)


/**
 * Function for submitting forms using javascript
 * Parameters:
 *  form - name of form to submit
 *  submitvalue - sets a value to differentiate the type of submit
 */
function submitform(form, submitvalue) {
    // Hidden arguments 3 and 4 ([2] and [3]) and beyond set a form element by
    // id and value before the form is submitted.

    if (document.forms[form][0] && typeof document.forms[form][0].length != 'undefined') {
      // Get the form by "name", Opera and IE will return an array of forms
      // with the same name.
      formToSubmit = document.forms[form][0];
      //alert('first'); // Testing
    } else if (typeof document.forms[form].length != 'undefined') {
      // Get the form by "name", Firefox will only return the first form with
      // the matching name even if there is more than one.
      formToSubmit = document.forms[form];
      //alert('second'); // Testing
    } else {
      // Get the form by "id"
      formToSubmit = document.getElementById(form);
      //alert('third'); // Testing
    }

    for (var i=2;i < arguments.length;i=i+2) {
      //alert(arguments[i] + " " + arguments[i+1]); // Testing
      if (arguments[i] != null && arguments[i+1] != null) {
	// Allow the form action page to be dynamically changed
	if (arguments[i] == 'form_action') {
	  formToSubmit.action = arguments[i+1];
	} else if (arguments[i] == 'validate') {
	  testelement = arguments[i+1].split("::");
	  noValue = true;
	  for (i=0; i < formToSubmit.elements.length; i++) {
	    if ( formToSubmit.elements[i].name == testelement[0] && ( (formToSubmit.elements[i].type.match(/^(checkbox|radio)$/) && formToSubmit.elements[i].checked) || ! formToSubmit.elements[i].type.match(/^(checkbox|radio)$/) ) ) {
	      if (formToSubmit.elements[i].value) noValue=false;
	    }
	  }
	  if (noValue) { alert(testelement[1]); return; }
	} else if (formToSubmit.elements[arguments[i]]) {
          // Look for elements by "name" within the given form "name"
	  //alert(formToSubmit.elements[arguments[i]].type); // Testing
	  if (typeof formToSubmit.elements[arguments[i]].length == 'undefined' || formToSubmit.elements[arguments[i]].type == 'select-one') {
	    // Handle input type text, hidden, and submit and select list type select-one
	    formToSubmit.elements[arguments[i]].value = arguments[i+1];
	  } else {
	    // Handle checkboxes and radios
	    for (var ielem=0; ielem < formToSubmit.elements[arguments[i]].length; ielem++) {
	      //alert('Trying to use element "'+arguments[i]+'" found by "name" with value "'+arguments[i+1]+'" was value "'+formToSubmit.elements[arguments[i]][ielem].value+'"!'); // Testing
	      //alert(formToSubmit.elements[arguments[i]][ielem].type); // Testing
	      if (formToSubmit.elements[arguments[i]][ielem].checked && formToSubmit.elements[arguments[i]][ielem].type.match(/^(checkbox|radio)$/)) formToSubmit.elements[arguments[i]][ielem].value = arguments[i+1];
	    }
	  }
        } else if (document.getElementById(arguments[i]) && formToSubmit.elements[document.getElementById(arguments[i]).name]) {
          // Look for elements by "id" within the entire document
          // IE6 does not allow you to search through the form in this way
          // Second: Make sure the found element is actually in the form
          //alert('Trying to use element found by "id"! ' + document.getElementById(arguments[i]).name); // Testing
          document.getElementById(arguments[i]).value = arguments[i+1];
        } else {
          //alert('Trying to create new element!'); // Testing
          var newInput = document.createElement("input");
          newInput.setAttribute("type", "hidden");
          newInput.setAttribute("id", arguments[i]);
          newInput.setAttribute("name", arguments[i]);
          newInput.setAttribute("value", arguments[i+1]);
          formToSubmit.appendChild(newInput);
        }
      }
    }
    // Always create a fake submitvalue button
    var hiddenSubmit = document.createElement("input");
    hiddenSubmit.setAttribute("type", "hidden");
    hiddenSubmit.setAttribute("name", "submitvalue");
    hiddenSubmit.setAttribute("value", submitvalue);
    formToSubmit.appendChild(hiddenSubmit);

    //alert('test');
    // Actually submit the form
    formToSubmit.submit();
} // function submitform(form, submitvalue)


/*
Function: $get
This function provides access to the "get" variable scope + the element anchor

Version: 1.3

Arguments:
key - string; optional; the parameter key to search for in the url’s query string (can also be "#" for the element anchor)
url - url; optional; the url to check for "key" in, location.href is default

Example:
>$get("foo","http://example.com/?foo=bar"); //returns "bar"
>$get("foo"); //returns the value of the "foo" variable if it’s present in the current url(location.href)
>$get("#","http://example.com/#moo"); //returns "moo"
>$get("#"); //returns the element anchor if any, but from the current url (location.href)
>$get(,"http://example.com/?foo=bar&bar=foo"); //returns {foo:’bar’,bar:’foo’}
>$get(,"http://example.com/?foo=bar&bar=foo#moo"); //returns {foo:’bar’,bar:’foo’,hash:’moo’}
>$get(); //returns same as above, but from the current url (location.href)
>$get("?"); //returns the query string (without ? and element anchor) from the current url (location.href)

Returns:
Returns the value of the variable form the provided key, or an object with the current GET variables plus the element anchor (if any)
Returns "" if the variable is not present in the given query string

Credits:
Regex from [url=http://www.netlobo.com/url_query_string_javascript.html]http://www.netlobo.com/url_query_string_javascript.html[/url]
Function by Jens Anders Bakke, webfreak.no
*/
function $get(key,url){
  if (arguments.length < 2) url =location.href;
  if (arguments.length > 0 && key != "") {
    if (key == "#") {
      var regex = new RegExp("[#]([^$]*)");
    } else if (key == "?") {
      var regex = new RegExp("[?]([^#$]*)");
    } else {
      var regex = new RegExp("[?&]"+key+"=([^&#]*)");
    }
    var results = regex.exec(url);
    return (results == null )? "" : results[1];
  } else {
    url = url.split("?");
    var results = {};
    if (url.length > 1) {
      url = url[1].split("#");
      if (url.length > 1) results["hash"] = url[1];
      url[0].split("&").each(function(item,index){
	item = item.split("=");
	results[item[0]] = item[1];
      });
    }
    return results;
  }
} // function $get(key,url)


/**
 *
 */
function backToPrevious() {
    submitform('backform', 'Back');
} // function backToPrevious()


/**
 * Javascript Date Selector
 * by Warren Brown (03/01/2004 Radiokop South Africa)
 *
 * Script to place YYYY/MM/DD onto a web page, leap year enabled
 *
 * Add the following to your HTML, the third argument is optional:
 * <script>
 *      fill_select(document.FRM, 'nwanswer_recorded', '2006/05/22');
 * </script>
*/

var date_arr = new Array;
var days_arr = new Array;

date_arr[0]=new Option("January",31);
date_arr[1]=new Option("February",28);
date_arr[2]=new Option("March",31);
date_arr[3]=new Option("April",30);
date_arr[4]=new Option("May",31);
date_arr[5]=new Option("June",30);
date_arr[6]=new Option("July",31);
date_arr[7]=new Option("August",31);
date_arr[8]=new Option("September",30);
date_arr[9]=new Option("October",31);
date_arr[10]=new Option("November",30);
date_arr[11]=new Option("December",31);


/**
 * Simple JavaScript date drop down lists function
 *
 * f - Form to add values to
 * n - Name of hidden form input field which stores the value
 * d - Default value
 */
function fill_select(f, n, d) {
    document.writeln("<INPUT type=\"hidden\" name=\""+n+"\" id=\""+n+"\" value=\"\" />");
    //document.writeln("<INPUT type=\"text\" name=\""+n+"\" value=\"\" />"); // Testing
    document.writeln("<SELECT name=\"ignoremonths"+n+"\" id=\"ignoremonths"+n+"\" onchange=\"update_days("+f.name+", '"+n+"', '"+d+"');\">");
    document.writeln("<OPTION value=\"\">-</OPTION>");
    for (x=0; x<12; x++)
        document.writeln("<OPTION value=\""+date_arr[x].value+"\">"+date_arr[x].text+"</OPTION>");
    document.writeln("</SELECT><SELECT name=\"ignoredays"+n+"\" id=\"ignoredays"+n+"\" onchange=\"update_hidden("+f.name+", '"+n+"', '"+d+"');\"></SELECT>");
    selection = f.elements['ignoremonths'+n][f.elements['ignoremonths'+n].selectedIndex].value;
    year_install(f, n, d);
} // function fill_select(f, n, d)


/**
 *
 */
function update_days(f, n, d) {
    temp=f.elements['ignoredays'+n].selectedIndex;
    for (x=days_arr.length;x>0;x--) {
        days_arr[x]=null;
        f.elements['ignoredays'+n].options[x]=null;
    }

    selection=parseInt(f.elements['ignoremonths'+n][f.elements['ignoremonths'+n].selectedIndex].value);

    ret_val = 0;
    if (f.elements['ignoremonths'+n][f.elements['ignoremonths'+n].selectedIndex].value == 28) {
        year=parseInt(f.elements['ignoreyears'+n].options[f.elements['ignoreyears'+n].selectedIndex].value);
        if (year % 4 != 0 || year % 100 == 0 ) ret_val=0;
        else
            if (year % 400 == 0)  ret_val=1;
            else
                ret_val=1;
    }
    selection = selection + ret_val;

    f.elements['ignoredays'+n].options[0]=new Option("-","");

    for (x=1;x < selection+1;x++) {
        days_arr[x-1]=new Option(x);
        f.elements['ignoredays'+n].options[x]=days_arr[x-1];
    }

    if (temp == -1 && f.elements['ignoredays'+n].options[0]) f.elements['ignoredays'+n].options[0].selected=true;
    else
	if (f.elements['ignoredays'+n].options[temp]) f.elements['ignoredays'+n].options[temp].selected=true;

    update_hidden(f, n, d);
} // function update_days(f, n, d)


/**
 *
 */
function update_hidden(f, n, d) {
    f.elements[n].value = "";

    // On IE 6/7 we cannot use:
    // f.ignoredays.options[f.ignoredays.selectedIndex].value
    // so we use: f.ignoredays.selectedIndex
    // which fortunately are equivalent
    if (f.elements['ignoreyears'+n].options[f.elements['ignoreyears'+n].selectedIndex].value &&
	f.elements['ignoremonths'+n].options[f.elements['ignoremonths'+n].selectedIndex].value &&
	f.elements['ignoredays'+n].selectedIndex) {
	f.elements[n].value += f.elements['ignoreyears'+n].options[f.elements['ignoreyears'+n].selectedIndex].value;
	f.elements[n].value += "/";
	f.elements[n].value += (f.elements['ignoremonths'+n].selectedIndex < 10) ?
                                "0"+f.elements['ignoremonths'+n].selectedIndex.toString() :
                                f.elements['ignoremonths'+n].selectedIndex;
	f.elements[n].value += "/";
	f.elements[n].value += (f.elements['ignoredays'+n].selectedIndex < 10) ?
                                "0"+f.elements['ignoredays'+n].selectedIndex.toString() :
                                f.elements['ignoredays'+n].selectedIndex;
	// mdavignon: Handle hiding Back and Next buttons (wdx_inputreplacer.js)
	if (typeof(reallyHideSubmit) != 'undefined')
	    reallyHideSubmit('hideSubmitButtonBack,hideSubmitButtonNext', 1, 1);
    } else {
	if (typeof(reallyHideSubmit) != 'undefined')
	    reallyHideSubmit('hideSubmitButtonBack,hideSubmitButtonNext', 1, 0);
    }
    // Set the default value when no values are present
    if (d &&
        ! f.elements['ignoreyears'+n].options[f.elements['ignoreyears'+n].selectedIndex].value &&
	! f.elements['ignoremonths'+n].options[f.elements['ignoremonths'+n].selectedIndex].value &&
	! f.elements['ignoredays'+n].options[f.elements['ignoredays'+n].selectedIndex].value) {
        // Expects YYYY/MM/DD
        var defaultDate = d.split('/');
        for (x = 0; x < f.elements['ignoreyears'+n].options.length; x++) {
            if (f.elements['ignoreyears'+n].options[x].value == defaultDate[0]) f.elements['ignoreyears'+n].options[x].selected=true;
        }
        // Remove leading zeros
        f.elements['ignoremonths'+n].options[defaultDate[1].replace(/^[0]+/g,"")].selected=true;
        update_days(f, n, d);
        f.elements['ignoredays'+n].options[defaultDate[2].replace(/^[0]+/g,"")].selected=true;
        f.elements[n].value = d;
    }
    //alert(f.elements[n].value); // Testing
} // function update_hidden(f, n, d)


/**
 *
 */
function year_install(f, n, d) {
    var Today = new Date();
    document.writeln("<SELECT name=\"ignoreyears"+n+"\" id=\"ignoreyears"+n+"\" onchange=\"update_days("+f.name+", '"+n+"', '"+d+"');\">");
    document.writeln("<OPTION value=\"\">-</OPTION>");
    // Maybe no one in the study will be over 100 years old
    for(x=Today.getFullYear(); x>=Today.getFullYear() - 100; x--) document.writeln("<OPTION value=\""+x+"\">"+x+"</OPTION>");
    document.writeln("</SELECT>");
    update_days(f, n, d);
} // function year_install(f, n, d)

// End of Javascript Date Selector


/**
 * Only allow numeric keys to be pressed, including the 101+ keyboard number
 * pad keys while retaining special keys like backspace, tab, home, end, arrows,
 * etc.
 *
 * Note: "key == 0" is required for onkeypress which struggles with special keys
 */
function checkForNumeric(e) {
    var key = window.event ? e.keyCode : e.which;

    //alert("'" + key + "'"); // Testing
    if (e.shiftKey == 1) {
        return key == 0
            || key == 9
    } else {
        return key == 0
            || key == 8
            || key == 9
            || (key > 34 && key < 41)
            || (key > 47 && key < 58)
            || (key > 95 && key < 106)
    }
} // function checkForNumeric(e)


/**
 *
 */
function checkForNumericDot(e) {
    var key = window.event ? e.keyCode : e.which;

    // 8 backspace
    // 9 tab
    // 46, 110, 190 are required for .
    // > 34 & < 41 arrows
    // > 47 & < 58 number keys
    // > 95 & < 106 number pad keys
    //alert("'" + key + "'"); // Testing
    if (e.shiftKey == 1) {
        return key == 0
            || key == 9
    } else {
        return key == 0
            || key == 8
            || key == 9
            || key == 46
            || key == 110
            || key == 190
            || (key > 34 && key < 41)
            || (key > 47 && key < 58)
            || (key > 95 && key < 106)
    }
} // function checkForNumericDot(e)


/**
 *
 */
function checkForGender(e) {
    var key = window.event ? e.keyCode : e.which;

    // 70, 102 f
    // 77, 109 m
    //alert("'" + key + "'"); // Testing
    if (e.shiftKey == 1) {
        return key == 0
            || key == 9
            || key == 70
            || key == 77
    } else {
        return key == 0
            || key == 8
            || key == 9
            || key == 70
            || key == 77
            || key == 102
            || key == 109
            || (key > 34 && key < 41)
    }
    //alert("'" + key + "'"); // Testing
} // function checkForGender(e)


/**
 *
 */
function checkAll(inputName, unCheck) {
    inputs = document.getElementsByName(inputName);
    //cycle trough the input fields
    for(var i=0; i < inputs.length; i++) {
      if(inputs[i].getAttribute('type') == 'checkbox') {
	if (unCheck) inputs[i].checked = '';
	else inputs[i].checked = 'checked';
      }
    }
} // function checkAll(inputName, unCheck)


/**
 *
 */
function isChildWindow() {
  return (window.opener && window.opener.location != window.location) ? true : false;
} // function isChildWindow()


/**
 *
 */
function grayOut(vis, options) {
  // Pass true to gray out screen, false to ungray
  // options are optional.  This is a JSON object with the following (optional) properties
  // opacity:0-100         // Lower number = less grayout higher = more of a blackout
  // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
  // in any order.  Pass only the properties you need to set.
  var options = options || {};
  var zindex = options.zindex || 50;
  var opacity = options.opacity || 70;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';

  var dark='';
  if (isChildWindow()) {
    dark=opener.document.getElementById('darkenScreenObject');
  } else {
    dark=document.getElementById('darkenScreenObject');
  }

  if (!dark) {
    // The dark layer doesn't exist, it's never been created.  So we'll
    // create it here and apply some basic styles.
    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           // Create the layer.
        tnode.style.position='absolute';                 // Position absolutely
        tnode.style.top='0px';                           // In the top
        tnode.style.left='0px';                          // Left corner of the page
        tnode.style.overflow='hidden';                   // Try to avoid making scroll bars
        tnode.style.display='none';                      // Start out Hidden
        tnode.id='darkenScreenObject';                   // Name it so we can find it later
    tbody.appendChild(tnode);                            // Add it to the web page
    dark=document.getElementById('darkenScreenObject');  // Get the object.
  }
  if (vis) {
    // Calculate the page width and height
    if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
        var pageWidth = document.body.scrollWidth+'px';
        var pageHeight = document.body.scrollHeight+'px';
    } else if( document.body.offsetWidth ) {
      var pageWidth = document.body.offsetWidth+'px';
      var pageHeight = document.body.offsetHeight+'px';
    } else {
       var pageWidth='100%';
       var pageHeight='100%';
    }
    //set the shader to cover the entire page and make it visible.
    dark.style.opacity=opaque;
    dark.style.MozOpacity=opaque;
    dark.style.filter='alpha(opacity='+opacity+')';
    dark.style.zIndex=zindex;
    dark.style.backgroundColor=bgcolor;
    dark.style.width= pageWidth;
    dark.style.height= pageHeight;
    dark.style.display='block';
  } else {
     dark.style.display='none';
  }
} // function grayOut(vis, options)


/**
 * Remove right clicks within IE and Firefox
 * Unless viewing sites from local host
 */
var message="";


/**
 *
 */
function clickIE() {
    if (document.all) {
        (message);
        return false;
    }
}


/**
 *
 */
function clickNS(e) {
    if (document.layers || (document.getElementById && !document.all)) {
        if (e.which==2||e.which==3) {
            (message);
            return false;
        }
    }
}


//alert(location.host);
var hostRegExp = new RegExp("(127.0.0.1|ccibis|ccibis.mgh.harvard.edu|blossom|blossom.earth.org|www.chromosome.bwh.harvard.edu)");
if ( ! hostRegExp.test(location.host) ) {
    if (document.layers) {
        document.captureEvents(Event.MOUSEDOWN);
        document.onmousedown=clickNS;
    } else {
        document.onmouseup=clickNS;
        document.oncontextmenu =clickIE;
    }
    document.oncontextmenu=new Function("return false");
}

// End of Remove right clicks within IE and Firefox


/**
 * Count the number of occurrences of a specific character in a string
 */
String.prototype.count=function(s1) {
    return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
} // String.prototype.count=function(s1)


/**
 * Automatically scroll to the top of the page
 */
function scrollToTop() {
    window.scrollTo(0,0)
} // function scrollToTop()


/**
 * Automatically scroll to the bottom of the page
 * Note: Should work well enough for most sites, but may not be enough for
 * all pages.
 */
function scrollToBottom(yval) {
    yval = (yval == parseInt(yval)) ? yval : 3000;
    //alert(yval);
    window.scrollTo(0,yval)
} // function scrollToTop(yval)


/**
 * Automatically scroll to id="scrollpoint"
 */
function scrollToPosition() {
    var scrollObj = document.getElementById('scrollpoint');
    scrollToBottom(findPosY(scrollObj));
} // function scrollToPosition()


/**
 *
 */
function useDataExport() { useSection('dataexport'); }

/**
 *
 */
function closeDataExport() { closeSection('dataexport'); }


/**
 *
 */
function useSection(section) {
    var sectionObj = document.getElementById(section);
    sectionObj.style.display = "";
    scrollToBottom(findPosY(sectionObj));
} // function useSection(section)


/**
 *
 */
function closeSection(section) {
    var sectionObj = document.getElementById(section);
    sectionObj.style.display = "none";
    scrollToTop();
} // function closeSection(section)


/**
 *
 */
function showHide(idattrList) {
  idArray = idattrList.split(',');
  for (var i=0; i<idArray.length; i++) {
    if ( document.getElementById(idArray[i]) ) {
      document.getElementById(idArray[i]).style.display = (document.getElementById(idArray[i]).style.display) ? "" : "none";
    }
  }
} // function showHide(idattrList)


/**
 *
 */
function enableDisable(idattr) {
  document.getElementById(idattr).disabled = (document.getElementById(idattr).disabled) ? false : true;
} // function enableDisable(idattr)


/**
 *
 */
function onlyEnable(idattr) {
  document.getElementById(idattr).disabled = false;
} // function onlyEnable(idattr)


/**
 *
 */
function onlyDisable(idattr) {
  document.getElementById(idattr).disabled = true;
} // function onlyDisable(idattr)


/**
 *
 */
function hideList(idattrList) {
  idArray = idattrList.split(',');
  for (var i=0; i<idArray.length; i++) {
    if ( document.getElementById(idArray[i]) ) {
      document.getElementById(idArray[i]).style.display = "none";
    }
  }
} // function hideList(idattrList)


/**
 *
 */
function unhideList(idattrList) {
  idArray = idattrList.split(',');
  for (var i=0; i<idArray.length; i++) {
    if ( document.getElementById(idArray[i]) ) {
      document.getElementById(idArray[i]).style.display = "";
    }
  }
} // function unhideList(idattrList)


/**
 *
 */
function findPosX(obj) {
    var curleft = 0;
    if(obj.offsetParent)
        while(1)
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
}


/**
 *
 */
function findPosY(obj) {
    var curtop = 0;
    if(obj && obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj && obj.y)
        curtop += obj.y;
    return curtop;
}


/**
 *
 */
function iefileinputclick(fileinputid) {
  if ( document.getElementById(fileinputid) ) {
    var fileinputobj = document.getElementById(fileinputid);
    fileinputobj.click();
    //alert(fileinputobj.id); // Testing
  }
}


/**
 *
 */
function uncheckRemove(checkBoxValueID, checkBoxMsg, inputEnableID) {
  // checkBoxMsg default was 'upload queue'
  if (! checkBoxMsg) checkBoxMsg = "list";
  if ( document.getElementById(checkBoxValueID) ) {
    var checkBoxValueObj = document.getElementById(checkBoxValueID);

    var textNodeContents = '';
    var inputText = checkBoxValueObj.nextSibling;
    if (inputText.nodeType == 3) textNodeContents = inputText.nodeValue;
    var brNode = inputText.nextSibling;
    var imgNode = checkBoxValueObj.previousSibling;

    if( confirm( 'Are you sure you want to remove the item\r\n' +  textNodeContents + '\r\nfrom the ' + checkBoxMsg + '?' ) ){
      checkBoxValueObj.checked = '';
      checkBoxValueObj.style.display = 'none';
      if (inputText.nodeType == 3) inputText.nodeValue = '';
      if (brNode.tagName.toLowerCase() == 'br') brNode.style.display = 'none';
      if (imgNode.tagName.toLowerCase() == 'img') imgNode.style.display = 'none';
      onlyEnable(inputEnableID);
    } else {
      checkBoxValueObj.checked = 'checked';

      // Not needed since we should add the following to the page:
      // <script language="javascript" type="text/javascript">imgCheckboxTrue = 'images/cross_small.gif'; imgCheckboxFalse = 'images/cross_small.gif';</script>
      //if (imgNode.tagName.toLowerCase() == 'img') imgNode.src = imgCheckboxTrue;
    }
  }
} // function uncheckRemove(checkBoxValueID, checkBoxMsg, inputEnableID)


/**
 * Match the given URL with the navbar URL link and set the 'downState' class
 */
function navBreadCrumb(childURL) {
    var cookieName = 'lastURL';
    var tmplinks = document.getElementsByTagName('a');
    /*alert(childURL);*/
    var navMatch = 0;
    for (var i=0; i < tmplinks.length; i++) {
        /*alert(tmplinks[i].href);*/
        findUrlRegExp = new RegExp('/'+childURL+'$');
        if (findUrlRegExp.test(tmplinks[i].href)) {
	    tmplinks[i].className = 'downState';
	    /*alert(tmplinks[i].className);*/
            navMatch = 1;
            createCookie(cookieName,childURL,1825);
        }
    }
    // If no match was found, use the last matching URL stored in a cookie
    if (navMatch == 0 && childURL != 'index.htm') {
        childURL = readCookie(cookieName);
        for (var i=0; i < tmplinks.length; i++) {
            findUrlRegExp = new RegExp('/'+childURL+'$');
            if (findUrlRegExp.test(tmplinks[i].href)) {
                tmplinks[i].className = 'downState';
            }
        }
    }
} // function navBreadCrumb(childURL)


/**
 * Uncheck non-matching radio groups by unique id
 */
function radioChangeByUniqueId(radioName) {
    // load all the inputs into tmp array
    var matchUniqueID = radioName.substr(0,32);
    //alert(matchUniqueID);
    tmpradios = document.getElementsByTagName('input');
    for (var i=0; i < tmpradios.length; i++) {
        if ( tmpradios[i].name.match(matchUniqueID) && tmpradios[i].name.match('radio_group') && radioName != tmpradios[i].name) {
            //alert(tmpradios[i].name);
            tmpradios[i].checked='';
        }
    }
} // function radioChangeByUniqueId(radioName)


/**
 *
 */
function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
	num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
	cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$' + num + '.' + cents);
}


/**
 * Multiply numbers and return the values to the given form field Id
 *
 * Besides the two obvious arguments, every additional argument should be the
 * matching element Id value of the element values to multiply.
 *
 * @param bool currency set to true if the result value should be in currency format
 * @param string resultID element Id value of the form field to apply the result value to
 */
function multiplyNumbers(currency, resultID) {
  var result = 1;
  for (var i=2;i < arguments.length;i++) {
    // Try a couple ways to get the value by Id
    var tempID = arguments[i];
    if (! document.getElementById(tempID) ) tempID = tempID.replace(/Value$/g, '');
    else if (document.getElementById(tempID).nodeName.toLowerCase() == "span") tempID = "nw" + tempID.replace(/Value$/g, '') + "hidden";

    //alert(tempID); // Testing
    var multiplyVal = 0;
    if ( document.getElementById(tempID) ) {
      //alert(document.getElementById(tempID).value); // Testing

      // Strip non-currency characters
      document.getElementById(tempID).value = document.getElementById(tempID).value.replace(/[^\d|\.|,|\$]/g, '');
      // If the current value begins with "$" format it
      var currencyRegExp = new RegExp("^\\$");
      if ( currencyRegExp.test(document.getElementById(tempID).value) )
        document.getElementById(tempID).value = formatCurrency( document.getElementById(tempID).value );

      //alert(document.getElementById(tempID).value); // Testing
      multiplyVal = document.getElementById(tempID).value.replace(/[,|\$]/g, '');
    }
    result = result * multiplyVal;
  }

  // Try a couple ways to store the value by Id
  if (! document.getElementById(resultID) ) resultID = resultID.replace(/Value$/g, '');

  if (currency) document.getElementById(resultID).value = formatCurrency(result);
  else document.getElementById(resultID).value = result;
} // function multiplyNumbers(currency, resultID)


/**
 * See: http://www.merlyn.demon.co.uk/js-date7.htm#WoDA
 * There should be a PHP equivalent of this function in the near future
 * specifically for grant reporting.
 */
function calculateSalary(dateStartId, dateEndId, hourlyId, fringePercentId, salary, fringe, total ) {
  // Expecting YYYY/MM/DD
  var dateStart = document.getElementById(dateStartId);
  var dateEnd = document.getElementById(dateEndId);
  var hourly = document.getElementById(hourlyId);
  var fringePercent = document.getElementById(fringePercentId);

  // Span elements
  var salarySpan = document.getElementById(salary);
  var fringeSpan = document.getElementById(fringe);
  var totalSpan = document.getElementById(total);

  // Hidden values
  var salaryHidden = document.getElementById('nw'+salary+'hidden');
  var fringeHidden = document.getElementById('nw'+fringe+'hidden');
  var totalHidden = document.getElementById('nw'+total+'hidden');

  if (! dateStart || ! dateEnd || ! salaryHidden || ! fringeHidden || ! totalHidden) return;

  var tmpArray = [];

  // JavaScript month starts at 0 but given date starts at 1
  tmpArray = dateStart.value.split('/'); tmpArray[1]--;
  ST = new Date(tmpArray[0], tmpArray[1], tmpArray[2]);

  // JavaScript month starts at 0 but given date starts at 1
  tmpArray = dateEnd.value.split('/'); tmpArray[1]--;
  EN = new Date(tmpArray[0], tmpArray[1], tmpArray[2]);

  CD = new Date();

  //alert(ST.getDay()+' '+ST.getDate()+'/'+ST.getMonth()+'/'+ST.getFullYear()); // Testing
  //alert(ST); // Testing
  //alert(EN); // Testing

  var wkdCnt = 0;
  // Currently include the Current or End Date
  if (CD > EN) CD = EN;
  for (var D = ST; ST <= CD; D.setDate(D.getDate() + 1)) {
    // Remove weekends
    if (D.getDay() % 6 == 0) continue;
    wkdCnt++;
  }
  //alert(D); // Testing

  salaryTD = wkdCnt * 8 * hourly.value;
  fringeTD = fringePercent.value / 100 * salaryTD;
  totalTD = salaryTD + fringeTD;

  salaryTD = formatCurrency(salaryTD);
  fringeTD = formatCurrency(fringeTD);
  totalTD = formatCurrency(totalTD);

  salarySpan.innerHTML = salaryTD;
  fringeSpan.innerHTML = fringeTD;
  totalSpan.innerHTML = totalTD;

  salaryHidden.value = salaryTD;
  fringeHidden.value = fringeTD;
  totalHidden.value = totalTD;

  //alert(salaryTD); // Testing
  //alert(dateStart.value+"-"+dateEnd.value); // Testing
} // function calculateSalary(dateStartId, dateEndId, hourlyId, fringePercentId, salary, fringe, total )


/**
 *
 */
function getfocus(elementname)
{
    var tmp = (document.getElementsByName(elementname));
    //if (tmp.length > 0) tmp[tmp.length-1].focus();
    // Always focus on the first or second occurrence not the last
    if (tmp.length > 1) {
	tmp[1].focus();
    } else if (tmp.length > 0) {
	tmp[0].focus();
    }
}


/**
 *
 */
function createCookie(name,value,days)
{
    if (days)
	{
	    var date = new Date();
	    date.setTime(date.getTime()+(days*24*60*60*1000));
	    var expires = "; expires="+date.toGMTString();
	}
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}


/**
 *
 */
function readCookie(name)
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++)
	{
	    var c = ca[i];
	    while (c.charAt(0)==' ') c = c.substring(1,c.length);
	    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
    return null;
}


/**
 *
 */
function eraseCookie(name)
{
    createCookie(name,"",-1);
}


/**
 *
 */
function hideshowCookie(num,tag) {
    idstring = "element-" + num;
    hidestring = "hide-" + idstring;

    var x = document.getElementsByTagName(tag);
    for (var i=0;i<x.length;i++) {

        if (x[i].id == idstring) {
            if ( x[i].style.display == "none")  {
                x[i].style.display = "";
                eraseCookie(num);
            } else {
                x[i].style.display = "none";
                createCookie(num,1,1825);
            }
        }

	// "hide-" tags should be in an opposite state
        if (x[i].id == hidestring) {
            if ( x[i].style.display == "none")  {
                x[i].style.display = "";
            } else {
                x[i].style.display = "none";
            }
        }
    }
}


/**
 *
 */
function hideshow(num)
{
    idstring = "element-" + num;
    chunk = document.getElementById(idstring);
    if ( chunk.style.display == "none")  {
        chunk.style.display = chunk.style.tag;
    } else {
        chunk.style.tag = chunk.style.display;
        chunk.style.display = "none";
    }
}


/**
 *
 */
function hide(num,tag) {
    idstring = "element-" + num;

    var x = document.getElementsByTagName(tag);
    for (var i=0;i<x.length;i++) {

        if (x[i].id == idstring) {
            x[i].style.display = "none";
        }
    }
}


/**
 *
 */
function closeWindow() {
    window.open('','_parent','');
    window.close();
}


/**
 *
 */
function findHideCookies(tag) {
    var ca = document.cookie.split(';');
    var x = document.getElementsByTagName(tag);
    for (var i=0;i<x.length;i++) {
	// if the tag name begins with "hide-" hide it by default
	var hideRegExp = new RegExp("^hide-");
        if (hideRegExp.test(x[i].id)) {
	    x[i].style.display = "none";
	}
	for(var j=0;j < ca.length;j++) {
	    var c = ca[j];
	    while (c.charAt(0)==' ') c = c.substring(1,c.length);
	    idstring = "element-" + c.substring(0,c.lastIndexOf("="));
	    hidestring = "hide-" + idstring;

	    // hide elements with matching cookies
	    if (x[i].id == idstring) {
		x[i].style.display = "none";
	    }

	    // do the opposite for hidden elements
	    if (x[i].id == hidestring) {
		x[i].style.display = "";
	    }
	}
    }
}


function rand(l,u) { // lower bound and upper bound
     return Math.floor((Math.random() * (u-l+1))+l);
}


/**
 * IE6/7 have a maximum URL length limit of 2083 characters. This function
 * gets around this by creating an new window containing a form with the
 * values that would have been passed through the URL which is the auto
 * submitted.
 */
function popitup(url, height, width, windowName, optionIndex, centerWindow) {
  // If no windowName was given make them overwrite each other, otherwise
  // keep opening new windows.
  if (typeof windowName == 'undefined' || windowName == "") windowName = 'name';
  else windowName += rand(1,100);
  //alert(windowName); // Testing

  if (typeof optionIndex == 'undefined' || (optionIndex.value == "" && optionIndex.text != "-") || centerWindow) {
    //alert("here!"); // Testing
    var left,winPosLeft,winPosTop;
    if (centerWindow) {
      winPosLeft = (window.screen.width/2) - (width/2 + 10);
      winPosTop = (window.screen.height/2) - (height/2 + 50);
    } else {
      left = window.screenLeft != undefined ? window.screenLeft : window.screenX;
      winPosLeft = left + 40;
      winPosTop = winPosLeft;
    }

    var sURL = url.split('?');
    var urlJSONObj = $get("",url);

    var sData = "<html><head></head><body>";
    sData += "<form name='popform' id='popform' action='" + sURL[0] + "' method='post'>";

    for (var att in urlJSONObj) {
      // Loop through the url parameters adding them as hidden input elements
      sData += '<input type="hidden" name="' + att + '" value="' + unescape(urlJSONObj[att].toString()) + '" />';
      //alert('"' + att + '"' + ' ' + '"' + typeof(urlJSONObj[att].toString()) + '"'); // Testing
    }

    sData += "</form>";
    sData += "<script type='text/javascript'>";
    sData += "document.popform.submit();</sc" + "ript>";
    sData += "</body></html>";

    newwindow=window.open("",windowName,'height=' + height + ',width=' + width + ',scrollbars=1,left=' + winPosLeft + ',top=' + winPosTop + ',screenX=' + winPosLeft + ',screenY=' + winPosTop);
    newwindow.document.write(sData);
    //var top = window.screenTop != undefined ? window.screenTop : window.screenY;
    //newwindow.moveTo(winPos,winPos);
    if (window.focus) newwindow.focus();
  }
  return false;
} // function popitup(url, height, width, windowName, optionIndex, centerWindow)


/*
    http://www.javascriptf1.com/tutorial/javascript-popup-window.html
    1. screenX=hh,screenY=yy
        specifies the location of the upper left corner of the window, measured from the top left corner of the monitor (for NetScape 4.0 and later)
    2. left=hh,top=yy
        specifies the location of the upper left corner of the window, measured from the top left corner of the monitor (for Internet Explorer 4.0 and later)
*/
var baseText = {};


/**
 *
 */
function showPopup(width, elementID, submitValue){
  if ($chk($(elementID))) {
    var popUp = $(elementID);

    // http://www.javascripter.net/faq/browserw.htm
    var varWidthHeight = getWidthHeight();

    // Calculate the page width and height (centered)
    if( varWidthHeight.width || varWidthHeight.height ) {
      winPosLeft = ((varWidthHeight.width/2) - (width/2));
      winPosTop = ((varWidthHeight.height/2) - (60/2 + 50));
    //} else if( document.body && ( window.innerWidth || window.innerHeight ) ) {
      //winPosLeft = ((window.innerWidth/2) - (width/2 + 10));
      //winPosTop = ((window.innerHeight/2) - (60/2 + 50));
    } else {
      winPosLeft=250;
      winPosTop=200;
    }

    if (! baseText[elementID]) baseText[elementID] = popUp.innerHTML;
    if (submitValue) {
        popUp.innerHTML = baseText[elementID] + "<div class=\"libraryLeft\"><button class=\"librarySubmit\" type=\"button\" onclick=\"submitform('form1', '" + submitValue + "');\">" + submitValue + "</button></div> \
        <div class=\"libraryRight\"><button class=\"librarySubmit\" type=\"button\" onclick=\"hidePopup('" + elementID + "');\">Cancel</button></div>";
    } else {
        popUp.innerHTML = baseText[elementID] + "<div class=\"libraryRight\"><button type=\"button\" onclick=\"hidePopup('" + elementID + "');\">Close</button></div>";
    }

    popUp.style.left = winPosLeft+"px";
    popUp.style.top = winPosTop+"px";

    popUp.style.width = width + "px";

    // Average height is about 60px
    //popUp.style.height = 60 + "px"; // Testing

    popUp.style.visibility = "visible";

    //alert("left: " + window.screen.width + " " + popUp.style.left); // Testing
    //alert("top: " + window.screen.height + " " + popUp.style.top); // Testing
    //alert("width: " + popUp.style.width); // Testing
    //alert("height: " + popUp.style.height); // Testing
  }
} // function showPopup(width, elementID, submitValue)


/**
 * http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
 *
 * window.innerHeight/Width
 * 	Provided by most browsers, but importantly, not Internet Explorer.
 * document.body.clientHeight/Width
 * 	Provided by many browsers, including Internet Explorer.
 * document.documentElement.­clientHeight/Width
 * 	Provided by most DOM browsers, including Internet Explorer.
 */
function getWidthHeight(){
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return {"width" : myWidth, "height" : myHeight};
} // function getWidthHeight()


/**
 *
 */
function hidePopup(elementID){
    var popUp = document.getElementById(elementID);
    popUp.style.visibility = "hidden";
}


/**
 * Java Script to Handle AutoSearch
 */
function onEnterSubmit()
{
	var sndr = window.event.srcElement;
	var key = window.event.keyCode;

	if(key == 13)
		sndr.onchange();
}


/**
 *
 */
function checkboxValue(elementCheckbox) {
  document.getElementById(elementCheckbox).value = "";
  if (document.getElementById(elementCheckbox) && document.getElementById(elementCheckbox).checked) { document.getElementById(elementCheckbox).value = "yes"; }
} // function checkboxValue(elementCheckbox)


/**
 *
 */
function checkboxHide(elementCheckbox, elementCSV) {
  var displayStyle = "none";
  document.getElementById(elementCheckbox).value = "";
  if (document.getElementById(elementCheckbox) && document.getElementById(elementCheckbox).checked) { displayStyle = ""; document.getElementById(elementCheckbox).value = "yes"; }
  //alert(displayStyle); // Testing
  var hideElementIds = elementCSV.split(',');
  for (var i=0; i < hideElementIds.length; i++)
    if (document.getElementById(hideElementIds[i])) document.getElementById(hideElementIds[i]).style.display = displayStyle;
} // function checkboxHide(elementCheckbox, elementCSV)


/**
 *
 */
function storeCheckboxValues(elementCollectionName, elementStoreId) {
  document.getElementById(elementStoreId).value = '';
  var elementCollection = document.getElementsByName(elementCollectionName);
  for (var e=0;e<elementCollection.length;e++) {
      if (elementCollection[e].checked && elementCollection[e].value) document.getElementById(elementStoreId).value = (document.getElementById(elementStoreId).value) ? document.getElementById(elementStoreId).value+'~~'+elementCollection[e].value : elementCollection[e].value;
  }
  //alert(document.getElementById(elementStoreId).value); // Testing
} // function storeCheckboxValues(elementCollectionName, elementStoreId)


/**
 *
 */
function reverseStoreCheckboxValues(elementCollectionName, elementStoreId) {
  var elementCollection = document.getElementsByName(elementCollectionName);
  for (var e=0;e<elementCollection.length;e++) {
      if ( elementCollection[e].value in oc(document.getElementById(elementStoreId).value.split('~~')) ) {
        elementCollection[e].checked='checked';
        //alert(elementCollection[e].value);
      } else {
        elementCollection[e].checked='';
      }
  }
  //alert(document.getElementById(elementStoreId).value); // Testing
} // function reverseStoreCheckboxValues(elementCollectionName, elementStoreId)


/**
 * Converts an array into an object literal
 */
function oc(a) {
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
} // function oc(a)


/**
 * The SMK_KeyPress function (SMK = Select Match Keystrokes) provides keystroke matching
 * for SELECT controls. The SELECT element declaration should direct the onkeypress event
 * to this function, and declare two expandos: smk_keystrokes and smk_lastpresstime.
 */
function SMK_KeyPress() {
    var sndr = window.event.srcElement;
    var key = window.event.keyCode;
    var character = String.fromCharCode(key);
    var sysdate = new Date();
    // if the last key press was more than 2 seconds ago, reset the keystrokes
    if(sndr.smk_lastpresstime=="" || sysdate.getTime()-sndr.smk_lastpresstime>2000) {
        sndr.smk_keystrokes = "";
    }
    sndr.smk_lastpresstime = sysdate.getTime();
    // set up a regular expression for comparing with list box entries
    // search by first character on
    var re = new RegExp("^" + sndr.smk_keystrokes + character, "i");        // "i" -> ignoreCase
    // search entire string
    //var re = new RegExp(sndr.smk_keystrokes + character, "i");        // "i" -> ignoreCase
    // check each list box item for a match
    for(var i=0; i<sndr.options.length; i++) {
        if(re.test(sndr.options[i].text)) {
            sndr.options[i].selected=true;
            sndr.smk_keystrokes += character;
            break;
        }
    }
    // sink the keypress, ie don't pass it on to Windows or anything else
    window.event.returnValue = false;
}


/**
 *
 */
function isValid(parm,val) {
  if (parm == "") return true;
  for (i=0; i<parm.length; i++) {
    if (val.indexOf(parm.charAt(i),0) == -1) return false;
  }
  return true;
}


/**
 *
 */
function isNumber(parm) {return isValid(parm,'0123456789');}
function isLower(parm) {return isValid(parm,'abcdefghijklmnopqrstuvwxyz');}
function isUpper(parm) {return isValid(parm,'ABCDEFGHIJKLMNOPQRSTUVWXYZ');}
function isAlpha(parm) {return isValid(parm,'abcdefghijklmnopqrstuvwxyz'+'ABCDEFGHIJKLMNOPQRSTUVWXYZ');}
function isAlphanum(parm) {return isValid(parm,'abcdefghijklmnopqrstuvwxyz'+'ABCDEFGHIJKLMNOPQRSTUVWXYZ'+'0123456789');}


var imgCkIntervalID;
var imgCkLocalImg;
var imgCkElement0;
var imgCkElement1;
var imgCkSubmit;
//var imgCkServerCheckTimeoutMillis = 10000 //10 seconds
var imgCkServerCheckTimeoutMillis = 5000 //5 seconds
var imgCkServer0 = false;
var imgCkDateNow = new Date();
var imgCkStartTimeMillis = imgCkDateNow.getTime();


/**
 * http://bytes.com/topic/javascript/answers/160062-image-loading-using-javascript-handling-timeouts-parrallel-loading-under-ie
 * Add http://www.ajaxload.info later
 */
function internetImgCheck(idImg, remoteImg, localImg) {
  imgCkLocalImg = localImg;
  imgCkElement0 = document.getElementById(idImg);
  imgCkElement1 = document.getElementById(idImg+'Wait');
  imgCkSubmit = document.getElementById('submit');

  imgCkSubmit.disabled = true;

  imgCkElement0.src = remoteImg;
  imgCkElement0.onload = function() {
    imgCkServer0=true;
    imgCkElement1.style.display='none';
    imgCkElement0.style.display='';
    imgCkSubmit.disabled = false;
  };
  imgCkElement0.onerror = function() {
    imgCkElement0.src = imgCkLocalImg;
    imgCkElement1.style.display='none';
    imgCkElement0.style.display='';
    imgCkSubmit.disabled = false;
  };

  imgCkIntervalID = window.setInterval("checkServers()",500);

} // function internetImgCheck(idImg, remoteImg, localImg)


function checkServers() {
  var isTimeoutHappened = false;
  var currentTimeMillis = -1;

  dNow = new Date();
  currentTimeMillis = dNow.getTime();

  if ((currentTimeMillis - imgCkStartTimeMillis) >= imgCkServerCheckTimeoutMillis)
    isTimeoutHappened = true;

  if (imgCkServer0 == true) {
    window.clearInterval(imgCkIntervalID);
  } else if (imgCkServer0 == false && isTimeoutHappened) {
    // Keep Safari from continuing to load the prior image
    window.stop();
    imgCkElement0.src = imgCkLocalImg;
    imgCkElement1.style.display='none';
    imgCkElement0.style.display='';
    imgCkSubmit.disabled = false;
    window.clearInterval(imgCkIntervalID);
  }

} // function checkServers()
