// JavaScript Document

$(function() {

	var myDates = new Array();
	var d = new Date();

	// load initial event batch
	$.ajax({
		url: '/event_feed.php', // gets current, previous and next month
		type: 'GET', 
		global: false,
		dataType: 'json', 
		data: {'year': d.getFullYear(), 'month': d.getMonth()+1},
		success: function(json) {
			if (parseInt(json.server_status)) {
				myDates.length = 0;
				for (i = 0; i < json.server_reply.length; i++) {
					myDates[i] = new Array(json.server_reply[i].event_date, json.server_reply[i].class_name, json.server_reply[i].description);
				}
			}
			// initialize datepicker with ajax events feed
			$("#eventspicker").datepicker({
				dateFormat: 'yy-mm-dd',
				beforeShowDay: getDays,
				onChangeMonthYear: getDates,
				onSelect: onSelect
			});
			$("td.custom-highlight, td.custom-highlight-important").tooltip();
		},
		error: function() {
			// initialize dummy datepicker without ajax events feed
			$("#eventspicker").datepicker({
				dateFormat: 'yy-mm-dd',
				onSelect: onSelect
			});
			$("td.custom-highlight, td.custom-highlight-important").tooltip();
		}
	});

	function getDays (d) {
		var theday = d.getFullYear()+"-"+zeroPad(d.getMonth()+1, 2)+"-"+zeroPad(d.getDate(),2); // format mysql date
		if (myDates.length) {
			for (i = 0; i < myDates.length; i++) {
				if (theday == myDates[i][0]) {
					return [true, myDates[i][1], myDates[i][2]];
				}
			}
		}
		return [true, ''];
	}

	function getDates(year, month) {
		$.ajax({
			url: '/event_feed.php', // gets current, previous and next month
			type: 'GET', 
			global: false,
			dataType: 'json', 
			data: {'year': year, 'month': month},
			success: function(json) {
				if (parseInt(json.server_status)) {
					myDates.length = 0;
					for (i = 0; i < json.server_reply.length; i++) {
						myDates[i] = new Array(json.server_reply[i].event_date, json.server_reply[i].class_name, json.server_reply[i].description);
					}
				}
				$("td.custom-highlight, td.custom-highlight-important").tooltip();
			}
		});
	}

	function onSelect (selectedDate) {
		var instance = $(this).data("datepicker");
		window.location.href = '/kalendarium/'+selectedDate+'/';
		$(this).delay(2000); // let the page reload before the datepicker disaperars
	}	
	

	function zeroPad (num, count) {
		var numZeropad = num + '';
		while(numZeropad.length < count) {
			numZeropad = "0" + numZeropad;
		}
		return numZeropad;
	}

});

