
function highlightFilterLetter(letter) {
  if(letter == "null" || letter == "" || letter == " ") {
    letter = "all";
  }
  el = "filter-" + letter;
  document.getElementById(el).style.fontWeight = 'bold';
}

function highlightFilterArrow(orderBy, orderType, context) {

  el = "sort-" + orderBy + "-" + orderType;

  path = context + "/images/";

  if(orderType == "asc" || orderType == "ASC") {
    path += "sort_up_on.gif";
  } else {
    path += "sort_down_on.gif";
  }
 
  document.getElementById(el).src = path;
 
}

function checkPhone(object)
{
	var temp = object.value;
	
	 var stripped = temp.replace(/[\(\)\.\-\ ]/g, '');
	//strip out acceptable non-numeric characters
	if (isNaN(parseInt(stripped))) {
	   alert("Not a number.  Please try again.");
	   object.select();
	   return false
	} 
	
	if ((stripped.length > 12)) {
	   alert("Too many digits.  Please try again.");
	   
	   return false
	}
		return true;
}



function checkEmail(obj){

var error = "";
var strng = obj.value; 
 
	var emailFilter=/^.+@.+\..{2,3}$/;
	if (!(emailFilter.test(strng))) { 
		   error = "Please enter a valid email address.\n";
	}
	
	var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/
	if (strng.match(illegalChars)) {
	   error = "The email address contains illegal characters.\n";
	
	}
	if (error != ""){
	alert(error); 
	return false;
	}
	else
	 {
	 	return true;
	 }
}








// File Name: Popup.js
//
// Description: Contains all JS logic for communication to, and opening of popup applets.
//
// Author: AJAYASUR
// Created: Feb 5 2003
// Modified Feb 5 2003

var oDiv = null;
var oWindow = null;
var m_bFirstTime = false;
var m_sDimensions = null;
var m_bInAssocPopup = false;
var m_sURLArg = null;
var m_bParentClose = false;
var m_bQuickCreate = false;
var aQuickCreates = null;
var m_bQCResizeDone = false;


function closeChildren()
{
        if (oWindow != null && !oWindow.closed  && oWindow.m_bQuickCreate == false)
        {
                oWindow.m_bParentClose = true;

                if (oWindow != null && !oWindow.closed)
                {
                        oWindow.close();
                }
        }
}

// Add the QuickCreate to the array
function addQuickCreate (qc)
{
    if(aQuickCreates == null)
    {
        aQuickCreates = new Array();
    }

    aQuickCreates.push (qc);
}

// Remove the QuickCreate from the array
function removeQuickCreate (qc)
{
    if (window.opener == null ||
            window.opener.closed == true ||
        window.opener.aQuickCreates == null ||
        window.opener.aQuickCreates.length == 0)
        return;

    // Find this QuickCreate and remove it from the array
    for( var i in window.opener.aQuickCreates)
    {
        if (window.opener.aQuickCreates[i] == qc)
        {
            window.opener.aQuickCreates.splice (i, 1);
            break;
        }
    }
}

// Check if there are any QuickCreate still open
function isQuickCreateOpen ()
{
    return aQuickCreates != null && aQuickCreates.length > 0;
}

// Close all QuickCreates
function closeQuickCreates()
{
    for( var i in aQuickCreates)
    {
        aQuickCreates[i].close();
    }

    if (aQuickCreates != null)
    {
        aQuickCreates.splice (0, aQuickCreates.length);
    }
}

function onPopupBodyOnunload()
{
        removeQuickCreate (window);
        var olDiv;

        if (oWindow != null && !oWindow.closed)
        {
                closeChildren();
        }

        if (!m_bParentClose)
        {
                if ((olDiv = document.getElementById("popupdiv")) != null)
                {
                        document.body.removeChild(olDiv);
                }
        }
}
//this function should set focus on the top level popup to fix defect 12-H6SF6X
function onFocusProcess()
{
        //oWindow is a variable that maintains reference to the child window
        if (oWindow != null && !oWindow.closed)
        {
                //first level popuip window
                if (oWindow.oWindow != null && !oWindow.oWindow.closed)
                {
                        //second level popuip window
                        if (oWindow.oWindow.oWindow != null && !oWindow.oWindow.oWindow.closed)
                        {
                                //third level popuip window
                                oWindow.oWindow.oWindow.focus();
                        }
                        else
                        {
                                oWindow.oWindow.focus();
                        }
                }
                else
                {
                        oWindow.focus();
                }
        }
}
//function to add a div element on the parent window for read and edit parent types
function onPopupBodyOnload(bResize)
{
        window.opener.document.body.style.cursor = "default";
        if (oDiv == null) //window.opener.oDiv == null)
        {
                if (window.opener.document.getElementById("popupdiv") == null)
                {
                        oDiv =  window.opener.document.createElement("<DIV style='filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);background-color:red' id=popupdiv onclick='javascript:window.event.returnValue =false;window.event.cancelBubble = true;' ONFOCUS='onFocusProcess()' style='position:absolute;z-index:1000;top:0px;left:0px;width:100%;height:100%'></DIV>");
                        window.opener.document.body.appendChild(oDiv);
                }
                //check the parent fix for defect 12-H6SF6X. When a second level popup window is launched from the
                //Quick Create we need to apply modality on the parent while 2-d level popup is open.
                if (window.opener.closed == false && window.opener.window.opener != null &&
                    window.opener.window.opener.closed==false && window.opener.oDiv != null && window.opener.m_bQuickCreate)
                {
                        if (window.opener.window.opener.document.getElementById("popupdiv") != null)
                        {
                                window.opener.window.opener.document.body.removeChild(window.opener.oDiv);
                        }
                        window.opener.oDiv = window.opener.window.opener.document.createElement("<DIV style='filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);background-color:red' id=popupdiv onclick='javascript:window.event.returnValue =false;window.event.cancelBubble = true;' ONFOCUS='onFocusProcess()' style='position:absolute;z-index:1000;top:0px;left:0px;width:100%;height:100%'></DIV>");
                        window.opener.window.opener.document.body.appendChild(window.opener.oDiv);
                }

        }
        //finally, check to see if there was an low-level error while trying to create a new record
          if (typeof(m_sErrorFunctionName) != "undefined" && m_sErrorFunctionName != null)
        {
                this[m_sErrorFunctionName]();
        }
}

quickCreateOnLoadCallBacks = "";

//function to add a div element on the parent window for quick create parent type
function onQuickCreatePopupBodyOnload()
{
        // if this is not a child window, don't do anything with the parent
        if (window.opener != null)
        {
                window.opener.document.body.style.cursor = "default";
        }
        else
        {
                // assume we're OEI - therefore assume we're opened in the right size window to start with
                var oMasterTable = document.getElementById("MasterTable");
                if (typeof(oMasterTable) != "undefined" && oMasterTable != null)
                {
                        oMasterTable.firstChild.firstChild.nextSibling.style.verticalAlign = "top";
                }
        }
        m_bQuickCreate = true;

        if (quickCreateOnLoadCallBacks.length > 0)
                eval(quickCreateOnLoadCallBacks);

        //finally, check to see if there was an low-level error while trying to create a new record
          if (typeof(m_sErrorFunctionName) != "undefined" && m_sErrorFunctionName != null)
        {
                this[m_sErrorFunctionName]();
        }
}

function registerQuickCreateOnLoadCallBack(s)
{
        quickCreateOnLoadCallBacks = quickCreateOnLoadCallBacks + s + ";";
}



function closePopup ()
{
        removeQuickCreate (window);
        closeChildren ();
        window.close ();
}

/*
        Method added as part of fix for 12-HCTZ6G
*/
function changeCursor(sFunc)
{
        document.body.style.cursor = "wait";

        setTimeout(sFunc,100);
}

/*
        Fix for 12-HCTZ6G - showPopup is the original openPop function
*/
function openPopup (url, height, width)
{
        showPopup(url,height,width);
}

/*
        Fix for 12-HCTZ6G - showPopup is the original openPop function
*/
function openPopup (url, height, width, winname, bAssoc)
{
        showPopup(url,height,width,winname,bAssoc);
}

// open a popup from a popup, need different window name
//
function showPopup (url, height, width, winname, bAssoc)
{
        // set smaller window size, resize it after load.
        var sFeatures = "";
        //only hardcode values if its an association popup
        if (bAssoc)
        {
                sFeatures += "status=yes,scrollbars=yes";
                sFeatures += ",width=" + 800;
                sFeatures += ",height=" + 500;
                sFeatures += ",top=" + (screen.availHeight - 500)/2;
                sFeatures += ",left=" + (screen.availWidth - 800)/2;
        }
        else
        {
                sFeatures = "status=yes,height=" + height;
                sFeatures += ",width=" + width;
                sFeatures += ",top=" + (screen.availHeight - height)/2;
                sFeatures += ",left=" + (screen.availWidth - width)/2;
        }

        oWindow=window.open(url,winname,sFeatures);
        window.setTimeout("checkPopup()",5) ;
}

sideEffects = new Array();

function registerSideEffect(ctrlId, action)
{
        se = sideEffects[ctrlId];

        if (typeof(se)=="undefined")
        {
                se = "";
        }

        if (action.substring(action.length-1) != ";")
        {
                action += ";"
        }

        sideEffects[ctrlId] = se + action;
}

function checkSideEffect(ctrlId, newvalue)
{
        se = sideEffects[ctrlId];

        if (typeof(se)!="undefined")
        {
                eval(se);
        }
}

// This function is called by the Date-only popup control
function setControlValues (aCtrlIds, aCtrlValues, sbClosePopup, bOverrideParentValues)
{
 // var oParentWindow;
        var sCtrlName;

        //oParentWindow = window.dialogArguments[0];

        if (aCtrlIds.length != aCtrlValues.length)
        {
           alert(getJSMsg ("OCCAM_JS_POPUP_MISMATCH_ERR"));
        }
        for (i = 0; i < aCtrlIds.length; i++)
        {

                if (bOverrideParentValues)
                {
                        window.opener.setControlValue (aCtrlIds[i], aCtrlValues[i], true);
                }
                else
                {
                        window.opener.setControlValue (aCtrlIds[i], aCtrlValues[i], false);
                }
        }

        if (sbClosePopup)
        {
                window.close ();
        }
}

function setControlValue (ctrlId, ctrlValue, bOverride)
{
        var o = document.getElementById(ctrlId);

        if (o != null && typeof(o) != "undefined" && bOverride)
        {
                o.value = ctrlValue;
                checkSideEffect(ctrlId, ctrlValue);
        }
        else if (o != null && typeof(o) != "undefined" && !bOverride)
        {
                var str = "" + o.value;
                if (str == "")
                {
                        o.value = ctrlValue;
                        checkSideEffect(cltrlId, ctrlValue);
                }
        }

}

function appendURLArgs(url)
{
        return url + "&" + m_sURLArg + "=" + m_sDimensions;
}

function AssocKeyPress(frmId, method)
{
        if (event.keyCode == 13)
        {
                event.cancelBubble=true;
                doSubmit(frmId, method);
        }
}
function AssocClear(frmId, method)
{
        var o = document.getElementById(frmId + ".searchValue");
        if (o != null && typeof(o) != "undefined")
        {
                o.value = "";
                doSubmit(frmId, method);
        }

}

/*
        Fix for 12-HCTZ6G - showResizablePopup is the original openResizablePopup function
*/
function openResizablePopup (url, winname, height, width, bShowToolbar)
{
        showResizablePopup(url,winname,height,width,bShowToolbar);

}

// open resizable popup window
function showResizablePopup (url, winname, height, width, bShowToolbar)
{
        sFeatures = "status=yes,height=" + height;
        sFeatures += ",width=" + width;
        sFeatures += ",top=" + (screen.availHeight - height)/4;
        sFeatures += ",left=" + (screen.availWidth - width)/4*3;
        sFeatures += ",resizable=yes";
        if (bShowToolbar)
        {
                sFeatures += ",toolbar=yes,menubar=yes";
        }
        oWindow=window.open(url,winname,sFeatures);
        oWindow.focus();
}

/*
        Fix for 12-HCTZ6G - showResizablePopupAt is the original openResizablePopupAt function
*/
function openResizablePopupAt (url, winname, height, width, top, left, bShowToolbar)
{
        showResizablePopupAt(url,winname,height,width,top,left,bShowToolbar);
}

// open resizable popup window at location (top, left)
function showResizablePopupAt (url, winname, height, width, top, left, bShowToolbar)
{
        sFeatures = "status=yes,height=" + height;
        sFeatures += ",width=" + width;
        sFeatures += ",top=" + top;
        sFeatures += ",left=" + left;
        sFeatures += ",resizable=yes";
        if (bShowToolbar)
        {
                sFeatures += ",toolbar=yes,menubar=yes,scrollbars=yes";
        }
        oWindow=window.open(url,winname,sFeatures);
}

// open non-resizable popup window at location (top, left)
function showPopupAt (url, winname, height, width, top, left, bShowToolbar)
{
        sFeatures = "status=yes,height=" + height;
        sFeatures += ",width=" + width;
        sFeatures += ",top=" + top;
        sFeatures += ",left=" + left;
        if (bShowToolbar)
        {
                sFeatures += ",toolbar=yes,menubar=yes";
        }
        oWindow=window.open(url,winname,sFeatures);
}

/*
        Fix for 12-HCTZ6G - showQuickCreatePopup is the original openQuickCreatePopup function
*/
function openQuickCreatePopup (url, height, width)
{
        showQuickCreatePopup(url,height,width);
}

// open popup window, but don't show show until ready
function showQuickCreatePopup (url, height, width)
{
        (screen.availHeight - 500)/2;
        sFeatures = "status=yes,height=500";
        sFeatures += ",width=800";
        sFeatures += ",resizable=yes";
        sFeatures += ",top=";
        sFeatures += (screen.availHeight - 500)/2;
        sFeatures += ",left=";
        sFeatures += (screen.availWidth - 800)/2;
        sFeatures += ",scrollbars=yes";
        window.focus();
        oWindow=window.open(url,"_blank", sFeatures);

        addQuickCreate (oWindow);
}

// if user resizes and auto resize is done, enable scrollbars
function onQuickCreatePopupResize ()
{
        if (m_bQCResizeDone)
        {
                document.body.scroll="yes";
        }
}

function checkPopup()
{

        if (oWindow != null && oWindow.closed)
        {
                onPopupBodyOnunload ();
        }
        else
        {
                window.setTimeout("checkPopup()",5);

        }
}

//openPopup used by phone popup control
function openPopup (url, height, width, winname, bAssoc, sCtrlId)
{
   var oCtrl = document.getElementById(sCtrlId);
   if (oCtrl != null)
   {
      var sValue = oCtrl.value;
      //replace country and extension delimitors to characters that could be read
      //by OccamPhonePopup
      sValue = sValue.replace(/\+/, 'c');
      sValue = sValue.replace(/\#/, 'd');
      url += "&ControlValue=";
      url += sValue;
   }
        showPopup(url,height,width,winname,bAssoc);
}

//shadiman, 01-10-2004, RTO 5,Object DeAssociation, Assocation cotrolId,START
//openPopup used by Assoc popup control
function openAssocPopup (url, height, width, winname, sAssocControl,bAssoc )
{
        var sAssocCtrl =document.getElementById(sAssocControl);
        if (sAssocCtrl!=null)
    {
            var sAssocCtrlVal= sAssocCtrl.value;
            url += "&assocval=";
                url += sAssocCtrlVal;
   }
   showPopup(url,height,width,winname,bAssoc);
}
//shadiman, 01-10-2004, RTO 5, Object DeAssociation, Assocation controlId,END

function openScrollablePopup (url, height, width, winname, bAssoc)
{
        showScrollablePopup(url,height,width,winname,bAssoc);
}

// open a popup from a popup with scrollbars, need different window name
//
function showScrollablePopup (url, height, width, winname, bAssoc)
{
        // set smaller window size, resize it after load.
        var sFeatures = "";
        //only hardcode values if its an association popup
        if (bAssoc)
        {
                sFeatures += "status=yes,top=0,left=10000";
        }
        else
        {
                sFeatures = "status=yes,height=" + height;
                sFeatures += ",width=" + width;
                sFeatures += ",top=" + (screen.availHeight - height)/2;
                sFeatures += ",left=" + (screen.availWidth - width)/2;
        }
        sFeatures += ",scrollbars=yes";
        if (url.indexOf("resize=false") < 0 )
        {
                sFeatures += ",resizable=yes";
        }

        oWindow=window.open(url,winname,sFeatures);
        window.setTimeout("checkPopup()",5) ;
}

//  <!-- rvarshney/06-09-04/RT05/Object De-association/START -->
//	This Function is called by all the popups
function removeAssocValue(obj,aCtrls)
{
try {

        if (confirm(getJSMsg ("OCCAM_JS_DEASSOC_CONFIRM_MSG")))
        {
          for(var count=0;count<aCtrls.length;count++)
           {

                   try{
                top.window.opener.document.getElementById(aCtrls[count]).value="";
                }catch(e)
                {}
      }
      window.close();
        }

        }catch(e)
        {

        }
}
var weblinktargetObj;
function weblinkformUrl(obj)
{
        if ( obj == null || typeof(obj) == "undefinded")
                return;

        myValue = "%%%" + obj.options[obj.selectedIndex].value + "%%%";
        if ( weblinktargetObj == null )
        {
                weblinktargetObj = document.getElementById("EWLF.Web Link URL");
        }

        if (document.selection)
        {
                weblinktargetObj.focus();
                sel = document.selection.createRange();
                sel.text = myValue;
        }
//MOZILLA/NETSCAPE support
        else if (weblinktargetObj.selectionStart || weblinktargetObj.selectionStart == '0')
        {
                var startPos = weblinktargetObj.selectionStart;
                var endPos = weblinktargetObj.selectionEnd;
                weblinktargetObj.value = weblinktargetObj.value.substring(0, startPos)
                + myValue
                + weblinktargetObj.value.substring(endPos, weblinktargetObj.value.length);
        }
    else
        {
                weblinktargetObj.value += myValue;
        }

}

function weblinkfocus(obj)
{
        weblinktargetObj = obj;
}


/*

Copyright Connecti 2005

Steven Pettigrew
06/01/2005


*/




// this keeps track of the windows that have been opened by the page this file is included in
var openedWindows = new Array();


/**
 *	This opens a window at a specific position on the page when given a url, width and height, x and y coordinates,
 *	the name to give the window and whether to allow scrollbars or not.
 */
function openPopupPos(url, width, height, topCoOr, leftCoOr, name, scrollbars) {
                winOptions = "status=no";
                winOptions += ",scrollbars=" + scrollbars;
                winOptions += ",width=" + width;
                winOptions += ",height=" + height;
                winOptions += ",left=" + leftCoOr;
                winOptions += ",top=" + topCoOr;
                winOptions += ",screenX=" + leftCoOr;
                winOptions += ",screenY=" + topCoOr;

        openedWindows[openedWindows.length] = window.open(url, name, winOptions);
}


/**
 *	This opens a popup at 50,50 using the given url, width and height, name and scrollbar options
 */
function openPopup(url, width, height, name, scrollbars) {

        openPopupPos(url, width, height, "50", "50", name, scrollbars);
}


/**
 *	This opens a window centred in the screen using the given url, width and height, name and scrollbar options
 */
function openPopupCentred(url, width, height, name, scrollbars) {
        topCoOr = (screen.availHeight - height)/2;
        leftCoOr = (screen.availWidth - width)/2;

        openPopupPos(url, width, height, topCoOr, leftCoOr, name, scrollbars);
}


/**
 *	This opens a window taking up the full screen using the given url, name and scrollbar options
 */
function openPopupFullScreen(url, name, scrollbars) {
        width = screen.availWidth - 3;
        height = screen.availHeight;
        openPopupPos(url, width, height, "0", "0", name, scrollbars);
}


/**
 *	This will close all windows that have been opened from the page that includes this file
 */
function closeAllOpenedWindows() {
        for(i = 0; i < openedWindows.length; i++) {
                if (openedWindows[i] != null && !openedWindows[i].closed) {
                        openedWindows[i].close();
                }
        }
}


/**
 *	This will bring the window named to the front if it is still open and has been opened from the page that included this file
 */
function refocusOpenedWindow(winName) {
        for(i = 0; i < openedWindows.length; i++) {
                if(openedWindows[i] != null && !openedWindows[i].closed && openedWindows[i].name == winName) {
                        openedWindows[i].focus();
                }
        }
}


/**
 *	This will bring the window that opened the one this function is called from to the front
 */
function refocusOpener() {
        window.opener.focus();
}


/**
 *	This displays an "ok/cancel" box and return the value of the button clicked (ok = true/cancel = false)
 */
function confirmDialogue(text) {
        return confirm(text);
}


/**
 *	This displays text and if the user clicks OK will go to the url provided
 */
function askAndGoTo(text, url) {
        if(confirm(text)) {
                window.location = url;
        }
}


/**
 *	This hides each element that is passed to the function
 *
 *	EG: ..."javascript:hideElems('textbox1', 'pic2', 'button9', 'jumpBox');"...
 */
function hideElems() {
        var args = hideElems.arguments;

        for(i=0; i < args.length; i++) {
                el = document.getElementById(args[i]);
                if(el != null) {
                        el.style.display = "none";
                }
        }
}


/**
 *	This shows each element that is passed to the function
 *
 *	EG: ..."javascript:showElems('textbox1', 'pic2', 'button9', 'jumpBox');"...
 */
function showElems() {
        var args = showElems.arguments;

        for(i=0; i < args.length; i++) {
                el = document.getElementById(args[i]);
                if(el != null) {
                        el.style.display = "block";
                }
        }
}


/**
version 1.4
December 20, 2004
Julian Robichaux -- http://www.nsftools.com
*/

var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";

var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

// these variables define the date formatting we're expecting and outputting.
// If you want to use a different format by default, change the defaultDateSeparator
// and defaultDateFormat variables either here or on your HTML page.
var defaultDateSeparator = "/";		// common values would be "/" or "."
var defaultDateFormat = "dmy"	// valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;

/**
This is the main function you'll call from the onClick event of a button.
Normally, you'll have something like this on your HTML page:

Start Date: <input name="StartDate">
<input type=button value="select" onclick="displayDatePicker('StartDate');">

That will cause the datepicker to be displayed beneath the StartDate field and
any date that is chosen will update the value of that field. If you'd rather have the
datepicker display beneath the button that was clicked, you can code the button
like this:

<input type=button value="select" onclick="displayDatePicker('StartDate', this);">

So, pretty much, the first argument (dateFieldName) is a string representing the
name of the field that will be modified if the user picks a date, and the second
argument (displayBelowThisObject) is optional and represents an actual node
on the HTML document that the datepicker should be displayed below.

In version 1.1 of this code, the dtFormat and dtSep variables were added, allowing
you to use a specific date format or date separator for a given call to this function.
Normally, you'll just want to set these defaults globally with the defaultDateSeparator
and defaultDateFormat variables, but it doesn't hurt anything to add them as optional
parameters here. An example of use is:

<input type=button value="select" onclick="displayDatePicker('StartDate', false, 'dmy', '.');">

This would display the datepicker beneath the StartDate field (because the
displayBelowThisObject parameter was false), and update the StartDate field with
the chosen value of the datepicker using a date format of dd.mm.yyyy
*/
function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep)
{
  var targetDateField = document.getElementsByName(dateFieldName).item(0);

  // if we weren't told what node to display the datepicker beneath, just display it
  // beneath the date field we're updating
  if (!displayBelowThisObject)
    displayBelowThisObject = targetDateField;

  // if a date separator character was given, update the dateSeparator variable
  if (dtSep)
    dateSeparator = dtSep;
  else
    dateSeparator = defaultDateSeparator;

  // if a date format was given, update the dateFormat variable
  if (dtFormat)
    dateFormat = dtFormat;
  else
    dateFormat = defaultDateFormat;

  var x = displayBelowThisObject.offsetLeft;
  var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight;

  // deal with elements inside tables and such
  var parent = displayBelowThisObject;
  while (parent.offsetParent) {
    parent = parent.offsetParent;
    x += parent.offsetLeft;
    y += parent.offsetTop;
  }

  drawDatePicker(targetDateField, x, y);
}


/**
Draw the datepicker object (which is just a table with calendar elements) at the
specified x and y coordinates, using the targetDateField object as the input tag
that will ultimately be populated with a date.

This function will normally be called by the displayDatePicker function.
*/
function drawDatePicker(targetDateField, x, y)
{
  var dt = getFieldDate(targetDateField.value);

  // the datepicker table will be drawn inside of a <div> with an ID defined by the
  // global datePickerDivID variable. If such a div doesn't yet exist on the HTML
  // document we're working with, add one.
  if (!document.getElementById(datePickerDivID)) {
    // don't use innerHTML to update the body, because it can cause global variables
    // that are currently pointing to objects on the page to have bad references
    //document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
    var newNode = document.createElement("div");
    newNode.setAttribute("id", datePickerDivID);
    newNode.setAttribute("class", "dpDiv");
    newNode.setAttribute("style", "visibility: hidden;");
    document.body.appendChild(newNode);
  }

  // move the datepicker div to the proper x,y coordinate and toggle the visiblity
  var pickerDiv = document.getElementById(datePickerDivID);
  pickerDiv.style.position = "absolute";
  pickerDiv.style.left = x + "px";
  pickerDiv.style.top = y + "px";
  pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
  pickerDiv.style.zIndex = 10000;

  // draw the datepicker table


  //
  //
  //Steven Pettigrew - ADDED THIS 'IF' TO MAKE SURE IT DEFAULTS TO TODAYS DATE IF THE DATE RETRIEVED GOES TO THE DEFAULT 1970 DATE
  //
  //
  //alert("y = " + dt.getFullYear() + "\nm = " + dt.getMonth() + "\nd = " + dt.getDate() + "\n\ndate = " + dt);
  if(dt.getFullYear() == 1970 || isNaN(dt.getFullYear())) {
    refreshDatePicker(targetDateField.name);
  } else {
    refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
  }
}


/**
This is the function that actually draws the datepicker calendar.
*/
function refreshDatePicker(dateFieldName, year, month, day)
{
  // if no arguments are passed, use today's date; otherwise, month and year
  // are required (if a day is passed, it will be highlighted later)
  var thisDay = new Date();

  if ((month >= 0) && (year > 0)) {
    thisDay = new Date(year, month, 1);
  } else {
    day = thisDay.getDate();
    thisDay.setDate(1);
  }

  // the calendar will be drawn as a table
  // you can customize the table elements with a global CSS style sheet,
  // or by hardcoding style and formatting elements below
  var crlf = "\r\n";
  var TABLE = "<table cols=7 class='dpTable'>" + crlf;
  var xTABLE = "</table>" + crlf;
  var TR = "<tr class='dpTR'>";
  var TR_title = "<tr class='dpTitleTR'>";
  var TR_days = "<tr class='dpDayTR'>";
  var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
  var xTR = "</tr>" + crlf;
  var TD = "<td class='dpTD'";	// leave this tag open, because we'll be adding an onClick event
  var TD_title = "<td colspan=5 class='dpTitleTD'>";
  var TD_buttons = "<td class='dpButtonTD'>";
  var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
  var TD_days = "<td class='dpDayTD'>";
  var TD_selected = "<td class='dpDayHighlightTD'";	// leave this tag open, because we'll be adding an onClick event
  var xTD = "</td>" + crlf;
  var DIV_title = "<div class='dpTitleText'>";
  var DIV_selected = "<div class='dpDayHighlight'>";
  var xDIV = "</div>";

  // start generating the code for the calendar table
  var html = TABLE;

  // this is the title bar, which displays the month and the buttons to
  // go back to a previous month or forward to the next month
  html += TR_title;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "&lt;") + xTD;
  html += TD_title + DIV_title + monthArrayLong[thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, "&gt;") + xTD;
  html += xTR;

  // this is the row that indicates which day of the week we're on
  html += TR_days;
  for(i = 0; i < dayArrayShort.length; i++)
    html += TD_days + dayArrayShort[i] + xTD;
  html += xTR;

  // now we'll start populating the table with days of the month
  html += TR;

  // first, the leading blanks
  for (i = 0; i < thisDay.getDay(); i++)
    html += TD + "&nbsp;" + xTD;

  // now, the days of the month
  do {
    dayNum = thisDay.getDate();
    TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";

    if (dayNum == day)
      html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
    else
      html += TD + TD_onclick + dayNum + xTD;

    // if this is a Saturday, start a new row
    if (thisDay.getDay() == 6)
      html += xTR + TR;

    // increment the day
    thisDay.setDate(thisDay.getDate() + 1);
  } while (thisDay.getDate() > 1)

  // fill in any trailing blanks
  if (thisDay.getDay() > 0) {
    for (i = 6; i > thisDay.getDay(); i--)
      html += TD + "&nbsp;" + xTD;
  }
  html += xTR;

  // add a button to allow the user to easily return to today, or close the calendar
  var today = new Date();
  var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[today.getMonth()] + " " + today.getDate();
  html += TR_todaybutton + TD_todaybutton;
  html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>today</button> ";
  html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>close</button>";
  html += xTD + xTR;

  // and finally, close the table
  html += xTABLE;

  document.getElementById(datePickerDivID).innerHTML = html;
  // add an "iFrame shim" to allow the datepicker to display above selection lists
  adjustiFrame();
}


/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateFieldName, dateVal, adjust, label)
{
  var newMonth = (dateVal.getMonth() + adjust) % 12;
  var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
  if (newMonth < 0) {
    newMonth += 12;
    newYear += -1;
  }

  return "<button class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
}


/**
Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString(dateVal)
{
  var dayString = "00" + dateVal.getDate();
  var monthString = "00" + (dateVal.getMonth()+1);
  dayString = dayString.substring(dayString.length - 2);
  monthString = monthString.substring(monthString.length - 2);

  switch (dateFormat) {
    case "dmy" :
      return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
    case "ymd" :
      return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
    case "mdy" :
    default :
      return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
  }
}


/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
  var dateVal;
  var dArray;
  var d, m, y;

  try {
    dArray = splitDateString(dateString);
    if (dArray) {
      switch (dateFormat) {
        case "dmy" :
          d = parseInt(dArray[0], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
        case "ymd" :
          d = parseInt(dArray[2], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[0], 10);
          break;
        case "mdy" :
        default :
          d = parseInt(dArray[1], 10);
          m = parseInt(dArray[0], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
      }
      dateVal = new Date(y, m, d);
    } else {
      dateVal = new Date(dateString);
    }
  } catch(e) {
    dateVal = new Date();
  }

  return dateVal;
}


/**
Try to split a date string into an array of elements, using common date separators.
If the date is split, an array is returned; otherwise, we just return false.
*/
function splitDateString(dateString)
{
  var dArray;
  if (dateString.indexOf("/") >= 0)
    dArray = dateString.split("/");
  else if (dateString.indexOf(".") >= 0)
    dArray = dateString.split(".");
  else if (dateString.indexOf("-") >= 0)
    dArray = dateString.split("-");
  else if (dateString.indexOf("\\") >= 0)
    dArray = dateString.split("\\");
  else
    dArray = false;

  return dArray;
}

/**
Update the field with the given dateFieldName with the dateString that has been passed,
and hide the datepicker. If no dateString is passed, just close the datepicker without
changing the field value.

Also, if the page developer has defined a function called datePickerClosed anywhere on
the page or in an imported library, we will attempt to run that function with the updated
field as a parameter. This can be used for such things as date validation, setting default
values for related fields, etc. For example, you might have a function like this to validate
a start date field:

function datePickerClosed(dateField)
{
  var dateObj = getFieldDate(dateField.value);
  var today = new Date();
  today = new Date(today.getFullYear(), today.getMonth(), today.getDate());

  if (dateField.name == "StartDate") {
    if (dateObj < today) {
      // if the date is before today, alert the user and display the datepicker again
      alert("Please enter a date that is today or later");
      dateField.value = "";
      document.getElementById(datePickerDivID).style.visibility = "visible";
      adjustiFrame();
    } else {
      // if the date is okay, set the EndDate field to 7 days after the StartDate
      dateObj.setTime(dateObj.getTime() + (7 * 24 * 60 * 60 * 1000));
      var endDateField = document.getElementsByName("EndDate").item(0);
      endDateField.value = getDateString(dateObj);
    }
  }
}

*/
function updateDateField(dateFieldName, dateString)
{
  var targetDateField = document.getElementsByName(dateFieldName).item(0);
  if (dateString)
    targetDateField.value = dateString;
  document.getElementById(datePickerDivID).style.visibility = "hidden";
  adjustiFrame();




//**************************************
  //EDIT: Steven Pettigrew 06/01/2005 - if target box is disabled, dont try to focus on it
  if(targetDateField.disabled == false) {
        targetDateField.focus();
  }
//**************************************






  // after the datepicker has closed, optionally run a user-defined function called
  // datePickerClosed, passing the field that was just updated as a parameter
  // (note that this will only run if the user actually selected a date from the datepicker)
  if ((dateString) && (typeof(datePickerClosed) == "function"))
    datePickerClosed(targetDateField);
}


/**
Use an "iFrame shim" to deal with problems where the datepicker shows up behind
selection list elements, if they're below the datepicker. The problem and solution are
described at:

http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
*/
function adjustiFrame(pickerDiv, iFrameDiv)
{
  if (!document.getElementById(iFrameDivID)) {
    // don't use innerHTML to update the body, because it can cause global variables
    // that are currently pointing to objects on the page to have bad references
    //document.body.innerHTML += "<iframe id='" + iFrameDivID + "' src='javascript:false;' scrolling='no' frameborder='0'>";
    var newNode = document.createElement("iFrame");
    newNode.setAttribute("id", iFrameDivID);
    newNode.setAttribute("src", "javascript:false;");
    newNode.setAttribute("scrolling", "no");
    newNode.setAttribute("frameborder", "0");
    document.body.appendChild(newNode);
  }

  if (!pickerDiv)
    pickerDiv = document.getElementById(datePickerDivID);
  if (!iFrameDiv)
    iFrameDiv = document.getElementById(iFrameDivID);

  try {
    iFrameDiv.style.position = "absolute";
    iFrameDiv.style.width = pickerDiv.offsetWidth;
    iFrameDiv.style.height = pickerDiv.offsetHeight;
    iFrameDiv.style.top = pickerDiv.style.top;
    iFrameDiv.style.left = pickerDiv.style.left;
    iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
    iFrameDiv.style.visibility = pickerDiv.style.visibility;
  } catch(e) {
  }
}

function popUp(URL) {
  day = new Date();
  id = day.getTime();
  eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=700,height=400,left = 112,top = 84');");
}


