/**
 * $Header: /home/mpdavig/proj/repository/html/home/work/company/ccib/library/lib/global.js,v 1.11 2008/12/02 05:02:56 mpdavig Exp $
 *
 * COPYRIGHT:
 *
 * This software is Copyright (c) 2006-2008 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)

            if (formToSubmit.elements[arguments[i]]) {
                // Look for elements by "name" within the given form "name"
                //alert('Trying to use element found by "name"!'); // Testing
                formToSubmit.elements[arguments[i]].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);
    // Actually submit the form
    formToSubmit.submit();
} // function submitform(form, submitvalue)


/**
 *
 */
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)


/**
 * 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(idattr) {
  document.getElementById(idattr).style.display = (document.getElementById(idattr).style.display) ? "" : "none";
} // function showHide(idattr)

/**
 *
 */
function enableDisable(idattr) {
  document.getElementById(idattr).disabled = (document.getElementById(idattr).disabled) ? false : true;
} // function enableDisable(idattr)


/**
 *
 */
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) {
  // 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';
    } 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;
    }
  }
}


/**
 * 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.php') {
        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);
}


/**
 *
 */
function popitup(url, height, width, windowName, optionIndex) {
  // 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 != "-")) {
    newwindow=window.open(url,windowName,'height=' + height + ',width=' + width + ',scrollbars=1');
    //var top = window.screenTop != undefined ? window.screenTop : window.screenY;
    var left = window.screenLeft != undefined ? window.screenLeft : window.screenX;
    var winPos = left + 40;
    newwindow.moveTo(winPos,winPos);
    if (window.focus) newwindow.focus();
  }
  return false;
} // function popitup(url, height, width, windowName, optionIndex)

/*
    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){
    var popUp = document.getElementById(elementID);

    popUp.style.top = "200px";
    popUp.style.left = "250px";
    popUp.style.width = width + "px";

    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.visibility = "visible";
}


/**
 *
 */
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;
}
