//jb 6.02.06
var weeksFirstDays;
var weeksLastDays;
var notBookedWeeksFirstDays;
var notBookedWeeksLastDays;

var day_class = "";
var booked = '';
var notBooked = '';
var pastDay='';
var bookedDay='';
//jb 6.02.06

//jb 20.12.05
//var weeksFirstDays;
//var weeksLastDays;
//jb 20.12.05

var day;
var month;
var year;
var hour;
var minute;
var second;
var clock_set = 0;

var todayDate = new Date();
var BookedPeriodsPrices = '';

var curPayStatus = '';
var curPeriodPrice = '';
var curResourceBidItemID = '';
//#############

//jb 6.02.06 calendar for bookPeriodManually
//#############
function initCalendarForManuallyBooking() {
    if (!year && !month && !day) {
        /* Called for first time */

            if (window.dateType == 'datetime' || window.dateType == 'date') {
                if (window.dateType == 'datetime') {
                    parts   = value.split(' ');
                    value   = parts[0];

                    if (parts[1]) {
                        time    = parts[1].split(':');
                        hour    = parseInt(time[0],10);
                        minute  = parseInt(time[1],10);
                        second  = parseInt(time[2],10);
                    }
                }
                date        = value.split("-");
                day         = parseInt(date[2],10);
                month       = parseInt(date[1],10) - 1;
                year        = parseInt(date[0],10);
            } else {
                year        = parseInt(value.substr(0,4),10);
                month       = parseInt(value.substr(4,2),10) - 1;
                day         = parseInt(value.substr(6,2),10);
                hour        = parseInt(value.substr(8,2),10);
                minute      = parseInt(value.substr(10,2),10);
                second      = parseInt(value.substr(12,2),10);
            }

        if (isNaN(year) || isNaN(month) || isNaN(day) || day == 0) {
            dt      = new Date();
            year    = dt.getFullYear();
            month   = dt.getMonth();
            day     = dt.getDate();
        }
        if (isNaN(hour) || isNaN(minute) || isNaN(second)) {
            dt      = new Date();
            hour    = dt.getHours();
            minute  = dt.getMinutes();
            second  = dt.getSeconds();
        }
		
    } else {
        /* Moving in calendar */
        if (month > 11) {
            month = 0;
            year++;
        }
        if (month < 0) {
            month = 11;
            year--;
        }
    }
	
    if (document.getElementById) {
        cnt = document.getElementById(calendarElementID);
    } else if (document.all) {
        cnt = document.all[calendarElementID];
    }
	
    cnt.innerHTML = "";

    str = ""

    //heading table
	//jb 9.12.05 =============== 
	//str +='<table table width="195" border="0" cellspacing="0" cellpadding="0"><tr>';
	//str +='<td width="195" height="200" valign="top" class="calendar">';
	str +='<table width="215" border="0" cellspacing="0" cellpadding="0" >';
	str +='<tr><td valign="top" class="calendartop" >';
	str +='<table width="160" border="0" align="center" cellpadding="0" cellspacing="0" ><tr>';
/*month name*/str +='<td class="monthsTitle">' + month_names[month] + '</td>'; //month name
	str +='</tr></table>';
	str +='</td><td width="20">&#160;</td></tr>';
	//===
	str +='<tr><td valign="top" class="calendarbottom" colspan="2" >';//calendarbottom
	str +='<table border="0" align="right" cellpadding="0" cellspacing="0" >';
	str +='<tr>'; //days header
	for (i = 0; i < 7; i++) {
		str +='<td width="1%" ><table border="0" cellspacing="0" cellpadding="2" class="calcolumn"><tr>';
        str += '<td class="day">' + day_names[i] + '</td>';
		str +='</tr></table></td>';
    }
	str +='<td align="right"></td>';
	str +='</tr>'; //end days header
	
	var firstDay = new Date(year, month, 1).getDay();
    var lastDay = new Date(year, month + 1, 0).getDate();
	
	//jb 14.12.05 get first week day in previous month
	firstInWeekDay = new Date(year, month, 0).getDay();//day number in week. if!=0 , then week start in previous month
	lastDayPreviousMonths = new Date(year, month, 1-firstInWeekDay).getDate(); //date of first date in week in previous month
	
	if(firstInWeekDay==0) {
		fmonth = month + 1;
		j = 1;
		fyear = year;
	} else {
		if(month==0) {
			fmonth = 12;
			fyear = year-1;
		} else {
			fmonth = month;
			fyear = year;
		  }
		j = lastDayPreviousMonths;
	  }
	  
	firstDayInWeek = formatNum4(fyear) + "-" + formatNum2(fmonth, 'month') + "-" + formatNum2(j, 'day');//for first week
	firstWeekDayDate = new Date(formatNum4(fyear),formatNum2(fmonth-1, 'month'),formatNum2(j, 'day'));
	if(firstWeekDayDate<=todayDate) {//if first week day < curdate,then show week days as booked style without checkbox.
		booked = true;
		pastDay = true;
	} else {booked = false;pastDay = false;}
	//=============== get last week day in next month
	
	fmonth = month+1;
	if(fmonth==12) {
		fyear = year+1;
	} else {
		fyear = year;
	  }
	firstDayNumberInWeekNextMonths = new Date(year, fmonth, 1).getDay();//day number in week. if!=0 , then week start in previous month
	fmonth = fmonth+1;
	if(firstDayNumberInWeekNextMonths>1) {
		j = 8-firstDayNumberInWeekNextMonths;
		if(fmonth==13) {
			fmonth = 1;
		}
	} else if(firstDayNumberInWeekNextMonths==1) {
		j = lastDay;
		fmonth = fmonth-1;
		if(fmonth==12) {
			fyear = year;
		}
	  } else if(firstDayNumberInWeekNextMonths==0) {
		  	if(fmonth==13) {
				fmonth = 1;
			}
		  	j = 1;
	    }
	lastDayInLastWeek = formatNum4(fyear) + "-" + formatNum2(fmonth, 'month') + "-" + formatNum2(j, 'day');//for first week
	// jb 14.12.05
	
	str +='<tr>'; //show first empty days
	dayInWeek = 0;
	if(firstDay==0) {firstDay=7} //!!!week begin from mon
	for (i = 1; i < firstDay; i++) { //week begin from mon
		str +='<td width="1%"><table border="0" cellspacing="0" cellpadding="2" class="calcolumn"><tr>';
        str += '<td >&nbsp;</td>';
		str +='</tr></table></td>';
		dayInWeek++;
    }
	//end show first empty days
	//start show days
	for (i = 1; i <= lastDay; i++) {
        if (dayInWeek == 7) {
			// set checkbox if week not booked
			//BookedPeriod = firstDayInWeek + '|' + lastDayInLastWeek;
			BookedPeriod = firstDayInWeek;
			if(notBooked) {
				str += '<td width="50" align="right"><input type="checkbox" name="BookedPeriods[]" value="' + BookedPeriod + '" /></td>';
			} else {
				str += '<td width="50" align="right">&#160;</td>';
			  }
            str += "</tr><tr>";
            dayInWeek = 0;
        }
		
        dispmonth = 1 + month;

        if (window.dateType == 'datetime' || window.dateType == 'date') {
            actVal = formatNum4(year) + "-" + formatNum2(dispmonth, 'month') + "-" + formatNum2(i, 'day');
        } else {
            actVal = "" + formatNum4(year) + formatNum2(dispmonth, 'month') + formatNum2(i, 'day');
        }

//========== set days style ==========//
		if(dayInWeek == 0) {
			firstDayInWeek = actVal;
			
			firstWeekDayDate = new Date(formatNum4(year),formatNum2(dispmonth-1, 'month'),formatNum2(i, 'day'));
			if(firstWeekDayDate<=todayDate) {//if first week day < curdate,then set style switcher as pastPeroids
				pastDay = true;
			} else {pastDay = false;}
		}
		if(dayInWeek == 6) {
			lastDayInWeek = actVal;
		}
		
		if(weeksFirstDays!='') { //check if week already booked, set style switcher as booked
			re = new RegExp(firstDayInWeek,"g");
			if(weeksFirstDays.match(re)!=null) {
				booked = true;
				bookedDay = true;
			} else {booked = false;bookedDay = false;}
			re='';
		} 
		
		if(pastDay) {booked = true;}
		if(booked) {
			//alert(firstDayInWeek);
			if(pastDay) {
				day_class = "class='pastPeroids'";
			} else if(bookedDay) {
				day_class = "class='booked'";
			  } else {day_class = "";
			    }
		} else {
			day_class = "";
		}
		
//========== set days style ==========//

//========== set checkbox switcher ==========//
		if(notBookedWeeksFirstDays!='') { //check if week not booked, set checkbox switcher as true
			re = new RegExp(firstDayInWeek,"g");
			if(notBookedWeeksFirstDays.match(re)!=null) {
				notBooked = true;
			} else {notBooked = false;}
			re='';
		} 
//========== set checkbox switcher ==========//	
		
		str +='<td ><table border="0" cellspacing="0" cellpadding="2" class="calcolumn"><tr>';
		//link on day
        //str += "<td " + style + " "+day_class+"><a href=\"javascript:returnDateOnLocalWindow('" + actVal + "');\">" + i + "</a></td>";
		str += "<td "+day_class+">"+ i +"</td>";
		str +='</tr></table></td>';
        dayInWeek++;
    }
	//end show days
	//start show last empty days
    for (i = dayInWeek; i < 7; i++) {
        str += "<td>&nbsp;</td>";
    }
	
	// set checkbox if week not booked
	//BookedPeriod = firstDayInWeek + '|' + lastDayInLastWeek;
	BookedPeriod = firstDayInWeek;
	if(notBooked) {
		str += '<td width="50" align="right"><input type="checkbox" name="BookedPeriods[]" value="' + BookedPeriod + '" /></td>';
	} else {
		str += '<td width="50" align="right">&#160;</td>';
	  }
	str +='</tr>';
	//end show last empty days
	
	
	str +='</table>';
	str +='</td></tr>';//end calendarbottom
	str +='</table>';
	//str +='</td></tr></table>';
	//jb 9.12.05 ===============
		
    cnt.innerHTML = str; //set html content for <div id="calendar_data">

    // Should we handle time also?
    if (window.dateType != 'date' && !clock_set) {

        if (document.getElementById) {
            cnt = document.getElementById("clock_data");
        } else if (document.all) {
            cnt = document.all["clock_data"];
        }

        str = '';
        str += '<form class="clock">';
        str += 'h:m<br/><input id="hour" type="text" size="2" maxlength="2" onblur="this.value=formatNum2(this.value, \'hour\')" value="' + formatNum2(hour, 'hour') + '" />:';
        str += '<input id="minute"  type="text" size="2" maxlength="2" onblur="this.value=formatNum2(this.value, \'minute\')" value="' + formatNum2(minute, 'minute') + '" />';
        str += '<input id="second"  type="hidden" size="2" maxlength="2" onblur="this.value=formatNum2(this.value, \'second\')" value="' + formatNum2(second, 'second') + '" />';
		str += '</form>';

        cnt.innerHTML = str; //set html content for <div id="clock_data">
        clock_set = 1;
    }

}
//#############
//jb 6.02.06

/**
 jb 20.12.05 modified 
 Initializes static calendar window
 */
function initStaticCalendar() {
    if (!year && !month && !day) {
        /* Called for first time */

            if (window.dateType == 'datetime' || window.dateType == 'date') {
                if (window.dateType == 'datetime') {
                    parts   = value.split(' ');
                    value   = parts[0];

                    if (parts[1]) {
                        time    = parts[1].split(':');
                        hour    = parseInt(time[0],10);
                        minute  = parseInt(time[1],10);
                        second  = parseInt(time[2],10);
                    }
                }
                date        = value.split("-");
                day         = parseInt(date[2],10);
                month       = parseInt(date[1],10) - 1;
                year        = parseInt(date[0],10);
            } else {
                year        = parseInt(value.substr(0,4),10);
                month       = parseInt(value.substr(4,2),10) - 1;
                day         = parseInt(value.substr(6,2),10);
                hour        = parseInt(value.substr(8,2),10);
                minute      = parseInt(value.substr(10,2),10);
                second      = parseInt(value.substr(12,2),10);
            }

        if (isNaN(year) || isNaN(month) || isNaN(day) || day == 0) {
            dt      = new Date();
            year    = dt.getFullYear();
            month   = dt.getMonth();
            day     = dt.getDate();
        }
        if (isNaN(hour) || isNaN(minute) || isNaN(second)) {
            dt      = new Date();
            hour    = dt.getHours();
            minute  = dt.getMinutes();
            second  = dt.getSeconds();
        }
		
    } else {
        /* Moving in calendar */
        if (month > 11) {
            month = 0;
            year++;
        }
        if (month < 0) {
            month = 11;
            year--;
        }
    }
	
    if (document.getElementById) {
        cnt = document.getElementById(calendarElementID);
    } else if (document.all) {
        cnt = document.all[calendarElementID];
    }
	
    cnt.innerHTML = "";

    str = ""

    //heading table
	//jb 9.12.05 =============== 
	//str +='<table table width="195" border="0" cellspacing="0" cellpadding="0"><tr>';
	//str +='<td width="195" height="200" valign="top" class="calendar">';
/*!!!*/str +='<table width="330" border="0" cellspacing="0" cellpadding="0" >';
	str +='<tr><td valign="top" class="calendartop" >';
	str +='<table width="195" border="0" align="center" cellpadding="0" cellspacing="0" ><tr>';
/*month name*/str +='<td class="monthsTitle">' + month_names[month] + '</td>'; //month name
	str +='</tr></table>';
	str +='</td><td width="135">&#160;</td></tr>';
	//===
	str +='<tr><td valign="top" class="calendarbottom" colspan="2" >';//calendarbottom
/*!!!*/str +='<table border="0" align="right" cellpadding="0" cellspacing="0" >';
	str +='<tr>'; //days header
	for (i = 0; i < 7; i++) {
		str +='<td width="1%" ><table border="0" cellspacing="0" cellpadding="2" class="calcolumn"><tr>';
        str += '<td class="day">' + day_names[i] + '</td>';
		str +='</tr></table></td>';
    }
	str +='<td align="right"></td>';
	str +='</tr>'; //end days header
	
	var firstDay = new Date(year, month, 1).getDay();
    var lastDay = new Date(year, month + 1, 0).getDate();
	
	//jb 14.12.05 get first week day in previous month
	firstInWeekDay = new Date(year, month, 0).getDay();//day number in week. if!=0 , then week start in previous month
	lastDayPreviousMonths = new Date(year, month, 1-firstInWeekDay).getDate(); //date of first date in week in previous month
	
	if(firstInWeekDay==0) {
		fmonth = month + 1;
		j = 1;
		fyear = year;
	} else {
		if(month==0) {
			fmonth = 12;
			fyear = year-1;
		} else {
			fmonth = month;
			fyear = year;
		  }
		j = lastDayPreviousMonths;
	  }
	  
	firstDayInWeek = formatNum4(fyear) + "-" + formatNum2(fmonth, 'month') + "-" + formatNum2(j, 'day');//for first week
	firstWeekDayDate = new Date(formatNum4(fyear),formatNum2(fmonth-1, 'month'),formatNum2(j, 'day'));
		if(firstWeekDayDate>todayDate) {//if first week day < curdate,then show week days as booked style without price input.
			isWeekFuture = true;
			//CHECK PAY STATUS and set price for week if exist this periods in DB
			if(BookedPeriodsPrices!=='') {
				curPayStatus = '';
				curPeriodPrice = '';
				curResourceBidItemID = '';
				for(k=1;k<=BookedPeriodsCount;k++) {
					if(firstDayInWeek==BookedPeriodsPrices[k]['TimeStart']) {
						curPayStatus = BookedPeriodsPrices[k]['ResourceBidStatus'];
						if(curPayStatus=='paid') {//status = paid
							curPeriodPrice = BookedPeriodsPrices[k]['ResourceBidItemPrice'];
							isWeekFuture = false;
						} else {
							curResourceBidItemID = BookedPeriodsPrices[k]['ResourceBidItemID'];
							curPeriodPrice = BookedPeriodsPrices[k]['ResourceBidItemPrice'];
						  }
						break;
					}
				}
			}
			//alert(firstWeekDayDate);
		} else {isWeekFuture = false;}
	//=============== get last week day in next month
	
	fmonth = month+1;
	if(fmonth==12) {
		fyear = year+1;
	} else {
		fyear = year;
	  }
	firstDayNumberInWeekNextMonths = new Date(year, fmonth, 1).getDay();//day number in week. if!=0 , then week start in previous month
	fmonth = fmonth+1;
	if(firstDayNumberInWeekNextMonths>1) {
		j = 8-firstDayNumberInWeekNextMonths;
		if(fmonth==13) {
			fmonth = 1;
		}
	} else if(firstDayNumberInWeekNextMonths==1) {
		j = lastDay;
		fmonth = fmonth-1;
		if(fmonth==12) {
			fyear = year;
		}
	  } else if(firstDayNumberInWeekNextMonths==0) {
		  	if(fmonth==13) {
				fmonth = 1;
			}
		  	j = 1;
	    }
	lastDayInLastWeek = formatNum4(fyear) + "-" + formatNum2(fmonth, 'month') + "-" + formatNum2(j, 'day');//for first week
	// jb 14.12.05
	
	str +='<tr>'; //show first empty days
	dayInWeek = 0;
	if(firstDay==0) {firstDay=7} //!!!week begin from mon
	for (i = 1; i < firstDay; i++) { //week begin from mon
		str +='<td width="1%"><table border="0" cellspacing="0" cellpadding="2" class="calcolumn"><tr>';
        str += '<td >&nbsp;</td>';
		str +='</tr></table></td>';
		dayInWeek++;
    }
	//end show first empty days
	//start show days
	for (i = 1; i <= lastDay; i++) {
        if (dayInWeek == 7) {
			// set checkbox if week not booked
			//!!!str += '<td>'+firstDayInWeek+'<br />'+lastDayInWeek+'</td>';
			BookedPeriod = firstDayInWeek + '|' + lastDayInWeek;
			if(!booked) {
				//str += '<td width="100"><input class="periodPrice" type="text" size="20" name="PeriodsPrice[]" value="' + BookedPeriod + '" /></td>';
				if(curResourceBidItemID!='') {BookedPeriod = BookedPeriod + '|' + curResourceBidItemID;}
				str += '<td width="100">';
				str += '<input type="hidden" size="20" name="PeriodDates[]" value="' + BookedPeriod + '" />';
				str += '<input class="periodPrice" type="text" size="10" name="PeriodsPrice[]" value="' + curPeriodPrice + '" />';
				str += '</td>';
			} else {
				if(curPeriodPrice!='') {
					str += '<td width="100"><input disabled="true" class="periodPrice" type="text" size="10" name="PeriodsPrice[]" value="' + curPeriodPrice + '" /></td>';
				} else { str += '<td width="100" align="right">&#160;</td>';}
			  }
            str += "</tr><tr>";
            dayInWeek = 0;
        }
		
        dispmonth = 1 + month;

        if (window.dateType == 'datetime' || window.dateType == 'date') {
            actVal = formatNum4(year) + "-" + formatNum2(dispmonth, 'month') + "-" + formatNum2(i, 'day');
        } else {
            actVal = "" + formatNum4(year) + formatNum2(dispmonth, 'month') + formatNum2(i, 'day');
        }
		//jb 14.12.05
		if(dayInWeek == 0) {
			firstDayInWeek = actVal;//fill date in format 2005-12-12
			firstWeekDayDate = new Date(formatNum4(year),formatNum2(dispmonth-1, 'month'),formatNum2(i, 'day'));
			if(firstWeekDayDate>todayDate) {//if first week day < curdate,then show week days as booked style without price input.
				isWeekFuture = true;
				//CHECK PAY STATUS and set price for week if exist this periods in DB
				if(BookedPeriodsPrices!=='') {
					curPayStatus = '';
					curPeriodPrice = '';
					curResourceBidItemID = '';
					for(k=1;k<=BookedPeriodsCount;k++) {
						if(firstDayInWeek==BookedPeriodsPrices[k]['TimeStart']) {
							curPayStatus = BookedPeriodsPrices[k]['ResourceBidStatus'];
							if(curPayStatus=='paid') {//status = paid
								curPeriodPrice = BookedPeriodsPrices[k]['ResourceBidItemPrice'];
								isWeekFuture = false;
							} else {
								curResourceBidItemID = BookedPeriodsPrices[k]['ResourceBidItemID'];
								curPeriodPrice = BookedPeriodsPrices[k]['ResourceBidItemPrice'];
							  }
							break;
						}
					}
				}
			} else {isWeekFuture = false;}
		}
		if(dayInWeek == 6) {
			lastDayInWeek = actVal;
		}
		//jb 14.12.05

		
		//jb 28.12.05 set css class
		var day_class = '';
		var booked = ''; 

		if(!isWeekFuture) {//check if week already began
			booked = true; //!!!
			day_class = "class='booked'";
		}
		/*
		if(i == day) {
            day_class = 'class="selected"';
        }
		*/
		
		//jb 28.12.05 
		
		str +='<td ><table border="0" cellspacing="0" cellpadding="2" class="calcolumn"><tr>';
		//link on day
        //str += "<td " + style + " "+day_class+"><a href=\"javascript:returnDateOnLocalWindow('" + actVal + "');\">" + i + "</a></td>";
		str += "<td "+day_class+">"+ i +"</td>";
		str +='</tr></table></td>';
        dayInWeek++;
    }
	//end show days
	//start show last empty days
    for (i = dayInWeek; i < 7; i++) {
        str += "<td>&nbsp;</td>";
    }
	
	// set checkbox if week not booked
	//!!!str +='<td>'+firstDayInWeek+'<br />'+lastDayInLastWeek+'</td>';
	BookedPeriod = firstDayInWeek + '|' + lastDayInLastWeek;
	if(!booked) {
		//str += '<td width="100"><input class="periodPrice" type="text" size="20" name="PeriodsPrice[]" value="' + BookedPeriod + '" /></td>';
		if(curResourceBidItemID!='') {BookedPeriod = BookedPeriod + '|' + curResourceBidItemID;}
		str += '<td width="100">';
		str += '<input type="hidden" size="20" name="PeriodDates[]" value="' + BookedPeriod + '" />';
		str += '<input class="periodPrice" type="text" size="10" name="PeriodsPrice[]" value="' + curPeriodPrice + '" />';
		str += '</td>';
	} else {
		if(curPeriodPrice!='') {
			str += '<td width="100"><input disabled="true" class="periodPrice" type="text" size="10" name="PeriodsPrice[]" value="' + curPeriodPrice + '" /></td>';
		} else { str += '<td width="100" align="right">&#160;</td>';}
	  }
	str +='</tr>';
	//end show last empty days
	
	
	str +='</table>';
	str +='</td></tr>';//end calendarbottom
	str +='</table>';
	//str +='</td></tr></table>';
	//jb 9.12.05 ===============
		
    cnt.innerHTML = str; //set html content for <div id="calendar_data">

    // Should we handle time also?
    if (window.dateType != 'date' && !clock_set) {

        if (document.getElementById) {
            cnt = document.getElementById("clock_data");
        } else if (document.all) {
            cnt = document.all["clock_data"];
        }

        str = '';
        str += '<form class="clock">';
        str += 'h:m<br/><input id="hour" type="text" size="2" maxlength="2" onblur="this.value=formatNum2(this.value, \'hour\')" value="' + formatNum2(hour, 'hour') + '" />:';
        str += '<input id="minute"  type="text" size="2" maxlength="2" onblur="this.value=formatNum2(this.value, \'minute\')" value="' + formatNum2(minute, 'minute') + '" />';
        str += '<input id="second"  type="hidden" size="2" maxlength="2" onblur="this.value=formatNum2(this.value, \'second\')" value="' + formatNum2(second, 'second') + '" />';
		str += '</form>';

        cnt.innerHTML = str; //set html content for <div id="clock_data">
        clock_set = 1;
    }

}
//#############






/**
 * Opens calendar window.
 *
 * @param   string      calendar.php parameters
 * @param   string      form name
 * @param   string      field name
 * @param   string      edit type - date/timestamp
 */
function openCalendar(url, form, field, type) {
    window.open(url, "calendar", "width=200,height=180,status=no");
    dateField = eval("document." + form + "." + field);
    dateType = type;
}
/**
 * Formats number to two digits.
 *
 * @param   int number to format.
 */
function formatNum2(i, valtype) {
    f = (i < 10 ? '0' : '') + i;
    if (valtype && valtype != '') {
        switch(valtype) {
            case 'month':
                f = (f > 12 ? 12 : f);
                break;

            case 'day':
                f = (f > 31 ? 31 : f);
                break;

            case 'hour':
                f = (f > 24 ? 24 : f);
                break;

            default:
            case 'second':
            case 'minute':
                f = (f > 59 ? 59 : f);
                break;
        }
    }

    return f;
}

/**
 * Formats number to four digits.
 *
 * @param   int number to format.
 */
function formatNum4(i) {
    return (i < 1000 ? i < 100 ? i < 10 ? '000' : '00' : '0' : '') + i;
}

/**
 * Initializes calendar window.
 */
function initCalendar() {
    if (!year && !month && !day) {
        /* Called for first time */
        if (window.opener.dateField.value) {
            value = window.opener.dateField.value;
            if (window.opener.dateType == 'datetime' || window.opener.dateType == 'date') {
                if (window.opener.dateType == 'datetime') {
                    parts   = value.split(' ');
                    value   = parts[0];

                    if (parts[1]) {
                        time    = parts[1].split(':');
                        hour    = parseInt(time[0],10);
                        minute  = parseInt(time[1],10);
                        second  = parseInt(time[2],10);
                    }
                }
                date        = value.split("-");
                day         = parseInt(date[2],10);
                month       = parseInt(date[1],10) - 1;
                year        = parseInt(date[0],10);
            } else {
                year        = parseInt(value.substr(0,4),10);
                month       = parseInt(value.substr(4,2),10) - 1;
                day         = parseInt(value.substr(6,2),10);
                hour        = parseInt(value.substr(8,2),10);
                minute      = parseInt(value.substr(10,2),10);
                second      = parseInt(value.substr(12,2),10);
            }
        }
        if (isNaN(year) || isNaN(month) || isNaN(day) || day == 0) {
            dt      = new Date();
            year    = dt.getFullYear();
            month   = dt.getMonth();
            day     = dt.getDate();
        }
        if (isNaN(hour) || isNaN(minute) || isNaN(second)) {
            dt      = new Date();
            hour    = dt.getHours();
            minute  = dt.getMinutes();
            second  = dt.getSeconds();
        }
    } else {
        /* Moving in calendar */
        if (month > 11) {
            month = 0;
            year++;
        }
        if (month < 0) {
            month = 11;
            year--;
        }
    }

    if (document.getElementById) {
        cnt = document.getElementById("calendar_data");
    } else if (document.all) {
        cnt = document.all["calendar_data"];
    }

    cnt.innerHTML = "";

    str = ""

    //heading table
    str += '<table class="calendar"><tr><th width="50%">';
    str += '<form method="NONE" onsubmit="return 0">';
    str += '<a href="javascript:month--; initCalendar();">&laquo;</a> ';
    str += '<select id="select_month" name="monthsel" onchange="month = parseInt(document.getElementById(\'select_month\').value); initCalendar();">';
    for (i =0; i < 12; i++) {
        if (i == month) selected = ' selected="selected"';
        else selected = '';
        str += '<option value="' + i + '" ' + selected + '>' + month_names[i] + '</option>';
    }
    str += '</select>';
    str += ' <a href="javascript:month++; initCalendar();">&raquo;</a>';
    str += '</form>';
    str += '</th><th width="50%">';
    str += '<form method="NONE" onsubmit="return 0">';
    str += '<a href="javascript:year--; initCalendar();">&laquo;</a> ';
    str += '<select id="select_year" name="yearsel" onchange="year = parseInt(document.getElementById(\'select_year\').value); initCalendar();">';
    for (i = year - 80; i < year + 25; i++) {
        if (i == year) selected = ' selected="selected"';
        else selected = '';
        str += '<option value="' + i + '" ' + selected + '>' + i + '</option>';
    }
    str += '</select>';
    str += ' <a href="javascript:year++; initCalendar();">&raquo;</a>';
    str += '</form>';
    str += '</th></tr></table>';

    str += '<table class="calendar"><tr>';
    for (i = 0; i < 7; i++) {
        str += "<th>" + day_names[i] + "</th>";
    }
    str += "</tr>";

    var firstDay = new Date(year, month, 1).getDay();
    var lastDay = new Date(year, month + 1, 0).getDate();

    str += "<tr>";

    dayInWeek = 0;
    for (i = 0; i < firstDay; i++) {
        str += "<td>&nbsp;</td>";
        dayInWeek++;
    }
    for (i = 1; i <= lastDay; i++) {
        if (dayInWeek == 7) {
            str += "</tr><tr>";
            dayInWeek = 0;
        }

        dispmonth = 1 + month;

        if (window.opener.dateType == 'datetime' || window.opener.dateType == 'date') {
            actVal = formatNum4(year) + "-" + formatNum2(dispmonth, 'month') + "-" + formatNum2(i, 'day');
        } else {
            actVal = "" + formatNum4(year) + formatNum2(dispmonth, 'month') + formatNum2(i, 'day');
        }
        if (i == day) {
            style = ' class="selected"';
        } else {
            style = '';
        }
        str += "<td" + style + "><a href=\"javascript:returnDate('" + actVal + "');\">" + i + "</a></td>"
        dayInWeek++;
    }
    for (i = dayInWeek; i < 7; i++) {
        str += "<td>&nbsp;</td>";
    }

    str += "</tr></table>";

    cnt.innerHTML = str;

    // Should we handle time also?
    if (window.opener.dateType != 'date' && !clock_set) {

        if (document.getElementById) {
            cnt = document.getElementById("clock_data");
        } else if (document.all) {
            cnt = document.all["clock_data"];
        }

        str = '';
        str += '<form class="clock">';
        str += 'h:m<br/><input id="hour" type="text" size="2" maxlength="2" onblur="this.value=formatNum2(this.value, \'hour\')" value="' + formatNum2(hour, 'hour') + '" />:';
        str += '<input id="minute"  type="text" size="2" maxlength="2" onblur="this.value=formatNum2(this.value, \'minute\')" value="' + formatNum2(minute, 'minute') + '" />';
        str += '<input id="second"  type="hidden" size="2" maxlength="2" onblur="this.value=formatNum2(this.value, \'second\')" value="' + formatNum2(second, 'second') + '" />';
		str += '</form>';

        cnt.innerHTML = str;
        clock_set = 1;
    }

}

/**
 * Returns date from calendar.
 *
 * @param   string     date text
 */
function returnDate(d) {
    txt = d;
    if (window.opener.dateType != 'date') {
        // need to get time
        h = parseInt(document.getElementById('hour').value,10);
        m = parseInt(document.getElementById('minute').value,10);
        s = parseInt(document.getElementById('second').value,10);
        if (window.opener.dateType == 'datetime') {
            txt += ' ' + formatNum2(h, 'hour') + ':' + formatNum2(m, 'minute') + ':' + formatNum2(s, 'second');
        } else {
            // timestamp
            txt += formatNum2(h, 'hour') + formatNum2(m, 'minute') + formatNum2(s, 'second');
        }
    }

    window.opener.dateField.value = txt;
    window.close();
}
