var cal_monthName;
var cal_HolidaysCounter = 0;
var cal_Holidays = new Array();
var cal_fixedX = -1;              /* x position (-1 if to appear below control) */
var cal_fixedY = -1;              /* y position (-1 if to appear below control) */
var cal_startAt = 0;              /* 0 - sunday ; 1 - monday */
var cal_showWeekNumber = 0;       /* 0 - don't show; 1 - show */
var cal_showToday = 1;            /* 0 - don't show; 1 - show */
var cal_imgDir = "wlp/calendar/images/"; /** directory for images ... e.g. var cal_imgDir="/img/" */
var cal_selectDateMessage = "[date]";            // do not replace [date], it will be replaced by date.
var cal_crossobj, cal_crossMonthObj, cal_crossYearObj, cal_monthSelected, cal_yearSelected, cal_dateSelected, cal_omonthSelected, cal_oyearSelected, cal_odateSelected, cal_monthConstructed, cal_yearConstructed;
var cal_intervalID1, cal_intervalID2, cal_timeoutID1, cal_timeoutID2, cal_ctlToPlaceValue, cal_ctlNow, cal_dateFormat, cal_nStartingYear;
var cal_today = new    Date();
var cal_dateNow = cal_today.getDate();
var cal_monthNow = cal_today.getMonth();
var cal_yearNow = cal_today.getFullYear();
var cal_imgsrc = new Array("drop1.gif", "drop2.gif", "left1.gif", "left2.gif", "right1.gif", "right2.gif");
var cal_img = new Array();
var cal_bShow = false;
var cal_sHTML1;
var cal_styleAnchor;
var cal_styleLightBorder;
var cal_dayName;

var i18n_cal_gotoString;
var i18n_cal_todayString;
var i18n_cal_weekString;
var i18n_cal_scrollLeftMessage;
var i18n_cal_scrollRightMessage;
var i18n_cal_selectMonthMessage;
var i18n_cal_selectYearMessage;

var i18n_cal_cal_i18n_invalid_time;
var i18n_cal_dateTimeFormat;
var i18n_cal_timeFormat;
var i18n_cal_calendarFormat;

var i18n_cal_done;

var cal_resourceRootPath;
var cal_timeOnly;

var clearDate; //used to clear


/*
    Initialize i18n resources.
*/
function init_i18n_calendar(gotoString, todayString, weekString, scrollLeftMessage, scrollRightMessage,
                            selectMonthMessage, selectYearMessage, cal_i18n_invalid_time,
                            dateTimeFormat, timeFormat, calendarFormat, done)
{
    this.i18n_cal_gotoString = gotoString;
    this.i18n_cal_todayString = todayString;
    this.i18n_cal_weekString = weekString;
    this.i18n_cal_scrollLeftMessage = scrollLeftMessage;
    this.i18n_cal_scrollRightMessage = scrollRightMessage;
    this.i18n_cal_selectMonthMessage = selectMonthMessage;
    this.i18n_cal_selectYearMessage = selectYearMessage;
    this.i18n_cal_cal_i18n_invalid_time = cal_i18n_invalid_time;
    this.i18n_cal_dateTimeFormat = dateTimeFormat;
    this.i18n_cal_timeFormat = timeFormat;
    this.i18n_cal_calendarFormat = calendarFormat;
    this.i18n_cal_done = done;
}


/*
    Initialize the array of months based on i18n values.
*/
function init_calendar_months(jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec)
{
    this.cal_monthName = new Array(jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec);
}


/*
    Initialize the array of days based on i18n values.
*/
function init_calendar_days(cal_startAt, sun, mon, tue, wed, thu, fri, sat)
{
    this.cal_startAt = cal_startAt;
    if (cal_startAt == 0)
    {
        cal_dayName = new Array(sun, mon, tue, wed, thu, fri, sat);
    }
    else
    {
        cal_dayName = new Array(mon, tue, wed, thu, fri, sat, sun);
    }
}


function init_calendar()
{
    // Determine if init_calendar has already been called in way that works for AJAX environments
    try
    {
        if(document.getElementById("__calendar__")) return;
    } catch(e)
    {
        // element does not exist from previous init, so we need to keep running
    }
    var resourceRootPath = contextPath;
    this.cal_resourceRootPath = resourceRootPath + '/';
    for (i = 0; i < cal_imgsrc.length; i++)
    {
        cal_img[i] = new Image;
        cal_img[i].src = cal_resourceRootPath + cal_imgDir + cal_imgsrc[i];
    }

    calendarDiv = document.createElement("div");
    calendarDiv.id = "__calendar__";
    calendarDiv.onClick = "cal_bShow=true";
    calendarDiv.style.zIndex = "5999";
    calendarDiv.style.position = "absolute";
    calendarDiv.style.display = "none";


    cal_sHTML1 = "<span id='spanLeft' style='border-style:solid;border-width:1;border-color:#3366FF;cursor:pointer' onmouseover='swapImage(\"changeLeft\",\"left2.gif\");this.style.borderColor=\"#88AAFF\";window.status=\"" + i18n_cal_scrollLeftMessage + "\"' onclick='javascript:decMonth()' onmouseout='clearInterval(cal_intervalID1);swapImage(\"changeLeft\",\"left1.gif\");this.style.borderColor=\"#3366FF\";window.status=\"\"' onmousedown='clearTimeout(cal_timeoutID1);cal_timeoutID1=setTimeout(\"StartDecMonth()\",500)' onmouseup='clearTimeout(cal_timeoutID1);clearInterval(cal_intervalID1)'>&nbsp<IMG id='changeLeft' SRC='" + cal_resourceRootPath + cal_imgDir + "left1.gif' width=10 height=11 BORDER=0>&nbsp</span>&nbsp;";
    cal_sHTML1 += "<span id='spanRight' style='border-style:solid;border-width:1;border-color:#3366FF;cursor:pointer' onmouseover='swapImage(\"changeRight\",\"right2.gif\");this.style.borderColor=\"#88AAFF\";window.status=\"" + i18n_cal_scrollRightMessage + "\"' onmouseout='clearInterval(cal_intervalID1);swapImage(\"changeRight\",\"right1.gif\");this.style.borderColor=\"#3366FF\";window.status=\"\"' onclick='incMonth()' onmousedown='clearTimeout(cal_timeoutID1);cal_timeoutID1=setTimeout(\"StartIncMonth()\",500)' onmouseup='clearTimeout(cal_timeoutID1);clearInterval(cal_intervalID1)'>&nbsp<IMG id='changeRight' SRC='" + cal_resourceRootPath + cal_imgDir + "right1.gif' width=10 height=11 BORDER=0>&nbsp</span>&nbsp";
    cal_sHTML1 += "<span id='spanMonth' style='border-style:solid;border-width:1;border-color:#3366FF;cursor:pointer' onmouseover='swapImage(\"changeMonth\",\"drop2.gif\");this.style.borderColor=\"#88AAFF\";window.status=\"" + i18n_cal_selectMonthMessage + "\"' onmouseout='swapImage(\"changeMonth\",\"drop1.gif\");this.style.borderColor=\"#3366FF\";window.status=\"\"' onclick='popUpMonth()'></span>&nbsp;";
    cal_sHTML1 += "<span id='spanYear' style='border-style:solid;border-width:1;border-color:#3366FF;cursor:pointer' onmouseover='swapImage(\"changeYear\",\"drop2.gif\");this.style.borderColor=\"#88AAFF\";window.status=\"" + i18n_cal_selectYearMessage + "\"' onmouseout='swapImage(\"changeYear\",\"drop1.gif\");this.style.borderColor=\"#3366FF\";window.status=\"\"' onclick='popUpYear()'></span>&nbsp;";
    //We set the zIndex over 5001 because of the 'popup' dialog framework which is at a zIndex of 5001 (and we need the
    // calendar to sit over it)
    var sHtml = ("<table width=" + ((cal_showWeekNumber == 1)?250:220) + " style='font-family:arial;font-size:11px;border-width:1;border-style:solid;border-color:#a0a0a0;font-family:arial; font-size:11px}' bgcolor='#ffffff'>");
    sHtml += ("<tr bgcolor='#0000aa'><td>");
    sHtml += ("  <table width='" + ((cal_showWeekNumber == 1)?248:218) + "'><tr><td style='padding:2px;font-family:arial; font-size:11px;'>");
    sHtml += ("     <font color='#ffffff'><B><span id='caption'>" + cal_sHTML1 + "</span></B></font>");
    sHtml += ("  </td><td align=right>");
    sHtml += ("     <a href='javascript:hideCalendar()'><IMG SRC='" + cal_resourceRootPath + cal_imgDir + "close.gif' WIDTH='15' HEIGHT='13' BORDER='0' ALT='Close the Calendar'></a>");
    sHtml += ("  </td></tr></table>");
    sHtml += ("</td></tr>");
    sHtml += ("<tr><td style='padding:5px' bgcolor=#ffffff>");
    sHtml += ("<span id='content'></span></td></tr>");
    if (cal_showToday == 1)
    {
/*
        sHtml += ("<tr bgcolor=#f0f0f0><td style='padding:5px' align=center><span id='lblToday'>" + i18n_cal_todayString + " <a onmousemove='window.status=\"" + i18n_cal_gotoString + "\"' onmouseout='window.status=\"\"' title='" + i18n_cal_gotoString + "' style='" + cal_styleAnchor + "' href='javascript:cal_monthSelected=cal_monthNow;cal_yearSelected=cal_yearNow;constructCalendar();'>" + cal_dayName[(cal_today.getDay() - cal_startAt == -1)?6:(cal_today.getDay() - cal_startAt)] + ", " + cal_dateNow + " " + cal_monthName[cal_monthNow].substring(0, 3) + " " + cal_yearNow + "</a>" + "</span></td></tr>");
*/
        /* CR261027 - commented out 'today is' value */
        sHtml += ("<tr bgcolor=#f0f0f0><td style='padding:0px' align=center><span id='lblToday'></span></td></tr>");
    }

    sHtml += "</table>";
    calendarDiv.innerHTML = sHtml;

    document.body.appendChild(calendarDiv);
    selectMonthDiv = document.createElement("div");
    selectMonthDiv.id = "selectMonth";
    selectMonthDiv.style.zIndex = "6000";
    selectMonthDiv.style.position = "absolute";
    selectMonthDiv.style.visibility = "hidden";
    document.body.appendChild(selectMonthDiv);

    selectYearDiv = document.createElement("div");
    selectYearDiv.id = "selectYear";
    selectYearDiv.style.zIndex = "6000";
    selectYearDiv.style.position = "absolute";
    selectYearDiv.style.visibility = "hidden";
    document.body.appendChild(selectYearDiv);

    cal_styleAnchor = "text-decoration:none;color:black;";
    cal_styleLightBorder = "border-style:solid;border-width:1px;border-color:#a0a0a0;";

    cal_crossobj = calendarDiv.style;
    cal_crossMonthObj = selectMonthDiv.style;
    cal_crossYearObj = selectYearDiv.style;
    cal_monthConstructed = false;
    cal_yearConstructed = false;
}


function HolidayRec(d, m, y, desc)
{
    this.d = d;
    this.m = m;
    this.y = y;
    this.desc = desc;
}

function hideCalendar()
{
    cal_crossobj.display = "none";
    if (cal_crossMonthObj != null)
    {
        cal_crossMonthObj.visibility = "hidden";
    }
    if (cal_crossYearObj != null)
    {
        cal_crossYearObj.visibility = "hidden";
    }
    var t_captionDiv = document.getElementById("caption");
    if ( t_captionDiv != null )
    {
        t_captionDiv.style.visibility = "hidden";
    }
    cal_showIeSelects();
    // Removed to fix CR171952
    // var timeoutText = "toScroll(" + document.body.scrollTop + "," + document.body.scrollLeft + ");";
    // setTimeout(timeoutText, 20);
}



function addHoliday(d, m, y, desc)
{
    cal_Holidays[cal_HolidaysCounter++] = new HolidayRec (d, m, y, desc);
}

function swapImage(srcImg, destImg)
{
    document.getElementById(srcImg).setAttribute("src", cal_resourceRootPath + cal_imgDir + destImg);
}

function padZero(num)
{
    return (num < 10)? '0' + num : num;
}



function constructDate(d, m, y)
{
    sTmp = cal_dateFormat;
    sTmp = sTmp.replace("Z", "");
    sTmp = sTmp.replace("dd", "<e>");
    sTmp = sTmp.replace("d", "<d>");
    sTmp = sTmp.replace("<e>", padZero(d));
    sTmp = sTmp.replace("<d>", d);
    sTmp = sTmp.replace("yyyy", "<z>");
    sTmp = sTmp.replace("yy", "<y>");
    sTmp = sTmp.replace("MMMM", "<o>");             // January
    sTmp = sTmp.replace("MMM", "<k>");              // Jan
    sTmp = sTmp.replace("MM", "<n>");               // 01
    sTmp = sTmp.replace("M", "<m>");                // 1
    sTmp = sTmp.replace("<m>", m + 1);
    sTmp = sTmp.replace("<n>", padZero(m + 1));
    sTmp = sTmp.replace("<o>", cal_monthName[m]);
    sTmp = sTmp.replace("<k>", cal_monthName[m].substring(0, 3));
    sTmp.replace("<y>", y.toString().substring(2));
    return sTmp.replace("<z>", y);
}

function clearCalendar() {
    hideCalendar();
    if (cal_ctlToPlaceValue.type == "text") {
        cal_ctlToPlaceValue.value = "";
    }
    else {
        cal_ctlToPlaceValue.innerHTML = "";
    }
}

function closeCalendar()
{
    var sTmp;
    var isTimeValid = true;

    if (document.getElementById(cal_ctlToPlaceValue.id + "TimeSpinner") != null)
    {
        isTimeValid = validTime();
    }

    if (isTimeValid)
    {
        hideCalendar();
        if (cal_ctlToPlaceValue.type == "text")
        {
            if (document.getElementById(cal_ctlToPlaceValue.id + "TimeSpinner") != null)
            {
                if ( cal_timeOnly == true )
                {
                    cal_ctlToPlaceValue.value = constructTime();
                }
                else
                {
                    cal_ctlToPlaceValue.value = constructDateTime(constructDate(cal_dateSelected, cal_monthSelected, cal_yearSelected));
                }
            }
            else
            {
                cal_ctlToPlaceValue.value = constructDate(cal_dateSelected, cal_monthSelected, cal_yearSelected);
            }
        }
        else
        {
            if (document.getElementById(cal_ctlToPlaceValue.id + "TimeSpinner") != null)
            {
                if ( cal_timeOnly == true )
                {
                    cal_ctlToPlaceValue.value = constructTime();
                }
                else
                {
                    cal_ctlToPlaceValue.innerHTML = constructDateTime(constructDate(cal_dateSelected, cal_monthSelected, cal_yearSelected));
                }
            }
            else
            {
                cal_ctlToPlaceValue.innerHTML = constructDate(cal_dateSelected, cal_monthSelected, cal_yearSelected);
            }
        }
    }
    else
    {
        alert(cal_i18n_invalid_time);
    }
}

function constructTime()
{
    var mTmp = cal_dateFormat;
    mTmp = mTmp.replace("Z", "");
//    mTmp = mTmp.replace(cal_dateFormat, document.getElementById(cal_ctlToPlaceValue.id + "TimeSpinnerTime").value);
    mTmp = mTmp.replace(mTmp, document.getElementById(cal_ctlToPlaceValue.id + "TimeSpinnerTime").value);
    return mTmp;
}


function constructDateTime(date)
{
    var t_dateTimeFormat = cal_dateFormat;
    var t_dateTimeFormatWithoutZ = t_dateTimeFormat.replace(" Z", "");
    var t_timeFormat = timePortionOfFormat(t_dateTimeFormatWithoutZ);
    if(document.getElementById(cal_ctlToPlaceValue.id + "TimeZone")!=null)
    {
        t_dateTimeFormat = t_dateTimeFormat.replace("Z", document.getElementById(cal_ctlToPlaceValue.id + "TimeZone").innerHTML);
    }
    t_dateTimeFormat = t_dateTimeFormat.replace(t_dateTimeFormatWithoutZ, date);
    timeSpinnerValue = document.getElementById(cal_ctlToPlaceValue.id + "TimeSpinnerTime").value;
    t_dateTimeFormat = t_dateTimeFormat.replace(t_timeFormat, document.getElementById(cal_ctlToPlaceValue.id + "TimeSpinnerTime").value);
    return t_dateTimeFormat;
}



/* Month Pulldown */
function StartDecMonth()
{
    cal_intervalID1 = setInterval("decMonth()", 80);
}



function StartIncMonth()
{
    cal_intervalID1 = setInterval("incMonth()", 80);
}

function incMonth()
{
    cal_monthSelected++;
    if (cal_monthSelected > 11)
    {
        cal_monthSelected = 0;
        cal_yearSelected++;

    }
    constructCalendar();
}

function decMonth()
{
    cal_monthSelected--;
    if (cal_monthSelected < 0)
    {
        cal_monthSelected = 11;
        cal_yearSelected--;
    }
    constructCalendar();
}


function constructMonth()
{
    popDownYear();
    if (!cal_monthConstructed)
    {
        sHTML = ""
        for (i = 0; i < 12; i++)
        {
            sName = cal_monthName[i];
            if (i == cal_monthSelected)
            {
                sName = "<B>" + sName + "</B>"
            }
            sHTML += "<tr><td id='m" + i + "' onmouseover='this.style.backgroundColor=\"#FFCC99\"' onmouseout='this.style.backgroundColor=\"\"' style='cursor:pointer' onclick='cal_monthConstructed=false;cal_monthSelected=" + i + ";constructCalendar();popDownMonth();event.cancelBubble=true'>&nbsp;" + sName + "&nbsp;</td></tr>"
        }
        document.getElementById("selectMonth").innerHTML = "<table width=70 style='font-family:arial; font-size:11px; border-width:1; border-style:solid; border-color:#a0a0a0;' bgcolor='#FFFFDD' cellspacing=0 onmouseover='clearTimeout(cal_timeoutID1)' onmouseout='clearTimeout(cal_timeoutID1);cal_timeoutID1=setTimeout(\"popDownMonth()\",100);event.cancelBubble=true'>" + sHTML + "</table>"
        cal_monthConstructed = true
    }
}

function popUpMonth()
{
    constructMonth();
    cal_crossMonthObj.visibility = "visible";
    cal_crossMonthObj.left = parseInt(cal_crossobj.left) + 50 + "px";
    cal_crossMonthObj.top = parseInt(cal_crossobj.top) + 26 + "px";
}

function popDownMonth()
{
    cal_crossMonthObj.visibility = "hidden";
}

/* Year Pulldown */
function incYear()
{
    for (i = 0; i < 7; i++)
    {
        newYear = (i + cal_nStartingYear) + 1
        if (newYear == cal_yearSelected)
        {
            txtYear = "&nbsp;<B>" + newYear + "</B>&nbsp;"
        }
        else
        {
            txtYear = "&nbsp;" + newYear + "&nbsp;"
        }
        document.getElementById("y" + i).innerHTML = txtYear;
    }
    cal_nStartingYear ++;
    cal_bShow = true
}

function decYear()
{
    //We only want the calendar to go down to the year 1000 AD.  This is for two resons;One being that we wanted to follow the
    // model that exists within the IDE, the second being that when Phil parses expressions based on date, he can assume the dates
    // are AD (and there should be no reason would want to enter in a BC date)
    if (cal_nStartingYear > 1000)
    {
        for (i = 0; i < 7; i++)
        {
            newYear = (i + cal_nStartingYear) - 1
            if (newYear == cal_yearSelected)
            {
                txtYear = "&nbsp;<B>" + newYear + "</B>&nbsp;"
            }
            else
            {
                txtYear = "&nbsp;" + newYear + "&nbsp;"
            }
            document.getElementById("y" + i).innerHTML = txtYear;
        }
        cal_nStartingYear --;
    }
    cal_bShow = true
}


function selectYear(nYear)
{
    cal_yearSelected = parseInt(nYear + cal_nStartingYear);
    cal_yearConstructed = false;
    constructCalendar();
    popDownYear();
}

function constructYear()
{
    popDownMonth();
    sHTML = ""
    if (!cal_yearConstructed)
    {
        sHTML = "<tr><td align='center' onmouseover='this.style.backgroundColor=\"#FFCC99\"' onmouseout='clearInterval(cal_intervalID1);this.style.backgroundColor=\"\"' style='cursor:pointer' onmousedown='clearInterval(cal_intervalID1);cal_intervalID1=setInterval(\"decYear()\",30)' onmouseup='clearInterval(cal_intervalID1)'>-</td></tr>"
        j = 0
        cal_nStartingYear = cal_yearSelected - 3
        for (i = (cal_yearSelected - 3); i <= (cal_yearSelected + 3); i++)
        {
            sName = i;
            if (i == cal_yearSelected)
            {
                sName = "<B>" + sName + "</B>"
            }
            sHTML += "<tr><td id='y" + j + "' onmouseover='this.style.backgroundColor=\"#FFCC99\"' onmouseout='this.style.backgroundColor=\"\"' style='cursor:pointer' onclick='selectYear(" + j + ");event.cancelBubble=true'>&nbsp;" + sName + "&nbsp;</td></tr>"
            j ++;
        }
        sHTML += "<tr><td align='center' onmouseover='this.style.backgroundColor=\"#FFCC99\"' onmouseout='clearInterval(cal_intervalID2);this.style.backgroundColor=\"\"' style='cursor:pointer' onmousedown='clearInterval(cal_intervalID2);cal_intervalID2=setInterval(\"incYear()\",30)' onmouseup='clearInterval(cal_intervalID2)'>+</td></tr>";
        document.getElementById("selectYear").innerHTML = "<table width=44 style='font-family:arial; font-size:11px; border-width:1; border-style:solid; border-color:#a0a0a0;' bgcolor='#FFFFDD' onmouseover='clearTimeout(cal_timeoutID2)' onmouseout='clearTimeout(cal_timeoutID2);cal_timeoutID2=setTimeout(\"popDownYear()\",100)' cellspacing=0>" + sHTML + "</table>";
        cal_yearConstructed = true
    }
}

function popDownYear()
{
    clearInterval(cal_intervalID1)
    clearTimeout(cal_timeoutID1)
    clearInterval(cal_intervalID2)
    clearTimeout(cal_timeoutID2)
    cal_crossYearObj.visibility = "hidden";
}

function popUpYear()
{
    var leftOffset
    constructYear()
    cal_crossYearObj.visibility = "visible";
    leftOffset = parseInt(cal_crossobj.left) + document.getElementById("spanYear").offsetLeft + 6;
    cal_crossYearObj.left = leftOffset + "px";
    cal_crossYearObj.top = parseInt(cal_crossobj.top) + 26 + "px";
}

/* calendar */

function WeekNbr(n)
{
    // Algorithm used:
    // From Klaus Tondering's Calendar document (The Authority/Guru)
    // hhtp://www.tondering.dk/claus/calendar.html
    // a = (14-month) / 12
    // y = year + 4800 - a
    // m = month + 12a - 3
    // J = day + (153m + 2) / 5 + 365y + y / 4 - y / 100 + y / 400 - 32045
    // d4 = (J + 31741 - (J mod 7)) mod 146097 mod 36524 mod 1461
    // L = d4 / 1460
    // d1 = ((d4 - L) mod 365) + L
    // WeekNumber = d1 / 7 + 1

    year = n.getFullYear();
    month = n.getMonth() + 1;
    if (cal_startAt == 0)
    {
        day = n.getDate() + 1;
    }
    else
    {
        day = n.getDate();
    }
    a = Math.floor((14 - month) / 12);
    y = year + 4800 - a;
    m = month + 12 * a - 3;
    b = Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400);
    J = day + Math.floor((153 * m + 2) / 5) + 365 * y + b - 32045;
    d4 = (((J + 31741 - (J % 7)) % 146097) % 36524) % 1461;
    L = Math.floor(d4 / 1460);
    d1 = ((d4 - L) % 365) + L;
    week = Math.floor(d1 / 7) + 1;
    return week;
}

function constructCalendar()
{
    var aNumDays = Array(31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
    var dateMessage
    var startDate = new    Date (cal_yearSelected, cal_monthSelected, 1)
    var endDate
    if (cal_monthSelected == 1)
    {
        endDate = new Date (cal_yearSelected, cal_monthSelected + 1, 1);
        endDate = new Date (endDate - (24 * 60 * 60 * 1000));
        numDaysInMonth = endDate.getDate()
    }
    else
    {
        numDaysInMonth = aNumDays[cal_monthSelected];
    }
    datePointer = 0
    dayPointer = startDate.getDay() - cal_startAt
    if (dayPointer < 0)
    {
        dayPointer = 6
    }


    sHTML = "<table border=0 style='font-family:verdana;font-size:10px;'><tr>"
    if (cal_showWeekNumber == 1)
    {
        sHTML += "<td width=27><b>" + i18n_cal_weekString + "</b></td><td width=1 rowspan=7 bgcolor='#d0d0d0' style='padding:0px'><cal_img src='" + cal_resourceRootPath + cal_imgDir + "divider.gif' width=1></td>"
    }
    for (i = 0; i < 7; i++)
    {
        sHTML += "<td width='27' align='right'><B>" + cal_dayName[i] + "</B></td>"
    }
    sHTML += "</tr><tr>"
    if (cal_showWeekNumber == 1)
    {
        sHTML += "<td align=right>" + WeekNbr(startDate) + "&nbsp;</td>"
    }

    for (var i = 1; i <= dayPointer; i++)
    {
        sHTML += "<td>&nbsp;</td>"
    }
    for (datePointer = 1; datePointer <= numDaysInMonth; datePointer++)
    {
        dayPointer++;
        sHTML += "<td align=right>"
        sStyle = cal_styleAnchor
        if ((datePointer == cal_odateSelected) && (cal_monthSelected == cal_omonthSelected) && (cal_yearSelected == cal_oyearSelected))
        {
            sStyle += cal_styleLightBorder
        }
        sHint = ""
        for (k = 0; k < cal_HolidaysCounter; k++)
        {
            if ((parseInt(cal_Holidays[k].d) == datePointer) && (parseInt(cal_Holidays[k].m) == (cal_monthSelected + 1)))
            {
                if ((parseInt(cal_Holidays[k].y) == 0) || ((parseInt(cal_Holidays[k].y) == cal_yearSelected) && (parseInt(cal_Holidays[k].y) != 0)))
                {
                    sStyle += "background-color:#FFDDDD;"
                    sHint += sHint == ""?cal_Holidays[k].desc:"\n" + cal_Holidays[k].desc
                }
            }
        }

        var regexp = /\"/g
        sHint = sHint.replace(regexp, "&quot;")
        dateMessage = "onmousemove='window.status=\"" + cal_selectDateMessage.replace("[date]", constructDate(datePointer, cal_monthSelected, cal_yearSelected)) + "\"' onmouseout='window.status=\"\"' "
        if ((datePointer == cal_dateNow) && (cal_monthSelected == cal_monthNow) && (cal_yearSelected == cal_yearNow))
        {
            sHTML += "<b><a " + dateMessage + " title=\"" + sHint + "\" style='" + sStyle + "' href='javascript:cal_dateSelected=" + datePointer + ";closeCalendar();'><font color=#ff0000>&nbsp;" + datePointer + "</font>&nbsp;</a></b>"
        }
        else if (dayPointer % 7 == (cal_startAt * -1) + 1)
        {
            sHTML += "<a " + dateMessage + " title=\"" + sHint + "\" style='" + sStyle + "' href='javascript:cal_dateSelected=" + datePointer + ";closeCalendar();'>&nbsp;<font color=#909090>" + datePointer + "</font>&nbsp;</a>"
        }
        else
        {
            sHTML += "<a " + dateMessage + " title=\"" + sHint + "\" style='" + sStyle + "' href='javascript:cal_dateSelected=" + datePointer + ";closeCalendar();'>&nbsp;" + datePointer + "&nbsp;</a>"
        }


        sHTML += ""
        if ((dayPointer + cal_startAt) % 7 == cal_startAt)
        {
            sHTML += "</tr><tr>"
            if ((cal_showWeekNumber == 1) && (datePointer < numDaysInMonth))
            {
                sHTML += "<td align=right>" + (WeekNbr(new Date(cal_yearSelected, cal_monthSelected, datePointer + 1))) + "&nbsp;</td>"
            }
        }
    }
    document.getElementById("content").innerHTML = sHTML
    document.getElementById("spanMonth").innerHTML = "&nbsp;" + cal_monthName[cal_monthSelected] + "&nbsp;<IMG id='changeMonth' SRC='" + cal_resourceRootPath + cal_imgDir + "drop1.gif' WIDTH='12' HEIGHT='10' BORDER=0>"
    document.getElementById("spanYear").innerHTML = "&nbsp;" + cal_yearSelected + "&nbsp;<IMG id='changeYear' SRC='" + cal_resourceRootPath + cal_imgDir + "drop1.gif' WIDTH='12' HEIGHT='10' BORDER=0>"
}

function popUpCalendar(ctl, ctl2, showTimeSpinner, showTimezoneChooser, p_calFormat, p_timeOnly)
{
    cal_timeOnly = p_timeOnly;

    var sTop;
    var sLeft;

    if (document.documentElement.scrollTop)
    {
        sTop = document.documentElement.scrollTop;
        sLeft = document.documentElement.scrollLeft;
    }
    else
    {
        sTop = document.body.scrollTop;
        sLeft = document.body.scrollLeft;
    }

    if (cal_crossobj.display == "none")
    {
        cal_ctlToPlaceValue = ctl2
        if ( p_calFormat == null || p_calFormat.length == 0 )
        {
            cal_dateFormat = i18n_cal_calendarFormat;
        }
        else
        {
            cal_dateFormat = p_calFormat;
        }

        // This is what is parsing the date.
        // wow - what an algorithm :(

        // find the last position of the date stuff

        var searchItems = new Array("MMMM", "yyyy", "MMM", "MM", "dd", "d");
        var lastPos = 0;
        for (i=0;i<searchItems.length;i++)
        {
            var location = cal_dateFormat.lastIndexOf(searchItems[i]);
            if (location != -1)
            {
                location +=  searchItems[i].length;
                lastPos = Math.max(lastPos,location);
            }
        }
        var t_cal_dateFormat = cal_dateFormat;
        if (lastPos > 0 )
        {
            t_cal_dateFormat = cal_dateFormat.substring(0, lastPos);
        }

        formatChar = " ";
        aFormat = t_cal_dateFormat.split(formatChar)
        if (aFormat.length < 3)
        {
            formatChar = "/"
            aFormat = t_cal_dateFormat.split(formatChar)
            if (aFormat.length < 3)
            {
                formatChar = "."
                aFormat = t_cal_dateFormat.split(formatChar)
                if (aFormat.length < 3)
                {
                    formatChar = "-"
                    aFormat = t_cal_dateFormat.split(formatChar)
                    if (aFormat.length < 3)
                    {
                        // invalid date format
                        formatChar = ""
                    }
                }
            }
        }
        var userTime = "";
        // use user's date
        if (ctl2.type == "text")

        {
            userTime = ctl2.value;
        }
        else
        {
            userTime = ctl2.innerHTML;
        }
        tokensChanged = 0
        if (formatChar != "")
        {
            aData = userTime.split(formatChar);
            for (i = 0; i < 3; i++)
            {
                if ((aFormat[i] == "d") || (aFormat[i] == "dd"))
                {
                    cal_dateSelected = parseInt(aData[i], 10)
                    tokensChanged ++
                }
                else if ((aFormat[i] == "MM") || (aFormat[i] == "MMM"))
                {
                    cal_monthSelected = parseInt(aData[i], 10) - 1
                    tokensChanged ++
                }
                else if (aFormat[i] == "yyyy")
                {
                    cal_yearSelected = parseInt(aData[i], 10)
                    tokensChanged ++
                }
                else if (aFormat[i] == "MMMM")
                {
                    for (j = 0; j < 12; j++)
                    {
                        if (aData[i] == cal_monthName[j])
                        {
                            cal_monthSelected = j
                            tokensChanged ++
                        }
                    }
                }
            }
        }

        // Another 'great' algorithm
        // Pull out the timezone
        var gmtOffset = "0000";
        if (cal_dateFormat.indexOf("Z") != -1
            && userTime.length > 3)
        {
            // if the format has the only supported TZ representation
            // then pull off the last 4 or 5 characters
            var t_offset = userTime.substr(userTime.length-4,4);
            if (t_offset != "0000"
                && userTime.length>4)
            {
                var plusMinus = userTime.charAt(userTime.length-5);
                gmtOffset = plusMinus + t_offset;
            }
        }
        if ((tokensChanged != 3) || isNaN(cal_dateSelected) || isNaN(cal_monthSelected) || isNaN(cal_yearSelected))
        {
            cal_dateSelected = cal_dateNow;
            cal_monthSelected = cal_monthNow;
            cal_yearSelected = cal_yearNow;
        }
        cal_odateSelected = cal_dateSelected;
        cal_omonthSelected = cal_monthSelected;
        cal_oyearSelected = cal_yearSelected;
        cal_crossobj.left = cal_fixedX == -1 ? wlpCalendarFindPosX(ctl) - 100 + "px" : cal_fixedX - 100 + "px"; //adjusting so it is not to the far right
        cal_crossobj.top = cal_fixedY == -1 ?    wlpCalendarFindPosY(ctl) + ctl.offsetHeight + 2 + "px" : cal_fixedY + "px";

        var captionDiv = document.getElementById("caption");
        if ( !p_timeOnly )
        {
            constructCalendar(1, cal_monthSelected, cal_yearSelected);
            captionDiv.style.visibility = "visible";
        }
        else
        {
            document.getElementById("content").innerHTML = "";
            captionDiv.style.visibility = "hidden";
        }
        cal_hideIeSelects();
        cal_crossobj.display = "block";

        cal_bShow = true;
        if (cal_showToday == 1)
        {
            if (showTimeSpinner == true)
            {
                newInnerHTML = "";
                newInnerHTML += "<TABLE>";
                newInnerHTML += "<TR>";
                newInnerHTML += "<TD nowrap>";
                newInnerHTML += "<SPAN ID='" + ctl2.id + "TimeSpinner' style='white-space: nowrap;'>";
                newInnerHTML += userTime;
                newInnerHTML += "</SPAN>";
                newInnerHTML += "</TD>";
                if ( showTimezoneChooser == true )
                {
                    newInnerHTML += "<TD>";
                    newInnerHTML += "<DIV ID='" + cal_ctlToPlaceValue.id + "TimeZone' style='white-space: nowrap;'>";
                    newInnerHTML += gmtOffset;
                    newInnerHTML += "</DIV>";
                    newInnerHTML += "</TD>";
                }
                newInnerHTML += "<TD>";
                newInnerHTML += "<A HREF='javascript:clearCalendar()'>";
                newInnerHTML += "<IMG NAME='calendarClear' SRC='" + cal_resourceRootPath + cal_imgDir + "button_clear.gif' ALT='" + i18n_cal_done + "' BORDER='0' HSPACE='4' VSPACE='4'>";
                newInnerHTML += "</A><BR>";

                newInnerHTML += "<A HREF='javascript:closeCalendar()'>";
                newInnerHTML += "<IMG NAME='calendarDone' SRC='" + cal_resourceRootPath + cal_imgDir + "button_done.gif' ALT='" + i18n_cal_done + "' BORDER='0' HSPACE='4' VSPACE='4'>";
                newInnerHTML += "</A>";
                newInnerHTML += "</TD>";


                /*
                Timezone chooser
                */
                if ( showTimezoneChooser == true )
                {
                    var tz_displayNames = document.getElementById("timezone_display_values").innerHTML.split(",");
                    var tz_ids = document.getElementById("timezone_ids").innerHTML.split(",");
                    var tz_offsets = document.getElementById("timezone_raw_offsets").innerHTML.split(",");

                    newInnerHTML += "<TR>";
                    newInnerHTML += "<TD  COLSPAN='3' >";
                    newInnerHTML += "<SELECT ID='" + ctl2.id + "TimeZoneSelect' SIZE='5' onchange='javascript:updateTimeZone(\"" + cal_ctlToPlaceValue.id + "\")'>";
                    for (i = 0; i < tz_displayNames.length; i++)
                    {
                        newInnerHTML += "<OPTION value='" + tz_offsets[i] + "'>" + tz_displayNames[i] + " [" + tz_ids[i] + "]</OPTION>";
                    }
                    newInnerHTML += "</SELECT>";
                    newInnerHTML += "</TD>";
                    newInnerHTML += "</TR>";
                }

                newInnerHTML += "</TR>";
                newInnerHTML += "</TABLE>";
                document.getElementById("lblToday").innerHTML = newInnerHTML;

                // Replace the Timezone formatter so that the spinner will work.
//                t_p_calFormat = timePortionOfFormat(p_calFormat);
                t_p_calFormat = p_calFormat;
                initTimeSpinner(ctl2.id + "TimeSpinner", true, cal_resourceRootPath, t_p_calFormat);
            }
            else
            {
                newInnerHTML = "";
                newInnerHTML += "<TABLE width='100%'>";
                newInnerHTML += "<TR><TD>&nbsp;</TD>";
                newInnerHTML += "<TD align='right'>";
                newInnerHTML += "<A HREF='javascript:clearCalendar()'>";
                newInnerHTML += "<IMG NAME='calendarClear' SRC='" + cal_resourceRootPath + cal_imgDir + "button_clear.gif' ALT='" + i18n_cal_done + "' BORDER='0' HSPACE='4' VSPACE='4'>";
                newInnerHTML += "</A>";

                newInnerHTML += "<A HREF='javascript:closeCalendar()'>";
                newInnerHTML += "<IMG NAME='calendarDone' SRC='" + cal_resourceRootPath + cal_imgDir + "button_done.gif' ALT='" + i18n_cal_done + "' BORDER='0' HSPACE='4' VSPACE='4'>";
                newInnerHTML += "</A>";
                newInnerHTML += "</TD>";
                newInnerHTML += "</TR>";
                newInnerHTML += "</TABLE>";
                document.getElementById("lblToday").innerHTML = newInnerHTML;
            
/*
                document.getElementById("lblToday").innerHTML = i18n_cal_todayString + " <a onmousemove='window.status=\"" + i18n_cal_gotoString + "\"' onmouseout='window.status=\"\"' title='" + i18n_cal_gotoString + "' style='" + cal_styleAnchor + "' href='javascript:cal_monthSelected=cal_monthNow;cal_yearSelected=cal_yearNow;constructCalendar();'>" + cal_dayName[(cal_today.getDay() - cal_startAt == -1)?6:(cal_today.getDay() - cal_startAt)] + ", " + cal_dateNow + " " + cal_monthName[cal_monthNow].substring(0, 3) + " " + cal_yearNow + "</a>"
*/
                /* CR261027 - commented out 'today is' value */
            }
        }
        var timeoutText = "toScroll(" + sTop + "," + sLeft + ");";
        setTimeout(timeoutText, 1);
    }
}

function timePortionOfFormat(timeDateFormat)
{
    lastYearPos = timeDateFormat.lastIndexOf("y");
    lastMonthPos = timeDateFormat.lastIndexOf("M");
    maxValue = Math.max(lastYearPos, lastMonthPos);
    lastDatePos = timeDateFormat.lastIndexOf("d");
    maxValue = Math.max(maxValue, lastDatePos);
    if ( maxValue != -1 )
    {
        maxValue = maxValue+2;
        if ( (maxValue) < (timeDateFormat.length-1) )
        {
            timeDateFormat = (timeDateFormat.substr(maxValue));
        }
    }
    return timeDateFormat;
}

function updateTimeZone(ctl2_id)
{
    var selected = document.getElementById(ctl2_id + "TimeZoneSelect");
    var selectedIndex = selected.selectedIndex;
    var selectedValue = selected.options[selectedIndex].value;
    document.getElementById(ctl2_id + "TimeZone").innerHTML = selectedValue;

}

/*
document.onClick = function hidecal2(event)
{
    if (!cal_bShow)
    {
        hideCalendar()
    }
    cal_bShow = false
}
*/

function toScroll(top, left)
{
    window.scrollTo(left, top);
}

// <select> elements in IE show through and "over" everything, including the Calendar widget
// Temporarily hide them all while the widget is displayed
function cal_hideIeSelects()
{
    if(document.all)
    {
        var theSelects = document.getElementsByTagName("SELECT");
        for (i = 0; i < theSelects.length; i++)
        {
            var oldVisibility = theSelects[i].style.visibility;
            theSelects[i].style.visibility="hidden";
            theSelects[i].setAttribute("oldVisibility", oldVisibility);
        }
    }
}
// Revert <select> elements in IE their previous visibility setting (see above "cal_hideIeSelects()"
function cal_showIeSelects()
{
    if(document.all)
    {
        var theSelects = document.getElementsByTagName("SELECT");
        for (i = 0; i < theSelects.length; i++)
        {
            var oldVisibility = theSelects[i].getAttribute("oldVisibility");
            if(oldVisibility != null)
            {
                theSelects[i].style.visibility=oldVisibility;
            }
        }
    }
}

function wlpCalendarFindPosX(obj)
{
    var curleft = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
    {
        curleft += obj.x;
    }
    return curleft;
}

function wlpCalendarFindPosY(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
    {
        curtop += obj.y;
    }

    return curtop;
}