//
//
// Enhanced JavaScript Event Calendar
//
// Author:  Rick Pike
// Website: http://calendar.pikesys.com
// Email: calendar@pikesys.com
// Developmental Version 20051017
//
// based on an earlier script by Kevin Ilsen (http://calendar.ilsen.net or kevin@ilsen.net)
//
// Permission is granted to use my adaptations in this script as long as the above information is included

// Configurable values are set to defaults here; you can override them before calling Calendar( ) from your HTML page

var classNumPast = "daynumPastTOC";
var classNumToday = "todayTOC";
var classNumFuture = "daynumTOC";
var classCellOut = "outTOC";
var classCellWeek = "weekTOC";
var classCellWeekEnd = "weekEndTOC";
var classCellHoliday = "holidayTOC";

var SpecialDay = 0; 		// 1=Sunday, 2=Monday, . . . 7=Saturday
var OrderSpecialDay = 2;
var OrderHoliday = 1;
var OrderToday = 0;
var OrderEvent = 3;

var FadeAll = true;		// override holiday and special day highlighting
var showHolidays = false; 	// add display of holidays using result from user supplied "holidays(dy, mo, yr)" function
var showMini = true; 		// add minimonth display of prior and next months if first and/or last boxes are available 
var showNav = true; 		// enable month navigation (might disable for print version)
var PrintPage = ""; 		// name of html page for printer-friendly format
var PrintPageRule = ""; 	// Text strings separated by a "|" to prepend and append to yearmonth to construct varying PrintPage (i.e. "print|.pdf")
var doAltNames = false;
var startWeekday = 1; 	// 1=Sunday, 2=Monday, etc.

// Create the arrays of month and weekday names (used in various places)
var language = "italian";
var monthsEn = new arr("January","February","March","April","May","June","July","August","September","October","November","December");
var monthsIt = new arr("Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre");
var monthsSp = new arr("enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre");
var months = monthsIt;
var alt_months = months;

var weekdaysEn = new arr("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var weekdaysIt = new arr("Dom","Lun","Mar","Mer","Gio","Ven","Sab");
var weekdaysSp = new arr("Dom","Lun","Mar","Mi&eacute;","Jue","Vie","S&aacute;b");
var weekdays = weekdaysIt;
var alt_weekdays = weekdays;

var daysEn = new arr("S","M","T","W","T","F","S");
var daysIt = new arr("D","L","M","M","G","V","S");
var daysSp = new arr("D","L","M","M","J","V","S");
var days = daysIt;
var alt_days = days;

var wordsEn = new Object; 
wordsEn.prev ="<< "; wordsEn.next = " >>"; wordsEn.legend = "Legend"; wordsEn.localtime = "Local time";
wordsEn.AV = "AV"; wordsEn.TC = "TC";
wordsEn.AVlink = "&lt;a href=&quot;http://cyberitalian.ivocalize.net/&quot;&gt;Click to enter AudioVideo Class&lt;/a&gt;";
wordsEn.TClink = "&lt;a href=&quot;/cgi-local/perl_wrapper.php?cgidir=cgi-local&cgi=_new_textchat.cgi&doctree=HOME/Community&doctitle=Chat+with+the+Prof&chat_room=prof&quot;&gt;Click to enter Text Chat&lt;/a&gt;";
wordsEn.my = "My tasks";
wordsEn.B1 = "Beginner 1"; wordsEn.B2 = "Beginner 2"; wordsEn.I = "Intermediate"; wordsEn.A = "Advanced";
wordsEn.Tutored = "For TUTORED students"; wordsEn.Private = "For PRIVATE students"; wordsEn.length = "length";
wordsEn.tutored_tit = "Class";
wordsEn.tutored_desc = "This is a 25 minutes class where students practice what they have learned during the course, ask questions or discuss various subjects. Some of the subjects are proposed by the Prof, others are proposed by the students, and others spring up spontaneously during the class.";
wordsEn.private_tit = "Private";
wordsEn.private_desc = "Meet your teacher for a 60 min private lesson.";
wordsEn.assignment_tit = "Assignment";
wordsEn.assignment_desc = "You have to complete your assignment by this date.";
wordsEn.exam_tit = "Exam";
wordsEn.exam_desc = "You have to take your exam/test by this date.";

var wordsSp = new Object;
wordsSp.prev ="<< "; wordsSp.next = " >>"; wordsSp.legend = "Leyenda"; wordsSp.localtime = "Hora local";
wordsSp.AV = "AV"; wordsSp.TC = "CT";
wordsSp.AVlink = "&lt;a href=&quot;http://cyberitalian.ivocalize.net/&quot;&gt;Haz clic para la Clase AudioVideo&lt;/a&gt;";
wordsSp.TClink = "&lt;a href=&quot;/cgi-local/perl_wrapper.php?cgidir=cgi-local&cgi=_new_textchat.cgi&doctree=HOME/Community&doctitle=Chat+with+the+Prof&chat_room=prof&language=spanish&quot;&gt;Haz clic para el Chat de Texto&lt;/a&gt;";
wordsSp.my = "Mi tareas";
wordsSp.B1 = "Principiantes 1"; wordsSp.B2 = "Principiantes 2"; wordsSp.I = "Intermedios"; wordsSp.A = "Avanzados";
wordsSp.Tutored = "Para estudiantes con TUTOR"; wordsSp.Private = "Para estudiantes PRIVADOS"; wordsSp.length = "duraci&oacute;n";
wordsSp.tutored_tit = "Clase T.";
wordsSp.tutored_desc = "Esta es una clase de 25 minutos donde los estudiantes practican lo que han aprendido en el curso, preguntan al profe o tratan varios temas. Algunos temas son propuestos por el Profe, otros son propuestos por los estudiantes, y otros surgen espont&aacute;neamente durante la clase.";
wordsSp.private_tit = "Clase P.";
wordsSp.private_desc = "Encuentra el profesor para tu clase particular.";
wordsSp.assignment_tit = "Tarea";
wordsSp.assignment_desc = "Hay que completar tu tarea dentro de esta fecha.";
wordsSp.exam_tit = "Examen";
wordsSp.exam_desc = "Hoy hay que tomar el examen/test.";

var words = wordsEn;
var alt_words = words;

// all format codes must have "|" to separate before and after tags
var defaultFormat = "<div class='titleTOC'>|</div>";
var holidayFormat = "<div class='titleTOC'>|</div>";

// Initialize the range of the calendar to Jan - Dec of the current year.
// Event definitions will change this as needed; or it can be explicitly
// overridden before calling Calendar( ) from the HTML page.
var today = new Date();
var FirstMonth=GetFullYear(today) * 100 + 1;
var LastMonth=FirstMonth + 11;
var pre, post, tmp, gloMo, gloYr, gloYearmonth;
pre = post = "";

// this date every month, this date every year, and just this date
var inds = new Array(3); 	

// SpecialDays[] is an array of numbers corresponding to "special" days of the week (1=Sun, 2=Mon, ...)
// Call DefineSpecial() to populate it
var SpecialDays = new Array;

// Events[] is a SPARSE array; Call AddEvent( ) to populate it 
var Events = new Array;

// length in min., type is (Chat/AudioVideo/Holiday), level is usual, stype is (Private/Tutored), my is t/f
function AddEvent(datetime, title, description, length, type, level, stype, my) {
	var i;
	var localDatetime;
	var mydate;
	var mytime = datetime.substr(8,4);
	if (mytime == "0000") {
		mydate = datetime.substr(0,8);
		mytime = "";
	} else {
		localDatetime = localTime(datetime);
		mydate = localDatetime.substr(0,8);
		mytime = localDatetime.substr(8,4);
	}
	if (!Events[mydate]) Events[mydate] = new Array;
	i = Events[mydate].length;
	Events[mydate][i] = new myEvent(mydate, mytime, title, description, length, type, level, stype, my);

	// Adjust the minimum and maximum month & year to include this date
	if (mydate > 1231) { 	// ignore dates without years
		tmp = Math.floor(mydate / 100);
		if (tmp < FirstMonth) FirstMonth = tmp;
		if (tmp > LastMonth) LastMonth = tmp;
	}

}

// Event constructor
function myEvent(date, time, title, description, length, type, level, stype, my) {

//	alert('event = ' + date + ' ' + time + ' ' + title );
	this.date = date;
	if (time) {
	   this.time = time;
	}
	this.title = title;
	if (description) {
		this.description = description;
	}
	if (length) {
	   this.length = length;
	}
	if (type) {
	   this.type = type;
	}
	if (level) {
	   this.level = level;
	}
	if (stype) {
	   this.stype = stype;
	}
	if (my) {
	   this.my = my;
	}
}

// Calendar( ) is the only routine that needs to be called to display the calendar
function Calendar() {
	var myhtml, curyr, curmo, curdy, yr, mo, dy, firstday, yearmonth, bgn, lastdate, jump;
	var i, j;
	var thispage = window.location.pathname;

	// localization
	if (language == "spanish") { months = monthsSp; weekdays = weekdaysSp; days = daysSp; words = wordsSp;}
	else if (language == "english") { months = monthsEn; weekdays = weekdaysEn; days = daysEn; words = wordsEn;}
	else if (language == "italian") { months = monthsIt; weekdays = weekdaysIt; days = daysIt; words = wordsIt;}

// get number of months to display on page from argument (or default to 1)
	var loopCal = (Calendar.arguments.length == 1 ? Calendar.arguments[0] : 1);

	// Handle a single SpecialDay definition  (for compatability)
	if (SpecialDay) DefineSpecial(SpecialDay);

	// Save current day and month for comparison
	curdy = today.getDate();
	curmo = today.getMonth()+1;
	curyr = GetFullYear(today);
	
	initCal(curmo, curyr);
	mo = gloMo; yr = gloYr; yearmonth = gloYearmonth;
//	getLayersVisible(); 		// get layer visibility settings from cookie

	// potentially loop over multiple months on page
	for (var loop=1; loop<=loopCal; loop++) {
	
	// Create a date object for the first day of the desired month
	//bgn = new Date(months[mo] + " 1," + yr);
	bgn = new Date(yr, mo-1, 1);
	// Get the day-of-week of the first day, and the # days in the month
	//firstday = bgn.getDay();
	firstday = (bgn.getDay() + 8 - startWeekday)%7; 	// shift week start to specified day
	lastdate = NumDaysIn(mo,yr);
	lastday = 1 + (firstday + lastdate - 1)%7;
	prev = next = "&nbsp;";
	
	if (showNav) {
		if (yearmonth > FirstMonth)
			prev = '<a href="' + thispage + '?'+PrevYearMonth(yearmonth)+'">'+ words.prev +'</a>';
		if (yearmonth < LastMonth)
			next += '<a href="' + thispage + '?'+NextYearMonth(yearmonth)+'">'+ words.next +'</a>';
	}

// Display header row with navigation
	myhtml = "<form name='myForm'><table class='mainTableTOC' cellspacing='1' cellpadding='0' border='0'>\n";
	myhtml += " <tr>\n";
	myhtml += "  <td class='monthYearRowTOC' colspan='3'><span class='monthYearTextTOC'>" + months[mo] + " " + yr;
	myhtml += "</span></td>\n  <td class='monthYearRowTOC'>" + prev + "</td>\n";
	myhtml += "<td class='monthYearRowTOC' colspan='2'>" + BuildSelectionList(yearmonth, thispage) + "</td>";
	myhtml += "  <td class='monthYearRowTOC'>" + next + "</td>\n</tr>\n";
	document.write(myhtml);
//	alert('1 = ' + myhtml);
	
// Display day names row
	myhtml = " <tr>\n";
	for (var i=1; i<=7; i++){
		myhtml += "  <td class='dayNamesRowTOC'><span class='dayNamesTextTOC'>"+weekdays[i]+"</span></td>\n";
	}
	myhtml += " </tr>\n";
	document.write(myhtml);
//	alert('2 = ' + myhtml);

// Display event rows
	myhtml = "";
	dy = 1;
	while (dy <= lastdate) {
		myhtml += " <tr class='rowsTOC'>\n";
		for (var j=1; j<=7; j++) {
			
// If the day cell is before the first day of the month, print a miniMonth display of previous month, 
// otherwise print a space in this cell of the table.
			if (dy == 1 && j <= firstday) {
				if (j == 1) {
					if (showMini && firstday>=2) {
						myhtml += "  <td class='" + classCellOut + "' style='text-align:left'>";
						myhtml += "<a href=" + thispage + '?'+PrevYearMonth(yearmonth)+">";
						myhtml +=  MiniMonth(PrevYearMonth(yearmonth));
						myhtml += "</a></td>\n";
					}
				} else {
					myhtml += "  <td class='" + classCellOut + "'>&nbsp;</td>\n";
				}

// If the day cell is after the last day of the month, print a miniMonth display of following month, 
// otherwise print a space in this cell of the table.
			} else if (dy > lastdate) {
				if (showMini && j==6) {
					myhtml += "  <td class='" + classCellOut + "' style='text-align:right' colspan='2'>";
					myhtml += "<a href=" + thispage + '?'+NextYearMonth(yearmonth)+">";
					myhtml += MiniMonth(NextYearMonth(yearmonth));
					myhtml += "</a></td>\n";
					j++;
				} else {
					myhtml += "  <td class='" + classCellOut + "' >&nbsp;</td>";
				}
			// Otherwise, write date and the event, if any, in this cell of the table.
			} else {
				myhtml += ShowDate(yr,mo,dy,j,curyr,curmo,curdy);
				dy++;
			}
		}
		myhtml += " </tr>\n";
		
	}
	document.write(myhtml);
//	alert('3 = ' + myhtml);

// Display legend and local time row
	myhtml = " <tr><td class='legendRowTOC' colspan='7'>\n";
	myhtml += "<div class='legendTextTOC' style='white-space: nowrap;'>"+words.legend+":&nbsp;" +
			  "<span class='cPre'>&nbsp;"+words.B1+"&nbsp;</span>&nbsp;" +
			  "<span class='cBeg'>&nbsp;"+words.B2+"&nbsp;</span>&nbsp;" +
			  "<span class='cInt'>&nbsp;"+words.I+"&nbsp;</span>&nbsp;" +
			  "<span class='cAdv'>&nbsp;"+words.A+"&nbsp;</span>&nbsp;" +
			  "<span class='bMy'>&nbsp;"+words.my+"&nbsp;</span>" +
			  "&nbsp;&nbsp;&nbsp;"+words.localtime+":&nbsp;" +
			  "<input class='legendTextTOC' type='text' size='4' name='clock' value='' /></div>";
	myhtml += " </td></tr>\n";
	document.write(myhtml);

// close table and form
	myhtml = "</table></form>\n";
	document.write(myhtml);

// increment month variables for next loop iteration
	yearmonth = NextYearMonth(yearmonth);
	mo = yearmonth % 100;
	yr = (yearmonth - mo) / 100;
	if (loop < loopCal) document.write("<p>&nbsp;</p>");
	} // loopCal loop
	
}

// Display a date in the appropriate color, with events (if there are any)

function ShowDate(yr, mo, dy, dayofweek, currentyear, currentmonth, currentday) {

	var i, j, myhtml, htmlClassCell, htmlClassNum, ind, dayHighlight, borderHighlight, cellColor, tmp, event;

	htmlClassNum = classNumFuture; // default
	htmlClassCell = classCellWeek; // default
	orderDay = 10;
	// check for SpecialDay, and Holiday (in order of increasing precedence)
	if (SpecialDays[dayofweek] && OrderSpecialDay<orderDay) {
		orderDay = OrderSpecialDay;
		htmlClassCell = classCellWeekEnd;
		htmlClassNum = classNumFuture;
	}
	if (showHolidays) {
		if (holidays(dy,mo,yr)  && OrderHoliday<orderDay) {
			orderDay = OrderHoliday;
			htmlClassCell = classCellHoliday;
			htmlClassNum = classNumFuture;
		}
	}
	if ((yr == currentyear) && (mo == currentmonth) && (dy == currentday)) {
		orderDay = OrderToday;
		htmlClassNum = classNumToday;
	}
	if (FadeAll && yr == currentyear && mo==currentmonth && dy < currentday) 	htmlClassNum = classNumPast;

	inds[0] = dy; 					// this date every month
	inds[1] = dy+100*mo; 				// this date every year
	inds[2] = dy+100*(mo+100*yr); 		// just this date

	for (var i in inds) { 	// this date every month, this date every year, just this date
		ind = inds[i];
		if (Events[ind]) {
			if (OrderEvent<orderDay) {	// today or special day take precedence
				orderDay = OrderEvent;
			}
		}
	}


	myhtml = "  <td class='" + htmlClassCell + "'><div class='" + htmlClassNum + "'>" + dy + "</div>\n";
	
	if (showHolidays) {
		tmp = holidays(dy,mo,yr);
		if (tmp) {
			parseFormat(holidayFormat);
			myhtml += pre + tmp + post;
		}
	}

	images=0;
	for (var i in inds) { 	// this date every month, this date every year, just today
	  ind = inds[i];
	  for (var j in Events[ind]) {
		ev = Events[ind][j];
// Build the HTML string for this event
		evFormat(ev.date, ev.time, ev.title, ev.description, ev.length, ev.type, ev.level, ev.stype, ev.my);
		myhtml += pre + post;
	  }
	}
	myhtml += "</td>";
	return myhtml;
}

function initCal(curmo, curyr) {

	// Default to current month and year
	mo = curmo;
	yr = curyr;
	yearmonth = (yr * 100) + mo;

	// Handle non-English date names (weekdays & days defined as Sun to Sat even if startWeekday shift is specified)
	if (doAltNames) {
		for (var i=0; i<12; i++) { months[i+1] = alt_months[i+1]; }
		for (var i=0; i<7; i++) { weekdays[i+1] = alt_weekdays[i+1]; }
		for (var i=0; i<7; i++) { days[i+1] = alt_days[i+1]; }
		for (var i in words) { words[i] = alt_words[i]; }
// for (var i=0; i<words.length; i++) { words[i+1] = alt_words[i+1]; }
	}

	// shift week start to specified day
	if (startWeekday > 1) {
		for (var i=1; i<startWeekday; i++) {
			weekdays.cycle();
			days.cycle();
		}
	}

	// If querystring parameter is present, get the month/year ("calendar.htm?YYYYMM")
	if (location.search.length > 1) {
		yearmonth = parseInt(location.search.substring(1,location.search.length));
		if ((""+yearmonth).length == 6) {
			mo = yearmonth % 100;
			yr = (yearmonth - mo) / 100;
		}
	}

	// Constrain to the range of months with events
	if (yearmonth < FirstMonth) {
		mo = FirstMonth % 100;
		yr = (FirstMonth - mo) / 100;
		yearmonth = FirstMonth;
	}
	if (yearmonth > LastMonth) {
		mo = LastMonth % 100;
		yr = (LastMonth - mo) / 100;
		yearmonth = LastMonth;
	}
	gloMo = mo; gloYr = yr; gloYearmonth = yearmonth;
}

// Create a mini display of the desired month
function MiniMonth(yearmonth) {
	var dy, i, d, mo, y, myhtml, bgn, firstday, lastdate, miniweek;

	mo = yearmonth % 100;
	yr = (yearmonth - mo) / 100;
	//bgn = new Date(months[mo] + " 1," + yr);
	bgn = new Date(yr, mo-1, 1);
	// Get the day-of-week of the first day, and the # days in the month
	//firstday = bgn.getDay();
	firstday = (bgn.getDay() + 8 - startWeekday)%7; 	// shift week start to specified day
	lastdate = NumDaysIn(mo,yr);
	myhtml = "<div class='miniCal'><tt>&nbsp;" + months[mo] + "<br/>";
	miniweek = "&nbsp;<u>";
	for (var d=0; d<7; d++) { miniweek += "&nbsp;" + days[d+1] + "&nbsp;"; }
	myhtml += miniweek + "</u>";
	dy = 1;
	// Rest of the weeks . . .
	while (dy <= lastdate) {
		miniweek = "<br/>";
		for (var i=1; i<=7; i++) {
			// If the day is less than the day of the week of the first day of the month, append spaces
			if (dy == 1 && i <= firstday){
				miniweek += "&nbsp;&nbsp;&nbsp;";
			// End minimonth if the day > last day of the month
			} else if (dy > lastdate) {
				miniweek += "&nbsp;&nbsp;&nbsp;";
			// Otherwise, append date (w/ extra space for single digits)
			} else {
				miniweek += "&nbsp;" + ( dy<10 ? "&nbsp;" : "" ) +dy;
				dy++;
			}
		}
		myhtml += miniweek;
	}
	myhtml += "</tt></div>";
	return myhtml;
}

// main event format routine
function evFormat(date, time, title, description, length, type, level, stype, mycourse) {
	var cssclass, desc;

	// Init vars
	if (!description || !title) {
		if (type == 'AudioVideo') {
			if (stype == 'Private') {
				tit = words.private_tit;
				desc = words.private_desc;
			} else {
				tit = words.tutored_tit;
				desc = words.tutored_desc;
			}
		} else if (type == 'Assignment' || type == 'Project') {
			tit = words.assignment_tit;
			desc = words.assignment_desc;
		} else if (type == 'Exam' || type == 'Midterm') {
			tit = words.exam_tit;
			desc = words.exam_desc;
		}
	} else {
		tit = title;
		desc = description;
	}

	if (type == 'AudioVideo') {tit += " [" + words.AV + "]"; desc += "<br />" + words.AVlink;}
	else if (type == 'Chat') {tit += " [" + words.TC + "]"; desc += "<br />" + words.TClink;}

	// pre and post are globals
	pre = "<div class='titleTOC'>";
	post = "</div>";
	
	// format with level color and my border
	if (level == "B1") { cssclass = 'cPre'; col = "cPre"; }
	else if (level == "B2") { cssclass = 'cBeg'; col = "cBeg"; }
	else if (level == "I") { cssclass = 'cInt'; col = "cInt"; }
	else if (level == "A") { cssclass = 'cAdv'; col = "cAdv"; }
	else { cssclass = ""; col = ""; }
	if (mycourse) {cssclass += ' bMy';}
	pre += "<span class='" +cssclass+ "'>&nbsp;";
	post = "&nbsp;</span>" + post;

	if (time) time = time.substr(0,2) + ":" + time.substr(2,2);
	if (date) {
		d = date.substr(6,2);
		m = date.substr(4,2);
		y = date.substr(0,4);
	}

	// format with javascript popup
	if (desc || time || length) {
		pre += "<a href='javascript:void(0);' onmouseover=\"return overlib('" +
					"<table class=&quot;popupTable&quot;>" +
					  "<tr>" +
						"<td class=&quot;popupDate&quot;>"+d+" "+months[parseInt(m)]+" "+y+"</td>" +
						"<td class=&quot;popupClose&quot;><a href=&quot;javascript:void(0);&quot; " +
						 "onmouseover=&quot;javascript:cClick();&quot;>" +
						 "<span class=&quot;popupClose&quot;>[X]</span></a></td>" +
					  "</tr>" +
					  "<tr>" +
						"<td class=&quot;popupEventTitle "+col+"&quot; colspan=&quot;2&quot;>"+tit+" - "+words[level];
		if (stype) pre += "<br/>"+words[stype];
		pre += 		    "</td>" +
					  "</tr>";
		if (time) pre += "<tr>" +
							"<td class=&quot;popupEventTime&quot; colspan=&quot;2&quot;>"+time;
		if (length) pre += " " +words.length+": " +length+ " min</td>";
		pre += 		  	 "</tr>";
		pre += 		  "<tr>" +
						"<td class=&quot;popupEventDescription&quot; colspan=&quot;2&quot;>"+desc+"</td>" +
					  "</tr>" +
					"</table>');\" onmouseout='return nd();'>";
		post = tit+"</a>" + post;
	}
}

// Remaining routines are utilities used above
function DefineSpecial() {
	for (var n=0; n<DefineSpecial.arguments.length; n++) {
		SpecialDays[DefineSpecial.arguments[n]] = true;
	}
}

function NumDaysIn(mo,yr) {
	if (mo==4 || mo==6 || mo==9 || mo==11) return 30;
	else if ((mo==2) && LeapYear(yr)) return 29;
	else if (mo==2) return 28;
	else return 31;
}

function LeapYear(yr) {
	return ( (yr%4 == 0 && yr%100 != 0) || yr % 400 == 0 ? true : false );
}

// fixes a Netscape 2 and 3 bug
function GetFullYear(d) { // d is a date object
	var yr = d.getYear();
	return ( yr < 1000 ? yr + 1900 : yr );
}

function PrevMonth(mth) {
	return ( mth == 1 ? 12 : mth - 1 );
}

function NextMonth(mth) {
	return ( mth == 12 ? 1 : mth + 1 );
}

function PrevYearMonth(yrmth) {
	return ( yrmth%100 == 1 ? yrmth-100+11 : yrmth-1 );
}

function NextYearMonth(yrmth) {
	return ( yrmth%100 == 12 ? yrmth-11+100 : yrmth+1 );
}

function JumpTo(calendar, thispage) {
	var sel, yrmo;

	sel = calendar.selectedIndex;
	yrmo = calendar.form.jumpmonth[sel].value;
	document.location = thispage + "?" + yrmo;
}

function BuildSelectionList(current, thispage) {
	var mo, yr, yearmonth;

	yearmonth = FirstMonth;
	tmp = "<select name=\"jumpmonth\" size=1 onchange=\"JumpTo(this,'" + thispage + "')\">";
	while (yearmonth <= LastMonth) {
		mo = yearmonth % 100;
		yr = (yearmonth - mo) / 100;
		selected = (yearmonth == current ? " selected" : "");
		tmp += "<option value=" + yearmonth + selected + ">" + months[mo]+ " " + yr + "</option>";
		yearmonth = NextYearMonth(yearmonth);
	}

	return(tmp + "</select>");
}

// mail to
function escramVal(j,k){var a,b,c,d,e;a='<a href=\"mai';c='\">';a+='lto:';b=j+'@';e='</a>';b+=k;d=b;return(a+b+c+d+e);}

// Utility function to populate an array with values
function arr() {
	for (var n=0; n<arr.arguments.length; n++) {	this[n+1] = arr.arguments[n]; }
	this.length = arr.arguments.length;
	this.cycle = function () {
		var tmp = this[1];
		for (var n=2; n<=this.length; n++) { this[n-1] = this[n]; }
		this[this.length] = tmp;
	}
}

// Utility function to "" a string
function qw(string) {
	return "&quot;" + string + "&quot;";
}

// old utility to parse format
function parseFormat(format) {
	// pre and post are globals
	pre = post = "";
	if (format) {		
		var sep = format.indexOf("|");
		if (sep > 0) {  // split format into pre and post strings
			pre = format.substring(0, sep);
			post = format.substring(1+sep, format.length);
		}
	}
}

function checkFormat(String) {
	var okay;
	okay =(String == "layer" || String == "custom" || String.indexOf("|")>0);
	if (!okay) alert("Invalid Calendar Format String: " + String);
	return okay;
}

function checkTime(i) {
	if (i<10) {i="0" + i;} 
	return i;
}

// convert to local date and time
function localTime(datetime) {
	var output;
	dbDate = new Date();
	datetime = String(datetime);

	dbDate.setUTCFullYear(datetime.substr(0,4));
	dbDate.setUTCMonth(datetime.substr(4,2)-1); 
	dbDate.setUTCDate(datetime.substr(6,2)); 
	dbDate.setUTCHours(datetime.substr(8,2)); 
	dbDate.setUTCMinutes(datetime.substr(10,2)); 
	dbDate.setUTCSeconds(0);
	
	output = "" + checkTime(dbDate.getFullYear()) + checkTime(dbDate.getMonth()+1) + checkTime(dbDate.getDate()) +
			 checkTime(dbDate.getHours()) + checkTime(dbDate.getMinutes());
	
	return output;
}

// return local time hh:mm
function displayTime () {
  var curtime = new Date();
  var curhour = curtime.getHours();
  var curmin = curtime.getMinutes();
  var time = "";
 
  if(curhour == 0) curhour = 12;
  time = (curhour < 10 ? "0" : "") + curhour + ":" +
         (curmin < 10 ? "0" : "") + curmin;
 
  document.myForm.clock.value = time;
}
