// TO DO : 
// ADD START END TIMES AND DATE HANDLERS, 
//  USE DOM INSTEAD OF CREATING SOURCE HTML?
//  USE  DOM TO ADD SCRIPT ENTRY TO FETCH FROM GOOGLE


// ======= convert from google time to regular displyable format ======================================= 
function convertTime(gtime){ 
	// google time format 2008-06-09T16:00:00.000-07:00
	//                    01234567890123456378901234567
	//                    0         1          2     
	// so simplistically we would just use chars 11 - 15 minus 12 to convert to am/pm
	if (gtime.length<11) { return ""} 
	else {
		var hour = gtime.substr(11, 2);
		var mins = gtime.substr(14, 2);
		var ampm = (hour>11) ? 'pm' : 'am';
		hour = (hour>12) ? (hour-12) : hour; 
		return hour+':'+mins+ampm;
	}
	};
// ======== format a string that indicates range of event ============================= 
function getFromToTime(startTime12hr, endTime12hr) {
	var fromToTime = startTime12hr+"-"+endTime12hr;
	var onthehour = /:00/g;
	var amtoam = /am(.*)am/;
	var pmtopm = /pm(.*)pm/;
	var amtoamreplacement = "$1am";
	var pmtopmreplacement = "$1pm";
	
	var x = fromToTime.replace(onthehour, "");
	x = x.replace(amtoam, amtoamreplacement);
	x = x.replace(pmtopm, pmtopmreplacement);
	if (x=="-") {x=""}; // if no start and  end time
	return x;
	}
// =========== in case the user has entered a time in the title. this removes it======== 	
function stripTimeFromTitle(title) {
	var timeToTime = /(\d+(:\d+)*\s*((am)|(pm))*)\s*-\s*(\d+(:\d+)*\s*((am)|(pm)))/ig;
	
	var x = title.replace(timeToTime,"");
	
    return (x);
	}
// ======================= replaces links in the content with popups and teh word 'link' ===============================================	
function makeLinksInContent(content) {
	var searchforlink = /(http:[^\s]+)(\s|$)/g;
	var replacelink = ' <a href = "$1" class="popup">link</a> ';
	x = content.replace(searchforlink, replacelink);
	return x;
	}	
// ====================================================================================== listEvents
// This function creates the 'events' array from the feed provided by google
// each entry contains: MONTH, DAY, YEAR, START, END, FROMTOTIME, TITLE, CONTENT
function listEvents(root) {  // this gets called by the google get-json-in-script return
    var feed = root.feed;
    var entries = feed.entry || [];
    for (var i = 0; i < entries.length; ++i) { 
      var entry = entries[i];
      var title = entry.title.$t;
	  var content = entry.content.$t; if(content==undefined) {content = ""};
      var startTime = ((entry['gd$when']) ? entry['gd$when'][0].startTime : "");
	   var endTime = ((entry['gd$when']) ? entry['gd$when'][0].endTime : "");
	  var startYear = startTime.substr(0,4);
	  var startMonth = startTime.substr(5,2)-1; // adjust month to zero like javascript likes it
	  var startDay = startTime.substr(8,2);
	  var startTime12hr = convertTime(startTime);
	  var endTime12hr = convertTime(endTime);
	  var fromToTime = getFromToTime(startTime12hr, endTime12hr);
	  title = stripTimeFromTitle(  title);
	  content = makeLinksInContent(content);
      events.push( {
				  	"month":startMonth,
					"day":startDay,
					"year":startYear, 
					"start":startTime12hr, 
					"end":endTime12hr ,
					"fromToTime":fromToTime,
					"title":title, 
					"content":content});
    }
  }
// ====================================================================================== getEvents
function getEvents(day, month, year, nDays) {
// returns array of events for this date (month starts at 0)
// should be able to access this much more directly
// GLOBAL  VAR events
		 if (typeof nDays == "undefined") {
			nDays = 1;
		  }
		var d = new Date();
		d.setDate(day);
		d.setMonth(month);
		d.setYear(year);
		eventsOfTheDay = [];
		for (var x = 0; x < nDays; x++) {
				/*for (var i=0; i < events.length;  i++ ) {*/
				for ( var i = events.length - 1; i >= 0; i--) {
				      if (events[i].day == day && events[i].month == month && events[i].year == year ) {
					  			eventsOfTheDay.push(events[i]);
					  }
				}
				d.setDate(d.getDate()+1);
				day = d.getDate();
				month = d.getMonth();
				year = d.getFullYear();
		}
		return eventsOfTheDay;
}
/* ===========================================================================================================  previousMonthAndYear*/
function previousMonthAndYear(month, year ) {
		if (month == 0) {
			month = 11;
			year = year -1 ;
		} else
		{
			month = month - 1;
		}
		return [month, year];
}
/* ===========================================================================================================  nextMonthAndYear*/
function nextMonthAndYear( month, year) {
		if (month == 11) {
			month = 0;
			year = year + 1;
		} else {
			month = month + 1;
		}
	   return [ month, year ];
}
/* ===========================================================================================================  getDaysInMonth */
function getDaysInMonth(month,year)  {
		var days;
		month = month + 1; // to make it more readable.
		function isLeapYear (Year) {
				if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) {
				return (true);
				} else { return (false); }
		};
		if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
			{days=31;}
		else if (month==4 || month==6 || month==9 || month==11)
			{ days=30; }
		else if (month==2)  {
				if (isLeapYear(year))
				{ days=29; 	}
				else { days=28; }
		}
		return (days);
}
/* ===========================================================================================================  buildCalendarEntry*/
function getDayOfWeek (day, month, year) {
	var daysoftheweek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
	var date = new Date((month+1)+'/'+day+'/'+year); 
	return daysoftheweek[ date.getDay()];
	}
/* ===========================================================================================================  buildCalendarEntry*/
// the following should cycle through the calendar page calling the function calendarEntry(year, month, day)
function buildCalendarEntry( day, month, year, calendarPosition, monthClass ) {
    var e = getEvents(day, month, year); 
	var entryHTML = ""; // this will be the html for this entry

		entryHTML += (
			'<div class="calCell ' 
			+ monthClass + ' ' 
			+ ((e.length>0) ? "isEvents" : "") + '">') + '<span class="calendarDate"> ';
// get the titles from events for today and build a title to be used in a popup hover link	 for cuetip	(reallly for the minical)
		if (e.length>0) {
			/*var eList = [];
			for (var i=0; i<e.length; i++) {eList.push( e[i].title) ;};
			var titleString = (month+1) +'.' + day + '.' + year + '|' + eList.join('|');*/
			entryHTML += ('<a href="#" class="eventList">');
		};
		entryHTML +=  ( (day<10) ? ("&nbsp;" + day) : day );
		if  (e.length>0) { entryHTML += ('</a>'); };
		entryHTML += '</span>';
		entryHTML += buildEventList(day,month,year,1);
		entryHTML +=  ("</div>");
		if (6==calendarPosition%7) { entryHTML += ('<br class="clearFloat">')}; 
		//it would be better not to have to do the above  (eg. by relying on the css to set width of containing div such that floats 
		// happen in the right place)
		return entryHTML;
}
/* =========================================================================================================== buildCalendar */
function buildCalendar( day, month, year, fn) {
//
// This returns the html string that represents the calendar. Note that it is the same whether this is a large calendar or a mini version. The only difference 
// is the css styling that is applied, and that is done independently of the javascript
// This function actually just runs through the 42 calendar entries appropriate to the date, calling the html creation function 'fn' - this means that we 
// can tweak the function called to (eg.) manipulate the dom rather than directly building a string of html
//
		var days = getDaysInMonth(month,year);
		var firstOfMonth = new Date (year, month, 1);
		var startingPos = firstOfMonth.getDay(); // sunday = 0, monday = 1 etc
		var calendarHTML = ""; // this will hold the final calendar html
// prior month runs fro positions 0 to startingPos-1
// actual month runs from startingPos to days-1
// next month from days to 41 (giving us 6 rows of weeks)
		days += startingPos;
		before = previousMonthAndYear ( month, year ); // returns the month year for the previous month
		firstDate = getDaysInMonth( before[0] , before[1]) - startingPos + 1;
// ru n through the 42 calendar entries calling the callback fun ction with params date, month, year, calendar position and a class indicator
// the class indicator is a string 'priorMonth', 'currentMonth', 'currentMonth today', 'nextMonth'
		for (i = 0; i < startingPos; i++) {
				calendarHTML += fn(firstDate + i, before[0], before[1], i, "priorMonth");
		}
		for (i = startingPos; i < days; i++) {
				calendarDay = i-startingPos+1;
				calendarHTML += fn( calendarDay, month, year, i, (calendarDay==day) ?"currentMonth today" :"currentMonth");
		}
		for (i=days; i<42; i++)  {
				calendarDay =  i-days+1;
				calendarHTML += fn( calendarDay, nextMonthAndYear(month, year)[0], nextMonthAndYear(month, year)[1], i, "nextMonth");
		}
		return calendarHTML;
}
// ============================================================================================ buildFutureEvents
function buildEventList (day, month, year, nDays) { // THIS STYLE IS USED INSIDE THE CALENDAR CELL AND POPUPS
		var e = getEvents (day, month, year, nDays);
		var eventListHTML = "";
		for (var i = 0; i<e.length; i++){
		        var date = (e[i].month +1) +'-' + e[i].day + '-'+ e[i].year;
				eventListHTML += ( 
				'<div class="event"><span class="date">'
				+date+ '</span><span class="start">'
				+ e[i].fromToTime + ' </span><span class="title">'
				+ e[i].title
				+'</span>' 
				+ '<span class="content">'
				+e[i].content+
				'</span></div>');
		}
		
		return eventListHTML;
}
// ========================================================================================== build event list in 'list1' style
function buildEventList_style1 (day, month, year, nDays) {
// <div class="l1">
//    <h4><span>TITLE</span>START DATE</h4>
//    <p>CONTENT</p>
//</div>
		var e = getEvents (day, month, year, nDays); // get events for next n days
		var eventListHTML = "";                      // this will hold the html
		for (var i = 0; i<e.length; i++){            // loop through each event
		        var date = (e[i].month +1) +'-' + e[i].day + '-'+ e[i].year;
				var start = e[i].start;
				var title = e[i].title;
				var content = e[i].content;
				eventListHTML += 
				'<div class="list1"><h4><span>'+title+'</span>'+start+' '+ date+'</h4><p>'+content+'</p></div>';
		};
		
		
		return eventListHTML;
}
// ============================================================================================ 
function buildEventList_style2 (day, month, year, nDays, nEntries) {
// <div class="l1">
//    <h4><span>TITLE</span>START DATE</h4>
//    <p>CONTENT</p>
//</div>
		var e = getEvents (day, month, year, nDays); // get events for next n days
		var eventListHTML = "";                      // this will hold the html
		for (var i = 0; (i<e.length) && (i<nEntries); i++){            // loop through each event
		        var date = (e[i].month +1) +'/' + e[i].day + '/'+ e[i].year;
				var start = e[i].start;
				var title = e[i].title;
				var content = e[i].content;
				var dayofweek = getDayOfWeek(e[i].day ,e[i].month , e[i].year);
				eventListHTML += 
				'<div class="event"><span class="timeandday">'+dayofweek +' ' + (e[i].month+1) +'/'+(e[i].day)+'</span><span class="title">'+start+" "+title+'</span></div>';
		};
		
		
		return eventListHTML;
}
// ============================================================================================ 

function buildEventList_style3 (day, month, year, nDays, nEntries) {
// <div class="listcalendar">
//    <span class="calheader">
//			<span class="caldate">START DATE</span>
//			<span class="caltitle">TITLE</span>
//	  </span>
//    <p>CONTENT</p>
//</div>
		var e = getEvents (day, month, year, nDays); // get events for next n days
		var eventListHTML = "";                      // this will hold the html
		for (var i = 0; (i<e.length) && (i<nEntries); i++){            // loop through each event
		        var month = months[e[i].month]; // eg. June
				var day = e[i].day;              // eg. 25
				 
				var start = e[i].start;
				var title = e[i].title;
				var content = e[i].content;
				var dayname = getDayOfWeek( e[i].day , e[i].month, e[i].year);
				
				eventListHTML += 
				'<div class="listcalendar"><span class="calheader"><span class="timeandday">'+ dayname + ', ' + day + ' ' + month +' '+ start  + '</span><span class="title">'+title+'</span></span><p>'+content+'</p></div>';
		};
		
		
		return eventListHTML;
}
// ============================================================================================ 
