/* JSLibrary.js

This is a library of common routines.  It includes:
* Functions created by Vern Baker to 
* Froms from Kevin Vanzonneveld (he has a complete list of JavaScript functions created to replicate PHP ... Impressive
*/

// A way to include a javascript file 
function include_js(file)
{
	var include_file = document.createElement('script');
	include_file.type = 'text/javascript';
	include_file.src = file;
	document.getElementsByTagName('head')[0].appendChild(include_file);
}


/*
* PHP functions re-written in JavaScript (Nice!) 
** Note: See  http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_substr/
** Also: Downloads were made for easy cutting and pasting
* Date and Date picker functions 
*/
function substr( f_string, f_start, f_length ) {
    // http://kevin.vanzonneveld.net
    // +     original by: Martijn Wieringa
    // +     bugfixed by: T.Wild
    // +      tweaked by: Onno Marsman
    // *       example 1: substr('abcdef', 0, -1);
    // *       returns 1: 'abcde'
    // *       example 2: substr(2, 0, -6);
    // *       returns 2: ''
 
    f_string += '';
 
    if(f_start < 0) {
        f_start += f_string.length;
    }
 
    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }
 
    if(f_length < f_start) {
        f_length = f_start;
    }
 
    return f_string.substring(f_start, f_length);
}

function strlen (string) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Sakimori
    // +      input by: Kirk Strobeck
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +    revised by: Brett Zamir
    // %        note 1: May look like overkill, but in order to be truly faithful to handling all Unicode
    // %        note 1: characters and to this function in PHP which does not count the number of bytes
    // %        note 1: but counts the number of characters, something like this is really necessary.
    // *     example 1: strlen('Kevin van Zonneveld');
    // *     returns 1: 19
    // *     example 2: strlen('A\ud87e\udc04Z');
    // *     returns 2: 3
 
    var str = string+'';
    var i = 0, chr = '', lgth = 0;
 
    var getWholeChar = function (str, i) {
        var code = str.charCodeAt(i);
        var next = '', prev = '';
        if (0xD800 <= code && code <= 0xDBFF) { // High surrogate(could change last hex to 0xDB7F to treat high private surrogates as single characters)
            if (str.length <= (i+1))  {
                throw 'High surrogate without following low surrogate';
            }
            next = str.charCodeAt(i+1);
            if (0xDC00 > next || next > 0xDFFF) {
                throw 'High surrogate without following low surrogate';
            }
            return str[i]+str[i+1];
        } else if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
            if (i === 0) {
                throw 'Low surrogate without preceding high surrogate';
            }
            prev = str.charCodeAt(i-1);
            if (0xD800 > prev || prev > 0xDBFF) { //(could change last hex to 0xDB7F to treat high private surrogates as single characters)
                throw 'Low surrogate without preceding high surrogate';
            }
            return false; // We can pass over low surrogates now as the second component in a pair which we have already processed
        }
        return str[i];
    };
 
    for (i=0, lgth=0; i < str.length; i++) {
        if ((chr = getWholeChar(str, i)) === false) {
            continue;
        } // Adapt this line at the top of any loop, passing in the whole string and the current iteration and returning a variable to represent the individual character; purpose is to treat the first part of a surrogate pair as the whole character and then ignore the second part
        lgth++;
    }
    return lgth;
}

function trim (str, charlist) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
    // *     example 3: trim(16, 1);
    // *     returns 3: 6
 
    var whitespace, l = 0, i = 0;
    str += '';
    
    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    }
    
    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}



// Get current date
function y2k(number){return (number < 1000) ? number + 1900 : number;}

// Functions that can be provided easily
// stripchars:  tempvar =  tempvar.replace(/[^a-zA-Z 0-9]+/g,'');


// Email validate 
function emailValidate(str) 
{
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		return false
	 }
	
	 if (str.indexOf(" ")!=-1){
		return false
	 }

	 return true					
}

// Show the date in a specific Div
function ShowDate(pDiv) 
{ 
  var now = new Date();

  // List the days
  var days = new Array('Sunday','Monday','Tuesday','Wednesday',
                        'Thursday','Friday','Saturday');
  // List the months
  var months = new Array('January','February','March','April',
                         'May','June','July','August','September',
                         'October','November','December');
  // What day number is it
  var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
  // Convert year to four figure format
  // Join it all together
  today =  days[now.getDay()] + " - " +
           date + " " +
           months[now.getMonth()] + ", " +
           (y2k(now.getYear())) ;

  // write it to the page
  document.getElementById(pDiv).innerHTML="&nbsp;&nbsp;&nbsp;"+today;
}


// Get the current date in TF format
function teleflowNowDate()
{
	var currDate = new Date();
	mReturn = formatTeleFlowDate(currDate.getFullYear(), Number(currDate.getMonth())+1, currDate.getDate());
	return mReturn;
}

// Ensures zero padding etc
function formatTeleFlowDate(pYear,pMonth,pDay)
{
	mReturn = pYear+'';
	mReturn += ((parseInt(pMonth,10) < 10) ? "-0" : "-") + (pMonth);
	mReturn += ((parseInt(pDay,10)   < 10) ? "-0" : "-") + (pDay);
	return mReturn;
}

// Add months to date
function addMonth(d,month)
{
	t  = new Date (d);
	t.setMonth(d.getMonth()+ month) ;
	if (t.getDate() < d.getDate())
	{
	  t.setDate(0);
	}
	return t;
} 


// Make sure its strong enough
// - parm 1 = Password send
// - parm 2 = Minimum lenght (0 defaults to 5)
function PassWordStrength(passwd, minLen) 
{
	var intScore 	= 0
	var	testSize 	= 0
	var strLog 		= ""
	
	testSize = minLen;
	if (minLen == 0)
	{
		testSize = 5
	}
	
	
	// PASSWORD LENGTH
	if (passwd.length<5)                         // length 4 or less
	{
		intScore = (intScore+3)
		strLog   = strLog + "3 points for length (" + passwd.length + ")\n"
	}
	else if (passwd.length>4 && passwd.length<8) // length between 5 and 7
	{
		intScore = (intScore+6)
		strLog   = strLog + "6 points for length (" + passwd.length + ")\n"
	}
	else if (passwd.length>7 && passwd.length<16)// length between 8 and 15
	{
		intScore = (intScore+12)
		strLog   = strLog + "12 points for length (" + passwd.length + ")\n"
	}
	else if (passwd.length>15)                    // length 16 or more
	{
		intScore = (intScore+18)
		strLog   = strLog + "18 point for length (" + passwd.length + ")\n"
	}
	
	
	// LETTERS (Not exactly implemented as dictacted above because of my limited understanding of Regex)
	if (passwd.match(/[a-z]/))                              // [verified] at least one lower case letter
	{
		intScore = (intScore+1)
		strLog   = strLog + "1 point for at least one lower case char\n"
	}
	
	if (passwd.match(/[A-Z]/))                              // [verified] at least one upper case letter
	{
		intScore = (intScore+5)
		strLog   = strLog + "5 points for at least one upper case char\n"
	}
	
	// NUMBERS
	if (passwd.match(/\d+/))                                 // [verified] at least one number
	{
		intScore = (intScore+5)
		strLog   = strLog + "5 points for at least one number\n"
	}
	
	if (passwd.match(/(.*[0-9].*[0-9].*[0-9])/))             // [verified] at least three numbers
	{
		intScore = (intScore+5)
		strLog   = strLog + "5 points for at least three numbers\n"
	}
	
	// SPECIAL CHAR
	if (passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/))            // [verified] at least one special character
	{
		intScore = (intScore+5)
		strLog   = strLog + "5 points for at least one special char\n"
	}	
	// [verified] at least two special characters
	if (passwd.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/))
	{
		intScore = (intScore+5)
		strLog   = strLog + "5 points for at least two special chars\n"
	}
	
	// COMBOS
	if (passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))        // [verified] both upper and lower case
	{
		intScore = (intScore+2)
		strLog   = strLog + "2 combo points for upper and lower letters\n"
	}

	if (passwd.match(/([a-zA-Z])/) && passwd.match(/([0-9])/)) // [verified] both letters and numbers
	{
		intScore = (intScore+2)
		strLog   = strLog + "2 combo points for letters and numbers\n"
	}

	// [verified] letters, numbers, and special characters
	if (passwd.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/))
	{
		intScore = (intScore+2)
		strLog   = strLog + "2 combo points for letters, numbers and special chars\n"
	}

	
	// Show the result
	// .pass_bad,.pass_weak,.pass_moderate,.pass_strong,.pass_great,.pass_match
	if(intScore <= 10) // 16
	{
	   StrengthFinal='<span class="pass_bad">VERY WEAK</span>';
	}
	else if (intScore > 10 && intScore <= 16)
	{
	   StrengthFinal='<span class="pass_weak">WEAK</span>';
	}
	else if (intScore > 16 && intScore <= 28)
	{
	   StrengthFinal='<span class="pass_moderate">MODERATE</span>';
	}
	else if (intScore > 28 && intScore <= 40)
	{
	   StrengthFinal='<span class="pass_strong">STRONG</span>';
	}
	else
	{
	   StrengthFinal='<span class="pass_great">VERY STRONG</span>';
	}

	
	// Overide with too short or show nothing message
	if (passwd.length==0)  
	{
		StrengthFinal='';
		// Reject
		intScore = 0;
	}
	// Overide with too short message
	else if (passwd.length<testSize)  
	{
		StrengthFinal='<span class="pass_bad">Too Short</span>';
		// Reject
		intScore = 0;
	}
	
	document.getElementById('password_strength').innerHTML=StrengthFinal;
	//document.getElementById('Strength Visual').innerHTML=Bar ;
	
	return intScore;
} //PassWordStrength

// Password tester
function PassMatchTest(Pass1, Pass2)
{
	var matchFlag=false;
	if (Pass2.length == 0)
	{
	   MatchUP=''; 
	}
	else if (Pass1 == Pass2 )
	{
	   MatchUP='<span class="pass_strong">Matching!</span>';
	   matchFlag=true;
	}
	else
	{
	   MatchUP='<span class="pass_bad">Mismatch</span>';
	}

	document.getElementById('password_match').innerHTML=MatchUP;
	//document.getElementById('Strength Visual').innerHTML=Bar ;	
	return matchFlag;
}


// Find the appropriate button number for a letter - include asterisk, but not pound
function telephoneButton(pChar) {
	//alert(pChar);
	mChar = pChar.charCodeAt(0)
	if (mChar >= 42 && mChar<=  42) return String.fromCharCode(mChar);  // *
	if (mChar >= 48 && mChar<=  57) return String.fromCharCode(mChar);  // 0...9
	if (mChar >= 65 && mChar<=  67) return 2; // ABC
	if (mChar >= 68 && mChar<=  70) return 3; // DEF
	if (mChar >= 71 && mChar<=  73) return 4; // GHI
	if (mChar >= 74 && mChar<=  76) return 5; // JKL
	if (mChar >= 77 && mChar<=  79) return 6; // MNO
	if (mChar >= 80 && mChar<=  83) return 7; // PQRS
	if (mChar >= 84 && mChar<=  86) return 8; // TUV
	if (mChar >= 87 && mChar<=  90) return 9; // WXYZ
return ''}





/**
This is a drop-down datepicker. This script is not as
full-featured as others you may find on the Internet, but it's free, it's easy to
understand, and it's easy to change.

version 1.6
April 24, 2008
Julian Robichaux -- http://www.nsftools.com
Vern Baker -- http://teleflow.org

HISTORY
--  version 1.0 (Sept. 4, 2004):
Initial release.

--Version 1.6(Apr 24, 2008)
Added current date highlight, and improved the look and feel - Vern Baker
*/

/* Includes
===CSS===
* <link href="images/datepicker.css" rel="stylesheet" media="screen,,projection" title="default" type="text/css"  />

===Graphics for Popup option===
* <img src='images/calendar.gif' border='0' align='top' onclick="displayDatePicker('startdate','','mdy');">

===Example image with datepicker.css installed===
* jslibrary-datepicker-example.gif

*/

/**
===Bugs,Deficiencies and Feature Requests===
* Bug: Selected date disappears if you move to another month and return to current
* Feature: Static mode
** - Where the datepicker stays showing when a date is selected
** - Close button is not show., 
** - eg:  function displayDatePickerSTATIC(dateFieldName, dtFormat, dtSep)  // Calls displayDatePicker after setting a global variable

*/

/* Example Code:
An example of using a graphic 
<img src='images/calendar.gif' border='0' align='top' onclick="displayDatePicker('startdate','','mdy');">

Here's an example of displaying the datepicker below a text field:
<b>A Date:</b> <input name="ADate"> 
<input type=button value="select" onclick="displayDatePicker('ADate');">
</form>

And here's an example of displaying it below the button that was clicked:
<b>Another Date:</b> <input name="AnotherDate"> 
<input type=button value="select" onclick="displayDatePicker('AnotherDate', this);">

And here's an example of displaying the resulting value with a date format of dd.mm.yyyy:
<b>Yet Another Date:</b> <input name="YetAnotherDate"> 
<input type=button value="select" onclick="displayDatePicker('YetAnotherDate', false, 'dmy', '.');">
*/

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 = "ymd";   // valid values are "mdy", "dmy", and "ymd"
var defaultAllowClose = "TRUE";   // Is the user allowed to close the calendar
// Set the defaults
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;
var allowClose = defaultAllowClose;

/**
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 displayStaticDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep)
{
   // This variable is set to display a static date
   allowClose = "FALSE";
   displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep);
}

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 -1 ;
 
  // 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);
  // Popups?
  if (allowClose == "TRUE")
  {  
     pickerDiv.style.position = "absolute";
  } 
  
  document.getElementById(datePickerDivID).style.left = x + "px";
  pickerDiv.style.left = x + "px";
  pickerDiv.style.top = y + "px";
  pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
  pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
  pickerDiv.style.zIndex = 10000;
 
  // draw the datepicker table
  refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
}

/**
This will select todays date.  Its only for use with Static calendar
*/
function todayDatePicker(dateFieldName, year, month, day)
{    
    //Show the calendar with todays date
    refreshDatePicker(dateFieldName);

	// Now, select todays date
    var thisDay = new Date();
	thisDay.setDate(thisDay.getDate());
	updateDateField(dateFieldName, getDateString(thisDay));
	//alert(day);
}


/**
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);
  }

  // Determine todays date
  var thisToday = new Date();
  mTodayDay = thisToday.getDate();
  
  // 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' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
  var TD_today = "<td class='dpTDToday' onMouseOut='this.className=\"dpTDToday\";' onMouseOver=' this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
  var TD_blank = "<td class='dpTDBlank' onMouseOut='this.className=\"dpTDBlank\";' onMouseOver=' this.className=\"dpTDHover\";' ";    // 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' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' ";    // 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_blank + "&nbsp;" + xTD;
 
  // now, the days of the month
  do {
    dayNum = thisDay.getDate();
    TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
    
    // Selected day
    if (dayNum == day)
      html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
    else
    {
      // Check for today's date
      if ((dayNum == mTodayDay) && (thisDay.getMonth() == thisToday.getMonth()))
      {
         // It's today
         html += TD_today + TD_onclick + "<b>" + dayNum + "</b>" +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_blank + "&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;

  // Popups?
  if (allowClose == "TRUE")
  {
     html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>Select Today</button> ";
     html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>Close</button>";
  }
  else
  {
     // Static
     //html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>Locate Today</button> ";
     html += "<button class='dpTodayButton' onClick='todayDatePicker(\"" + dateFieldName + "\");'>Select Today</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
  if (allowClose == "TRUE")
  {
     // I put the allow close, because somehow this adds a word "false"
     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 if (dateString) {
      dateVal = new Date(dateString);
    } else {
      dateVal = new Date();
    }
  } 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;
 
  // SHould we close?
  if (allowClose == "TRUE")
  {
     var pickerDiv = document.getElementById(datePickerDivID);
     pickerDiv.style.visibility = "hidden";
     pickerDiv.style.display = "none";
    
     adjustiFrame();
     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);
  }
  else
  {
    // Now, refresh the page
	pageRefresh();
	// pageRefresh should be in the main php program and include lines like this:
	/*
  //alert('Tested to Here');	
  var DateField = document.getElementsByName('startdate').item(0).value;
  window.location="CalendarTest.php?startdate="+DateField;       	
	*/
  }
}


/**
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)
{
  // we know that Opera doesn't like something about this, so if we
  // think we're using Opera, don't even try
  var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
  if (is_opera)
    return;
  
  // put a try/catch block around the whole thing, just in case
  try {
    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 ;
      iFrameDiv.style.display = pickerDiv.style.display;
    } catch(e) {
    }
 
  } catch (ee) {
  }
 
}

