var MCEVENTTEXTCOLOUR = "#EB1400";
var MCEVENTBACKGROUNDCOLOUR = "#FFF3A7";
var MAXMARQUEECOUNT = 100;
var HEADERCOLOUR = "#888888";
var HEADERTEXTCOLOUR = "#000000";
var BCKGNDTEXTCOLOUR = "#000000";
var BCKGNDCOLOUR = "#FFFFFF";
var SS_NUM_TRG_PROG_ENTRIES_REQD = 6;
var SS_NUM_TRG_PROG_MAX_MONTHS_TO_ADVANCE = 2;

var FROM_FIRST_OF_NEXT_MONTH = 1;
var FROM_TODAY = 2;
var TO_END_OF_MONTH = 1;
var ONE_MONTH_EXACTLY = 2;
var TUESDAY = 2;
var FRIDAY = 5;
var HOME_PAGE_EVENTS = 1;
var DIARY_PAGE_EVENTS = 2;
var NEXT_10_EVENTS = 3;
var SS_CURRENT = 1;
var SS_NEXT = 2;

var ONEDAY  = (60*60*24*1000);
var ONEDAY_2 = (60*60*25*1000); // Quirk of Google Dates - If no start and end time set then the default is a 25hr day!
var SEVENDAYS = (ONEDAY * 7);
var TENDAYS = (ONEDAY * 10);

var MonthLong = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var MonthShort = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var DOTW = new Array("Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ","Saturday ");
var GotNext10 = false;
var Notices = new Array();
var StaffNotices = new Array();
var Newsflashes = new Array();
var ForthComingEvents=new Array();
var TrainingInfoEntryWhatsOn = new Array();
var ForthComingEventsNewUpdate=new Array();
var HTMLEventsString = "";
var HTMLTrgProgString = "";
var HTMLEmailString = "";
var GenerateComplete = false;
var GoogleError = false;
var ForthComingEventscounter = 0;
var contentcounter = 0;
var CurDay = -1;
var CurMonth = -1;
var CurYear = -1;
var EmailGeneration = false;
var TheMonth = -1;
var TheYear = -1;
var EmailIncludeEvents = 0;
var EmailIncludeTrgProg = 0;
var LoggedIn = 0;
var LastLogin = null;
var colourtouse = 0;
var EmailStartFrom = FROM_FIRST_OF_NEXT_MONTH;
var TodaysDate = new Date();
var UserType=-1;

/*************************************************************************/
/* Function: google.load                                                                             */
/*                                                                                                          */
/* Loads the Google data JavaScript client library                                       */
/*                                                                                                          */
/*************************************************************************/
try
{
	google.load("gdata", "1");
}
catch( e )
{
	GoogleError = true;
}

/*************************************************************************/
/* Function: GetPublicKey()                                                                               */
/*                                                                                                          */
/* The private key to access Public Dudhope Calendar                                 */
/*                                                                                                          */
/*************************************************************************/
function GetPublicKey()
{
	return "http://www.google.com/calendar/feeds/2450sqn@googlemail.com/private-19638468590e163bafa15e9947feb04b/full"
}

/*************************************************************************/
/* Function: GetPrivateKey()                                                                               */
/*                                                                                                          */
/* The private key to access Private Dudhope Calendar                                 */
/*                                                                                                          */
/*************************************************************************/
function GetPrivateKey()
{
	return "http://www.google.com/calendar/feeds/9b183f4iar0jcdrblilokgelto%40group.calendar.google.com/private-e0063c7a792f355de18e1617df8df348/full"
}
/*************************************************************************/
/* Function: initCal()                                                                               */
/*                                                                                                          */
/* Initialises the Calendars                                                                      */
/*                                                                                                          */
/*************************************************************************/
function initCal()
{
	if( !GoogleError )
	{
		// init the Google data JS client library with an error handler
		try
		{
			google.gdata.client.init(handleGDError);
		}
		catch( e )
		{
			GoogleError = true;
		}
	}
}


/*************************************************************************/
/* Function: padNumber()                                                                          */
/*                                                                                                          */
/* Adds a leading zero to a single-digit number.  Used for displaying dates.      */
/*                                                                                                          */
/*************************************************************************/
function padNumber(num)
{
	if (num <= 9)
	{
		return "0" + num;
	}
	return num;
}

/*************************************************************************/
/* Function: GetLastDate()                                                                        */
/*                                                                                                          */
/* Returns the number of days in a particular month                                     */
/*                                                                                                          */
/*************************************************************************/
function GetLastDate( navmonth )
{
	var lastDate;
	if(navmonth == 2)
	{
		// Feb - so 28 or 29 days
		var leapTestNumbers = TodaysDate.getFullYear() / 4;
		var leapTest = (leapTestNumbers) - Math.round(leapTestNumbers);

		if (leapTest != 0)
		{
			lastDate = 28;
		}
		else
		{
			lastDate = 29;
		}
	}
	else
	if (((navmonth == 4) || (navmonth == 6) || (navmonth == 9) || (navmonth == 11)))
	{
		lastDate = 30;
	}
	else
	{
		lastDate = 31;
	}

	return lastDate;
}

function FormatDate( theDate )
{
	switch( theDate )
	{
		case 1:
		case 21:
		case 31 :
		{
			return theDate.toString() + "st";
		}
		break;
		case 2: 
		case 22:
		{
			return theDate.toString() + "nd";
		}
		break;
		case 3:
		case 23:
		{
			return theDate.toString() + "rd";
		}
		break;
		default:
		{	
			return theDate.toString() + "th";
		}
		break;

	}

}
/*************************************************************************/
/* Function: loadHomePageCalendar()                                                           */
/*                                                                                                          */
/* Loods the events from the google calendar for the Home Page                    */
/*                                                                                                          */
/*************************************************************************/
function loadHomePageCalendar(theUserType)
{
	UserType = theUserType;
	
	initCal();

	// Mini-Calendar and Notices only. Interested in events from start of THIS month up to current date + 31 only
	var MonthStart = TodaysDate.getMonth()+1;
	var str_start = TodaysDate.getFullYear().toString() + "-" + MonthStart.toString() + "-01";

	var EndDate=new Date();
	EndDate.setDate(TodaysDate.getDate()+31);

	var MonthEnd = EndDate.getMonth()+1;
	var YeadEnd = EndDate.getFullYear();
	var MonthEndStr = padNumber(MonthEnd);
	var DayEndStr = padNumber(EndDate.getDate());

	var str_end = YeadEnd.toString() + "-" + MonthEndStr.toString() + "-" + DayEndStr.toString();
	str_end = YeadEnd.toString() + "-" + MonthEndStr.toString() + "-" + DayEndStr.toString();

	// LOAD TRG PROG, NOTICES AND NEWSFLASHES
	loadHomePageTrgPrg();

	// LOAD CALENDAR EVENTS
	loadCalendar(str_start, str_end, HOME_PAGE_EVENTS);
}

/*************************************************************************/
/* Function: loadDiaryCalendar()                                                                */
/*                                                                                                          */
/* Loods 2 calendars for the Diary Page - the Next 10 Events and the current */
/* months events                                                                                     */
/*                                                                                                          */
/*************************************************************************/
function loadDiaryCalendar( CurrentDay, CurrentMonth, CurrentYear, LoggedIn )
{
	CurMonth = CurrentMonth-1;
	CurYear = CurrentYear;
	CurDay = CurrentDay;
	IsLoggedIn = LoggedIn;

	initCal();

	// Next 10 Events Cal
	// Mini-Calendar and Notices only. Interested in events from start of THIS month up to current date + 31 only
	var MonthStart = TodaysDate.getMonth()+1;
	var str10_start = TodaysDate.getFullYear().toString() + "-" + MonthStart.toString() + "-01"
	var YearEnd = TodaysDate.getFullYear() + 2;
	var str_end = YearEnd.toString() + "-12-31"

	loadCalendar(str10_start, str_end, NEXT_10_EVENTS);

	// Diary Calendar. Interested in Month Specified + Next 10 events....so set a valid start date and end date far enough ahead to get next 10 events

	// start time
	var str_start = CurrentYear.toString() + "-";
	str_start+=CurMonth.toString() + "-01";

	// end time
	YearEnd = CurrentYear+1;
	str_end = YearEnd.toString() + "-12-31";

	loadCalendar(str_start, str_end, DIARY_PAGE_EVENTS);

	adjustHeight();
}


/*************************************************************************/
/* Function: loadCalendar()                                                                        */
/*                                                                                                          */
/* Uses Google data JS client library to retrieve a calendar feed from the     */
/* specified URL.  The feed is controlled by several query parameters and a     */
/* callback function is called to process the feed results.                              */
/*************************************************************************/
function loadCalendar( str_start, str_end, CalSelection )
{
	var service = null;
	var query = null;
	var MaxResults = 100;
	try
	{
		service = new google.gdata.calendar.CalendarService('gdata-js-client-samples-simple');
		queryPublic = new google.gdata.calendar.CalendarEventQuery(GetPublicKey());
		queryPrivate = new google.gdata.calendar.CalendarEventQuery(GetPrivateKey());
	}
	catch ( e )
	{
		GoogleError = true;
	}

	if(!GoogleError)
	{
		try
		{
			queryPublic.setOrderBy('starttime');
			queryPublic.setSortOrder('ascending');
			queryPublic.setSingleEvents(true);
		
			queryPrivate.setOrderBy('starttime');
			queryPrivate.setSortOrder('ascending');
			queryPrivate.setSingleEvents(true);
			
			if (CalSelection == NEXT_10_EVENTS)
			{
				queryPublic.setFutureEvents(true);
				queryPrivate.setFutureEvents(true);
				MaxResults = 10;
			}
			else
			{
				queryPublic.setFutureEvents(false);
				queryPrivate.setFutureEvents(false);
			}

			queryPublic.setMaxResults(MaxResults);
			queryPublic.setMinimumStartTime(str_start);
			queryPublic.setMaximumStartTime(str_end);
	
			queryPrivate.setMaxResults(MaxResults);
			queryPrivate.setMinimumStartTime(str_start);
			queryPrivate.setMaximumStartTime(str_end);
		}
		catch (e)
		{
			GoogleError=true;
		}
	} 
	

	switch(CalSelection)
	{
		case HOME_PAGE_EVENTS: 	
				{
					if(!GoogleError )
					{
						try
						{
							if(UserType==3)	
								service.getEventsFeed(queryPrivate, listStaffEventsHomePage, handleGDError);
							service.getEventsFeed(queryPublic, listEventsHomePage, handleGDError);
						}
						catch(e)
						{
							listEventsHomePage(null);
							GoogleError=true;
						}
					}
					else
						listEventsHomePage(null);
				}
				break;
		case DIARY_PAGE_EVENTS: 
				{
					if(!GoogleError )
					{
						try
						{
							service.getEventsFeed(queryPublic, listEventsDiaryPage, handleGDError);
						}
						catch(e)
						{
							listEventsDiaryPage(null);
							GoogleError=true;
						}
					}
					else
						listEventsDiaryPage(null);
				}
				break;
		case NEXT_10_EVENTS:
		{
					// only do this once as should not change, unless using around midnight or left open
					if( !GotNext10 && !GoogleError)
					{
						try
						{
							service.getEventsFeed(queryPublic, listNext10Events, handleGDError);
							GotNext10 = true;
						}
						catch(e)
						{
							GoogleError=true;
							GotNext10 = false;
						}
						
					}
				}
				break;

		default:	
				break;
	}


}

/*************************************************************************/
/* Function: handleGDError()                                                                     */
/*                                                                                                          */
/* Callback function for the Google data JS client library to call when an       */
/* error  occurs during the retrieval of the feed.  Details available                */
/* depend partly on the web browser, but this shows a few basic examples. In   */
/* the case of a privileged environment using ClientLogin authentication, there */
/* may also be an e.type attribute in some cases.                                           */
/*************************************************************************/
function handleGDError(e)
{
	if (e instanceof Error)
	{
		//  with the error line number, file and message
		//alert('Error at line ' + e.lineNumber +          ' in ' + e.fileName + '\n' +          'Message: ' + e.message);
		// if available, output HTTP error code and status text
		if (e.cause)
		{
			var status = e.cause.status;
			var statusText = e.cause.statusText;
			//alert('Root cause: HTTP error ' + status + ' with status text of: ' +             statusText);
		}
	}
	else
	{
		//alert(e.toString());
	}
}


TitleText = new Array();

// POPULATES MINI CALENDAR AND WHAT'S ON DIV ON HOME PAGE WITH EVENTS FROM GOOGLE CALENDAR
function listEventsHomePage(feedRoot)
{
	// For timing - when we get here we can also add the training programme entries 
	ProcessAndAddNoticesAndNewsFlashesToHomePage();
	ProcessAndAddTrainingProgrammeToHomePage();
	
	var entries = null;
	var ul = document.createElement('ul');
	var len = 0;
	var WhatsOnDiv = null;
	var ForthcomingEventsDiv = null;
	var HomePageWhatsOnDiv = document.getElementById("WhatsOn");
	var HomePageForthcomingEventsDiv = document.getElementById("ForthcomingEvents");
	var dateString = "";
	
	// loop through each event in the feed
	if( feedRoot != null)
	{
		entries = feedRoot.feed.getEntries();
		len = entries.length;
	}

	for (var i = 0; i < len; i++)
	{
		var entry = entries[i];
		var title = entry.getTitle().getText();
		
		var location = entry.getLocations();
		var content = entry.getContent();
		var times = entry.getTimes();
		
		var updated = entry.getUpdated().getValue().getDate();
		var UpdatedDate = new Date(updated);
				
		var startDateTime = null;
		var startJSDate = null;
		var startJSMonth = null;
		var startJSYear = null;
		var endDateTime = null;
		var endJSDate = null;
		var endJSMonth = null;
		var endJSYear = null;
		var times = entry.getTimes();

		ForthComingEvents[ForthComingEventscounter] = "";
		ForthComingEventsNewUpdate[ForthComingEventscounter] = false;
		
		if (times.length > 0)
		{
			startDateTime = times[0].getStartTime();
			startJSDate = startDateTime.getDate();
			startJSMonth = startJSDate.getMonth();
			startJSYear = startJSDate.getFullYear();
			endDateTime = times[0].getEndTime();
			endJSDate = endDateTime.getDate();
			endJSMonth = endJSDate.getMonth();
			endJSYear = endJSDate.getFullYear();
		}

		// Split off Cadets and Staff and SO from the Title
		var TestTitle = title.toUpperCase();
		var staffonly = TestTitle.indexOf('(SO)');
		var staff = TestTitle.indexOf('(STAFF');
		var cadets = TestTitle.indexOf('(CADETS');

		// Find the 1st occurance
		var HUGEVALUE = 999999;
		var FirstOccurance = HUGEVALUE;

		if( staffonly != -1)
			FirstOccurance = staffonly;

		if( staff != -1)
			FirstOccurance = Math.min (FirstOccurance, staff);

		if( cadets != -1)
			FirstOccurance = Math.min (FirstOccurance, cadets);

		var titletodisplay = null;

		if( FirstOccurance != HUGEVALUE )
		{
			// if a non-zero value then remove string from title for displaying
			titletodisplay = title.substring(0, FirstOccurance-1);
		}
		else
			titletodisplay = title;


		if( startJSDate.getTime() > TodaysDate || endJSDate.getTime() > TodaysDate)
		{
			dateString = padNumber(startJSDate.getDate()) ;
			var texttodisplay = dateString;

			// ADD END DATE TOO IF ENDS ON A DIFFERENT DAY
			if (startDateTime.isDateOnly() && 
			( ( !endDateTime.isDateOnly() && ((endJSDate.getTime() - startJSDate.getTime() ) > ONEDAY) )
			|| (endDateTime.isDateOnly() && ( (endJSDate.getTime() - startJSDate.getTime() ) > ONEDAY_2)) )) // yes - it's a weird value slighly greater than one day 
			{
				//if spans more than one day then add end date
				var EndDate=new Date();
				EndDate.setDate(endJSDate.getDate()-1);
				var enddateString = padNumber(EndDate.getDate()) + " " + MonthShort[endJSDate.getMonth()];
				
				if(startJSMonth == endJSDate.getMonth())
					texttodisplay += " to " + enddateString ;
				else
					texttodisplay += " " + MonthShort[startJSMonth] + " to " + enddateString ;				
			}
			else if ( !startDateTime.isDateOnly() && (( startJSDate.getDay() != endJSDate.getDay()) || (startJSDate.getMonth() != endJSDate.getMonth()) || (startJSDate.getFullYear() != endJSDate.getFullYear())  ))
			{
				var enddateString = padNumber(endJSDate.getDate())  + " " + MonthShort[endJSDate.getMonth()];
				if(startJSMonth == endJSDate.getMonth())
					texttodisplay += " to " + enddateString ;
				else
					texttodisplay += " " + MonthShort[startJSMonth] + " to " + enddateString ;	
			}
			else
			{
				// Single day so add month
				texttodisplay += " " + MonthShort[startJSMonth];
			}

			if ( LoggedIn==1 && UpdatedDate > LastLogin )
				ForthComingEventsNewUpdate[ForthComingEventscounter] = true;
				
			ForthComingEvents[ForthComingEventscounter] = texttodisplay + '  -  ' + titletodisplay;// + " " + ForthComingEventsNewUpdate[ForthComingEventscounter] ;
			ForthComingEventscounter++;			
			
			// If logged in then add tooltip if there is more information to display for this event
			var titletext="";
			var includetitletext=false; // so we don't include if everything set to 'no further information'
		
				if ( !startDateTime.isDateOnly() )
				{
					if(( startJSDate.getDay() != endJSDate.getDay()) || (startJSDate.getMonth() != endJSDate.getMonth()) || (startJSDate.getFullYear() != endJSDate.getFullYear())  )
					{
						includetitletext=true;
						titletext = "Time: " + startJSDate.getHours() + ":" + padNumber(startJSDate.getMinutes()) + " Hrs - " + endJSDate.getHours() + ":" + padNumber(endJSDate.getMinutes()) + " Hrs"  + " on " + endJSDate.getDate() + " " + MonthShort[endJSDate.getMonth()];
					}
				}
				else if ((endJSDate.getTime() - startJSDate.getTime()) > ONEDAY_2)  //Only have day month year but we do know that it spans more than one day so can mention that!
				{
					var EndDate=new Date();
					EndDate.setDate(endJSDate.getDate()-1);

					includetitletext=true;
					titletext = "Time: " + startJSDate.getDate() + " " + MonthShort[startJSDate.getMonth()] + " - " + EndDate.getDate() + " " + MonthShort[endJSDate.getMonth()];
				}
				else
					titletext = "Time: No further info";
				
				if( location[0].getValueString() != undefined && location[0].getValueString() != "" )
				{
					if(titletext!="")
						titletext+="<br/>";
					includetitletext=true;
					titletext += "Location: " + location[0].getValueString();
				}
				else
					titletext = "Location: No further info";
	
				if( content.getText() !=undefined && content.getText() != "" )
				{
					if(titletext!="")
						titletext+="<br/>";
					includetitletext=true;
					titletext += "Details: " + content.getText() ;
				}
				else
					titletext = "Details: No further info";
	
				/*if( cadetstodisplay != null )
				{
					Cadets[startJSDate.getDate()] [NoofEntries] = cadetstodisplay;
					titletext += "<br /><font size='1'>Cadets: " + Cadets[startJSDate.getDate()] [NoofEntries] + "</font>" ;
				}
	
				if( stafftodisplay != null )
				{
					Staff[startJSDate.getDate()] [NoofEntries] = stafftodisplay;
					titletext += "<br /><font size='1'>Staff: " + Staff[startJSDate.getDate()] [NoofEntries] + "</font>" ;
				}*/				
			
			//if start or end date within 7 days then add it to the Whats On section, otherwise add it to the forthcoming events section
			if( ((startJSDate.getTime() - TodaysDate.getTime()) <  SEVENDAYS ) || ( (endJSDate.getTime() - TodaysDate.getTime()) < SEVENDAYS) )
			{
				if(WhatsOnDiv == null)
				{
					WhatsOnDiv = document.createElement("div");
					if(WhatsOnDiv)
					{
						var br =  document.createElement("br");
						WhatsOnDiv.appendChild(br);
						ul = document.createElement('ul');
						ul.innerHTML = "This Week's Events"						
					}
				}
	
				if(WhatsOnDiv)
				{
					li = document.createElement('li');
					
					if(LoggedIn==1 && includetitletext)
					{
						// Logged in and event has further details so add a tooltip (done by adding a title element) and bold the text...
						titletext = "<b><center>" + titletodisplay + "</center></b>" + titletext;
						li.innerHTML=texttodisplay + '  -  ' + titletodisplay;
						li.setAttribute('title', titletext);
						li.setAttribute('style','font-weight:bold;');
						li.setAttribute('href', 'diary.asp?month=' + (startJSMonth+1) + '&year=' + startJSYear);
					}
					/*else if(includetitletext)
					{
						// Not logged in so set up a link instead...
						var aElem = document.createElement('a');
						aElem.href='diary.asp?month=' + (startJSMonth+1) + '&year=' + startJSYear;
						//Append the <a> text node to the <a> element
						aElem.appendChild(document.createTextNode(texttodisplay + '  -  ' + titletodisplay));
						li.appendChild(aElem);
					}*/
					else
					{
						li.appendChild(document.createTextNode(texttodisplay + '  -  ' + titletodisplay));
					}
					
					ul.appendChild(li);					
				}
			}
			else
			{
				// Add to Forthcoming Events table instead
				
				if(ForthcomingEventsDiv == null)
				{
					ForthcomingEventsDiv = document.createElement("div");
					if(ForthcomingEventsDiv)
					{
						var br =  document.createElement("br");
						ForthcomingEventsDiv.appendChild(br);
						ul = document.createElement('ul');
						ul.innerHTML = "In The Next Month"						
					}
				}
	
				if(ForthcomingEventsDiv)
				{
					li = document.createElement('li');
					li.appendChild(document.createTextNode(texttodisplay + '  -  ' + titletodisplay));
					ul.appendChild(li);					
				}
			
			}
		}

		
		if(HomePageWhatsOnDiv && WhatsOnDiv)
		{
			WhatsOnDiv.appendChild(ul);	
			HomePageWhatsOnDiv.appendChild( WhatsOnDiv );	
		}
				
		if(HomePageForthcomingEventsDiv && ForthcomingEventsDiv)
		{
			ForthcomingEventsDiv.appendChild(ul);	
			HomePageForthcomingEventsDiv.appendChild( ForthcomingEventsDiv );	
		}

		// Add to the Mini-Calendar...........
		if(TodaysDate.getMonth() == startJSMonth)
		{
			var idstring = "theDate" + startJSDate.getDate();
			var calendarDiv = document.getElementById(idstring);

			if(calendarDiv)
			{
				for(var loop = calendarDiv.childNodes.length-1; loop >=0; loop--)
					calendarDiv.removeChild(calendarDiv.childNodes[loop]);

				var entryLink = document.createElement('a');
				var hreftext = "diary.asp?year=" + TodaysDate.getFullYear() + "&month=" + (startJSMonth+1) + "&day=" + startJSDate.getDate();
				entryLink.setAttribute('href', hreftext);
				entryLink.appendChild(document.createTextNode(startJSDate.getDate()));
				calendarDiv.appendChild(entryLink);

				calendarDiv.style.fontWeight="bold";
				calendarDiv.style.color = MCEVENTTEXTCOLOUR;
				calendarDiv.style.backgroundColor = MCEVENTBACKGROUNDCOLOUR;
			}


			if(TitleText[startJSDate.getDate()] != undefined)
				TitleText[startJSDate.getDate()] += ('<br />' + titletodisplay);
			else
				TitleText[startJSDate.getDate()] = titletodisplay;
		}

	}

	//Loop around settin all borders to WHITE except for TODAY which will be set to RED
	for( var borderloop = 1; borderloop <= GetLastDate( TodaysDate.getMonth() + 1);  borderloop++ )
	{
		// Set Today to RED
		var idborderstring = "theDate" + borderloop;
		var calendarborderDiv = document.getElementById(idborderstring);

		if (calendarborderDiv)
		{
			if( borderloop == TodaysDate.getDate())
				calendarborderDiv.style.border="1px solid " + MCEVENTTEXTCOLOUR;
			else
				calendarborderDiv.style.border="1px solid #FFFFFF";
		}

	}

	// Remove the "Generating, Please wait" line
	var HomePageStaffWhatsOnDiv = document.getElementById("StaffWhatsOn");
	if (HomePageStaffWhatsOnDiv.childNodes.length>1)
		HomePageStaffWhatsOnDiv.removeChild(HomePageStaffWhatsOnDiv.childNodes[1]);
	
	adjustHeight();
}



// POPULATES MINI CALENDAR AND WHAT'S ON DIV ON HOME PAGE WITH ***********STAFF********EVENTS FROM GOOGLE CALENDAR
function listStaffEventsHomePage(feedRoot)
{
	ProcessAndAddStaffNoticesAndNewsFlashesToHomePage();
	
	var entries = null;
	var ul = document.createElement('ul');
	var len = 0;
	var WhatsOnDiv = null;
	var ForthcomingEventsDiv = null;
	var HomePageWhatsOnDiv = document.getElementById("StaffWhatsOn");
	var HomePageForthcomingEventsDiv = document.getElementById("StaffForthcomingEvents");
	var dateString = "";
	
	// loop through each event in the feed
	if( feedRoot != null)
	{
		entries = feedRoot.feed.getEntries();
		len = entries.length;
	}

	for (var i = 0; i < len; i++)
	{
		var entry = entries[i];
		var title = entry.getTitle().getText();
		
		var updated = entry.getUpdated().getValue().getDate();
		var UpdatedDate = new Date(updated);
				
		var startDateTime = null;
		var startJSDate = null;
		var startJSMonth = null;
		var startJSYear = null;
		var endDateTime = null;
		var endJSDate = null;
		var endJSMonth = null;
		var endJSYear = null;
		var times = entry.getTimes();

		ForthComingEvents[ForthComingEventscounter] = "";
		ForthComingEventsNewUpdate[ForthComingEventscounter] = false;
		
		if (times.length > 0)
		{
			startDateTime = times[0].getStartTime();
			startJSDate = startDateTime.getDate();
			startJSMonth = startJSDate.getMonth();
			startJSYear = startJSDate.getFullYear();
			endDateTime = times[0].getEndTime();
			endJSDate = endDateTime.getDate();
			endJSMonth = endJSDate.getMonth();
			endJSYear = endJSDate.getFullYear();
		}

		// Split off Cadets and Staff and SO from the Title
		var TestTitle = title.toUpperCase();
		var staffonly = TestTitle.indexOf('(SO)');
		var staff = TestTitle.indexOf('(STAFF');
		var cadets = TestTitle.indexOf('(CADETS');

		// Find the 1st occurance
		var HUGEVALUE = 999999;
		var FirstOccurance = HUGEVALUE;

		if( staffonly != -1)
			FirstOccurance = staffonly;

		if( staff != -1)
			FirstOccurance = Math.min (FirstOccurance, staff);

		if( cadets != -1)
			FirstOccurance = Math.min (FirstOccurance, cadets);

		var titletodisplay = null;

		if( FirstOccurance != HUGEVALUE )
		{
			// if a non-zero value then remove string from title for displaying
			titletodisplay = title.substring(0, FirstOccurance-1);
		}
		else
			titletodisplay = title;


		if( startJSDate.getTime() > TodaysDate || endJSDate.getTime() > TodaysDate)
		{
			dateString = padNumber(startJSDate.getDate())  + " " + MonthShort[startJSMonth];
			var texttodisplay = dateString;

			// ADD END DATE TOO IF ENDS ON A DIFFERENT DAY
			if (startDateTime.isDateOnly() && ( (endJSDate.getTime() - startJSDate.getTime() ) > ONEDAY))
			{
				//if spans more than one day then add end date
				var EndDate=new Date();
				EndDate.setDate(endJSDate.getDate()-1);

				var enddateString = padNumber(EndDate.getDate())  + " " + MonthShort[endJSDate.getMonth()];
				texttodisplay += " to " + enddateString;
			}
			else if ( !startDateTime.isDateOnly() && (( startJSDate.getDay() != endJSDate.getDay()) || (startJSDate.getMonth() != endJSDate.getMonth()) || (startJSDate.getFullYear() != endJSDate.getFullYear())  ))
			{
				var enddateString = padNumber(endJSDate.getDate())  + " " + MonthShort[endJSDate.getMonth()];
				texttodisplay += " to " + enddateString;
			}

			if ( LoggedIn==1 && UpdatedDate > LastLogin )
				ForthComingEventsNewUpdate[ForthComingEventscounter] = true;
				
			ForthComingEvents[ForthComingEventscounter] = texttodisplay + '  -  ' + titletodisplay;
			ForthComingEventscounter++;
			
			//if start or end date within 7 days then add it to the Whats On section, otherwise add it to the forthcoming events section
			
			if( ((startJSDate.getTime() - TodaysDate.getTime()) <  SEVENDAYS ) || ( (endJSDate.getTime() - TodaysDate.getTime()) < SEVENDAYS) )
			{
				if(WhatsOnDiv == null)
				{
					WhatsOnDiv = document.createElement("div");
					if(WhatsOnDiv)
					{
						ul = document.createElement('ul');
						ul.innerHTML = "Staff Info"	
						ul.style.color = "#FF0000";						
					}
				}
	
				if(WhatsOnDiv)
				{
					li = document.createElement('li');
					li.appendChild(document.createTextNode(texttodisplay + '  -  ' + titletodisplay));
					ul.appendChild(li);					
				}
			}
			else
			{
				// Add to Forthcoming Events table instead
				
				if(ForthcomingEventsDiv == null)
				{
					ForthcomingEventsDiv = document.createElement("div");
					if(ForthcomingEventsDiv)
					{
						var br =  document.createElement("br");
						ForthcomingEventsDiv.appendChild(br);
						ul = document.createElement('ul');
						ul.innerHTML = "Staff Info for Next Month"
						ul.style.color = "#FF0000";						
					}
				}
	
				if(ForthcomingEventsDiv)
				{
					li = document.createElement('li');
					li.appendChild(document.createTextNode(texttodisplay + '  -  ' + titletodisplay));
					ul.appendChild(li);					
				}
			
			}
		}
		
		
		if(HomePageWhatsOnDiv && WhatsOnDiv)
		{
			WhatsOnDiv.appendChild(ul);	
			HomePageWhatsOnDiv.appendChild( WhatsOnDiv );	
		}
				
		if(HomePageForthcomingEventsDiv && ForthcomingEventsDiv)
		{
			ForthcomingEventsDiv.appendChild(ul);	
			HomePageForthcomingEventsDiv.appendChild( ForthcomingEventsDiv );	
		}

		// Add to the Mini-Calendar...........
		if(TodaysDate.getMonth() == startJSMonth)
		{
			var idstring = "theDate" + startJSDate.getDate();
			var calendarDiv = document.getElementById(idstring);

			if(calendarDiv)
			{
				for(var loop = calendarDiv.childNodes.length-1; loop >=0; loop--)
					calendarDiv.removeChild(calendarDiv.childNodes[loop]);

				var entryLink = document.createElement('a');
				var hreftext = "diary.asp?year=" + TodaysDate.getFullYear() + "&month=" + (startJSMonth+1) + "&day=" + startJSDate.getDate();
				entryLink.setAttribute('href', hreftext);
				entryLink.appendChild(document.createTextNode(startJSDate.getDate()));
				calendarDiv.appendChild(entryLink);

				calendarDiv.style.fontWeight="bold";
				calendarDiv.style.color = MCEVENTTEXTCOLOUR;
				calendarDiv.style.backgroundColor = MCEVENTBACKGROUNDCOLOUR;
			}


			if(TitleText[startJSDate.getDate()] != undefined)
				TitleText[startJSDate.getDate()] += ('<br />' + titletodisplay);
			else
				TitleText[startJSDate.getDate()] = titletodisplay;
		}

	}

	//Loop around settin all borders to WHITE except for TODAY which will be set to RED
	for( var borderloop = 1; borderloop <= GetLastDate( TodaysDate.getMonth() + 1);  borderloop++ )
	{
		// Set Today to RED
		var idborderstring = "theDate" + borderloop;
		var calendarborderDiv = document.getElementById(idborderstring);

		if (calendarborderDiv)
		{
			if( borderloop == TodaysDate.getDate())
				calendarborderDiv.style.border="1px solid " + MCEVENTTEXTCOLOUR;
			else
				calendarborderDiv.style.border="1px solid #FFFFFF";
		}

	}

	adjustHeight();
}



// POPULATES HOME PAGE WITH TRG PROG, NOTICES AND NEWSFLASHES
function loadHomePageTrgPrg()
{
	var ul = document.createElement('ul');
	var len = 0;


	for( var trgprogloop = 1; trgprogloop <= 31; trgprogloop++)
	{
		if( TrainingInfo[trgprogloop] != null && (TrainingInfo[trgprogloop][4]!="" ||  TrainingInfo[trgprogloop][7]!=""))
		{
			// add it to the CalendarDiv
			var idstring = "theDate" + trgprogloop;
			var calendarDiv = document.getElementById(idstring);

			if(calendarDiv)
			{
				if(calendarDiv.style.color != MCEVENTTEXTCOLOUR)
				{
					for(var loop = calendarDiv.childNodes.length-1; loop >=0; loop--)
						calendarDiv.removeChild(calendarDiv.childNodes[loop]);

					var entryLink = document.createElement('a');
					var hreftext = "diary.asp?year=" + TodaysDate.getFullYear() + "&month=" + (TodaysDate.getMonth()+1) + "&day=" + trgprogloop;
					entryLink.setAttribute('href', hreftext);
					entryLink.appendChild(document.createTextNode(trgprogloop));
					calendarDiv.appendChild(entryLink);

					calendarDiv.style.fontWeight="bold";
					calendarDiv.style.color = MCEVENTTEXTCOLOUR;
					calendarDiv.style.backgroundColor = MCEVENTBACKGROUNDCOLOUR;
				}
			}
		}
	}

	//Loop around setting all borders to WHITE except for TODAY which will be set to RED
	for( var borderloop = 1; borderloop <= GetLastDate( TodaysDate.getMonth() + 1);  borderloop++ )
	{
		// Set Today to RED
		var idborderstring = "theDate" + borderloop;
		var calendarborderDiv = document.getElementById(idborderstring);

		if (calendarborderDiv)
		{
			if( borderloop == TodaysDate.getDate())
				calendarborderDiv.style.border="1px solid " + MCEVENTTEXTCOLOUR;
			else
				calendarborderDiv.style.border="1px solid #FFFFFF";
		}

	}

	initialiseImages();
}


// POPULATES NEXT 10 EVENTS FOR DIARY - ONLY NEEDS CALLED ONCE
function listNext10Events(feedRoot)
{
	var entries = null;
	var ul = document.createElement('ul');
	var NoofEntries = 0;
	var CurrentMonth = -1;
	var Next10EventsDiv = document.getElementById("EventsDiv");
	var len = 0;
	var dateString = "";

	// loop through each event in the feed
	if( feedRoot != null)
	{
		entries = feedRoot.feed.getEntries();
		len = entries.length;
	}

	for (var i = 0; i < len; i++)
	{
		var entryfound = false;

		var entry = entries[i];
		var title = entry.getTitle().getText();

		var startDateTime = null;
		var startJSDate = null;
		var startJSMonth = null;

		var times = entry.getTimes();
		if (times.length > 0)
		{
			startDateTime = times[0].getStartTime();
			startJSDate = startDateTime.getDate();
			startJSDay = startJSDate.getDate();
			startJSMonth = startJSDate.getMonth();
			startJSYear = startJSDate.getFullYear();
		}

		dateString = padNumber(startJSDate.getDate())  + " " + MonthShort[startJSMonth];

		// Add to the Next 10 Events list....
		if(( startJSDate >TodaysDate  && NoofEntries < 10) ||
			((TodaysDate.getDate() == startJSDay) && (TodaysDate.getMonth() == startJSMonth) && (TodaysDate.getFullYear() == startJSYear)))
		{
			if( startJSDate.getMonth() != CurrentMonth )
			{
				//Need to close off previous month and start a new month

				// close off old month
				if(ul && Next10EventsDiv)
				{
					var li = document.createElement('li');
					li.appendChild(document.createTextNode(" "));
					ul.appendChild(li);
					Next10EventsDiv.appendChild(ul);
				}

				// Start new month
				ul = document.createElement('ul');
				CurrentMonth = startJSDate.getMonth();

				ul.innerHTML = "<br/>" + MonthLong[CurrentMonth] ;
				var li = document.createElement('li');
				li.appendChild(document.createTextNode(" "));
				ul.appendChild(li);
			}

			NoofEntries++;

			// Split off Cadets and Staff and SO from the Title
			var TestTitle = title.toUpperCase();
			var staffonly = TestTitle.indexOf('(SO)');
			var staff = TestTitle.indexOf('(STAFF');
			var cadets = TestTitle.indexOf('(CADETS');

			// Find the 1st occurance
			var HUGEVALUE = 999999;
			var FirstOccurance = HUGEVALUE;

			if( staffonly != -1)
				FirstOccurance = staffonly;
			if( staff != -1)
				FirstOccurance = Math.min (FirstOccurance, staff);
			if( cadets != -1)
				FirstOccurance = Math.min (FirstOccurance, cadets);

			var titletodisplay = null;

			if( FirstOccurance != HUGEVALUE )
			{
				// if a non-zero value then remove string from title for displaying
				titletodisplay = title.substring(0, FirstOccurance-1);
			}
			else
				titletodisplay = title;

			var li = document.createElement('li');
			li.appendChild(document.createTextNode(dateString + " - " + titletodisplay));
			ul.appendChild(li);
		}
	}

	if ( Next10EventsDiv && ul )
	{
		Next10EventsDiv.appendChild(ul);
	}

	// Update Next 10 Events list with actual number found
	var NoofEventsHeader = document.getElementById("NoofEvents");
	if(NoofEntries>0)
	{
		NoofEventsHeader.appendChild(document.createTextNode("Next " + NoofEntries + " Events"));
	}
	else
	{
		NoofEventsHeader.appendChild(document.createTextNode("No More Events"));
	}

}


// POPULATE DIARY CALENDAR
var Title = new Array(32);
var Staff = new Array(32);
var Location = new Array(32)
var Details = new Array(32);
var Times = new Array(32);
var Cadets = new Array(32);


// THIS FUNCTION USED BOTH FOR DIARY CALENDAR AND GENERATING MONTHLY E_MAILS
/*************************************************************************/
/* Function: listEventsDiaryPage(feedRoot)                                                 */
/*                                                                                                          */
/* Function is used to poulate the Diary Pages (calendarDiv will not be null     */
/* for this case) OR generate the strings used for the e-mail generation        */
/* (appropriate flags set to handle this case)                                              */
/*                                                                                                          */
/*************************************************************************/
function listEventsDiaryPage(feedRoot)
{
	// Initialise arrays where each event will be stored
	for (var loop = 1; loop <= 31; loop++)
	{
		Title[loop] = new Array();
		Staff[loop] = new Array();
		Location[loop] = new Array();
		Details[loop] = new Array();
		Times[loop] = new Array();
		Cadets[loop] = new Array();
	}

	var entries = null;
	var len = 0;
	var ul = null;
	var CurrentDay = -1;
	var calendarDiv  = null;
	var NoofEntries = 0;
	var tableopen = false;
	
	HTMLEventsString = "<div align='center' width='600' style='text-align:center'><font size='4' color='#FF0000'>Forthcoming Events</font><br /><br />"

	if( feedRoot != null )
	{
		entries = feedRoot.feed.getEntries();
		len = entries.length;
	}

	// loop through each event in the feed
	for (var i = 0; i < len; i++)
	{
		var entryfound = false;

		var entry = entries[i];
		var title = entry.getTitle().getText();

		var startDateTime = null;
		var startJSDate = null;
		var startJSMonth = null;

		var times = entry.getTimes();
		var location = entry.getLocations();
		var content = entry.getContent();

		if (times.length > 0)
		{
			startDateTime = times[0].getStartTime();
			endDateTime = times[0].getEndTime();
			endJSDate = endDateTime.getDate();
			startJSDate = startDateTime.getDate();
			startJSDay = startJSDate.getDate();
			startJSMonth = startJSDate.getMonth();
			startJSYear = startJSDate.getFullYear();
		}

		var dateString = padNumber(startJSDate.getDate())  + " " + MonthShort[startJSMonth];

		// Add to this months Diary...........
		if( ( (CurMonth == startJSMonth) && (CurYear == startJSYear) ) || EmailGeneration == true ) // FOR EMAIL WE HAVE SPECIFIED DATE RANGE APPROPRIATELY SO DON@T NEED TO TEST DATES
		{
			if (CurrentDay != startJSDate.getDate() || CurrentMonth != startJSMonth)
			{
				//Need to close off previous month and start a new month

				// close off old month
				if(ul && calendarDiv)
				{
						calendarDiv.appendChild(ul);
				}

				// Start new month
				ul = document.createElement('ul');
				CurrentDay = startJSDay;
				CurrentMonth = startJSMonth;
				NoofEntries=0;
			}


			var idstring = null;
			idstring = "theDate" + startJSDate.getDate();

			calendarDiv = document.getElementById(idstring); //For E-mails this will be null
			if(calendarDiv)
			{
				calendarDiv.style.fontWeight="bold";
				calendarDiv.style.color = MCEVENTTEXTCOLOUR;
				calendarDiv.style.backgroundColor = MCEVENTBACKGROUNDCOLOUR;
			}

			// Split off Cadets and Staff and SO from the Title
			var TestTitle = title.toUpperCase();
			var staffonly = TestTitle.indexOf('(SO)');
			var staffstart = TestTitle.indexOf('(STAFF');
			var cadetsstart = TestTitle.indexOf('(CADETS');

			// Find the 1st occurance
			var HUGEVALUE = 999999;
			var FirstOccurance = HUGEVALUE;

			if( staffonly != -1)
				FirstOccurance = staffonly;
			if( staffstart != -1)
			{
				FirstOccurance = Math.min (FirstOccurance, staffstart);
				staffstart += 7;
				staffend = TestTitle.indexOf(')', staffstart);
			}
			if( cadetsstart != -1)
			{
				FirstOccurance = Math.min (FirstOccurance, cadetsstart);
				cadetsstart += 8;
				cadetsend = TestTitle.indexOf(')', cadetsstart);
			}

			var titletodisplay = null;
			var stafftodisplay = null;
			var cadetstodisplay = null;

			titletodisplay = title.substring(0, FirstOccurance-1);
			titletodisplay += " ";

			// Get the other information
			if(staffstart != -1 && staffend > staffstart) // CORRECT THIS
				stafftodisplay = title.substring(staffstart, staffend)

			if(cadetsstart != -1 && cadetsend > cadetsstart) // CORRECT THIS
				cadetstodisplay = title.substring(cadetsstart, cadetsend)


			var li = document.createElement('li');
			var TitleLinkNode = document.createTextNode(titletodisplay)
			if(!tableopen)
			{
				HTMLEventsString+="<table style='text-align:center'> <table style='text-align:left' border='1'><font color='" + HEADERTEXTCOLOUR + "'><tr style='background:" + HEADERCOLOUR + "';>"
				HTMLEventsString+= "<td width='120'><strong>Date</strong></td>";
				HTMLEventsString+= "<td width='480' ><strong>Event Details</strong></td>";
				HTMLEventsString+= "</tr></font>";				
				tableopen=true;
			}
						
			if(colourtouse==1)
				colourtouse=0;
			else
				colourtouse=1;
			
			HTMLEventsString += "<tr style='background:" + BCKGNDCOLOUR + "';><td>" + DOTW[startJSDate.getDay()] + dateString + "</td><td style='text-align:left'>" +  titletodisplay ;
			
			li.appendChild( TitleLinkNode );
			ul.appendChild(li);

			// Store for use in the Detailed Event Info field
			Title[startJSDate.getDate()] [NoofEntries] = titletodisplay;


			if ( !startDateTime.isDateOnly() )
			{
				Times[startJSDate.getDate()] [NoofEntries] = " " + startJSDate.getHours() + ":" + padNumber(startJSDate.getMinutes()) + " Hrs - " + endJSDate.getHours() + ":" + padNumber(endJSDate.getMinutes()) + " Hrs";
				if(( startJSDate.getDay() != endJSDate.getDay()) || (startJSDate.getMonth() != endJSDate.getMonth()) || (startJSDate.getFullYear() != endJSDate.getFullYear())  )
				{
					Times[startJSDate.getDate()] [NoofEntries] += " on " + endJSDate.getDate() + " " + MonthShort[endJSDate.getMonth()];
					HTMLEventsString += "<br /><font size='1'>Time: " + Times[startJSDate.getDate()] [NoofEntries] + "</font>" ;
				}
			}
			else if ((endJSDate.getTime() - startJSDate.getTime()) > ONEDAY_2)  //Only have day month year but we do know that it spans more than one day so can mention that!
			{
				var EndDate=new Date();
				EndDate.setDate(endJSDate.getDate()-1);

				Times[startJSDate.getDate()] [NoofEntries] = " " + startJSDate.getDate() + " " + MonthShort[startJSDate.getMonth()] + " - " + EndDate.getDate() + " " + MonthShort[endJSDate.getMonth()];
				HTMLEventsString += "<br /><font size='1'>Time: " + Times[startJSDate.getDate()] [NoofEntries] + "</font>" ;
			}

			if( location[0].getValueString() != undefined && location[0].getValueString() != "" )
			{
				Location[startJSDate.getDate()] [NoofEntries] = location[0].getValueString();
				HTMLEventsString += "<br /><font size='1'>Location: " + Location[startJSDate.getDate()] [NoofEntries] + "</font>" ;
			}

			if( content.getText() !=undefined && content.getText() != "" )
			{
				Details[startJSDate.getDate()] [NoofEntries] = content.getText();
				HTMLEventsString += "<br /><font size='1'>Details: " + Details[startJSDate.getDate()] [NoofEntries] + "</font>" ;
			}

			if( cadetstodisplay != null )
			{
				Cadets[startJSDate.getDate()] [NoofEntries] = cadetstodisplay;
				HTMLEventsString += "<br /><font size='1'>Cadets: " + Cadets[startJSDate.getDate()] [NoofEntries] + "</font>" ;
			}

			if( stafftodisplay != null )
			{
				Staff[startJSDate.getDate()] [NoofEntries] = stafftodisplay;
				HTMLEventsString += "<br /><font size='1'>Staff: " + Staff[startJSDate.getDate()] [NoofEntries] + "</font>" ;
			}

			HTMLEventsString += "</td></tr>"

			NoofEntries++;
		}
	}

	if(tableopen == true)
	{
		HTMLEventsString+="</table></table></div>"
		HTMLEventsString+="<div width='600' style='text-align:center'><font size='1' color='#FFFFFF'>Events are continually added and updated so keeping checking the website for the latest information</font></div><br /><br />";
		tableopen = false;
	}

	HTMLTrgProgString = "<div width='600' style='text-align:center'> <font size='4'  color='#FF0000'>Training Programme</font><br /><br />"

	
	//Training Info Format
	//TrainingInfo[Day] = new Array ( DOTW, Day, Month, Year, Period1, Location1, Description1, Period2, Location2, Description2 )

	// Email Format - Use TrainingInfoList 
	if(EmailGeneration)
	{
		var trgloopstart = 0;
		for( var trgprogloop = trgloopstart; trgprogloop < TrainingInfoList.length; trgprogloop++)
		{

			if( TrainingInfoList[trgprogloop] != null && (TrainingInfoList[trgprogloop][4] != "" ||  TrainingInfoList[trgprogloop][7] != "") )
			{
				var entryMonth = 0;
				var myDate= new Date();
				
				switch(TrainingInfoList[trgprogloop][2])
				{
				case "January" : 	{ entryMonth = 0; break;}
				case "February" :	{ entryMonth = 1; break;}
				case "March" :		{ entryMonth = 2; break;}
				case "April" :		{ entryMonth = 3; break;}
				case "May" :		{ entryMonth = 4; break;}
				case "June" :		{ entryMonth = 5; break;}
				case "July" :		{ entryMonth = 6; break;}
				case "August" :	{ entryMonth = 7; break;}
				case "September" :	{ entryMonth = 8; break;}
				case "October" :	{ entryMonth = 9; break;}
				case "November" :	{ entryMonth = 10; break;}
				case "December" :	{ entryMonth = 11; break;}
				default: 			{break;}
				}
		
				dateString = padNumber(TrainingInfoList[trgprogloop][1])  + " " + MonthShort[entryMonth];
				myDate.setFullYear(TrainingInfoList[trgprogloop][3], entryMonth, TrainingInfoList[trgprogloop][1]);
	
				if(tableopen == false)
				{
					HTMLTrgProgString+="<table style='text-align:center;' border='1'>"
					HTMLTrgProgString+= "<font color='" + HEADERTEXTCOLOUR + "'><tr style='background:" + HEADERCOLOUR + "'>";
					HTMLTrgProgString+= "<td width='120'><strong>Date</strong></td>";
					HTMLTrgProgString+= "<td width='240'><strong>Period 1</strong></td>";
					HTMLTrgProgString+= "<td width='240'><strong>Period 2</strong></td>";
					HTMLTrgProgString+= "</tr></font>";
					tableopen = true;
				}
				
				HTMLTrgProgString+="<tr style='background:" + BCKGNDCOLOUR + "'><td>" + DOTW[myDate.getDay()] + " " + dateString + "</td>";
	
			
				if( TrainingInfoList[trgprogloop][4] != "" )
				{
					HTMLTrgProgString+="<td>"+ TrainingInfoList[trgprogloop][4] + "</td>"
				}
				
				if( TrainingInfoList[trgprogloop][7] != "" )
				{
					HTMLTrgProgString+="<td>"+ TrainingInfoList[trgprogloop][4] + "</td>"
				}
					HTMLTrgProgString+="</tr>";
			}
		}
	}
	else
	{
		// Diary Format - Use TrainingInfo
		var trgloopstart = 1;
		for( var trgprogloop = trgloopdaystart; trgprogloop <= 31; trgprogloop++)
		{
			dateString = padNumber(trgprogloop)  + " " + MonthShort[TheMonth-1];
	
			if( TrainingInfo[trgprogloop] != null && (TrainingInfo[trgprogloop][4] != "" ||  TrainingInfo[trgprogloop][7] != "") )
			{
				// add it to the CalendarDiv
				var idstring = "theDate" + trgprogloop;
				var calendarDiv2 = document.getElementById(idstring);
	
				if(calendarDiv2)
				{
					calendarDiv2.style.fontWeight="bold";
					calendarDiv2.style.color = MCEVENTTEXTCOLOUR;
					calendarDiv2.style.backgroundColor = MCEVENTBACKGROUNDCOLOUR;
				}
	
				var myDate= new Date();
				myDate.setFullYear(TheYear,TheMonth-1,trgprogloop);
	
				var ul2 = document.createElement('ul');
	
				if(tableopen == false)
				{
					HTMLTrgProgString+="<table style='text-align:center;' border='1'>"
					HTMLTrgProgString+= "<font color='" + HEADERTEXTCOLOUR + "'><tr style='background:" + HEADERCOLOUR + "';>";
					HTMLTrgProgString+= "<td width='120'><strong>Date</strong></td>";
					HTMLTrgProgString+= "<td width='240'><strong>Period 1</strong></td>";
					HTMLTrgProgString+= "<td width='240'><strong>Period 2</strong></td>";
					HTMLTrgProgString+= "</tr></font>";
					tableopen = true;
				}
				
				
				
				HTMLTrgProgString+="<tr style='background:" + BCKGNDCOLOUR + "'><td>" + DOTW[myDate.getDay()] + dateString + "</td>";
	
					var li2 = document.createElement('li');
				li2.appendChild(document.createTextNode("Training Programme..."));
				ul2.appendChild(li2);
				
				if( TrainingInfo[trgprogloop][4] != "" )
				{
					var li3 = document.createElement('li');
	
					li3.appendChild(document.createTextNode("P1-" + TrainingInfo[trgprogloop][4]));
					HTMLTrgProgString+="<td>"+ TrainingInfo[trgprogloop][4] + "</td>"
					ul2.appendChild(li3);
				}
				
				if( TrainingInfo[trgprogloop][7] != "" )
				{
					var li3 = document.createElement('li');
					li3.appendChild(document.createTextNode("P2-" + TrainingInfo[trgprogloop][7]));
					HTMLTrgProgString+="<td'>"+ TrainingInfo[trgprogloop][4] + "</td>"
					ul2.appendChild(li3);
				}
					HTMLTrgProgString+="</tr>";
					if(calendarDiv2)
						calendarDiv2.appendChild(ul2);
			}
		}
	}
	
	if(tableopen == true)
	{
		HTMLTrgProgString+="</table></div><br /><br />"
	}

	if( !EmailGeneration)
	{
		// COLOUR THE BORDERS OF THE TABLE
		for( var borderloop = 1; borderloop <= GetLastDate( CurMonth+1 ); borderloop++ )
		{
			// Set Today to RED
			var idborderstring = "theDate" + borderloop;
			var calendarborderDiv = document.getElementById(idborderstring);

			if (calendarborderDiv)
			{
				if( borderloop == TodaysDate.getDate() && CurMonth==TodaysDate.getMonth() && CurYear==TodaysDate.getFullYear())
				{
					calendarborderDiv.style.border="1px solid " + MCEVENTTEXTCOLOUR;
				}
				else
				{
					calendarborderDiv.style.border="1px solid #FFFFFF";
				}
			}
		}


		if(ul && calendarDiv)
		{
			calendarDiv.appendChild(ul);
		}

		if(CurDay != -1 && IsLoggedIn == 1 )
		{
			showeventdetails(CurDay, MonthLong[CurMonth], CurYear)
		}

		adjustHeight();
	}
	
	if(EmailIncludeEvents==1)
		HTMLEmailString+=HTMLEventsString;
	if(EmailIncludeTrgProg==1)
		HTMLEmailString+=HTMLTrgProgString;

	/*if(EmailGeneration)
		PreviewEmail();*/
		
	EmailGeneration = false;
	GenerateComplete = true;	
}


// USED TO SHOW EVENTS ON MINI-CALENDAR WHEN MOUSE HOVERED OVER
function showeventtitle(Date, Month, Year)
{
	var EventAdded = false;
	CurrentDate = Date;
	theDaysInfo = document.getElementById("DayInfo");
	theDaysTrainingInfo = document.getElementById("DayTrainingInfo");
	
	if (document.all||document.getElementById)
	{
		theString1 = "theDate" + Date;

		if( (TitleText[CurrentDate] != undefined) || ( TrainingInfo[CurrentDate] != null && (TrainingInfo[CurrentDate][4]!="" || TrainingInfo[CurrentDate][7]!="") ) )
		{
			// remove existing text
			var length = theDaysInfo.childNodes.length;
			if (length > 0)
			{
				for(var loop = length-1; loop >=0; loop--)
				{
					theDaysInfo.removeChild(theDaysInfo.childNodes[loop]);
				}
			}

			length = theDaysTrainingInfo.childNodes.length;
			if (length > 0)
			{
				for(var loop = length-1; loop >=0; loop--)
				{
					theDaysTrainingInfo.removeChild(theDaysTrainingInfo.childNodes[loop]);
				}
			}


			theDaysTrainingInfo.style.color = "#0000FF"
			theDaysInfo.style.color = "#0000FF"
		}


		if(TitleText[CurrentDate] != undefined)
		{
			theDaysInfo.style.paddingTop = "5px";
			theDaysInfo.style.paddingBottom = "5px";

			var ul = document.createElement('ul');
			var dateString = "Events on " + Date + " " + Month + " " + Year;
			ul.appendChild(document.createTextNode(dateString));

			thetitle=TitleText[CurrentDate].split('<br />');
			if (thetitle.length > 1 )
			{
				for (var i=0;i<thetitle.length;i++)
				{
					var li = document.createElement('li');

					li.appendChild(document.createTextNode(thetitle[i]));
					ul.appendChild(li);
				}
			}
			else
			{
			    var li = document.createElement('li');
				li.appendChild(document.createTextNode(TitleText[CurrentDate]));

				ul.appendChild(li);
			}

			theDaysInfo.appendChild(ul);

			EventAdded = true;
		}
		else
		{
			theDaysInfo.style.paddingTop = "0px";
			theDaysInfo.style.paddingBottom = "0px";
		}

		// Add Training programme info if any
		if( TrainingInfo[CurrentDate] != null && (TrainingInfo[CurrentDate][4]!="" || TrainingInfo[CurrentDate][7]!="") )
		{
			//Add 5px of padding at the top
			theDaysTrainingInfo.style.paddingTop = "5px";
			theDaysTrainingInfo.style.paddingBottom = "5px";

			var entryadded = false;
			
			if (TrainingInfo[CurrentDate][4] !="") // Period 1
			{
				var ul = document.createElement('ul');
				var TrgProgString = "Training Prog on " + Date + " " + Month + " " + Year ;
				ul.appendChild(document.createTextNode(TrgProgString));

				var li = document.createElement('li');
				li.appendChild(document.createTextNode("Period 1-" + TrainingInfo[CurrentDate][4]));
				ul.appendChild(li);
				
				entryadded = true;
			}
			if (TrainingInfo[CurrentDate][7] !="") // Period 2
			{
				if( ! entryadded )
				{
					var ul = document.createElement('ul');
					var TrgProgString = "Training Prog on " + Date + " " + Month + " " + Year ;
					ul.appendChild(document.createTextNode(TrgProgString));
					entryadded = true;
				}

				var li = document.createElement('li');
				li.appendChild(document.createTextNode("Period 2-" + TrainingInfo[CurrentDate][7]));
				ul.appendChild(li);
				
				theDaysTrainingInfo.appendChild(ul);
			}

			if( entryadded )
				theDaysTrainingInfo.appendChild(ul);
		}
		else
		{
			theDaysTrainingInfo.style.paddingTop = "0px";
			theDaysTrainingInfo.style.paddingBottom = "0px";
		}
	}
	else
	if (document.layers)
	{
		if(TitleText[Date]!=undefined)
				text = TitleText[Date];
		else
				text = "";

		document.tooltip.document.write('<layer bgColor="white" style="border:1px solid black;font-size:12px;">'+text+'</layer>')
		document.tooltip.document.close()
		document.tooltip.left=e.pageX+5
		document.tooltip.top=e.pageY+5
		document.tooltip.visibility="show"
	}

	adjustHeight();
}

// USED TO SHOW FULL EVENTS ON DIARY CALENDAR WHEN CLICKED ON, AND LOGGED IN
function showeventdetails(Day, Month, Year)
{
	var EntryAdded = false;

	var DetailedInfo = document.getElementById("DetailedInfo");

	if (DetailedInfo.childNodes.length > 0)
	{
		for(var loop = DetailedInfo.childNodes.length-1; loop >=0; loop--)
			DetailedInfo.removeChild(DetailedInfo.childNodes[loop]);
	}

	var DetailedInfoHeader = document.getElementById("DetailedInfoHeader");
	if (DetailedInfoHeader.childNodes.length > 0)
	{
		DetailedInfoHeader.removeChild(DetailedInfoHeader.childNodes[0]);
	}

	var dateString = padNumber(Day)  + " " + Month + " " + Year;
	DetailedInfoHeader.appendChild(document.createTextNode("Detailed Event Information for " + dateString));

	if (document.all||document.getElementById)
	{
		DetailedInfo.style.color = "#FF0000"

		// loop getting all the info
		if (Title[Day].length>0)
		{
			// loop around populating all the info for the event
			for (var loop = 0; loop < Title[Day].length; loop ++)
			{
				var ul = document.createElement('ul');
				ul.appendChild(document.createTextNode(Title[Day][loop]));
				var li = document.createElement('li');

				if( Times[Day][loop] != undefined && Times[Day][loop] != null )
					li.appendChild(document.createTextNode("Time:            " + Times[Day][loop]));
				else
					li.appendChild(document.createTextNode("Time:             Information not available"));
				ul.appendChild(li);
				li = document.createElement('li');

				if( Location[Day][loop] != undefined && Location[Day][loop] != null )
					li.appendChild(document.createTextNode("Location:      " + Location[Day][loop]));
				else
					li.appendChild(document.createTextNode("Location:      Information not available"));
				ul.appendChild(li);
				 li = document.createElement('li');

				if( Details[Day][loop] != undefined && Details[Day][loop] != null )
					li.appendChild(document.createTextNode("Details:         " + Details[Day][loop]));
				else
					li.appendChild(document.createTextNode("Details:         Information not available"));
				ul.appendChild(li);

				if( Cadets[Day][loop] != undefined && Cadets[Day][loop] != null )
				{
					li = document.createElement('li');
					li.appendChild(document.createTextNode("Cadets:           " + Cadets[Day][loop]));
					ul.appendChild(li);
				}

				if( Staff[Day][loop] != undefined && Staff[Day][loop] != null )
				{
					li = document.createElement('li');
					li.appendChild(document.createTextNode("Staff:            " + Staff[Day][loop]));
					ul.appendChild(li);
				}

				DetailedInfo.appendChild(ul);
				EntryAdded = true;
			}
		}

		//Format of TrainingInfo[Day] = new Array ( DOTW, Day, Month, Year, Period1, Location1, Description1, Period2, Location2, Description2 )
		// Add Training programme info if any
		if( TrainingInfo[Day] != null && (TrainingInfo[Day][4]!="" || TrainingInfo[Day][7]!="") )
		{
			if (TrainingInfo[Day][4]!="")
			{
				var ul = document.createElement('ul');
				ul.appendChild(document.createTextNode("Training Programme for " + dateString));

				var li = document.createElement('li');
				li.appendChild(document.createTextNode("Period 1: " + TrainingInfo[Day][4]));
				ul.appendChild(li);

				EntryAdded = true;
			}
			if (TrainingInfo[Day][7]!="")
			{
				if(!EntryAdded)
				{
					var ul = document.createElement('ul');
					ul.appendChild(document.createTextNode("Training Programme for " + dateString));
					EntryAdded = true;
				}

				var li = document.createElement('li');
				li.appendChild(document.createTextNode("Period 2: " + TrainingInfo[Day][7]));
				ul.appendChild(li);
				
				EntryAdded = true;
			}
			
			if( EntryAdded )
				DetailedInfo.appendChild(ul);
		}


		if(EntryAdded == false)
		{
			DetailedInfo.style.color = "#626262"
			var ul = document.createElement('ul');
			var li = document.createElement('li');
			li.appendChild(document.createTextNode("No events found for this date"));
			ul.appendChild(li);
			DetailedInfo.appendChild(ul);
		}
	}
	else
	if (document.layers)
	{
		document.tooltip.document.write('<layer bgColor="white" style="border:1px solid black;font-size:12px;">'+text+'</layer>')
		document.tooltip.document.close()
		document.tooltip.left=e.pageX+5
		document.tooltip.top=e.pageY+5
		document.tooltip.visibility="show"
	}

	adjustHeight();
}

function hidetitle()
{
	var length = 0;
	if (document.layers)
	{
		document.tooltip.visibility="hidden"
	}
	else
	{
		var DateInfoDiv = document.getElementById("DayInfo");

		length = DateInfoDiv.childNodes.length;
		if (length > 0)
		{
			for(var loop = length-1; loop >=0; loop--)
			{
				DateInfoDiv.removeChild(DateInfoDiv.childNodes[loop]);
			}
		}

		var theDaysTrainingInfo = document.getElementById("DayTrainingInfo");
		length = theDaysTrainingInfo.childNodes.length;
		if (length > 0)
		{
			for(var loop = length-1; loop >=0; loop--)
			{
				theDaysTrainingInfo.removeChild(theDaysTrainingInfo.childNodes[loop]);
			}
		}

		theDaysInfo.style.paddingTop = "0px";
		theDaysInfo.style.paddingBottom = "0px";

		DateInfoDiv.style.paddingTop = "0px";
		DateInfoDiv.style.paddingBottom = "0px";

		var ul = document.createElement('ul');
		ul.appendChild(document.createTextNode("Highlight a day to see events on that day....."));
		DateInfoDiv.style.color ="#888888"
		DateInfoDiv.appendChild(ul);
	}
}

var TrainingInfo = new Array(32);
var TrainingInfoList = new Array();
var NumTrainingEntries = 0;

function StoreTrainingProgramme( DOTW, Day, Month, Year, Period1, Location1, Description1, Period2, Location2, Description2, MiniCalendarOnly )
{
	// Store by Day for Home Page and Diary Calendars
	if( MiniCalendarOnly == "true" )
		TrainingInfo[Day] = new Array ( DOTW, Day, Month, Year, Period1, Location1, Description1, Period2, Location2, Description2 )
	
	// Store programe entries from today for What's On list
	TrainingInfoList[NumTrainingEntries++] = new Array (DOTW, Day, Month, Year, Period1, Location1, Description1, Period2, Location2, Description2 );	
	

}

function SetLoginDetails( loggedIn, lastLoginDate )
{
	LoggedIn = loggedIn;
	LastLogin = new Date(lastLoginDate);
}


// ADMINISTRATION JAVASCRIPT
/*
StartFrom 1 = 1st of Month, 2 = Today
EndAt 1 = End of this month, 2 =  One months entries from start date

var FROM_FIRST_OF_NEXT_MONTH = 1;
var FROM_TODAY = 2;
var TO_END_OF_MONTH = 1;
var ONE_MONTH_EXACTLY = 2;
*/
function GenerateEmail(IncludeEvents, IncludeTrgProg, StartFrom, EndAt )
{
	EmailGeneration = true;
	EmailIncludeEvents = IncludeEvents
	EmailIncludeTrgProg = IncludeTrgProg;
	EmailStartFrom = StartFrom;
	EmailEndAt = EndAt;
	var str_start = StartFrom;
	var str_end = EndAt;
	
	initCal();

	// TheMonth is global so it can be used in the email generated strings
	TheDay = TodaysDate.getDate();
	TheMonth = TodaysDate.getMonth();
	TheYear = TodaysDate.getFullYear();

	// Set up Start Date 
	/*var str_start="";
	if( EmailStartFrom == FROM_TODAY )
	{
		str_start = TheYear + "-" + padNumber(TheMonth+1) + "-" + padNumber(TheDay);
	}
	else
	{
		// FIRST_OF_NEXT_MONTH
		TheDay = 1;
		
		if(TheMonth == 11)
		{
			
			TheMonth=0;
			TheYear++;
			str_start = TheYear.toString() + "-" + padNumber(TheMonth+1) + "-" + padNumber(TheDay);
		}
		else
		{	
			TheMonth++;
			str_start = TheYear.toString() + "-" + padNumber(TheMonth+1) + "-" + padNumber(TheDay);
		}
	}
	
	
	// Set Up End Date
	var str_end = "";
	if(EndAt == TO_END_OF_MONTH)
	{
		str_end = (TheYear.toString()) + "-" + padNumber(TheMonth+1)  + "-" + GetLastDate( TheMonth+1 ) + ""; 
	}
	else // ONE_MONTH_EXACTLY
	{
		if(TheMonth == 11)
		{
			TheMonth=0;
			TheYear++;
			str_end = TheYear.toString() + "-" + padNumber(TheMonth+1) + "-" + padNumber(TheDay);
		}
		else
		{	
			TheMonth++;
			str_end = TheYear.toString() + "-" + padNumber(TheMonth+1) + "-" + padNumber(TheDay);
		}
	}*/	
	
	HTMLEmailString = "";
	HTMLEventsString = "";
	HTMLTrgProgString = "";
	
	if(IncludeEvents==1 || IncludeTrgProg==1 ) // Blogs and other entries added by calling asp script
	{
		CurMonth = TheMonth;
		CurYear = TheYear;
		CurDay = TheDay;
		// Use same calendar as Diary pages as this is already getting one months events and training programme entries
		loadCalendar(str_start, str_end, DIARY_PAGE_EVENTS);
	}
}

function ProcessAndAddNoticesAndNewsFlashesToHomePage()
{
	var NoticesDiv = document.getElementById("Notices")
	var ul = null;
	var li = null;
	var entryadded=false;
	
	if(NoticesDiv)
	{	
		for(var NewsFlashloop = 0; NewsFlashloop < Newsflashes.length; NewsFlashloop++)
		{
			if(NewsFlashloop == 0)
			{
				ul = document.createElement('ul');
				if(StaffNotices.length > 0)
					ul.innerHTML = "Cadet Notices";			
				else
					ul.innerHTML = "Notices";			
			}	
			
			li = document.createElement('li');
			li.appendChild(document.createTextNode(Newsflashes[NewsFlashloop]));
			li.style.color="#FF0000";
			
					
			ul.appendChild(li);			
		}	
		
		//Add notices to the marquee if there are any
		for( var noticeloop = 0; noticeloop < Notices.length; noticeloop++)
		{
			if( Newsflashes.length == 0 && noticeloop == 0)
			{
				ul = document.createElement('ul');
				if(StaffNotices.length > 0)
					ul.innerHTML = "Cadet Notices";			
				else
					ul.innerHTML = "Notices";
			}	
			
			li = document.createElement('li');
			li.appendChild(document.createTextNode(Notices[noticeloop]));
					
			ul.appendChild(li);	
		}
		
		if(Newsflashes.length > 0 || Notices.length > 0)
		{
			NoticesDiv.appendChild(ul);
			var br =  document.createElement("br");
			NoticesDiv.appendChild(br);
		}
	}
}


function ProcessAndAddStaffNoticesAndNewsFlashesToHomePage()
{
	var StaffNoticesDiv = document.getElementById("StaffNotices")
	var ul = null;
	var li = null;
	
	if(StaffNoticesDiv)
	{
		//Add staff notices to the marquee if there are any
		for( var staffnoticeloop = 0; staffnoticeloop < StaffNotices.length; staffnoticeloop++)
		{
			if( staffnoticeloop == 0)
			{
				ul = document.createElement('ul');
				ul.innerHTML = "Staff Notices";
				ul.style.color = "#FF0000";
			}	
			
			li = document.createElement('li');
			li.appendChild(document.createTextNode(StaffNotices[staffnoticeloop]));
					
			ul.appendChild(li);	
		}
		
		if(StaffNotices.length > 0)
		{
			StaffNoticesDiv.appendChild(ul);
			var br =  document.createElement("br");
			StaffNoticesDiv.appendChild(br);
		}
	}
}


function ProcessAndAddTrainingProgrammeToHomePage()
{
	var currentMonth = TodaysDate.getMonth();
	var currentYear = TodaysDate.getFullYear() ;
	var ss_NumEntriesFound = 0;
	var ss_Period1 = "";
	var ss_Period2 = "";
	
	// Assume 2 months worth of entries - what is last month/year
	var lastMonth = currentMonth + 1;
	var lastYear = currentYear;
	
	if(lastMonth == 12)
	{
		lastMonth = 0;
		lastYear++;
	}
	
	for (var eventEntryLoop=0; eventEntryLoop < NumTrainingEntries; eventEntryLoop++)
	{	
	        //Format of Data
		//TrainingInfoList[NumTrainingEntries++] = new Array (DOTW, Day, Month, Year, Period1, Location1, Description1, Period2, Location2, Description2, Include );	// Store a 2D array
		var entryDOTW = TrainingInfoList[eventEntryLoop][0];
		var entryDay = TrainingInfoList[eventEntryLoop][1];
		var entryMonthStr = TrainingInfoList[eventEntryLoop][2];
		var entryYear = TrainingInfoList[eventEntryLoop][3];
		
		var entryMonth = -1;
		switch(entryMonthStr)
		{
			case "January" :		{ entryMonth = 0; break;}
			case "February" :		{ entryMonth = 1; break;}
			case "March" :		{ entryMonth = 2; break;}
			case "April" :		{ entryMonth = 3; break;}
			case "May" :		{ entryMonth = 4; break;}
			case "June" :		{ entryMonth = 5; break;}
			case "July" :		{ entryMonth = 6; break;}
			case "August" :		{ entryMonth = 7; break;}
			case "September" :	{ entryMonth = 8; break;}
			case "October" :		{ entryMonth = 9; break;}
			case "November" :	{ entryMonth = 10; break;}
			case "December" :	{ entryMonth = 11; break;}
			default: 			{alert ("Error Loading Training Programme", "Training Programme Month Not Found");break;}
		}

		if( ! ((entryYear == currentYear && entryMonth == currentMonth) || (entryYear == lastYear && entryMonth == lastMonth)) )
		{
			// Not the months we want
			continue;
		}
		
		var entryDate=new Date();
		entryDate.setFullYear(entryYear, entryMonth, entryDay);
		
		var currentDayofWeek = entryDate.getDay() ;
						
		if(currentDayofWeek != TUESDAY && currentDayofWeek != FRIDAY)
		{
			continue;
		}		
								
		// Not interested in any entries before today
		if( entryDate < TodaysDate)
		{
			continue;
		}
													
		// So we have info for a Tues and a Friday - store it!
		TrainingInfoEntryWhatsOn[ss_NumEntriesFound] = "";

		TrainingInfoEntryWhatsOn[ss_NumEntriesFound++] = new Array( entryDay, entryMonth, entryYear, currentDayofWeek,
												TrainingInfoList[eventEntryLoop][4], TrainingInfoList[eventEntryLoop][7] )
															
		if( ss_NumEntriesFound ==  SS_NUM_TRG_PROG_ENTRIES_REQD)
			break;
		
	}
		
	var EntryFound = false;	
	var Text = "";
	var PeriodText = "";
	var ul = null;
	var li = null;
	var br = null;
	
	var WhatsOnDiv = document.createElement("div");

	//GET NEXT TRAINING NIGHTS ENTRIES
	//Format of Data
	//TrainingInfoEntryWhatsOn[ss_NumEntriesFound++] = new Array( entryDay, entryMonth, entryYear, currentDayofWeek,
	//											TrainingInfoList[eventEntryLoop][4],TrainingInfoList[eventEntryLoop][7] )
			
	if(TrainingInfoEntryWhatsOn.length>0)
	{
		if(TrainingInfoEntryWhatsOn[0].length>3 &&TrainingInfoEntryWhatsOn[0][4] && TrainingInfoEntryWhatsOn[0][4].length >0)
		{
		
			ul = document.createElement('ul');
											
			if(TodaysDate.getDay() != TUESDAY && TodaysDate.getDay() != FRIDAY)
			{
				if ( TodaysDate.getDay() > FRIDAY || TodaysDate.getDay() < TUESDAY )
					Text="Tuesday's";	
				else
					Text="Friday's";
			}
			else
				Text="Tonight's";
				
			ul.innerHTML = "<br/>" + Text + " Training Prog";
						
			PeriodText = "P1 - " + TrainingInfoEntryWhatsOn[0][4] + "" ;
	
			li = document.createElement('li');
			//li.setAttribute('title', "blah blah");
			li.appendChild(document.createTextNode(PeriodText));
			
						
			ul.appendChild(li);
			if(WhatsOnDiv)
				WhatsOnDiv.appendChild(ul);	
			EntryFound = true;
		}
		
	
		if(TrainingInfoEntryWhatsOn[0].length>4 &&TrainingInfoEntryWhatsOn[0][5] && TrainingInfoEntryWhatsOn[0][5].length >0)
		{
			ul = document.createElement('ul');
			if( EntryFound != true)
			{
				if(TrainingInfoEntryWhatsOn[0][3] != TUESDAY && TrainingInfoEntryWhatsOn[0][3] != FRIDAY)
				{
					if ( TrainingInfoEntryWhatsOn[0][3] > FRIDAY || TrainingInfoEntryWhatsOn[0][3] < TUESDAY )
						Text="Tuesday";	
					else
						Text="Friday";
				}
				else
					Text="Tonight";
			
				ul.innerHTML = Text;
			}										
			li = document.createElement('li');
			PeriodText = "P2 - " + TrainingInfoEntryWhatsOn[0][5] + "" ;
			li.appendChild(document.createTextNode(PeriodText));
						
			ul.appendChild(li);
			if(WhatsOnDiv)
				WhatsOnDiv.appendChild(ul);	
			EntryFound = true;
		}
	}
	
	var HomePageWhatsOnDiv = document.getElementById("WhatsOn");
	//PADTEMP
	//for(var loop = HomePageWhatsOnDiv.childNodes.length-1; loop >=0; loop--)
	//	HomePageWhatsOnDiv.removeChild(HomePageWhatsOnDiv.childNodes[loop]);
	
	if(EntryFound)
	{	
		if(HomePageWhatsOnDiv && WhatsOnDiv)
			HomePageWhatsOnDiv.appendChild( WhatsOnDiv );
	}
	
	
	//GET FOLLOWING 2 NIGHTS TRAINING NIGHTS ENTRIES
	var ul = null;
	var li = null;
	var br = null;
	var FirstEntryFound = false;
	var ForthcomingEventsDiv = document.createElement("div");
	EntryFound = false;
	
	//if(ForthcomingEventsDiv)
	//	ForthcomingEventsDiv.innerHTML = "<br/>Next Week's Training Programme"
			
	if(TrainingInfoEntryWhatsOn.length>1)
	{
		if(TrainingInfoEntryWhatsOn[1].length>3 &&TrainingInfoEntryWhatsOn[1][4] && TrainingInfoEntryWhatsOn[1][4].length >0)
		{
			ul = document.createElement('ul');
			Text = "" + DOTW[TrainingInfoEntryWhatsOn[1][3]] + " " //;+ FormatDate(TrainingInfoEntryWhatsOn[1][0]) + " " + MonthLong[TrainingInfoEntryWhatsOn[1][1]] ;//+ " " + TrainingInfoEntryWhatsOn[1][2];
			ul.innerHTML = "Next Week's Training Prog" ;//Text;
					
			li = document.createElement('li');
			PeriodText = Text + "P1 - " + TrainingInfoEntryWhatsOn[1][4] + "" ;
			li.appendChild(document.createTextNode(PeriodText));
			ul.appendChild(li);
			if(ForthcomingEventsDiv)
				ForthcomingEventsDiv.appendChild(ul);	
			EntryFound = true;
			FirstEntryFound = true;
		}
		
		if(TrainingInfoEntryWhatsOn[1].length>4 &&TrainingInfoEntryWhatsOn[1][5] && TrainingInfoEntryWhatsOn[1][5].length >0)
		{
			ul = document.createElement('ul');
			if(FirstEntryFound != true)
			{
				Text = "" + DOTW[TrainingInfoEntryWhatsOn[1][3]] + " " //;+ FormatDate(TrainingInfoEntryWhatsOn[1][0]) + " " + MonthLong[TrainingInfoEntryWhatsOn[1][1]] ;//+ " " + TrainingInfoEntryWhatsOn[1][2];
				ul.innerHTML = "Next Week's Training Prog" ;//Text;
			
			}
			li = document.createElement('li');
			PeriodText = Text + "P2 - " + TrainingInfoEntryWhatsOn[1][5] + "";
			
			li.appendChild(document.createTextNode(PeriodText));
			ul.appendChild(li);
			if(ForthcomingEventsDiv)
			{
				ForthcomingEventsDiv.appendChild(ul);	
				br =  document.createElement("br");
				ForthcomingEventsDiv.appendChild(br);
			}
			EntryFound = true;
		}
	}
	
	//FirstEntryFound = false;
	
	if(TrainingInfoEntryWhatsOn.length>2)
	{
		if(TrainingInfoEntryWhatsOn[2].length>3 &&TrainingInfoEntryWhatsOn[2][4] && TrainingInfoEntryWhatsOn[2][4].length >0)
		{
			ul = document.createElement('ul');

			Text = "" + DOTW[TrainingInfoEntryWhatsOn[2][3]] + " "; //+ FormatDate(TrainingInfoEntryWhatsOn[2][0]) + " " + MonthLong[TrainingInfoEntryWhatsOn[2][1]];// + " " + TrainingInfoEntryWhatsOn[2][2];					
			
			if(FirstEntryFound != true)
			{
				ul.innerHTML = "Next Week's Training Prog" ;//Text;			
			}
									
			li = document.createElement('li');
			PeriodText = Text + "P1 - " + TrainingInfoEntryWhatsOn[2][4] + "";
			li.appendChild(document.createTextNode(PeriodText));
			ul.appendChild(li);
			
			if(ForthcomingEventsDiv)
				ForthcomingEventsDiv.appendChild(ul);	
			EntryFound = true;
			FirstEntryFound = true;
		}
		
		if(TrainingInfoEntryWhatsOn[2].length>4 &&TrainingInfoEntryWhatsOn[2][5] && TrainingInfoEntryWhatsOn[2][5].length >0)
		{
			ul = document.createElement('ul');
			if(FirstEntryFound != true)
			{
				Text = "" + DOTW[TrainingInfoEntryWhatsOn[2][3]] + " ";// + FormatDate(TrainingInfoEntryWhatsOn[2][0]) + " " + MonthLong[TrainingInfoEntryWhatsOn[2][1]];// + " " + TrainingInfoEntryWhatsOn[2][2];
				ul.innerHTML = "Next Week's Training Prog" ;//Text;
			}
			li = document.createElement('li');
			PeriodText = Text + "P2 - " + TrainingInfoEntryWhatsOn[2][5] + "";
			li.appendChild(document.createTextNode(PeriodText));
					
			ul.appendChild(li);
			if(ForthcomingEventsDiv)
				ForthcomingEventsDiv.appendChild(ul);	
			EntryFound = true;
		}
	}
	
	var HomePageForthcomingEventsDiv = document.getElementById("ForthcomingEvents");
	//for(var loop = HomePageForthcomingEventsDiv.childNodes.length-1; loop >=0; loop--)
	//	HomePageForthcomingEventsDiv.removeChild(HomePageForthcomingEventsDiv.childNodes[loop]);
	
	if(EntryFound)
	{	
		if(HomePageForthcomingEventsDiv && ForthcomingEventsDiv)
			HomePageForthcomingEventsDiv.appendChild( ForthcomingEventsDiv );
	}
	
}


