/****************** Variables */
var today = new Date();
today.setSeconds(0);
today.setMinutes(0);
today.setHours(0);
// show the current month year - month begins at 0
var month = today.getMonth();
var year = today.getFullYear();
// define dates data holder
var dates = {};
// where does the page containing full event information reside?
var eventDetailsUrl = getBaseUrl('conwaste') + 'events-calendar/event/';
// URL where the xml feed can be found for the events
var eventDataUrl = getBaseUrl('crwpmodel') + 'events/index/asxml';
// number of days to check for future events for
var futureEventDays = 30; // used to find the first future event to display on home page
/******************* End Variables */


jQuery(document).ready(function() {
	// hide the details and title for this event
	jQuery("#eventTitle").hide();
	jQuery("#eventDetails").hide();
	// load events when the page first loads.
	loadEvents(month, year);
});


function loadEvents(month,year)
{
	// sets the first day of the week to Monday (1) - 
	Date.firstDayOfWeek = Number(1);
	// set the calendar holder to invisible
	// get a list of events
	jQuery.ajax({
		type: "POST",
		url: eventDataUrl,
		data: "",
		success: function(xml){
			// loop through dates
			jQuery(xml).find('entry').each(function(){
				// load in dates
				// console.log("org: " + jQuery("organisation", this).text());
				var dateSplit = jQuery("summary", this).text().split('-');
				// use the split up date, make sure all array values are numbers and subtract 1 off the month to make it correct
				// var formattedDate = (new Date(parseInt(dateSplit[0]), (parseInt(dateSplit[1])-1), parseInt(dateSplit[2]))).getTime(); -- parseInt was causing problems
				var formattedDate = (new Date(dateSplit[0], (dateSplit[1]-1), dateSplit[2])).getTime();
				// console.log(jQuery("summary", this).text(), dateSplit[0], dateSplit[1], dateSplit[2], jQuery("title", this).text(), jQuery("content-formatted", this).text(), formattedDate);
				// store info about this date from the XML feed as an object
				dates['d' + formattedDate] = {
					id: 		jQuery("id", this).text(),
					content: 	formatDetails(
										"[b]Date: [/b]" + dateSplit[2] + "/" + dateSplit[1] + "/" + dateSplit[0] + "\n"
										 + "[b]Register: [/b]" + jQuery("registration", this).text() + "\n"
										 + "[b]Host: [/b]" + jQuery("organisation", this).text() + "\n"
										 + jQuery("content-formatted", this).text(), true),
					title: 		jQuery("title", this).text()
				}
			});
			// mark dates, render, add click events
			populateCalendar();
		}
	});
}

function populateCalendar() {
	// function to mark the event dates onto the calendar
	var markDates = function($td, thisDate, month, year) {
		// console.log(thisDate.asString(), thisDate.getTime(), dates['d' + thisDate.getTime()]);
		if (dates['d' + thisDate.getTime()]) {
			// console.log(thisDate, thisDate.getTime());
			var dateInfo = dates['d' + thisDate.getTime()];
			// bind events for when a user clicks this TD
			$td.bind(
				'click',
				function()
				{	
					if(openEventOnClick != undefined && openEventOnClick == true) {
						return true;											
					} else {
						// set the title of the details box
						jQuery("#eventTitle").html(dateInfo.title);
						jQuery("#eventDetails").html(dateInfo.content);
						// show the event details and title
						jQuery("#eventTitle").fadeIn();
						jQuery("#eventDetails").fadeIn();
						return false;
					}
				}
			);			
			// add a CSS class to the td tag in order to distinguish it.
			$td.addClass('has-event');
									
			// Adds a Google style bubble to the row
			$td.bind("mouseover", function(e) {
				var bubContent = dateInfo.content;
				bubContent = bubContent.replace('<li>&nbsp;</li>','');								
				jQuery("#bubbleContent").html(bubContent);
				
				jQuery("#bubble").css({
								left:jQuery(this).offset().left-5, 
								top:jQuery(this).offset().top-jQuery("#bubble").height()-35 
							}).show();
				e.stopPropagation(); // Stops the following click function from being executed
				jQuery(document).one("click", function(f) {
					jQuery("#bubble").hide();
				});
				
				jQuery("#bubble").bind("mouseleave", function(e) {
					jQuery("#bubble").hide();
				});
			});
			// STOP the menu from disappearing when it is clicked
			jQuery("#bubble").bind("click", function(e) { e.stopPropagation(); });
						
			// make the chosen date into a link
			$td.html(thisDate.getDate());
		}
	}

	// render the calendar, fading out the placeholder loading animation
	jQuery('#eventsCalendar div').fadeOut(function() {
		jQuery('#eventsCalendar div').css('background-image', 'none');
		jQuery('#eventsCalendar div').css('background-color', 'transparent'); // ie 6 fix
		// add in some navigation, if needs be
		if(jQuery('#eventsCalendarNav').length == 0) {
			var dtm = new Date((month+1)+"/01/"+year);
			jQuery('#eventsCalendar').prepend('<span id="eventsCalendarNav"><a href="#" id="nextMonth"><img src="' + getBaseUrl('conwaste') + 'mysite/images/events-arrow-right.gif" /></a><a href="#" id="prevMonth"><img src="' + getBaseUrl('conwaste') + 'mysite/images/events-arrow-left.gif" /></a><span id="monthLabel">' + dtm.getMonthName(true) + ' ' + year + '</span></span>');
		}
		jQuery('#eventsCalendar div').renderCalendar({month:month, year:year, renderCallback:markDates, showHeader:jQuery.dpConst.SHOW_HEADER_SHORT}).fadeIn();

		// add in hooks for the nav buttons
		jQuery('span#eventsCalendarNav a#prevMonth').click(function() {
			var newDate = calculateMonthYear('-1');
			jQuery("#bubble").hide();
			jQuery('#eventsCalendarNav span#monthLabel').html(newDate[2] + ' ' + newDate[3]);
			jQuery('#eventsCalendar div').renderCalendar({month:newDate[0], year:newDate[1], renderCallback:markDates, showHeader:jQuery.dpConst.SHOW_HEADER_SHORT});
			return false;
		});
		jQuery('span#eventsCalendarNav a#nextMonth').click(function() {
			var newDate = calculateMonthYear('+1');
			jQuery("#bubble").hide();
			jQuery('#eventsCalendarNav span#monthLabel').html(newDate[2] + ' ' + newDate[3]);
			jQuery('#eventsCalendar div').renderCalendar({month:newDate[0], year:newDate[1], renderCallback:markDates, showHeader:jQuery.dpConst.SHOW_HEADER_SHORT});
			return false;
		});
		
		// find the next up and coming event, looping through AJAX date info
		var dateFound = false;
		var dateCount = 0;
		var curDate = today;
		var firstEvent;
		while(dateFound == false && dateCount < futureEventDays) {
			// TODO: Fix this hack to subtract the bizarre '272' end to each time
			testDate = String(curDate.getTime());
			testDate = String(testDate.substring(0,(testDate.length - 3)));
			testDate += '000'; 
			// console.log(curDate.getTime(), curDate.asString(), dates['d' + curDate.getTime()], testDate, dateCount);
			// if(dates['d' + curDate.getTime()]) {
			// console.log(dates);
			if(dates['d' + testDate]) {
				// console.log('Date Found!');
				firstEvent = dates['d' + testDate];
				dateFound=true;
			}
			// increment the dateCount variable used to compare with var futureEventDays declared at the top of this file
			dateCount++;
			// add on one more day
			curDate.setDate(curDate.getDate()+1);
		}
		if(dateFound == true) {
			// populate the first event info
			jQuery("#eventTitle").html(firstEvent.title);
			jQuery("#eventDetails").html(firstEvent.content);
			// show info of the up and coming event
			jQuery("#eventTitle").fadeIn();
			jQuery("#eventDetails").fadeIn();		
		}
		
	});
}

function calculateMonthYear(increment) {
	var ret = {};
	if(increment == '-1') {
		if((month-1) < 0) {
			// asking for december of prev year, move year back 1 and month back to 11
			ret[0] = 11;
			ret[1] = year-1;
		} else {
			// normal month countdown
			ret[0] = month-1;
			ret[1] = year;
		}
	} else if(increment == '+1') {
		if((month+1) > 11) {
			// asking for January of next year
			ret[0] = 0;
			ret[1] = year+1;
		} else {
			// normal month increment
			ret[0] = month+1;
			ret[1] = year;
		}
	} else {
		// invalid increment value, default to current month year
		ret[0] = month;
		ret[1] = year;
	}
	// set global date preholding variables
	month = ret[0];
	year = ret[1];
	// set up date in words
	var dtm = new Date((ret[0]+1)+"/01/"+ret[1]);
	ret[2] = dtm.getMonthName(true);
	ret[3] = year;
	return ret;
}

// strips out BBCode and converts into a list
function formatDetails(text, asList) {
	// make into a list, exploiting line breaks
	if(asList == true) {
		var ret = "<ul><li>"+text.replace(/\n/g, "&nbsp;</li><li>")+"</li></ul>"; // the &nbsp; space is for IE6's benefit in case we have a blank line with no text!
	} else {
		var ret = text;
	}
	search = new Array(
	          /\[img\](.*?)=\1\[\/img\]/g,
	          /\[url=([\w]+?:\/\/[^ \\"\n\r\t<]*?)\](.*?)\[\/url\]/g,
	          /\[url\]((www|ftp|)\.[^ \\"\n\r\t<]*?)\[\/url\]/g,
	          /\[url=((www|ftp|)\.[^ \\"\n\r\t<]*?)\](.*?)\[\/url\]/g,
	          /\[email\](([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)?[\w]+))\[\/email\]/g,
	          /\[b\](.*?)\[\/b\]/g,
	          /\[url\](http:\/\/[^ \\"\n\r\t<]*?)\[\/url\]/g);

	replace = new Array(
	          "<img src=\"$1\" alt=\"An image\">",
	          "<a href=\"$1\" target=\"blank\">$2</a>",
	          "<a href=\"http://$1\" target=\"blank\">$1</a>",
	          "<a href=\"$1\" target=\"blank\">$1</a>",
	          // "<a href=\"mailto:$1\">$1</a>",
	          "<a href=\"mailto:$1\">Click here</a>",
	          "<strong>$1</strong>",
	          "<a href=\"$1\" target=\"blank\">$1</a>");
	for(i = 0; i < search.length; i++) {
	     ret = ret.replace(search[i],replace[i]);
	}
	return ret;
}

function getBaseUrl(app) {
	var host_name = document.location.hostname;
	if(host_name == 'ggdev.aeat.com' || host_name == 'ggdev') {
		var url = '/pmdev/';
	} else if(host_name == 'conwaste.aeastaging.co.uk') {
		var url = '/';
	} else {
		var url = '/';
	}
	if(app != '') {
		url += app + '/';
	}
	return url;
}