/* 
DESCRIPTION: This object implements a popup calendar to allow the user to
select a date, month, quarter, or year.

COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small
positioning errors - usually with Window positioning - occur on the 
Macintosh platform.
The calendar can be modified to work for any location in the world by 
changing which weekday is displayed as the first column, changing the month
names, and changing the column headers for each day.

USAGE:
// Create a new CalendarPopup object of type WINDOW
var cal = new CalendarPopup(); 

// Create a new CalendarPopup object of type DIV using the DIV named 'mydiv'
var cal = new CalendarPopup('mydiv'); 

// Easy method to link the popup calendar with an input box. 
cal.select(inputObject, anchorname, dateFormat);
// Same method, but passing a default date other than the field's current value
cal.select(inputObject, anchorname, dateFormat, '01/02/2000');
// This is an example call to the popup calendar from a link to populate an 
// input box. Note that to use this, date.js must also be included!!
<A HREF="#" onClick="cal.select(document.forms[0].date,'anchorname','MM/dd/yyyy'); return false;">Select</A>

// Set the type of date select to be used. By default it is 'date'.
cal.setDisplayType(type);

// When a date, month, quarter, or year is clicked, a function is called and
// passed the details. You must write this function, and tell the calendar
// popup what the function name is.
// Function to be called for 'date' select receives y, m, d
cal.setReturnFunction(functionname);
// Function to be called for 'month' select receives y, m
cal.setReturnMonthFunction(functionname);
// Function to be called for 'quarter' select receives y, q
cal.setReturnQuarterFunction(functionname);
// Function to be called for 'year' select receives y
cal.setReturnYearFunction(functionname);

// Show the calendar relative to a given anchor
cal.showCalendar(anchorname);

// Hide the calendar. The calendar is set to autoHide automatically
cal.hideCalendar();

// Set the month names to be used. Default are English month names
cal.setMonthNames("January","February","March",...);

// Set the month abbreviations to be used. Default are English month abbreviations
cal.setMonthAbbreviations("Jan","Feb","Mar",...);

// Show navigation for changing by the year, not just one month at a time
cal.showYearNavigation();

// Show month and year dropdowns, for quicker selection of month of dates
cal.showNavigationDropdowns();

// Set the text to be used above each day column. The days start with 
// sunday regardless of the value of WeekStartDay
cal.setDayHeaders("S","M","T",...);

// Set the day for the first column in the calendar grid. By default this
// is Sunday (0) but it may be changed to fit the conventions of other
// countries.
cal.setWeekStartDay(1); // week is Monday - Sunday

// Set the weekdays which should be disabled in the 'date' select popup. You can
// then allow someone to only select week end dates, or Tuedays, for example
cal.setDisabledWeekDays(0,1); // To disable selecting the 1st or 2nd days of the week

// Selectively disable individual days or date ranges. Disabled days will not
// be clickable, and show as strike-through text on current browsers.
// Date format is any format recognized by parseDate() in date.js
// Pass a single date to disable:
cal.addDisabledDates("2003-01-01");
// Pass null as the first parameter to mean "anything up to and including" the
// passed date:
cal.addDisabledDates(null, "01/02/03");
// Pass null as the second parameter to mean "including the passed date and
// anything after it:
cal.addDisabledDates("Jan 01, 2003", null);
// Pass two dates to disable all dates inbetween and including the two
cal.addDisabledDates("January 01, 2003", "Dec 31, 2003");

// When the 'year' select is displayed, set the number of years back from the 
// current year to start listing years. Default is 2.
// This is also used for year drop-down, to decide how many years +/- to display
cal.setYearSelectStartOffset(2);

// Text for the word "Today" appearing on the calendar
cal.setTodayText("Today");

// The calendar uses CSS classes for formatting. If you want your calendar to
// have unique styles, you can set the prefix that will be added to all the
// classes in the output.
// For example, normal output may have this:
//     <SPAN CLASS="cpTodayTextDisabled">Today<SPAN>
// But if you set the prefix like this:
cal.setCssPrefix("Test");
// The output will then look like:
//     <SPAN CLASS="TestcpTodayTextDisabled">Today<SPAN>
// And you can define that style somewhere in your page.

// When using Year navigation, you can make the year be an input box, so
// the user can manually change it and jump to any year
cal.showYearNavigationInput();

// Set the calendar offset to be different than the default. By default it
// will appear just below and to the right of the anchorname. So if you have
// a text box where the date will go and and anchor immediately after the
// text box, the calendar will display immediately under the text box.
cal.offsetX = 20;
cal.offsetY = 20;

NOTES:
1) Requires the functions in AnchorPosition.js and PopupWindow.js

2) Your anchor tag MUST contain both NAME and ID attributes which are the 
   same. For example:
   <A NAME="test" ID="test"> </A>

3) There must be at least a space between <A> </A> for IE5.5 to see the 
   anchor tag correctly. Do not do <A></A> with no space.

4) When a CalendarPopup object is created, a handler for 'onmouseup' is
   attached to any event handler you may have already defined. Do NOT define
   an event handler for 'onmouseup' after you define a CalendarPopup object 
   or the autoHide() will not work correctly.
   
5) The calendar popup display uses style sheets to make it look nice.

*/ 

// CONSTRUCTOR for the CalendarPopup Object
function CalendarPopup() {
	var c;
	if (arguments.length>0) {
		c = new PopupWindow(arguments[0]);
	}
	else {
		c = new PopupWindow();
		c.setSize(150,175);
	}
	// Calendar-specific properties
	c.offsetX = -125;		//swong:-152;
	c.offsetY = 20;	//25;
	c.autoHide();
	c.returnFunction = "CP_tmpReturnFunction";
	c.returnMonthFunction = "CP_tmpReturnMonthFunction";
	c.returnQuarterFunction = "CP_tmpReturnQuarterFunction";
	c.returnYearFunction = "CP_tmpReturnYearFunction";
	c.weekStartDay = 0;
	c.isShowYearNavigation = false;
	c.displayType = "date";
	c.disabledWeekDays = new Object();
	c.disabledDatesExpression = "";
	c.yearSelectStartOffset = 5;	//swong:2;  for dropdown year selection
	c.currentDate = null;
	c.cssPrefix="";
	c.isShowNavigationDropdowns=false;
	c.isShowYearNavigationInput=false;
	window.CP_calendarObject = null;
	window.CP_targetInput = null;
	window.CP_dateFormat = "MM/dd/yyyy";
	// Method mappings
	c.copyMonthNamesToWindow = CP_copyMonthNamesToWindow;
	c.setReturnFunction = CP_setReturnFunction;
	c.setReturnMonthFunction = CP_setReturnMonthFunction;
	c.setReturnQuarterFunction = CP_setReturnQuarterFunction;
	c.setReturnYearFunction = CP_setReturnYearFunction;
	c.setMonthNames = CP_setMonthNames;
	c.setMonthAbbreviations = CP_setMonthAbbreviations;
	c.setDayHeaders = CP_setDayHeaders;
	c.setWeekStartDay = CP_setWeekStartDay;
	c.setDisplayType = CP_setDisplayType;
	c.setDisabledWeekDays = CP_setDisabledWeekDays;
	c.addDisabledDates = CP_addDisabledDates;
	c.setYearSelectStartOffset = CP_setYearSelectStartOffset;
	c.setTodayText = CP_setTodayText;
	c.showYearNavigation = CP_showYearNavigation;
	c.showCalendar = CP_showCalendar;
	c.hideCalendar = CP_hideCalendar;
	c.getStyles = getCalendarStyles;
	c.refreshCalendar = CP_refreshCalendar;
	c.getCalendar = CP_getCalendar;
	c.select = CP_select;
	c.setCssPrefix = CP_setCssPrefix;
	c.showNavigationDropdowns = CP_showNavigationDropdowns;
	c.showYearNavigationInput = CP_showYearNavigationInput;
	
    // teros new features:
	c.show_calendar = show_calendar;        // must directly point to function
	c.CPsi_set_new_date = "CPsi_set_new_date";    // must use string
	c.CPsi_returnGateway = "CPsi_returnGateway";
	c.si_innerTextId = null;
	c.CPsi_setInnerTextId = CPsi_setInnerTextId;
	c.si_formatDate = si_formatDate;
	c.si_is_showTimeInput = 0;
	c.si_setTimeInput = si_setTimeInput;
	c.CPsi_showTimeInput = CPsi_showTimeInput;
	c.CPsi_getTimeInput = CPsi_getTimeInput;
	c.CPsi_get_month_refresh = CPsi_get_month_refresh;
	c.CPsi_get_year_refresh = CPsi_get_year_refresh;
	
	c.si_year = -1;
	c.si_month = -1;
	c.si_day = -1;
	c.si_hours = -1;
	c.si_minutes = -1;
	c.si_seconds = -1;

	c.CPsi_set_currentDate = CPsi_set_currentDate;
	c.CPsi_set_result_time = CPsi_set_result_time;
	c.si_get_result_time = si_get_result_time;
	c.si_getTimeFromStr = si_getTimeFromStr;
	c.si_setDateFormat = si_setDateFormat;
	c.si_getFormatedDateFromTime = si_getFormatedDateFromTime;
	c.si_offsets = si_offsets;
	c.si_check_time_range = si_check_time_range;
	c.si_selected_month = 1;
	c.si_selected_year = 2005;
	c.si_selected_value = 0;
	c.si_mouse_over = 'onmouseover=\'this.bgColor="#00eeee"\' onmouseout=\'this.bgColor="#ffffff"\'';

	// localizable strings:
	c.monthNames = get_vm('CAL_MONTHS').split(',');
	c.monthAbbreviations = get_vm('CAL_SHORT_MONTHS').split(',');
	c.dayHeaders = get_vm('CAL_DAY_HEADERS').split(',');

	c.todayText=get_vm('CAL_NOW');
    c.OKText=get_vm('CAL_OK');
	// icons:
	c.si_up_arrow = si_get_image_path('sort-up9.gif');
	c.si_down_arrow = si_get_image_path('sort-down9.gif');
	c.si_up_arrow_on = si_get_image_path('sort-up9-on.gif');
	c.si_down_arrow_on = si_get_image_path('sort-down9-on.gif');

	// Return the object
	c.copyMonthNamesToWindow();
	return c;
}
function CP_copyMonthNamesToWindow() {
	// Copy these values over to the date.js 
	if (typeof(window.MONTH_NAMES)!="undefined" && window.MONTH_NAMES!=null) {
		window.MONTH_NAMES = new Array();
		for (var i=0; i<this.monthNames.length; i++) {
			window.MONTH_NAMES[window.MONTH_NAMES.length] = this.monthNames[i];
		}
		for (var i=0; i<this.monthAbbreviations.length; i++) {
			window.MONTH_NAMES[window.MONTH_NAMES.length] = this.monthAbbreviations[i];
		}
	}
}
// Temporary default functions to be called when items clicked, so no error is thrown
function CP_tmpReturnFunction(y,m,d) { 
	if (window.CP_targetInput!=null) {
		var dt = new Date(y,m-1,d,0,0,0);
		if (window.CP_calendarObject!=null) { window.CP_calendarObject.copyMonthNamesToWindow(); }
		var formatted_date = formatDate(dt,window.CP_dateFormat);
		window.CP_targetInput.value = formatted_date;
		if (window.CP_calendarObject.si_innerTextId != null) {
			var obj = document.getElementById(window.CP_calendarObject.si_innerTextId);
			if (!obj) {
				alert("Unknown innerTextId: '"+window.CP_calendarObject.si_innerTextId+"'");
			}
			obj.innerText = formatted_date;
		}
	}
	else {
		alert('Use setReturnFunction() to define which function will get the clicked results!'); 
	}
}

function CP_tmpReturnMonthFunction(y,m) { 
	alert('Use setReturnMonthFunction() to define which function will get the clicked results!\nYou clicked: year='+y+' , month='+m); 
}
function CP_tmpReturnQuarterFunction(y,q) { 
	alert('Use setReturnQuarterFunction() to define which function will get the clicked results!\nYou clicked: year='+y+' , quarter='+q); 
}
function CP_tmpReturnYearFunction(y) { 
	alert('Use setReturnYearFunction() to define which function will get the clicked results!\nYou clicked: year='+y); 
}

// Set the name of the functions to call to get the clicked item
function CP_setReturnFunction(name) { this.returnFunction = name; }
function CP_setReturnMonthFunction(name) { this.returnMonthFunction = name; }
function CP_setReturnQuarterFunction(name) { this.returnQuarterFunction = name; }
function CP_setReturnYearFunction(name) { this.returnYearFunction = name; }

// Over-ride the built-in month names
function CP_setMonthNames() {
	for (var i=0; i<arguments.length; i++) { this.monthNames[i] = arguments[i]; }
	this.copyMonthNamesToWindow();
}

// Over-ride the built-in month abbreviations
function CP_setMonthAbbreviations() {
	for (var i=0; i<arguments.length; i++) { this.monthAbbreviations[i] = arguments[i]; }
	this.copyMonthNamesToWindow();
}

// Over-ride the built-in column headers for each day
function CP_setDayHeaders() {
	for (var i=0; i<arguments.length; i++) { this.dayHeaders[i] = arguments[i]; }
}

// Set the day of the week (0-7) that the calendar display starts on
// This is for countries other than the US whose calendar displays start on Monday(1), for example
function CP_setWeekStartDay(day) { this.weekStartDay = day; }

// Show next/last year navigation links
function CP_showYearNavigation() { this.isShowYearNavigation = (arguments.length>0)?arguments[0]:true; }

// Which type of calendar to display
function CP_setDisplayType(type) {
	if (type!="date"&&type!="week-end"&&type!="month"&&type!="quarter"&&type!="year") { alert("Invalid display type! Must be one of: date,week-end,month,quarter,year"); return false; }
	this.displayType=type;
}

// How many years back to start by default for year display
function CP_setYearSelectStartOffset(num) { this.yearSelectStartOffset=num; }

// Set which weekdays should not be clickable
function CP_setDisabledWeekDays() {
	this.disabledWeekDays = new Object();
	for (var i=0; i<arguments.length; i++) { this.disabledWeekDays[arguments[i]] = true; }
}
	
// Disable individual dates or ranges
// Builds an internal logical test which is run via eval() for efficiency
function CP_addDisabledDates(start, end) {
	if (arguments.length==1) { end=start; }
	if (start==null && end==null) { return; }
	if (this.disabledDatesExpression!="") { this.disabledDatesExpression+= "||"; }
	if (start!=null) { start = parseDate(start); start=""+start.getFullYear()+LZ(start.getMonth()+1)+LZ(start.getDate());}
	if (end!=null) { end=parseDate(end); end=""+end.getFullYear()+LZ(end.getMonth()+1)+LZ(end.getDate());}
	if (start==null) { this.disabledDatesExpression+="(ds<="+end+")"; }
	else if (end  ==null) { this.disabledDatesExpression+="(ds>="+start+")"; }
	else { this.disabledDatesExpression+="(ds>="+start+"&&ds<="+end+")"; }
}
	
// Set the text to use for the "Today" link
function CP_setTodayText(text) {
	this.todayText = text;
}

// Set the prefix to be added to all CSS classes when writing output
function CP_setCssPrefix(val) { 
	this.cssPrefix = val; 
}

// Show the navigation as an dropdowns that can be manually changed
function CP_showNavigationDropdowns() { this.isShowNavigationDropdowns = (arguments.length>0)?arguments[0]:true; }

// Show the year navigation as an input box that can be manually changed
function CP_showYearNavigationInput() { this.isShowYearNavigationInput = (arguments.length>0)?arguments[0]:true; }

// Hide a calendar object
function CP_hideCalendar() {
    CP_si_stop_timer();
	if (arguments.length > 0) { window.popupWindowObjects[arguments[0]].hidePopup(); }
	else { this.hidePopup(); }
}

// Refresh the contents of the calendar display
function CP_refreshCalendar(index) {
	var calObject = window.popupWindowObjects[index];
	if (arguments.length>1) { 
		//alert("CP_refreshCalendar: "+arguments[1]+','+arguments[2]+','+arguments[3]+','+arguments[4]+','+arguments[5]);
		calObject.populate(calObject.getCalendar(arguments[1],arguments[2],arguments[3],arguments[4],arguments[5]));
	}
	else {
		calObject.populate(calObject.getCalendar());
	}
	calObject.refresh();
}

// Populate the calendar and display it
function CP_showCalendar(anchorname) {
	if (arguments.length>1) {
		if (arguments[1]==null||arguments[1]=="") {
			this.currentDate=new Date();
		}
		else {
			this.currentDate=new Date(parseDate(arguments[1]));
		}
	}
	this.populate(this.getCalendar());
	this.showPopup(anchorname);
}

// Simple method to interface popup calendar with a text-entry box
function CP_select(inputobj, linkname, format) {
	var selectedDate=(arguments.length>3)?arguments[3]:null;    // 4th parameter contains the init_date
	if (!window.getDateFromFormat) {
		alert("calendar.select: To use this method you must also include 'date.js' for date formatting");
		return;
	}
	if (this.displayType!="date"&&this.displayType!="week-end") {
		alert("calendar.select: This function can only be used with displayType 'date' or 'week-end'");
		return;
	}
	if (inputobj.type!="text" && inputobj.type!="hidden" && inputobj.type!="textarea") { 
		alert("calendar.select: Input object passed is not a valid form input object"); 
		window.CP_targetInput=null;
		return;
	}
	if (inputobj.disabled) { 
        alert("Input object is currently disabled.");
        return; 
    }
	window.CP_targetInput = inputobj;
	window.CP_calendarObject = this;
	this.currentDate=null;
	var time=0;
	if (selectedDate!=null) {
		time = getDateFromFormat(selectedDate,format)
		//alert("selectedDate="+selectedDate+ ", time="+time);
	}
	else if (inputobj.value!="") {
		time = getDateFromFormat(inputobj.value,format);
	}
	if (selectedDate!=null || inputobj.value!="") {
		if (time==0) { this.currentDate=null; }
		else { this.currentDate=new Date(time); }
	}
    // if still null, default to now
    if (this.currentDate == null) {
		this.currentDate=new Date();
    }
    this.CPsi_set_currentDate(this.currentDate);
	window.CP_dateFormat = format;

	this.showCalendar(linkname);
}
	
// Get style block needed to display the calendar correctly
function getCalendarStyles() {
	var result = "";
	var p = "";
	if (this!=null && typeof(this.cssPrefix)!="undefined" && this.cssPrefix!=null && this.cssPrefix!="") { p=this.cssPrefix; }
	result += "<STYLE>\n";
	result += "."+p+"cpTimeNavigation"+"{ background-color:buttonface; text-align:right; vertical-align:center; text-decoration:none; color:#000000; font-weight:bold; }\n";
	result += "."+p+"cpSpinNavigation"+"{ background-color:buttonface; text-align:center; vertical-align:center; text-decoration:none; color:#000000; font-weight:bold; }\n";
	result += "."+p+"cpYearNavigation,."+p+"cpMonthNavigation { background-color:buttonface; text-align:center; vertical-align:center; text-decoration:none; color:#000000; font-weight:bold; }\n";
	result += "."+p+"cpDayColumnHeader, ."+p+"cpYearNavigation,."+p+"cpMonthNavigation,."+p+"cpCurrentMonthDate,."+p+"cpCurrentMonthDateDisabled,."+p+"cpOtherMonthDate,."+p+"cpOtherMonthDateDisabled,."+p+"cpCurrentDate,."+p+"cpCurrentDateDisabled,."+p+"cpTodayText,."+p+"cpTodayTextDisabled,."+p+"cpText { font-family:arial; font-size:8pt; }\n";
	result += "TD."+p+"cpDayColumnHeader { text-align:right; border:solid thin #C0C0C0;border-width:0px 0px 1px 0px; }\n";
	result += "."+p+"cpCurrentMonthDate, ."+p+"cpOtherMonthDate, ."+p+"cpCurrentDate  { text-align:right; text-decoration:none; }\n";
	result += "."+p+"cpCurrentMonthDateDisabled, ."+p+"cpOtherMonthDateDisabled, ."+p+"cpCurrentDateDisabled { color:#D0D0D0; text-align:right; text-decoration:line-through; }\n";
	result += "."+p+"cpCurrentMonthDate, .cpCurrentDate { color:#000000; }\n";
	result += "."+p+"cpOtherMonthDate { color:#808080; }\n";
	result += "TD."+p+"cpCurrentDate { color:white; background-color: #C0C0C0; border-width:1px; border:solid thin #800000; }\n";
	result += "TD."+p+"cpCurrentDateDisabled { border-width:1px; border:solid thin #FFAAAA; }\n";
	result += "TD."+p+"cpTodayText, TD."+p+"cpTodayTextDisabled { border:solid thin #C0C0C0; border-width:1px 0px 0px 0px;}\n";

	//result += "A."+p+"cpTodayText, SPAN."+p+"cpTodayTextDisabled { height:20px; }\n";
	result += "A."+p+"cpTodayText, SPAN."+p+"cpTodayTextDisabled { height:10px; }\n";
	result += "A."+p+"cpTodayText:link {color:black}\n";
	result += "A."+p+"cpTodayText:visited {color:black}\n";
	result += "A."+p+"cpTodayText:hover {color:green}\n";
	result += "A."+p+"cpTodayText:active {color:green}\n";
	result += "A."+p+"cpTodayText {font-weight:bold;text-decoration:none}\n";
	//result += "A."+p+"cpTodayText { color:black; }\n";
	result += "A."+p+"cpSpinNavigation {text-decoration:none}\n";

	result += "."+p+"cpTodayTextDisabled { color:#D0D0D0; }\n";
	result += "."+p+"cpBorder { border:solid thin #808080; }\n";
	result += "</STYLE>\n";
	return result;
}

// Return a string containing all the calendar code to be displayed
function CP_getCalendar() {
	var now = new Date();
	// Reference to window
	if (this.type == "WINDOW") { var windowref = "window.opener."; }
	else { var windowref = ""; }
	var result = "";
	// If POPUP, write entire HTML document
	if (this.type == "WINDOW") {
		result += "<HTML><HEAD><TITLE>Calendar</TITLE>"+this.getStyles()+"</HEAD><BODY MARGINWIDTH=0 MARGINHEIGHT=0 TOPMARGIN=0 RIGHTMARGIN=0 LEFTMARGIN=0>\n";
		result += '<CENTER><TABLE WIDTH=100% BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>\n';
	}
	else {
		result += '<TABLE CLASS="'+this.cssPrefix+'cpBorder" WIDTH=144 BORDER=1 BORDERWIDTH=1 CELLSPACING=0 CELLPADDING=1>\n';
		result += '<TR><TD ALIGN=CENTER>\n';
		result += '<CENTER>\n';
	}
	// Code for DATE display (default)
	// -------------------------------
	if (this.displayType=="date" || this.displayType=="week-end") {
		if (this.currentDate==null) { this.currentDate = now; }
		if (arguments.length > 0) { var month = arguments[0]; }
			else { var month = this.currentDate.getMonth()+1; }
		if (arguments.length > 1 && arguments[1]>0 && arguments[1]-0==arguments[1]) { var year = arguments[1]; }
			else { var year = this.currentDate.getFullYear(); }
			
		//------- new for time input ---------
		var hours, minutes, seconds;
		if (this.si_is_showTimeInput) {
			if (this.si_hours == -1) {
				this.si_hours   = this.currentDate.getHours();
				this.si_minutes = this.currentDate.getMinutes();
				this.si_seconds = this.currentDate.getSeconds();
			}
		}
			
		var daysinmonth= new Array(0,31,28,31,30,31,30,31,31,30,31,30,31);
		if ( ( (year%4 == 0)&&(year%100 != 0) ) || (year%400 == 0) ) {
			daysinmonth[2] = 29;
		}
		var current_month = new Date(year,month-1,1);
		var display_year = year;
		var display_month = month;
		var display_date = 1;
		var weekday= current_month.getDay();
		var offset = 0;
		
		offset = (weekday >= this.weekStartDay) ? weekday-this.weekStartDay : 7-this.weekStartDay+weekday ;
		if (offset > 0) {
			display_month--;
			if (display_month < 1) { display_month = 12; display_year--; }
			display_date = daysinmonth[display_month]-offset+1;
		}
		var next_month = month+1;
		var next_month_year = year;
		if (next_month > 12) { next_month=1; next_month_year++; }
		var last_month = month-1;
		var last_month_year = year;
		if (last_month < 1) { last_month=12; last_month_year--; }
		var date_class;
		if (this.type!="WINDOW") {
			result += "<TABLE WIDTH=144 BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>";
		}
		result += '<TR>\n';
		var refresh = windowref+'CP_refreshCalendar';
		var refreshLink = 'javascript:' + refresh;
		if (this.isShowNavigationDropdowns) {
		
			var month_refresh = this.CPsi_get_month_refresh(refresh, year);
			//result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="78" COLSPAN="3"><select CLASS="'+this.cssPrefix+'cpMonthNavigation" name="cpMonth" onChange="'+refresh+'('+this.index+',this.options[this.selectedIndex].value-0,'+(year-0)+');">';
			result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="78" COLSPAN="3"><select CLASS="'+this.cssPrefix+'cpMonthNavigation" name="cpMonth" onChange="'+month_refresh+'">';
			for( var monthCounter=1; monthCounter<=12; monthCounter++ ) {
				var selected = (monthCounter==month) ? 'SELECTED' : '';
				result += '<option value="'+monthCounter+'" '+selected+'>'+this.monthNames[monthCounter-1]+'</option>';
			}
			result += '</select></TD>';
			result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10">&nbsp;</TD>';

			var year_refresh = this.CPsi_get_year_refresh(refresh, month);
			//result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="56" COLSPAN="3"><select CLASS="'+this.cssPrefix+'cpYearNavigation" name="cpYear" onChange="'+refresh+'('+this.index+','+month+',this.options[this.selectedIndex].value-0);">';
			result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="56" COLSPAN="3"><select CLASS="'+this.cssPrefix+'cpYearNavigation" name="cpYear" onChange="'+year_refresh+'">';
			for( var yearCounter=year-this.yearSelectStartOffset; yearCounter<=year+this.yearSelectStartOffset; yearCounter++ ) {
				var selected = (yearCounter==year) ? 'SELECTED' : '';
				result += '<option value="'+yearCounter+'" '+selected+'>'+yearCounter+'</option>';
			}
			result += '</select></TD>';
		}
		else {
			if (this.isShowYearNavigation) {
				result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpMonthNavigation" HREF="'+refreshLink+'('+this.index+','+last_month+','+last_month_year+');">&lt;</A></TD>';
				result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="58"><SPAN CLASS="'+this.cssPrefix+'cpMonthNavigation">'+this.monthNames[month-1]+'</SPAN></TD>';
				result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpMonthNavigation" HREF="'+refreshLink+'('+this.index+','+next_month+','+next_month_year+');">&gt;</A></TD>';
				result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10">&nbsp;</TD>';

				result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="'+refreshLink+'('+this.index+','+month+','+(year-1)+');">&lt;</A></TD>';
				if (this.isShowYearNavigationInput) {
					result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="36"><INPUT NAME="cpYear" CLASS="'+this.cssPrefix+'cpYearNavigation" SIZE="4" MAXLENGTH="4" VALUE="'+year+'" onBlur="'+refresh+'('+this.index+','+month+',this.value-0);"></TD>';
				}
				else {
					result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="36"><SPAN CLASS="'+this.cssPrefix+'cpYearNavigation">'+year+'</SPAN></TD>';
				}
				result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="'+refreshLink+'('+this.index+','+month+','+(year+1)+');">&gt;</A></TD>';
			}
			else {
				result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="22"> </TD>\n';
				result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="100"><SPAN id=cpsi_month_nav_id CLASS="'+this.cssPrefix+'cpMonthNavigation">'+this.monthNames[month-1]+' '+year+'</SPAN></TD>\n';

                //var mouse1 = this.si_mouse_over+' onmousedown="'+ windowref + 'CP_si_next_month('+this.index+',';
                var mouse1 = 'onmousedown="'+ windowref + 'CP_si_next_month('+this.index+',';
                var mouse2 = ');" onmouseup="'+ windowref + 'CP_si_set_selected_month('+this.index+');"';
                var up_arrow   = ' onmouseover=\'this.src="'+this.si_up_arrow_on  +'"\' onmouseout=\'this.src="'+this.si_up_arrow  +'"\'';
                var down_arrow = ' onmouseover=\'this.src="'+this.si_down_arrow_on+'"\' onmouseout=\'this.src="'+this.si_down_arrow+'"\'';
				result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="22">'+
                    '<table cellspacing=2 cellpadding=0>'+
                        '<tr><td '+mouse1+last_month+','+last_month_year+',0'+mouse2 + '>'+
                            '<img border=0 src="'+this.si_up_arrow+'"'+up_arrow+'>'+
                        '</td></tr>'+
                        '<tr><td '+mouse1+next_month+','+next_month_year+',1'+mouse2 + '>'+
                            '<img border=0 src="'+this.si_down_arrow+'"'+down_arrow+'>'+
                        '</td></tr>'+
                    '</table></td>\n';
			}
		}
		result += '</TR></TABLE>\n';

        // create day matrix:
		result += '<TABLE WIDTH=120 BORDER=0 CELLSPACING=0 CELLPADDING=1 ALIGN=CENTER>\n';
		result += '<TR>\n';
		for (var j=0; j<7; j++) {
			result += '<TD CLASS="'+this.cssPrefix+'cpDayColumnHeader" WIDTH="14%"><SPAN CLASS="'+this.cssPrefix+'cpDayColumnHeader">'+this.dayHeaders[(this.weekStartDay+j)%7]+'</TD>\n';
		}
		result += '</TR>\n';
		for (var row=1; row<=6; row++) {
			result += '<TR>\n';
			for (var col=1; col<=7; col++) {
				var disabled=false;
				if (this.disabledDatesExpression!="") {
					var ds=""+display_year+LZ(display_month)+LZ(display_date);
					eval("disabled=("+this.disabledDatesExpression+")");
				}
				var dateClass = "";
				if ((display_month == this.currentDate.getMonth()+1) && (display_date==this.currentDate.getDate()) && (display_year==this.currentDate.getFullYear())) {
					dateClass = "cpCurrentDate";
				}
				else if (display_month == month) {
					dateClass = "cpCurrentMonthDate";
				}
				else {
					dateClass = "cpOtherMonthDate";
				}
				if (disabled || this.disabledWeekDays[col-1]) {
					result += '	<TD CLASS="'+this.cssPrefix+dateClass+'"><SPAN CLASS="'+this.cssPrefix+dateClass+'Disabled">'+display_date+'</SPAN></TD>\n';
				}
				else {
					var selected_date = display_date;
					var selected_month = display_month;
					var selected_year = display_year;
					if (this.displayType=="week-end") {
						var d = new Date(selected_year,selected_month-1,selected_date,0,0,0,0);
						d.setDate(d.getDate() + (7-col));
						selected_year = d.getYear();
						if (selected_year < 1000) { selected_year += 1900; }
						selected_month = d.getMonth()+1;
						selected_date = d.getDate();
					}
                    
                    // click to set newly selected date:
					result += '	<td class="'+this.cssPrefix+dateClass+'" '+this.si_mouse_over+
						' onclick="'+windowref+this.CPsi_set_new_date+'(\''+windowref+'\','+this.index+','+selected_year+','+selected_month+','+selected_date+');">'+
						'<a href="#" class="'+this.cssPrefix+dateClass+'">'+display_date+'</a></td>\n';
                    
					//result += '	<TD CLASS="'+this.cssPrefix+dateClass+'" '+this.si_mouse_over+'><A HREF="javascript:'+windowref+this.returnFunction+'('+selected_year+','+selected_month+','+selected_date+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+this.cssPrefix+dateClass+'">'+display_date+'</A></TD>\n';
				}
				display_date++;
				if (display_date > daysinmonth[display_month]) {
					display_date=1;
					display_month++;
				}
				if (display_month > 12) {
					display_month=1;
					display_year++;
				}
			}
			result += '</TR>';
		}
		var current_weekday = now.getDay() - this.weekStartDay;
		if (current_weekday < 0) {
			current_weekday += 7;
		}
		result += '<TR height=12><td height=12></td></tr><tr>\n';
		
		//---- insert time input if needed -----
		if (this.si_is_showTimeInput) {
			result += this.CPsi_showTimeInput();
		}

		//---- show 'Today' and 'OK' ----		
		result += '<tr>\n';
		result += '<td width=100% colspan=7 align=center><table width=100% cellspacing=0 cellpadding=0><tr>\n';
		result += '	<td width=50% align=center class="'+this.cssPrefix+'cpTodayText">\n';
		if (this.disabledDatesExpression!="") {
			var ds=""+now.getFullYear()+LZ(now.getMonth()+1)+LZ(now.getDate());
			eval("disabled=("+this.disabledDatesExpression+")");
		}
		if (disabled || this.disabledWeekDays[current_weekday+1]) {
			result += '		<SPAN CLASS="'+this.cssPrefix+'cpTodayTextDisabled">'+this.todayText+'</SPAN>\n';
		}
		else {
			//result += '		<A CLASS="'+this.cssPrefix+'cpTodayText" HREF="javascript:'+
			result += '		<a href="javascript:'+
                windowref+this.CPsi_returnGateway+'(\''+windowref+'\','+this.index+',1);'+
                windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+this.cssPrefix+'cpTodayText'+'">'+this.todayText+'</A>\n';
			//result += '		<A CLASS="'+this.cssPrefix+'cpTodayText" HREF="javascript:'+windowref+this.returnFunction+'(\''+now.getFullYear()+'\',\''+(now.getMonth()+1)+'\',\''+now.getDate()+'\');'+windowref+'CP_hideCalendar(\''+this.index+'\');">'+this.todayText+'</A>\n';
		}
        result += '</td>'+
		        '<td width=50% align=center class="'+this.cssPrefix+'cpTodayText">'+
			    '<a href="javascript:'+ windowref+this.CPsi_returnGateway+'(\''+windowref+'\','+this.index+',0);'+
                windowref+'CP_hideCalendar(\''+this.index+'\');" class="'+this.cssPrefix+'cpTodayText'+'">'+this.OKText+'</a>'+
                '</td></tr></table>\n';
            
		//result += '		<BR>\n';
		result += '	</TD></TR></TABLE></CENTER></TD></TR></TABLE>\n';
	}

	// Code common for MONTH, QUARTER, YEAR
	// ------------------------------------
	if (this.displayType=="month" || this.displayType=="quarter" || this.displayType=="year") {
		if (arguments.length > 0) { var year = arguments[0]; }
		else { 
			if (this.displayType=="year") {	var year = now.getFullYear()-this.yearSelectStartOffset; }
			else { var year = now.getFullYear(); }
		}
		if (this.displayType!="year" && this.isShowYearNavigation) {
			result += "<TABLE WIDTH=144 BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>";
			result += '<TR>\n';
			result += '	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="22"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year-1)+');">&lt;&lt;</A></TD>\n';
			result += '	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="100">'+year+'</TD>\n';
			result += '	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="22"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year+1)+');">&gt;&gt;</A></TD>\n';
			result += '</TR></TABLE>\n';
		}
	}
		
	// Code for MONTH display 
	// ----------------------
	if (this.displayType=="month") {
		// If POPUP, write entire HTML document
		result += '<TABLE WIDTH=120 BORDER=0 CELLSPACING=1 CELLPADDING=0 ALIGN=CENTER>\n';
		for (var i=0; i<4; i++) {
			result += '<TR>';
			for (var j=0; j<3; j++) {
				var monthindex = ((i*3)+j);
				result += '<TD WIDTH=33% ALIGN=CENTER><A CLASS="'+this.cssPrefix+'cpText" HREF="javascript:'+windowref+this.returnMonthFunction+'('+year+','+(monthindex+1)+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">'+this.monthAbbreviations[monthindex]+'</A></TD>';
			}
			result += '</TR>';
		}
		result += '</TABLE></CENTER></TD></TR></TABLE>\n';
	}
	
	// Code for QUARTER display
	// ------------------------
	if (this.displayType=="quarter") {
		result += '<BR><TABLE WIDTH=120 BORDER=1 CELLSPACING=0 CELLPADDING=0 ALIGN=CENTER>\n';
		for (var i=0; i<2; i++) {
			result += '<TR>';
			for (var j=0; j<2; j++) {
				var quarter = ((i*2)+j+1);
				result += '<TD WIDTH=50% ALIGN=CENTER><BR><A CLASS="'+this.cssPrefix+'cpText" HREF="javascript:'+windowref+this.returnQuarterFunction+'('+year+','+quarter+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">Q'+quarter+'</A><BR><BR></TD>';
			}
			result += '</TR>';
		}
		result += '</TABLE></CENTER></TD></TR></TABLE>\n';
	}

	// Code for YEAR display
	// ---------------------
	if (this.displayType=="year") {
		var yearColumnSize = 4;
		result += "<TABLE WIDTH=144 BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>";
		result += '<TR>\n';
		result += '	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="50%"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year-(yearColumnSize*2))+');">&lt;&lt;</A></TD>\n';
		result += '	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="50%"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year+(yearColumnSize*2))+');">&gt;&gt;</A></TD>\n';
		result += '</TR></TABLE>\n';
		result += '<TABLE WIDTH=120 BORDER=0 CELLSPACING=1 CELLPADDING=0 ALIGN=CENTER>\n';
		for (var i=0; i<yearColumnSize; i++) {
			for (var j=0; j<2; j++) {
				var currentyear = year+(j*yearColumnSize)+i;
				result += '<TD WIDTH=50% ALIGN=CENTER><A CLASS="'+this.cssPrefix+'cpText" HREF="javascript:'+windowref+this.returnYearFunction+'('+currentyear+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">'+currentyear+'</A></TD>';
			}
			result += '</TR>';
		}
		result += '</TABLE></CENTER></TD></TR></TABLE>\n';
	}
	// Common
	if (this.type == "WINDOW") {
		result += "</BODY></HTML>\n";
	}
	return result;
}

//--------------- user-defined si functions ---------------
function CPsi_setInnerTextId(id) {
	this.si_innerTextId = id;
}

// Return getTime() of given date string using the format set
// call via c.si_getDateFromFormat()
function si_getTimeFromStr(date_str){
	return getDateFromFormat(date_str, window.CP_dateFormat);
}

// return formatted date string from time input (use current time if time is not passed)
function si_getFormatedDateFromTime(time){
	var cal_obj = window.CP_calendarObject;
	if (typeof(time) == "undefined") {
        time = new Date();
	}
	var formatted_date = formatDate(time,window.CP_dateFormat);
	return formatted_date;
}

// call via c.si_formatDate()
// use member date-time values if y is not defined
function si_formatDate(y,m,d){
	var cal_obj = window.CP_calendarObject;
	var dt;
	if (typeof(y) == "undefined") {
		var hours   = cal_obj.si_hours;
		var minutes = cal_obj.si_minutes;
		var seconds = cal_obj.si_seconds;
		if (hours == -1) {
			hours   = 0;
			minutes = 0;
			seconds = 0;
		}
		dt = new Date(cal_obj.si_year,cal_obj.si_month-1,cal_obj.si_day,   hours,minutes,seconds);
	} else {
		dt = new Date(y,m-1,d,0,0,0);
	}
	var formatted_date = formatDate(dt,window.CP_dateFormat);
	return formatted_date;
}

// show time input if 1
function si_setTimeInput(flag) {
	this.si_is_showTimeInput = flag;
}

// show hh:mm:ss
function CPsi_showTimeInput(){
	var result = '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" COLSPAN="7">';
    result += '<table cellspacing=0 cellpadding=0 width=100%><tr>';

    result += this.CPsi_getTimeInput(this.si_hours,   1, 'cpsi_hour_nav_id');
    result += this.CPsi_getTimeInput(this.si_minutes, 2, 'cpsi_minute_nav_id');
    result += this.CPsi_getTimeInput(this.si_seconds, 3, 'cpsi_second_nav_id');
    result += '</tr></table></td>';
	return result;
}

// which=1,2,3=hour,min,sec
function CPsi_getTimeInput(value, which, nav_id) {
	var value = LZ(value);
    var time1 = ' onmousedown="CP_si_next_time('+this.index+',';
    var time2 = ');" onmouseup="CP_si_set_selected_time('+this.index+',';
    var time_class = this.cssPrefix+'cpTimeNavigation';
    var spin_class = this.cssPrefix+'cpSpinNavigation';
    
    var up_arrow   = ' onmouseover=\'this.src="'+this.si_up_arrow_on  +'"\' onmouseout=\'this.src="'+this.si_up_arrow  +'"\'';
    var down_arrow = ' onmouseover=\'this.src="'+this.si_down_arrow_on+'"\' onmouseout=\'this.src="'+this.si_down_arrow+'"\'';
    var result = '<td width=40 class='+time_class+'>'+
                '<span id="'+nav_id+'" class='+time_class+'>'+value+'</span></td>'+
			  '<td class='+spin_class+' width=30>'+
                    '<table cellspacing=2 cellpadding=0 width=100%>'+
				        '<tr><td width=100% class='+spin_class+' '+time1+which+',0'+time2+which+');" ' + this.si_mouse_over + '>'+
                            '<img border=0 src="'+this.si_up_arrow+'"'+up_arrow+'>'+
                        '</td></tr>'+
                        '<tr><td width=100% class='+spin_class+' '+time1+which+',1'+time2+which+');"' + '>'+
                            '<img border=0 src="'+this.si_down_arrow+'"'+down_arrow+'>'+
                        '</td></tr></table></td>';
    if (which != 3) {   // no colon after seconds
	    result += '<td class='+spin_class+'>:</td>';
    }
    return result;
}

function CPsi_get_month_refresh(refresh, year){
	var str = refresh+'('+this.index+ ',this.options[this.selectedIndex].value-0,' +(year-0);
	str += ');';
	return str;
}

function CPsi_get_year_refresh(refresh, month){
	var str = refresh+'('+this.index+','+ month +',this.options[this.selectedIndex].value-0';
	str += ');';
	return str;
}

function CPsi_change_hours(cp_index, obj){
	var calObject = window.popupWindowObjects[cp_index];
	var val = obj.value;
	calObject.si_hours = val;
}
function CPsi_change_minutes(cp_index, obj){
	var calObject = window.popupWindowObjects[cp_index];
	var val = obj.value;
	calObject.si_minutes = val;
}
function CPsi_change_seconds(cp_index, obj){
	var calObject = window.popupWindowObjects[cp_index];
	var val = obj.value;
	calObject.si_seconds = val;
	//alert("CPsi_change_seconds: "+val);
}

// set new date from day matrix
function CPsi_set_new_date(windowref, cp_index, y,m,d){
    //alert("1");
	var calObject = window.popupWindowObjects[cp_index];
    // remember the resultant time (use si_get_resul_time() to get the time back)
    calObject.CPsi_set_result_time(y,m,d);
    calObject.refreshCalendar(cp_index);
}

// use now time if is_now=1 else 0 to use internal currentDate
function CPsi_returnGateway(windowref, cp_index, is_now){
	var calObject = window.popupWindowObjects[cp_index];
    var y, m, d;
    if (is_now) {
        // use current time
        var now = new Date();
        y = now.getFullYear();
        m = now.getMonth()+1;
        d = now.getDate();
        calObject.si_hours = now.getHours();
        calObject.si_minutes = now.getMinutes();
        calObject.si_seconds = now.getSeconds();
        calObject.CPsi_set_result_time(y,m,d);
    } else {
        var cur = calObject.currentDate;
        y = cur.getFullYear();
        m = cur.getMonth()+1;
        d = cur.getDate();
    }
    // remember to use si_get_result_time() to get the time back

	if (calObject.si_is_showTimeInput) {
		var cmd = windowref+calObject.returnFunction+'('+y+','+m+','+d+','+calObject.si_hours+','+calObject.si_minutes+','+calObject.si_seconds+')';
	} else {
		var cmd = windowref+calObject.returnFunction+'('+y+','+m+','+d+')';
	}
	//alert("cmd="+cmd);
	eval(cmd);
}

// set the currentDate based on the input pluse the internal time (si_hours etc.)
function CPsi_set_result_time(y,m,d){
	this.si_year  = y;
	this.si_month = m;
	this.si_day   = d;
	this.currentDate = new Date(y,m-1,d, this.si_hours,this.si_minutes,this.si_seconds);
}

function si_get_result_time(){
	return this.currentDate;
}

function si_setDateFormat(format){
	window.CP_dateFormat = format;
}

function si_offsets(offx, offy){
	this.offsetX = offx;
    this.offsetY = offy;
}

// return 1 if time if ok, 0 otherwise with alert
// input are date strings
function si_check_time_range(from_date, to_date){
    var from_time = this.si_getTimeFromStr(from_date);
    var to_time   = this.si_getTimeFromStr(to_date);
    if (from_time > to_time) {
        alert(get_vm('ERR_WRONG_TIME_RANGE'));
        return 0;
    }
    return 1;
}

var gCP_timer_id = null;
var gCP_timer_count = 600;
function CP_si_next_month(cp_index, last_month, last_year, next){
    CP_si_stop_timer();
	var calObject = window.popupWindowObjects[cp_index];
    calObject.si_selected_month = last_month;
    calObject.si_selected_year = last_year;
    gCP_timer_id = setTimeout('CP_si_do_next_month('+cp_index+ ','+next+ ')', 600);
}

function CP_si_do_next_month(cp_index, next){
	var calObject = window.popupWindowObjects[cp_index];
    var selected_month = calObject.si_selected_month;
    var selected_year = calObject.si_selected_year;
    if (next) {
        selected_month++;
        if (selected_month > 12) {
            selected_month = 1;
            selected_year++;
        }
    } else {
        selected_month--;
        if (selected_month <= 0) {
            selected_month = 12;
            selected_year--;
        }
    }
    calObject.si_selected_month = selected_month;
    calObject.si_selected_year  = selected_year;
    //alert('selected_month='+selected_month+' selected_year='+selected_year);
    document.getElementById('cpsi_month_nav_id').innerText = calObject.monthNames[selected_month-1]+' '+selected_year;

    time_interval = CP_si_get_time_interval();
    gCP_timer_id = setTimeout('CP_si_do_next_month('+cp_index+','+next+ ')', time_interval);
}

function CP_si_set_selected_month(cp_index){
    CP_si_stop_timer();
	var calObject = window.popupWindowObjects[cp_index];
    //alert('2. last_month='+last_month+' last_year='+last_year);
    var selected_month = calObject.si_selected_month;
    var selected_year = calObject.si_selected_year;
    calObject.refreshCalendar(cp_index, selected_month, selected_year);
}

// type=1,2,3='hour', 'minute' or 'second'
function CP_si_next_time(cp_index, type, next){
    CP_si_stop_timer();
	var calObject = window.popupWindowObjects[cp_index];
    var cur_value;
    if (type == 1) {
        cur_value = calObject.si_hours;
    } else if (type == 2) {
        cur_value = calObject.si_minutes;
    } else {
        cur_value = calObject.si_seconds;
    }
    calObject.si_selected_value = cur_value;
    //alert("type="+type+" cur_value="+cur_value);
    CP_si_do_next_time(cp_index, type, next);
    //gCP_timer_id = setTimeout('CP_si_do_next_time('+cp_index+ ','+type+ ','+next+ ')', 600);
}

function CP_si_do_next_time(cp_index, type, next){
	var calObject = window.popupWindowObjects[cp_index];
    var selected_value = calObject.si_selected_value;
    if (next) {
        selected_value++;
        if (type == 1) {    // hour
            if (selected_value > 23) {
                selected_value = 0;
            }
        } else {
            if (selected_value > 59) {
                selected_value = 0;
            }
        }
    } else {
        selected_value--;
        if (selected_value < 0) {
            if (type == 1) {
                selected_value = 23;
            } else {
                selected_value = 59;
            }
        }
    }
    calObject.si_selected_value = selected_value;
    var time_id = 'cpsi_second_nav_id';
    if (type == 1) {
        time_id = 'cpsi_hour_nav_id';
    } else if (type == 2) {
        time_id = 'cpsi_minute_nav_id';
    }
    document.getElementById(time_id).innerText = LZ(selected_value);
    time_interval = CP_si_get_time_interval();
    gCP_timer_id = setTimeout('CP_si_do_next_time('+cp_index+','+type+','+next+ ')', time_interval);
}

function CP_si_set_selected_time(cp_index, type){
    CP_si_stop_timer();
	var calObject = window.popupWindowObjects[cp_index];
    //alert('2. last_month='+last_month+' last_year='+last_year);
    var selected_value = calObject.si_selected_value;
    if (type == 1) {
        calObject.si_hours = selected_value;
    } else if (type == 2) {
        calObject.si_minutes = selected_value;
    } else {
        calObject.si_seconds = selected_value;
    }
}

function CP_si_get_time_interval(){
    gCP_timer_count -= 30;
    if (gCP_timer_count < 50) {
        gCP_timer_count = 50;
    }
    return gCP_timer_count;
}

function CP_si_stop_timer(){
    if (gCP_timer_id != null) {
        clearTimeout(gCP_timer_id);
        gCP_timer_id = null;
    }
    gCP_timer_count = 600;
}

// make sure the currentDate is in sync
function CPsi_set_currentDate(date) {
	this.currentDate = date;
	this.si_year  = date.getFullYear();
	this.si_month = date.getMonth()+1;
	this.si_day   = date.getDate();
    this.si_hours = date.getHours();
    this.si_minutes = date.getMinutes();
    this.si_seconds = date.getSeconds();
}

// element_id object should have the initial date otherwise it will be default to now
// optional: use init_date to force the date
function show_calendar(element_id, anchor_id, callback, init_date){
    var obj = document.getElementById(element_id);
    if (typeof(callback) != 'undefined' && callback != null) {
        this.setReturnFunction(callback);
    }
	var date_format = window.CP_dateFormat;
    this.select(obj, anchor_id, date_format, init_date);
}

