//Drives the Big Calendar on calendar index page.
Event.observe(window, 'load', function() {

var specialDays = ApathyIsBoringSpecialDays;

function checkSpecialDay(date, y,m,d) {
//console.trace();
	// @note everytime we switch months (or year) all the dates are run through again. So, here, we would add ajax call to get items. 
	var datesIndex = y + '-' + m + '-' + d;

	//Disable any non special days by returning true. (false would allow them to still be clickable)
	if(specialDays[datesIndex] === undefined) {
	
		//Special Case - Today with no events. 
		if(date.toDateString() == new Date().toDateString()) {
			return 'today';
		}
	
		return true;
	}	
	//There are events on this day, so add class of special to those cells.
	return 'special';
	
}

/**
 * Whenever nav clicked for calendar, goes through here. 
 * Handle displaying the date info box.
 *
 **/
function dateChanged(calendar) {
//console.log(calendar);
  // Beware that this function is called even if the end-user only
  // changed the month/year.  In order to determine if a date was
  // clicked you can use the dateClicked property of the calendar:
  if (calendar.dateClicked) {

    var y = calendar.date.getFullYear();
    var m = calendar.date.getMonth();     // integer, 0..11
    var d = calendar.date.getDate();      // integer, 1..31
	
		var datesIndex = y + '-' + m + '-' + d;
	
		//Special check. Technically, if day in calendar has been flagged, 
		//then it will exists
		if(specialDays[datesIndex] === undefined) {
			return false;
		}
	
		makeDayContent(specialDays[datesIndex]);	
	
		$('calendar-day-details').setStyle({display: 'block'});
  }
}

/**
 * Takes in an array of event info for the day, makes the html
 *
 * @return html
 **/
function makeDayContent(items) {

	var liTemplate = new Template('<li><span class="cal_type">#{type}</span><br><a href="#{aib_link}">#{title}</a><br><span class="date">#{display_date}</span><br>#{display_posted_by}</li>');

	var collect= '';
	items.each( function(item) {
		collect = collect.concat(liTemplate.evaluate(item));
	});

	$('event-detail-container').innerHTML = '';
	$('event-detail-container').insert(collect);
	
}

//Override their setdate to allow ajax refresh of the special days objects. specialDays
Calendar.prototype.setDate = function (date) {
	if (!date.equalsTo(this.date)) {
		
		if(Ajax.activeRequestCount > 0) {
			return false;
		}
		
		var lang = (typeof APATHY_USER_LANGUAGE === 'undefined') ? 'en' : APATHY_USER_LANGUAGE ;
		
		var url = 'json/'+lang+'/calendar/';		
		var month = 1 + date.getMonth();
		var year = date.getFullYear();
		//For successhandler...
		var that = this;

		var successHandler = function (transport) {
			
			if(transport.responseJSON) {
				specialDays = transport.responseJSON;
				that._init(that.firstDayOfWeek, date);
			} else {
				// some sort of error
				console.log('Problem With Response');
				console.log(transport);
			}

		};

		// @todo fix failure msg
		var failureHandler = function () {
			alert('Something went wrong... Try again please?');
		};


		var startHandler = function() {
			//Show the loading icon
			$('calendar-loading').removeClassName('hide');
		};

		var completeHandler = function() {
			//Show the loading icon
			$('calendar-loading').addClassName('hide');
		};

		new Ajax.Request( url.concat(year, '/', month),
		  {
		    method:'get',
		    onSuccess: successHandler,
		    onFailure: failureHandler,
				onCreate: startHandler,
				onComplete: completeHandler,
				evalJSON: true,
				sanitizeJSON: true
		  }
		);	

	}
};



Calendar.setup(
  {
    flat  : "calendar-container",        
    ifFormat    : "%Y-%m-%d %H:%M",    // the date format
    showsTime	  : false,
    weekNumbers : false,
		showOthers : true,
		dateStatusFunc : checkSpecialDay,
		flatCallback: dateChanged
   }
);

/**
 * Hide Day Details Box
 **/
function hideDayDetails() {
	$('calendar-day-details').setStyle({display: 'none'});
}

Event.observe('close-calendar-details', 'click', hideDayDetails);

});	

