/*

Written by Marco A. Gonzalez
Copyright (c) 2009 Amagavi, Inc.

web: http://www.amagavi.com/


*/

// variables to show the current day in the calendar
var todaydate=new Date();
var curmonth=todaydate.getMonth()+1; //get current month (1-12)
var curyear=todaydate.getFullYear(); //get current year
var selectedDay = 5;				// not supported yet
			

// depends on functions found in AmagaviHTML.js

// FIXME: 
// need cssForNonDay
// need the following css classes:
// 		nonDayCell
// 		previousMonthElement
//		nextMonthElement

// selectedDayNumber not supported yet
// 


function showAmagaviCalendarOnPage(id, calendarJSONfn){
	cssClassForDivAndTable = "amagaviCalendar";	// hard coded for now
	cssForTitle = "monthName";
	cssForDayNameRow = "daysOfWeek";
	cssForDayBox = "day";
	
	calendarHTML = makeCalendarHTML(id, calendarJSONfn, curmonth, selectedDay, curyear, cssClassForDivAndTable, cssForTitle, cssForDayNameRow, cssForDayBox);
	
	document.getElementById(id).innerHTML = calendarHTML;
}

function previousMonth(id, calendarJSONfn){
	curmonth--;
	if (curmonth < 1){
		curmonth = 12;
		curyear--;
	}
	showAmagaviCalendarOnPage(id, calendarJSONfn);
}

function nextMonth(id, calendarJSONfn){
	curmonth++;
	if (curmonth > 12){
		curmonth = 1;
		curyear++;
	}
	showAmagaviCalendarOnPage(id, calendarJSONfn);
}




function makeCalendarHTML(id, calendarJSONfn, m, selectedDayNumber, year, cssClassForDivAndTable, cssForTitle, cssForDayNameRow, cssForDay){
	var monthName=['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
	
	var dayNames=['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
		
	var calendarJSON = eval(calendarJSONfn);	// actually call the method to get the JSON data
	
	var oD = new Date(year, m-1, 1);
	oD.od=oD.getDay()+1; 

	var dim=[31,0,31,30,31,30,31,31,30,31,30,31];	// number of days in month
	
	// calculate whether Feb has 28 or 29 days, i.e. leap year
	dim[1]=(((oD.getFullYear()%100!=0)&&(oD.getFullYear()%4==0))||(oD.getFullYear()%400==0))?29:28;


	var todaydate=new Date();
	var dayNumberForToday = 0;
	if (year==todaydate.getFullYear() && m==todaydate.getMonth()+1){
		dayNumberForToday = todaydate.getDate();
	}
	
	var t="";
	
	t+=asHTMLOpenTag("div", asHTMLAttribute("class", cssClassForDivAndTable));
	
	additionalTableAttributes =  asHTMLAttribute("cols", "7")
									+ asHTMLAttribute("cellpadding", "0")
									+ asHTMLAttribute("cellspacing", "0");
									
	t+= asHTMLOpenTag("table", asHTMLAttribute("class", cssClassForDivAndTable) + additionalTableAttributes );
	
	// first row has monthName and year
	t+=asHTMLOpenTag("tr", asHTMLAttribute("class", cssForTitle));
	
	t+= asHTMLOpenTag("td", asHTMLAttribute("colspan", "7") + asHTMLAttribute("class", cssForTitle) );
		
	previousMonthMethodCall = "previousMonth("+"'"+id.toString()+"'"+", '" + calendarJSONfn + "');";
	t+= asHTMLContainer("span",
				asHTMLAttribute("id", "previousMonthID")
				+ asHTMLAttribute("onClick", previousMonthMethodCall )
				+ asHTMLAttribute("style", "float: left;")
				, "&lt;");

	nextMonthMethodCall = "nextMonth("+"'"+id.toString()+"'"+", '" + calendarJSONfn + "');";
	t+= asHTMLContainer("span", 
				asHTMLAttribute("id", "nextMonthID")
				+ asHTMLAttribute("style", "float: right;")
				+ asHTMLAttribute("onClick", nextMonthMethodCall)
				, "&gt;");
	
	t+= monthName[m-1]+' '+year;
	
	t+=asHTMLCloseTag("td");
	t+= asHTMLCloseTag("tr");
	
	
	// 2nd row has day names
	t+= asHTMLOpenTag("tr", asHTMLAttribute("class", cssForDayNameRow));

	for(s=0;s<7;s++){
		 t+= asHTMLOpenTag("td");
		 t+= dayNames[s];
		 t+= asHTMLCloseTag("td");
	}
	t+= asHTMLCloseTag("tr");
	
	
	attributeToAlignTop = asHTMLAttribute("style", "vertical-align: top;");
	tableRowOpenTag =  asHTMLOpenTag("tr", attributeToAlignTop);
	
	var dayCellHTML2 = "";
	// iterate over day cells
	t+= tableRowOpenTag;
	for(i=1;i<=42;i++){
		var x=((i-oD.od>=0)&&(i-oD.od<dim[m-1]))? i-oD.od+1 : '&nbsp;';
		
		tagForToday = "";
		if (x==dayNumberForToday){
			tagForToday = asHTMLContainer("span", asHTMLAttribute("id", "today"), x);
		}else{
			tagForToday = x;
		}
		
		dayNumber = 0;
		additionalAttributeForDay = "";
		// the day cell
		if (x != '&nbsp;'){
			dayNumber = x;
			
			dateParameters = year.toString() + ", " + m.toString() + ", " + dayNumber.toString();
						
			functionToUse = "showDetailForDayWithJSON"; // or could be "showDetailForDay"			
			if (functionToUse == "showDetailForDayWithJSON"){
				functionCallText = "showDetailForDayWithJSON('"+calendarJSONfn+"', "+dateParameters + ");";
				
			} else if (functionToUse == "showDetailForDay"){
				theText = getTextForMonthDayYear(calendarJSON, m, dayNumber, year, "description");	
				functionCallText = "showDetailForDay('" + escape(theText)+"',"+ dateParameters + ");";			
			} else {
				// should blow up because this should never happen!
			}

			additionalAttributeForDay = asHTMLAttribute("onClick", functionCallText);
		}
		
		// 2009-0429 MAG - Was testing something... not needed now
		// isHoliday(calendarJSONfn, year, m, dayNumber);
		
		t+= asHTMLOpenTag("td", 
							asHTMLAttribute("class", cssForDay)
							+ additionalAttributeForDay
						);
		
		t+= asHTMLOpenTag("div", asHTMLAttribute("style", "min-height: 3em;"));
		
		additionalAttributeIfSelectedDay = "";
//		if (selectedDayNumber == x){
//			additionalAttributeIfSelectedDay = asHTMLAttribute("style", "background-color: blue;");
//		}
		
		// the number of the day
		t+= asHTMLContainer("div", 
							asHTMLAttribute("class", "dayNumber") + additionalAttributeIfSelectedDay,
							tagForToday);
		
		// the text inside the day cell, if any
		if (dayNumber > 0){
			// 2009-0428 MAG - the commented out lines didn't work
			// got an infinite loop, but I couldn't figure out why
//			dayCellHTML2 = getTextForMonthDayYear(calendarJSON, m, dayNumber, year, "teaser");
//			t+= asHTMLUnorderedList(dayCellHTML2, "");

//			dayCellHTML = getTextForMonthDayYear(calendarJSON, m, dayNumber, year, "teaser");
//			t+=asHTMLList(dayCellHTML, "", true);

			dayCellText = getTextForMonthDayYear(calendarJSON, m, dayNumber, year, "teaser");
			
			
			cssClassForTeaserInDayBox = "teaserInDayBox";	// FIXME: should be parameter?
			textLines = dayCellText.split("\n");
			t+=asHTMLOpenTag("ul", asHTMLAttribute("class", cssClassForTeaserInDayBox));
			for(q=0; q<textLines.length; q++){
				if(textLines[q] != undefined && textLines[q].length > 0){
					t+=asHTMLContainer("li", "", textLines[q]);
				}
			}
			// dayCellHTML = asHTMLContainer("div", asHTMLAttribute("style", "color: red;"), textLines[0]);
			t+=asHTMLCloseTag("ul");
			
			// t+=dayCellHTML;

//			t+=getTextForMonthDayYear(calendarJSON, m, dayNumber, year, "teaser");
		} else {
			// t+='*';	// date cells outside of this month
		}
		
		t+= asHTMLCloseTag("div");
		t+= asHTMLCloseTag("td");

		if (i%7 == 0){
			if (i > 28 && (dayNumber == 0)){
				break;
			}else{
				t+=asHTMLCloseTag("tr");
				t+= tableRowOpenTag;			
			}
		}
	}
	t+= asHTMLCloseTag("tr");
	t+= asHTMLCloseTag("table");
	t+= asHTMLCloseTag("div");	

	return t;
}


// if text is not found, return empty string
function getTextForMonthDayYear(calendarJSON, month, day, year, fieldName){
	theText = "";
	numberOfDateEntries = calendarJSON.dates.length;
	
	for(dateEntryIndex=0;dateEntryIndex<numberOfDateEntries;dateEntryIndex++){
		dateEntry = calendarJSON.dates[dateEntryIndex];
		dateField = dateEntry.date;	
		testDay = dateField.substring(7,9) - 0;
		testMonth = dateField.substring(5,7) - 0;
		testYear = dateField.substring(0,4) - 0;
		
		if ((day == testDay) && (month == testMonth) && (year == testYear)){
			if (fieldName == "teaser"){
				fieldData = dateEntry.teaser;
				
			} else if (fieldName == "description"){
				fieldData = dateEntry.description;
				
			} else if (fieldName == "date"){
				fieldData = dateEntry.date;
			
			} else {
				fieldData = dateEntry.date + ":" + dateEntry.teaser + "; " + dateEntry.description;
			}						
			theText += fieldData + "\n";
		}
	}
	return theText;
}





// receives escaped text in theText
// FIXME: should take css names as parameters
// dailyEventList
// DailyDescriptionTitle
// DailyDescription
// this is the HTML id of the element that will be replaced: descriptionForDay
function showDetailForDay(theText, year, month, day){
	theDate = new Date(year, month-1, day);

	if (theText == undefined || theText == ''){
		theText = "";	// "no text available";
	}else{
		theText = unescape(theText);
		theText = asHTMLOrderedList(theText, asHTMLAttribute("class", "dailyEventList"));
	}
	
	titleHTML = asHTMLContainer("div", asHTMLAttribute("class", "DailyDescriptionTitle"), theDate.toDateString() );
	html = asHTMLContainer("div", asHTMLAttribute("class", "DailyDescription"), titleHTML + theText);
	document.getElementById("descriptionForDay").innerHTML = html;
}

function showDetailForDayWithJSON(calendarJSONfn, year, month, day){
	calendarJSON = eval(calendarJSONfn);

	theDate = new Date(year, month-1, day);
	titleHTML = asHTMLContainer("div", asHTMLAttribute("class", "DailyDescriptionTitle"), theDate.toDateString() );
	
	html = "";
	haveDetail = false;
	html += asHTMLOpenTag("dl", asHTMLAttribute("class", "dailyEventList"));
	numberOfDateEntries = calendarJSON.dates.length;
	
	for(dateEntryIndex=0;dateEntryIndex<numberOfDateEntries;dateEntryIndex++){
		dateEntry = calendarJSON.dates[dateEntryIndex];
		dateField = dateEntry.date;	
		testDay = dateField.substring(7,9) - 0;
		testMonth = dateField.substring(5,7) - 0;
		testYear = dateField.substring(0,4) - 0;
		
		if ((day == testDay) && (month == testMonth) && (year == testYear)){
			html += asHTMLContainer("dt", "", dateEntry.teaser);
			html += asHTMLContainer("dd", "", dateEntry.description);
			haveDetail = true;
		}
	}	
	html += asHTMLCloseTag("dl");
	
	if (!haveDetail){
		html = "";
	}

	html = asHTMLContainer("div", asHTMLAttribute("class", "DailyDescription"), titleHTML + html);
	document.getElementById("descriptionForDay").innerHTML = html;
}


// learning:
// keypath must exist in JSON data structure or else javascript dies
function isHoliday(calendarJSONfn, year, month, day){

	if (year.toString()=="2009" && month.toString()=="5" && day.toString()=="16"){
		datePath = ".Year_"+year.toString() + ".Month_"+month.toString()+".Day_"+day.toString();
		keyPath = ".isSchoolDay";
		value = eval(calendarJSONfn + datePath + keyPath);
		alert("isHoliday(): value = "+value);
	}
	

	
	/*
	if (year.toString()=="2009" && month.toString()=="5" && day.toString()=="16"){

		// worked: calendarJSON.Year_2009.Month_5.Day_16.teaser
		alert("path.teaser = " + path+".teaser");
		alert(eval(calendarJSONfn+datePath+".teaser"));
	}
	*/
}



