/**********************************/
/* Copyright John Tucker july2005 */
/* licensed under the GNU GPL v2  */
/*         No Known Bugs          */
/* you also need ./styles/cal.css */
/**********************************/

function calendarCode() {

	// latency
	L = 5

	// dates booked already
	busy = new Array(
  	"20081224",
  	"20081225",
  	"20081226",
	"20081230",
	"20081231",
	"20081229",
	"20081220",
   "20081221",
  	"20081222",
  	"20081223")  	
  	
	B = busy.length

	// get (this) day of month ("thisDayNo"), weekday ("thisDayName"), 
	// month number ("thisMonthNo"), and year number 
	// first create a new Date Object, default is today
	toDay = new Date();
	
	// getDate() returns day of the month into thisDayNo where 1 is first day
	thisDayNo = toDay.getDate()
	// alert(thisDayNo)
	// getDay() returns integer of 0-6 into thisDayName
        thisDayName = toDay.getDay();
        // alert(thisDayName) 
        // sunday is "0", saturday is "6"
	// getMonth() returns integer of 0-11 into thisMonthNo
	thisMonthNo = toDay.getMonth()

	// getYear() returns year which will be stored into thisYear
	thisYear = toDay.getYear()
	if (thisYear < 2000) {thisYear += 1900} // fix for y2k bug (in some browsers)

	monthNames = "JanFebMarAprMayJunJulAugSepOctNovDec";

	/* create array of DiM for this year                                 */
	DiM = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

	/* we are only interested in checking the *next* February            */
	/* add 1 to february's days if next (or this) feb is in a leap year  */
	leapYear = 0
	y = thisYear
	if (thisMonthNo > 1) { y=y+1 }
	if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) {
   	leapYear = 1;
		}
	DiM[1] = DiM[1] + leapYear

	// build 6x7day array for raw monthly calendar. Sunday is first column, numbered 0.
	// tuesday is today (column numbered 2) in the example on the line below, and latency is 2
	// ("past", "past", "now", "busy", "busy", "open", "open")
	aWeek0 = new Array("-", "-", "-", "-", "-", "-", "-");
	aWeek1 = new Array("-", "-", "-", "-", "-", "-", "-");
	aWeek2 = new Array("-", "-", "-", "-", "-", "-", "-");
	aWeek3 = new Array("-", "-", "-", "-", "-", "-", "-");
	aWeek4 = new Array("-", "-", "-", "-", "-", "-", "-");
	aWeek5 = new Array("-", "-", "-", "-", "-", "-", "-");
	
	aWeek = new Array(6);
	aWeek[0]=aWeek0;
	aWeek[1]=aWeek1;
	aWeek[2]=aWeek2;
	aWeek[3]=aWeek3;
	aWeek[4]=aWeek4;
	aWeek[5]=aWeek5;
	// now can say aWeek[1][4]
	// but only read, not write :(	

	// Latency uses ccyymmdd format where 0 < mm < 13, and 0 < dd < DiM[mm-1]
	// today is "thisYear" + "thisMonthNo+1" + "thisDayNo+1"
    // use tryDate = tryYear&tryMonth&tryDay

	// for each day of Latency ...
    var tryDay = thisDayNo
    var tryMonth = thisMonthNo
    var tryYear = thisYear
	for (i = 0; i < L; i++) {
    // check if next day is valid
       tryDay=tryDay+1
       var goodDate = false;
       if (checkValid(tryDay) == false) {
          tryDay = 1; 
          tryMonth = tryMonth + 1; 
          if (tryMonth == 13) {tryMonth = 1; tryYear = tryYear + 1; }
       }
    // add day to busy array
 // alert(tryDay); alert(tryMonth);
    // add day to busy array at B + i in ccyymmdd format 
   	// where 0 < mm < 13, and 0 < dd < DiM[mm-1]
	// single digits days and months are character & padded with "0"
	strD = (tryDay).toString();
	if (tryDay < 10) {
		strD = "0" + strD};
	strM = (tryMonth + 1).toString();
	if (tryMonth + 1 < 10) {
		strM = "0" + strM}
	strY = (tryYear).toString()
	strBkd = strY + strM + strD; 
	busy[B+i] = strBkd 
//    alert(busy);
    }
	

// now work out the start dates of the three months we want to display
//	var m = mnth + thisMonthNo  // days in month is DiM[m] 
//alert(m)
//	var y = thisYear
//	if (m>11){m = m%12; y++;} 
//	day0Name = (1 + thisDayName - (thisDayNo % 7))%7                   // backwards
//	if (day0Name < 0)  {day0Name = day0Name + 7}
//	day1Name = (thisDayName + (DiM[thisMonthNo] - thisDayNo + 1)%7)%7  // forwards
//	day2Name = (day1Name + DiM[m])%7	// ah! the general formula
	
	/*********************/
	// here's the engine  
			 	
        document.write("<DIV ID=\"Cals\"> ");
	document.write("<DIV ID=\"Cal_box\"> ");
	for (k = 0; k < 2; k++) {
		// Tag past, now, open, busy in aWeek, a 6x7days array 
		settags(k)
		// write a styled calendar table 5x5weekdays from 6x7days array
		writetable(k)
	}
	document.write("</DIV>");
	document.write("</DIV>");
								
	//    neat, eh?		
	/*********************/


function settags(mnth) {
	// Tag past, now, open, busy in a 6x7days array
	// mnth==0 means this month, mnth==1 next month, etc
	// day0Name is dayName (column) of 1st day of first month
	   
	var m = mnth + thisMonthNo  // days in month is DiM[m] 
	var y = thisYear
	if (m>11){m = m%12; y++;} 
	day0Name = (1 + thisDayName - (thisDayNo % 7))%7                   // backwards
	if (day0Name < 0)  {day0Name = day0Name + 7}
	day1Name = (thisDayName + (DiM[thisMonthNo] - thisDayNo + 1)%7)%7  // forwards
//alert(day1Name + "/" + DiM[m])
	day2Name = (day1Name + DiM[m-1])%7	// ah! the general formula
	// note: day1Name == (day0Name + DiM[m-1])%7 
// alert(m + "/" + day1Name)
	if (mnth == 0) {var dayName = day0Name; tag = "past" }
	if (mnth == 1) {var dayName = day1Name; tag = "open" }
	if (mnth == 2) {var dayName = day2Name; tag = "open" }
	var w = 0;
	var tag;
	var i
	
	// now to process each day in the current month
	for (i = 1; i != 1+DiM[m]; i++) {
		// today is i==thisDayNo
//alert(i + "/" + m + "/" + y);
		if (i==thisDayNo && m==thisMonthNo) {
			tag = "now" };
		if (tag == "open") {
			// check busy for Year, Month, DayNo
			if (checkbusy(y, m, i)) {
				tag = "busy"}
		}
// alert(i + "/" + m + "/" + y + "//" + w + " " + tag);		
   	// javascript arrays workabout
	 	// aWeek1[dayName] = tag - ok
		// aWeek[w][dayName] = tag - not ok
		
		if (w == 0) {
			aWeek0[dayName] = tag}
		else if (w == 1) {
			aWeek1[dayName] = tag}
		else if (w == 2) {
			aWeek2[dayName] = tag}
		else if (w == 3) {
			aWeek3[dayName] = tag}
		else if (w == 4) {
			aWeek4[dayName] = tag}
		else if (w == 5) {
			aWeek5[dayName] = tag}
		
		if (tag != "past") { tag = "open"};

		dayName++
// alert(m + "/" + w + "/" + dayName)
		if (dayName == 7) {
			dayName = 0
			w++
		} 
	} 
}


function checkbusy(y,m,i) {
	// check for availability (y,m+1,i)
	strI = (i).toString();
	if (i < 10) { strI = "0" + strI;}
	strM = (m+1).toString()
	if (m+1 < 10) { strM = "0" + strM;}
	todayStr = y.toString() + strM + strI;
   // look thru busy array for todayStr 
	var foundStr = false;
   for (j = 0; j < busy.length; j++) {
		if (todayStr == busy[j]) {foundStr = true; break} 
	}              
	return foundStr	
}

function checkValid(ccyymmdd) {
	// valid month/day combination?
    if (DiM[tryMonth] >= tryDay) { goodDate = true};
    return goodDate;}

function writetable(mnth) {
	// write 5x5 from 6x7
	// past is before thisWeek,thisDayName)
	// mnth==0 means this month
	var foo
	var m = mnth + thisMonthNo  // days in month is DiM[m]
	var y = thisYear
	if (m>11){m = m%12; y++;}
	// works for one year 
	var j=0
	// write table & month header
  	document.write("<TABLE>");
  	document.write("<TR><TH COLSPAN=7>");
	document.write("<SPAN CLASS=\"mnth\">");
  	document.write(monthNames.substring(m * 3, (m + 1) * 3));
  	document.write("</SPAN>");
	document.write("<SPAN CLASS=\"year\">");
  	document.write(y);
	document.write("</SPAN>");
	document.write("</TH></TR>");
  	document.write("<TR><TH></TH><TH>Mo </TH><TH>Tu </TH><TH>We </TH><TH>Th </TH><TH>Fr </TH><TH></TH></TR>");

//alert(DiM[m]);

	// for j = 1 to DiM[m] per settags 
	// need to assemble whole rows of output. Skip if just empty cells,
	//  but output a row of empty cells as the last row for February iff 
        //  it starts on a Sunday (this is the only case where just four rows 
        //  are needed to show the weekdays in the month) 
	var calLine
	for (w = 0; w < 6; w++) {
		calLine = "<TR>";
		for (d = 0; d < 7; d++) {
		//  tag = aWeek[w][d] workaround
//                alert(calLine)
 			if (w == 0) {
				tag = aWeek0[d]}
			else if (w == 1) {
				tag = aWeek1[d]}
			else if (w == 2) {
				tag = aWeek2[d]}
			else if (w == 3) {
				tag = aWeek3[d]}
			else if (w == 4) {
				tag = aWeek4[d]}
			else if (w == 5) {
				tag = aWeek5[d]} 
			
			if (d==0 || d==6){ calLine = calLine + "<TD></TD>";}
			if (tag == "-"){
				if (d!=0 && d!=6){ calLine = calLine + "<TD></TD>";}
			}
			else {
				j++;
				if (d!=0 && d!=6) {
					calLine = calLine + "<TD>";
					// build span string
					foo = '<SPAN TITLE=\"'
					// foo = foo + tag + '" '
					if (tag == "past"){foo = foo + 'The past' + '" ' }
					else if (tag == "now"){foo = foo + 'Today\" '}
					else if (tag == "open"){foo = foo + 'I may be free\" '}
				   else if (tag == "busy"){foo = foo + 'Booked\" '}
					foo = foo + 'CLASS=\"'
					foo = foo + tag
					foo = foo + '\"'
					foo = foo + '>'
					foo = foo + j 					// + "<br>" + tag
					foo = foo + '</SPAN>'
					calLine = calLine + foo;
					calLine = calLine + "</TD>";
				} 
			}	
		} 
		calLine = calLine + "</TR>";
		
//		alert(m + " " + w + " " + calLine)
        // output calendar line if not empty 
		if (calLine != "<TR><TD></TD><TD></TD><TD></TD><TD></TD><TD></TD><TD></TD><TD></TD></TR>") {
			document.write(calLine);}
        // output FEB's penultimate line (w == 4 and thisMonthNo == 1) iff blank
        // the &nbsp; is to force browsers to display the line
        else if ((calLine = "<TR><TD></TD><TD></TD><TD></TD><TD></TD><TD></TD><TD></TD><TD></TD></TR>") && (w == 4) && (m == 1)) {
            calLine = "<TR><TD></TD><TD></TD><TD></TD><TD> &nbsp; </TD><TD></TD><TD></TD><TD></TD></TR>"
			document.write(calLine);}
		} 
	document.write("</TABLE>");
	
	// clear 6x7days calendar array aWeek[w][d] 
	aWeek0 = new Array("-", "-", "-", "-", "-", "-", "-");
	aWeek1 = new Array("-", "-", "-", "-", "-", "-", "-");
	aWeek2 = new Array("-", "-", "-", "-", "-", "-", "-");
	aWeek3 = new Array("-", "-", "-", "-", "-", "-", "-");
	aWeek4 = new Array("-", "-", "-", "-", "-", "-", "-");
	aWeek5 = new Array("-", "-", "-", "-", "-", "-", "-");
	}	
}

