// startignore
// eap:startheader
/*****************************************************************\
|                                                                 |
|  Fair License                                                   |
|                                                                 |
|  PopCal Ver 1.0 - The C-o-o-lest Pop Up Calendar!               |
|  Copyright (C) 2004  Arun Narayanan                             |
|                                                                 |
|  For Latest Release visit:                                      |
|  http://jsutils.sourceforge.net/                                |
|                                                                 |
|  Usage of the works is permitted provided that this             |
|  instrument is retained with the works, so that any entity      |
|  that uses the works is notified of this instrument.            |
|                                                                 |
|  DISCLAIMER: THE WORKS ARE WITHOUT WARRANTY.                    |
|                                                                 |
|  [2004, Fair License: rhid.com/fair]                            |
|                                                                 |
\*****************************************************************/
// eap:endheader
// endignore

/*jsl:import .\popcal_config.js */

//Global Variables-------------->
var cal_today;
var cal_original;
var cal_currcell = null;
var cal_currfield = null;
var win = null;
var cal_dstart, cal_dend;	// month start/end cell numbers
var cal_savedparams = '';
var DEBUGMSG;				// Used by in-built debugger
var DEBUG = false;			// set it to true to see javascript errors
var cal_text = new Array();
var wkcnt = 6;
var daycnt = wkcnt * 7;
//END: Global Variables--------->

//Initializing Functions--------->
//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function popCal(field, params, x, y, cul, cap)
{
	var v, a, f, i, year = 0, month = 0, day = 1;

	DEBUGMSG = "Function: popCal";

	window.onerror = showErrMsg;

	//--- #4782 - Get localized text.
	
	if (cap) cal_CALENDAR_TITLE = cap;
	
	var culTxt = (cul && window.cal_text) ? window.cal_text[cul] : null;
	
	if (culTxt)
		PopTxt(culTxt);
	else if (window.JsonReq) 
		JsonReq('popcaltxt', 'v=2&cul=' + cul, PopTxt, 0x00000001);	// No timestamp allowing browser cache (by ver).
	
	//---

	cal_currfield = eval(field); //in case string is passed instead of obj
	v = CalGetCurrentVal();
	cal_currcell = null;

	if (win && !win.closed)
		closeWindow();

	if (cal_savedparams != '') //restore saved default settings
		eval(cal_savedparams);

	processParameters(params);

//	if (!checkDateFormat()) return;	// #4901 - NO, now support fmts w/out year.

	//--- Set up today's date.
	
	var dt = new Date();

	cal_today = { day: dt.getDate(), month: dt.getMonth() + 1, year: dt.getFullYear(), week: dt.getDay() };

  //--- Determine initial date.

  a = v.match(/[^./ :';-]+/g);		// #4901 - Match non-ascii month chars.
  f = DATEFORMAT.match(/\w+/g);
  
  if (a && a.length == f.length)
  {
    for (i=0;i<f.length;i++)
    {
	  if ((/d|dd/.test(f[i])) && (/\d{1,2}/.test(a[i])))
        day = parseIntZero(a[i]);
      else if ((/yyyy/.test(f[i])) && (/\d{4}/.test(a[i])))
        year = parseIntZero(a[i]);
      else if ((/y|yy/.test(f[i])) && (/\d{1,2}/.test(a[i])))
      {
        year = parseIntZero(a[i]);
        if (year < 100) year += (year < cal_Y2KYEAR) ? 2000 : 1900;
      }	
      else if ((/mmm|mmmm/.test(f[i])) && (/[^./ :';-]{3,}/.test(a[i])))	// #4901 - Match non-ascii month chars.
      {
		if (window.ParseMonth)
		{
			month = ParseMonth(a[i]);	// #4901 - Improved month abbrevs.
		}
		else
		{
			var r = new RegExp(a[i].substr(0,3),"i");
			for (var j=0;j<12;j++)
			{
			  if (r.test(MONTHS[j]))
			  {
				month = j + 1;
				break;
			  }
			}
		}
      }
      else if ((/m|mm/.test(f[i])) && (/\d{1,2}/.test(a[i])))
      {
        month = parseIntZero(a[i]);
      }
    }
  }

  if (year == 0) year = cal_today.year;		// #4901 - Handle dd-MMM fmt.
  
  cal_original = { day: day, month: month, year: year };
  
  initCalendar(month, year, x, y);
}

// #4782 - Handles I18N AJAX response.
function PopTxt(popCalTxt)
{
	if (popCalTxt && popCalTxt.__type == 'popCalTxt')
	{
		window.cal_text[popCalTxt.Culture] = popCalTxt;
		
		cal_BLANK_TEXT = popCalTxt.ClearDateCaption;
		//cal_CALENDAR_TITLE = popCalTxt.CalendarCaption;
		cal_TODAY_TEXT = popCalTxt.TodayCaption;
		cal_PREV_YEAR_TEXT = popCalTxt.PreviousYearTip;
		cal_PREV_MONTH_TEXT = popCalTxt.PreviousMonthTip;
		cal_NEXT_YEAR_TEXT = popCalTxt.NextYearTip;
		cal_NEXT_MONTH_TEXT = popCalTxt.NextMonthTip;
		cal_SELECT_MONTH_TEXT = popCalTxt.ChooseMonthTip;
		cal_SELECT_YEAR_TEXT = popCalTxt.ChooseYearTip;
		cal_GO_TO_TODAY_TEXT = popCalTxt.CurrentMonthTip;
		cal_SET_BLANK_DATE_TEXT = popCalTxt.ClearDateTip;
		cal_DEFAULT_STATUS_TEXT = popCalTxt.ChooseDateTip;
		cal_CLOSE_TIP = popCalTxt.CloseTip;
		
		document.getElementById('cal_disptoday').innerHTML = TodayText();
		document.getElementById('cal_butblank').innerHTML = cal_BLANK_TEXT;
		if (win.dtwidget.btnClose) SetTip(win.dtwidget.btnClose, cal_CLOSE_TIP);
	}
}

//-----------------------------------------------------------------------------------------
function TodayText()
{
	//return (cal_TODAY_TEXT + ': ' + FmtDate(DATESHORT, cal_today.day, cal_today.month, cal_today.year, ''));
	return (cal_TODAY_TEXT + ': ' + FmtDate(DATEFORMAT, cal_today.day, cal_today.month, cal_today.year, ''));
}

//-----------------------------------------------------------------------------------------
function initCalendar(month, year, x, y)
{
	var widget = openWindow(x, y, window.eapUtilVer);

	drawTable(widget);
	
	PositionDiv(widget, x, y);			// Must position after filling content.
	widget.style.display = 'block';
	
	// If month or year is not valid reset to current month/year
  
	win.cal_selmonth.value = (!month || month <= 0 || month > 12) ? cal_today.month : month;
	win.cal_selyear.value = (!year || year < cal_MINYEAR || year > cal_MAXYEAR) ? cal_today.year : year;
  
	updateCalendar();

	win.cal_maintab.style.display = "inline";
	showStatus();
}
//END: Initializing Functions---->

//Core Functions----------------->
// Build the content for the calendar.
function drawTable(widget)
{
  var i, j, w = "", cls;

  //--- Build the controls at top of calendar.
 
  w += '<select id="cal_selmonth" class="cal_sel" size="12" onchange="DelayedUpdate(event);" ' +
      'onclick="hideDropdowns(event);" onblur="hideDropdowns(event);" ' +
      'onkeydown="downKeySelectBox(event);" tabindex="4" neverDirty="1">';
  for (i=0;i<12;i++)
    w += '<option value="' + (i+1) + '">' + MONTHS[i] + '</option>';
  w += '</select>';

  w += '<select id="cal_selyear" class="cal_sel" size="8" onchange="DelayedUpdate(event);" ' +
      'onclick="hideDropdowns(event);" onblur="hideDropdowns(event);" ' +
      'onkeydown="downKeySelectBox(event);" tabindex="6" neverDirty="1">';
  for (i=cal_MINYEAR;i<=cal_MAXYEAR;i++)
    w += '<option value="' + i + '">' + i + '</option>';
  w += '</select>';

  w += '<table onkeydown="downKey(event);" onmouseover="setFocusHandler(event);" id="cal_maintab" class="cal_main" border="0" cellspacing="0" cellpadding="0">';
  w += '<tr><td>';

  w += '<table onmouseover="overButton(event);" onmouseout="outButton(event);"' +
       ' border="0" width="100%" cellspacing="0" cellpadding="0">';
  w += '<tr><td id="cal_fbkwd" onclick="go(event,\'<<\');" class="cal_fbkwd cal_arrow" tabindex="1">&nbsp;</td>';
  w += '<td id="cal_bkwd" onclick="go(event,\'<\');" class="cal_bkwd cal_arrow" tabindex="2">&nbsp;</td>';
  w += '<td id="cal_dispmonth" class="cal_button" onclick="toggle(event,this,cal_selmonth);" tabindex="3">';
  w += '</td><td id="cal_dispyear" width="52" class="cal_button" onclick="toggle(event,this,cal_selyear);" tabindex="5">';
  w += '</td><td id="cal_fwd" onclick="go(event,\'>\');" class="cal_fwd cal_arrow" tabindex="7">&nbsp;';
  w += '</td><td id="cal_ffwd" onclick="go(event,\'>>\');" class="cal_ffwd cal_arrow" tabindex="8">&nbsp;';    
  w += '</td></tr>';
  w += '</table>';
  
  w += '</td></tr><tr><td>';
  
  //--- Add calendar core.
  
  w += '<table onmouseover="hideDropdowns(event); overCell(event);"' +
       ' onclick="setDate(event);" onmouseout="outCell(event);"' +
       ' cellspacing="0" cellpadding="0" class="popcal">';
  w += '<tr>';
  for (i=0;i<7;i++)
    w += '<th class="cal" id="w' + i + '">' + WEEKS[i].substr(0,cal_WEEKHEAD_SIZE) + '</th>';
  w += '</tr>';
  for (i=0; i<wkcnt; i++)
  {
    w += '<tr height="100%">';
    for (j=0; j<7; j++)
    {
      cls = (j==0 || j==6) ? 'cal_holiday' : 'cal_normal';
      w += '<td height="100%" id="a' + (i * 7 + j) + '" class="' + cls + '"> </td>';
    }
    w += '</tr>';
  }
  w += '</table>';
  
  //--- Add calendar footer.
  
  w += '</td></tr><tr><td id="cal_dispstatus" class="cal_stat"></td></tr><tr><td>';
  
  w += '<table onmouseover="overButton(event);" onmouseout="outButton(event);"' +
       ' border="0" width="100%" cellspacing="0" cellpadding="0">';  
  
  w += '<tr><td id="cal_disptoday" class="cal_button2" tabindex="40" onclick="go(event,\'today\');">';
  w += TodayText();
  w += '</td><td id="cal_butblank" class="cal_button2" tabindex="41" onclick="setBlankDate(event);">' + cal_BLANK_TEXT + '</td>';
  w += '</tr>';
  w += '</table>';

  w += '</td></tr>';
  w += '</table>';
  
  //--- Close out table and write HTML.
  
	widget.content.innerHTML = w;

	//--- NQ, setup win references to objects
	
	if (win != null && win.cal_dispstatus == null)
	{
	    win.cal_dispstatus = win.document.getElementById('cal_dispstatus');
	    win.cal_dispmonth = win.document.getElementById('cal_dispmonth');
	    win.cal_dispyear = win.document.getElementById('cal_dispyear');
	    win.cal_selmonth = win.document.getElementById('cal_selmonth');
	    win.cal_selyear = win.document.getElementById('cal_selyear');
	    win.cal_maintab = win.document.getElementById('cal_maintab');
	}
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function updateCalendar(evt)
{
  var ii;
  var dnum = 1;
  var td;
  
  var month = win.cal_selmonth.value;
  var year = win.cal_selyear.value;
  var monthName = win.cal_selmonth.options[win.cal_selmonth.selectedIndex].text;
  
	win.cal_dispmonth.innerHTML = monthName;
	win.cal_dispyear.innerHTML = '' + year;

//	SetCellText(win.dtwidget.caption, cal_CALENDAR_TITLE + ': ' + monthName + ' ' + year);	// #4902, No.
	SetCellText(win.dtwidget.caption, cal_CALENDAR_TITLE);									// #4902, Yes.
	win.dtwidget.caption.style.whiteSpace = 'nowrap';										// #4902.

  //--- Clear all the day cells.
  
  for (ii=0;ii<daycnt;ii++) 
  {
	td = win.document.getElementById('a' + ii);

	td.innerHTML = '&nbsp;';
	td.day = 0;
    td.style.cursor = 'default';
	td.style.backgroundImage = '';
  }

  //--- Poke the day numbers in the day cells per the current month and year.

  cal_dstart = getFirstDay(month, year);
  cal_dend = getLastDay(month, year) + cal_dstart;
  
  for (ii=cal_dstart;ii<cal_dend;ii++)
  {
    td = win.document.getElementById('a' + (ii % daycnt));

    td.day = dnum;
    td.innerHTML = '' + dnum;
    td.style.cursor = 'pointer';

    dnum++;
  }
  
  //--- #5191 - Some weeks in the calender might not be used for particular months, show/hide accordingly.
  
  var wk = Math.floor((cal_dend-1) / 7);
  var tr;
  
  for (ii=0; ii<wkcnt; ii++)
  {
	tr = win.document.getElementById('a' + (ii*7)).parentNode;
	tr.style.display = (ii > wk) ? 'none' : '';
  }
  
  //--- Set the current day background image.
  
  var isCurrMonth = false;
  
  if (month == cal_today.month && year == cal_today.year)
  {
    td = win.document.getElementById('a' + (cal_dstart - 1 + cal_today.day)%daycnt);
    td.style.backgroundImage = "url(" + IMGDIR + "today.gif)";
    isCurrMonth = true;
  }

  //--- Set the selected day background image.

  if (month == cal_original.month && year == cal_original.year)
  {
    td = win.document.getElementById('a' + (cal_dstart - 1 + cal_original.day)%daycnt);
    if (isCurrMonth && cal_today.day == cal_original.day)
      td.style.backgroundImage = "url(" + IMGDIR + "origtoday.gif)";
    else
      td.style.backgroundImage = "url(" + IMGDIR + "origday.gif)";
    td.style.backgroundRepeat = "no-repeat";
    td.style.backgroundPosition = "center center";
  }

//  hideDropdowns();
}
//END: Core Functions------------>

//Event Handler Functions-------->
//-----------------------------------------------------------------------------------------
// It seems that, in Safari, if you call updateCalendar() directly from the year or month
// SELECT, it crashes the browser.  With this 20ms delay it works fine.  There was no
// problem calling updateCalendar() directly on IE, Firefox, or Opera.
//-----------------------------------------------------------------------------------------
function DelayedUpdate(evt)
{
	window.setTimeout('window.updateCalendar();', 20);
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function overCell(evt)
{
	if (!evt) evt = window.event;

	var obj = GetEventTarget(evt);

	if (cal_currcell != obj)
	{
		if (/^w\d$/.test(obj.id)) //week headings
		{
			showStatus(WEEKS[parseInt(obj.id.substr(1))]);
		}
		else if (obj.innerHTML != ' ')
		{
			var day = obj.day;
			var msg = '';

			if (day)
			{
				ReplaceCssClass(obj, null, 'cal_hilite');
				var dow = parseInt(obj.id.substr(1)) % 7;
				msg = FmtDate(DATELONG, day, win.cal_selmonth.value, win.cal_selyear.value, dow);
			}

			showStatus(msg);
		}
		
		cal_currcell = obj;
	}
}

//-----------------------------------------------------------------------------------------
// Format date.
function FmtDate(fmt, d, m, y, dow)	// #1492
{
	fmt = fmt.replace(/dddd/, 'zzzz');
	fmt = fmt.replace(/d+/, d);
	fmt = fmt.replace(/mmmm/, 'xxxx');
	fmt = fmt.replace(/mmm/, 'xxx');
	fmt = fmt.replace(/m+/, m);
	fmt = fmt.replace(/yyyy|yy/, y);
	fmt = fmt.replace(/zzzz/, WEEKS[dow]);
	fmt = fmt.replace(/xxxx/, MONTHS[m-1]);
	if (window.dt_months)
		fmt = fmt.replace(/xxx/, dt_months[m+12]);			// #4901 - Improved month abbrevs.
	else
		fmt = fmt.replace(/xxx/, MONTHS[m-1].substr(0,3));
	
	return (fmt);
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function outCell(evt)
{
	if (!evt) evt = window.event;

	cal_currcell = null;

	var obj = GetEventTarget(evt);

	if (obj.innerText != " ")
	{
		RemoveCssClass(obj, 'cal_hilite');
		showStatus();
	}
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function overButton(evt)
{
  if (!evt) evt = window.event;
  
  var s = '';
  var td = GetEventTarget(evt);

  switch (td.id)
  {
    case 'cal_fbkwd': 
      s = cal_PREV_YEAR_TEXT;
      break;
    case 'cal_bkwd': 
      s = cal_PREV_MONTH_TEXT;
      break;
    case 'cal_ffwd':
      s = cal_NEXT_YEAR_TEXT;
      break;
    case 'cal_fwd':
      s = cal_NEXT_MONTH_TEXT;
      break;
    case 'cal_dispmonth':
      s = cal_SELECT_MONTH_TEXT;
      break;
    case 'cal_dispyear':
      s = cal_SELECT_YEAR_TEXT;
      break;
    case 'cal_disptoday':
      s = cal_GO_TO_TODAY_TEXT;
      break;
    case 'cal_butblank':
      s = cal_SET_BLANK_DATE_TEXT;
      break;
    default:
      break;
  }
  showStatus(s);
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function outButton(evt)
{
  if (!evt) evt = window.event;
  
  var td = GetEventTarget(evt);
  
  //Give an unpressed button look
  td.style.borderRightColor = td.style.borderBottomColor = "ButtonShadow";
  td.style.borderLeftColor = td.style.borderTopColor = "ButtonHighlight";

  showStatus();
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function downKey(evt)
{
  if (!evt) evt = window.event;
  
  var p, i;

//  showStatus("Key: " + win.event.keyCode + "  ID: " + win.event.srcElement.id);
  var k = evt.keyCode;
  var e = GetEventTarget(evt);
  
  if (k == 13) //ENTER key pressed
    e.click();
  else if (k == 39) //Right arrow pressed
  {
    if (e.id == 'cal_butblank')
    {
      SetFocus(win.cal_fbkwd);
    }
    else
    {
      evt.keyCode = 9; //simulate TAB press
    }
  }
  else if (k == 40) //Down arrow pressed
  {
    if (/^a\d{1,2}$/.test(e.id)) //if calendar cell
    {
      i = parseInt(e.id.substr(1)) + 7;
      p = document.getElementById('a' + i); //eval("win.a" + i);
      if (i < daycnt && p.innerHTML != ' ')
      {
        SetFocus(p);
      }
      else
      {
        SetFocus(win.cal_disptoday);
      }
    }
    else if (/(cal_disptoday|cal_butblank)/.test(e.id))
    {
      SetFocus(win.cal_fbkwd);
    }
    else
    {
      SetFocus(document.getElementById('a' + cal_dstart));
    }
  }
  else if (k == 38) //Up arrow pressed
  {
    if (/^a\d{1,2}/.test(e.id)) //if calendar cell
    {
      i = parseInt(e.id.substr(1)) - 7;
      p = document.getElementById('a', + i); //eval("win.a" + i);
      if (i >= 0 && p.innerHTML != ' ')
      {
        SetFocus(p);
      }
      else
      {
        SetFocus(win.cal_fbkwd);
      }
    }
    else if (/(cal_disptoday|cal_butblank)/.test(e.id))
    {
      SetFocus(document.getElementById('a' + ((cal_dend -1) % daycnt)));
    }
    else
    {
      SetFocus(win.fbwkd);
    }
  }
  else if (k == 37) //Left arrow pressed
  {
    if (e.id == 'a' + cal_dstart)
      SetFocus(win.cal_ffwd);
    else if (e.id == 'cal_disptoday')
      SetFocus(document.getElementById('a' + ((cal_dend -1) % daycnt)));
    else if (e.id == 'cal_fbkwd')
      SetFocus(win.cal_butblank);
    else if (e.previousSibling)
    {
      SetFocus(e.previousSibling);
    }
    else if (e.parentNode.previousSibling)
    {
      SetFocus(e.parentNode.previousSibling.lastChild);
    }
  }
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function downKeySelectBox(evt)
{
  if (!evt) evt = window.event;

  var k = evt.keyCode;
  
  if (k == 27 || k == 13) //ESC or ENTER key pressed
    hideDropdowns();
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function setFocusHandler(evt)
{
  if (!evt) evt = window.event;
  
  var obj = GetEventTarget(evt);

  if (parseInt(obj.tabIndex) > 0)
  {
    if (obj.focus) obj.focus();
  }
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function go(evt, direction)
{
  var month = win.cal_selmonth.value;
  var year = win.cal_selyear.value;

  switch (direction)
  {
    case '>' : 
      if (month == 12 && year < cal_MAXYEAR) 
      {
        year++;
        month = 1;
      }
      else if (month < 12)
        month++;
      break;
      
    case '>>' : 
      if (year < cal_MAXYEAR)
        year++;
      break;
      
    case '<' : 
      if (month == 1 && year > cal_MINYEAR) 
      {
        year--;
        month = 12;
      }
      else if (month > 1)
        month--;
      break;
      
    case '<<' : 
      if (year > cal_MINYEAR) 
        year--;
      break;

    case "today" : 
      month = cal_today.month;
      year = cal_today.year;
      break;
      
    default:
      month = cal_today.month;
      year = cal_today.year;
      break;
  }

  win.cal_selmonth.value = month;
  win.cal_selyear.value = year;
  
  updateCalendar();
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function toggle(evt,t,obj)
{
  if (obj.style.display == 'inline')
    obj.style.display = 'none';
  else
  {
	obj.parentNode.removeChild(obj);
	win.dtwidget.appendChild(obj);
	
	var top = getTop(t,obj) + t.offsetHeight;// + 30;
	var left = getLeft(t, obj);
	
	if (document.body && document.body.scrollTop) top -= document.body.scrollTop;	/* #5539 */
	
	//--- #4506, avoid loss of focus problem.
	
	if (IsFirefox()) 
		top += -6;
	else if (IsOpera() || IsAppleWebKit()) 
		top += -2;
	
	obj.style.position = 'absolute';
    obj.style.display = 'inline';    
    obj.style.left = left + 'px';				// Safari requires the px for some reason.
    obj.style.top = top + 'px';					// Safari requires the px for some reason.
    obj.style.width = t.offsetWidth + 'px';		// Safari requires the px for some reason.
 	SetFocus(obj);
    
    obj.selectedIndex = obj.selectedIndex;		// #4507, scroll selected item into view.
  }
  
  //--- Hide the other dropdown if displayed currently
  
  if (obj.id == 'cal_selmonth')
    win.cal_selyear.style.display = 'none';
  else
    win.cal_selmonth.style.display = 'none';
    
    return CancelBubble(evt);  
}
//END: Event Handler Functions--->

//Utility Functions-------------->
//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function trimStr(str)
{
	return str.replace(/^\s+|\s+$/g,'');
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function processParameters(params)
{
  var p, v, i;

  DEBUGMSG = "Function: processParameters\nRecheck the parameters passed to the popCal function.";
  if (params == null || params == "") return;

  cal_savedparams = '';

  p = params.split(";");

  for (i = 0; i < p.length; i++)
  {
    if (!(/^[a-zA-Z_ ]+=/.test(p[i]))) continue;
    v = p[i].split("=");
    if (v.length == 2)
    {
      v[0] = trimStr(v[0]).toUpperCase();
      v[1] = trimStr(v[1]);
      if ((/^(MINYEAR|MAXYEAR|Y2KYEAR|CELLSIZE|WEEKHEAD_SIZE)$/.test(v[0])) &&
          (/^\s*\d+\s*$/.test(v[1])))
      {
        cal_savedparams += v[0] + "=" + eval(v[0]) + ";";
        eval(p[i]);
      }
      else if (/^(MONTHS|WEEKS)$/.test(v[0]))
      {
        cal_savedparams += v[0] + '="' + eval(v[0]) + '".split(",");';
        eval(v[0] + '="' + v[1] + '".split(",")');
      }
      else if (eval(v[0]) != "undefined")
      {
        cal_savedparams += v[0] + '="' + eval(v[0]) + '";';
        eval(v[0] + '="' + v[1] + '"');
      }
    }
  }
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function showErrMsg(msg,url,line)
{
  var s = "POPCAL DEBUGGER:\n\n";

  if (!DEBUG) return true;

  if (/^DEBUG:/.test(msg)) //custom error message
    s += msg;
  else
  {
    s += "An error was been caught.\n" +
      "Error: " + msg + "\nLine: " + line + "\n" +
      "URL: " + url;
  } 

  if (DEBUGMSG != "")
    s += "\n\nAdditional Info:\n" + DEBUGMSG;
  
  DEBUGMSG = "";
  
  alert(s);
  return true;
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function checkDateFormat()
{
  var df = DATEFORMAT;
///d|dd/.test(df) && 
  if ((/m|mm|mmm|mmmm/.test(df)) && (/y|yy|yyyy/.test(df)))
    return true;
  else
  {
	alert("DEBUG:Unknown Date Format (" + df + ")!\n\n" +
          "Make sure the config file and/or the params are correct.\n" +
          "Month and year format are mandatory.");
    showErrMsg("DEBUG:Unknown Date Format (" + df + ")!\n\n" +
          "Make sure the config file and/or the params are correct.\n" +
          "Month and year format are mandatory.");
    return false;
  }
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function setDate(evt)
{
  if (!evt) evt = window.event;
	
  var d, df;

  var obj = GetEventTarget(evt);

  //Check for valid cell click
  if (!(/^a\d{1,2}$/.test(obj.id))) return;
  if (obj.innerHTML == ' ') return;
  
  var day;
  
	day = obj.day;
  
  //--- If we got a valid day, set it on opener and close popup.
  
  if (day && day > 0)
  {
	  var month = win.cal_selmonth.value;
	  var year = win.cal_selyear.value;
	  var week = WEEKS[parseInt(obj.id.substr(1)) % 7];
	  
	  d = df = DATEFORMAT;
	  
	  //--- Get formatted month.
	  
	  if (/mmmm/.test(df))
		d = d.replace("mmmm",MONTHS[month-1]);
	  else if (/mmm/.test(df))
	  {
		if (window.dt_months)
			d = d.replace("mmm",dt_months[parseInt(month,10)+12]);		// #4901 - Improved month abbrevs.
		else
			d = d.replace("mmm",MONTHS[month-1].substr(0,3));
	  }
	  else if (/mm/.test(df))
		d = d.replace("mm",padOneZero(month));
	  else if (/m/.test(df))
		d = d.replace("m",month);

	  //--- Get formatted week.
	  
	  if (/wwww/.test(df))
		d = d.replace("wwww",week);
	  else if (/www/.test(df))
		d = d.replace("www",week.substr(0,3));
	  else if (/ww/.test(df))
		d = d.replace("ww",week.substr(0,2));

	  //--- Get formatted year.
	  
	  if (/yyyy/.test(df))
		d = d.replace("yyyy",year);
	  else if (/yy/.test(df))
		d = d.replace("yy",padOneZero(year%100));
	  else if (/y/.test(df))
		d = d.replace("y",year%100);

	  //--- Get formatted day.
	  
	  if (/dd/.test(df))
		d = d.replace("dd",padOneZero(day));
	  else if (/d/.test(df))
		d = d.replace("d",day);
	  
	  //--- Set date on invoking control.
	  
	  var oldVal = CalSetCurrentVal(d);
	  
	  //--- If value changed, force onchange event to fire on target.
	  
	  if (d != oldVal)
	  {
		OnChange(cal_currfield, evt);
	  }

	  //--- We're done.  Close the widget.

	  closeWindow();
	}
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function setBlankDate(evt)
{
	var oldVal = CalSetCurrentVal('');
	
	if (oldVal && oldVal != '')
	{
		OnChange(cal_currfield, evt);	// #5811 - Need to know about clears too.
	}
	
	closeWindow();
}

//-----------------------------------------------------------------------------------------
function CalGetCurrentVal()
{
	return (cal_currfield.tagName == 'INPUT') ? cal_currfield.value : cal_currfield.innerHTML;
}

//-----------------------------------------------------------------------------------------
function CalSetCurrentVal(val)
{
	var oldVal = CalGetCurrentVal();
	
	if (cal_currfield.tagName == 'INPUT')
		cal_currfield.value = val;
	else
		cal_currfield.innerHTML = val;
		
	return (oldVal);
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function openWindow(x, y, ver)
{
	//--- Create widget.
  
	var widget = CreateDivWidget('popcal', 'Calendar', cal_CLOSE_TIP);

	//--- For backward compat with pre-662 versions of EAPUtils js.
	
	if (!ver || ver < 662)
	{
		widget.caption = widget.childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0];
		widget.style.backgroundColor = 'buttonface';	// Indicates old ver.
		
		if (IsIE())
		{
			var shim = CreateShim();
			
			shim.style.position = 'absolute';
			shim.style.left = -2;
			shim.style.top = -2;
			shim.style.zIndex = -1;
			shim.style.height = '100%';
			shim.style.width = '100%';
	        
			window.setTimeout(function() { shim.style.height = widget.offsetHeight; shim.style.width = widget.offsetWidth; }, 1);

			widget.insertBefore(shim, null);
		}
	}
	
	//--- Sizing and positioning.

//	var w = 7 * cal_CELLSIZE + 30;	// Good for IE6 & Firefox
//	var h = 5 * cal_CELLSIZE + 76;	// Good for IE6 & Firefox
	
//	if (IsFirefox() || IsSafari() || IsChrome()) h += 8;		// Compensate for padding.
//	h = h + widget.caption.offsetHeight;
	
	widget.style.width = 7 * cal_CELLSIZE + 30;	// Good for IE6 & Firefox
	
	win = window;
	window.dtwidget = widget;
	win.cal_dispstatus = null;
	
	return (widget);
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function closeWindow()
{
	win.dtwidget.style.display = 'none';
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function padOneZero(num)
{
	return (num < 10) ? '0' + num : num;
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function parseIntZero(str)
{
	return parseInt(str.replace(/^0+/,'')); //remove leading zeros
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function getFirstDay(month, year)
{
	return (new Date(year, month-1, 1)).getDay();
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function getLastDay(month, year)
{ 
	var day;
	var numdays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);

	//--- Leap year check for February

	return (month == 2 && year%4 == 0 && (year%100 != 0 || year%400 == 0)) ? 29 : numdays[month-1];
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function showStatus(status_str)
{
  if (status_str == null || status_str == "" || status_str == "undefined")
    status_str = ''; //cal_DEFAULT_STATUS_TEXT;
    
  if (win != null && win.cal_dispstatus != null)
  {
    win.cal_dispstatus.innerHTML = status_str;
  }
}

//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function hideDropdowns(evt)
{
  //hide both the dropdowns
	if (win)
	{
		if (win.cal_selyear) win.cal_selyear.style.display = 'none';
		if (win.cal_selmonth) win.cal_selmonth.style.display = 'none';
	}
}

//END: Utility Functions--------->

//---------------------------------------------------------------------------------------------------------------
// Contents from popcal_config.js merged. #665
//---------------------------------------------------------------------------------------------------------------

//Constants--------------------->
//The select box associated with the year shows years from
//MINYEAR to MAXYEAR. These are also used for some validations.
var cal_MINYEAR = 1900; 
var cal_MAXYEAR = 2099; 
//The Y2KYEAR parameter is used when determining whether a two
//digit year belongs to the 19th or 20th century. A value of 30
//for example would take years from 00 to 29 as 2000 - 2029 and
//year values from 30 to 99 as 1930 to 1999.
var cal_Y2KYEAR = 50;

//The below two parameters (CELLSIZE & WEEKHEAD_SIZE) are display related.
//For small english calendar optimum values can be 32 and 2 respectively
//For a bigger english calendar optimum values can be 36 and 3 respectively
var cal_CELLSIZE = 30; //28; //Size of a cell in pixels. Increasing this would increase the calendar window size.
var cal_WEEKHEAD_SIZE = 2; //Size in characters of the Week Headings
//The following parameter (IMGDIR) stores the location of the path were the 
//calendar related images (the gif files found under the 'images' folder of the
//distribution zip. Specify the path with respect to the location of calling page
//(not the js location). Take care to end the path with a slash (/)
//If an absolute path or a path from the web root of a webserver is not specified
//the path might require to be set using the params argument of the 'popCal' function.
var IMGDIR = "images/calendar/"; 

//For a calendar in other languages, change the following text to equivalents.
var cal_CALENDAR_TITLE = "Calendar"; //Displayed in title bar of Popup
var cal_TODAY_TEXT = "TODAY"; //Displayed on the TODAY button
var cal_BLANK_TEXT = "BLANK"; //Displayed on the BLANK button
var cal_PREV_YEAR_TEXT = "Click to see Previous Year";
var cal_PREV_MONTH_TEXT = "Click to see Previous Month";
var cal_NEXT_YEAR_TEXT = "Click to see Next Year";
var cal_NEXT_MONTH_TEXT = "Click to see Next Month";
var cal_SELECT_MONTH_TEXT = "Click to choose a Month";
var cal_SELECT_YEAR_TEXT = "Click to choose the Year";
var cal_GO_TO_TODAY_TEXT = "Click to see Current Month";
var cal_SET_BLANK_DATE_TEXT = "Click to enter a Blank Date";
var cal_DEFAULT_STATUS_TEXT = "To choose a Date, click on the Day";
var cal_CLOSE_TIP = 'Click here to close.';
//END: Constants---------------->

//START: External Constants ---------------->
//DATEFORMAT: Should have (d or dd) and (m,mm,mmm or mmmm) and (y,yy or yyyy)
//Eg. For Mar 2, 2003:     2    02       3 03 Mar    March      3 03    2003
var DATEFORMAT = "mmmm d, yyyy"; 
var DATELONG = "dddd, mmmm d, yyyy";	// #1492
var DATESHORT = "mmm d, yyyy";			// #1492

//The below two parameters (MONTHS & WEEKS) store the names of the months and weeks.
//For a calendar in other languages, use equivalent month and week names.
var MONTHS = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var WEEKS = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
//END: External Constants ---------------->

