var perpage = 6;
var basePath = "/cheme/news/";

function init(page_index, currDay, currMonth, currYear, allFlag) {
	/* pagination variables */	
	var prev = null;
	var next = null;
	var total = 0;

	if ($.query != "") {
		page_index = $.query.get('page_index');
		currDay = $.query.get('day');		
		currMonth = $.query.get('month');		
		currYear = $.query.get('year');		
		allFlag = $.query.get('flag');
	}
	if (allFlag) {
		var time = new Date();
		currMonth = time.getMonth() + 1;
		currYear = time.getFullYear();
		currDay = time.getDate();
	}
	if (page_index == "all") {
		prev = null;
	}
	else if (page_index > 0) {
		prev = 1;
	}
	
	$.getJSON( basePath + "events-data.js",
		function(jsondata){
			$.datepicker.setDefaults({ prevText: '<<', nextText: '>>'});
			$('#calendar').datepicker();
			$('#calendar').datepicker("setDate", new Date (months[currMonth - 1] + "1, " + currYear));
			$('.ui-datepicker-prev').click(function() {
				if (currMonth > 1) {
					currMonth = currMonth - 1;
				}
				else {
					currMonth = 12;
					currYear = currYear - 1;
				}
				if (window.location.href.match(/news\/calendar\.html$/)) {
					init(null, null, currMonth, currYear, null);
				}
				else {
					window.location.href = basePath + "calendar.html?page_index=0&month=" + currMonth + "&year=" + currYear;
				}
			});
			$('.ui-datepicker-next').click(function() {
				if (currMonth < 12) {
					currMonth = currMonth + 1;
				}
				else {
					currMonth = 1;
					currYear = currYear + 1;
				}
				if (window.location.href.match(/news\/calendar\.html$/)) {
					init(null, null, currMonth, currYear, null);
				}
				else {
					window.location.href = basePath + "calendar.html?page_index=0&month=" + currMonth + "&year=" + currYear;
				}
			});
			entries = jsondata.items;
			hiliteDays (entries);
			if (allFlag == "all") {
//				$('#monthyear').text("For the Year " + currYear + " - " + (currYear + 1).toString());
				$('#monthyear').text("View All Events");
				info = getUpcoming(entries, "events");
				loadData(info, page_index);
			}
			else if (allFlag == "both") {
				info = getUpcoming(entries, "both");
				loadMixedData(info, page_index);
			}
			else if (allFlag) {
				info = getFromCategory(entries, allFlag).sort(sortByDay);
				loadData(info, page_index);
			}
			else if (currDay) {
				$('#monthyear').text(currDay + " " + months[currMonth - 1] + " " + currYear);
				info = getFromDate(entries, currDay, currMonth, currYear, null, "events").sort(sortByDay);
				loadData(info, page_index);
			}
			else {
				$('#monthyear').text(months[currMonth - 1] + " " + currYear);
				info = getFromDate(entries, null, currMonth, currYear, null, "events").sort(sortByDay);
				loadData(info, page_index);
			}
			total = info.length;
			info = getFromDate(entries, new Date().getDate(), new Date().getMonth() + 1, new Date().getFullYear(), 1, "events");
			loadSpotlight(info[0]);
			info = getUpcoming(entries, "events", 3);
			loadUpcoming(info);

			/* figure out pagination flags */
			if (page_index == "all") {
				next = null;
			}
			else if (((page_index + 1) * perpage) < total) {
				next = 1;
			}
			
			if (prev) {
				$('.prev a').click(function () {
					if (window.location.href.match(/\.html$/)) {
						init (page_index - 1, null, currMonth, currYear, allFlag);
					}
					else {
						window.location.href = basePath + "calendar.html?page_index=" + (parseInt(page_index) - 1).toString() + "&month=" + currMonth + "&year=" + currYear;
					}
					return false;
				});
				$('.prev a').removeClass("hide");
			}
			else {
				$('.prev a').click(function () {
					return false;
				});
				$('.prev a').addClass("hide");
			}
			
			if (next) {
				$('.next a').click(function () {
					if (window.location.href.match(/\.html$/)) {
						init (page_index + 1, null, currMonth, currYear, allFlag);
					}
					else {
						window.location.href = basePath + "calendar.html?page_index=" + (parseInt(page_index) + 1).toString() + "&month=" + currMonth + "&year=" + currYear;
					}
					return false;
				});
				$('.next a').removeClass("hide");
			}
			else {
				$('.next a').click(function () {
					return false;
				});
				$('.next a').addClass("hide");
			}
		}
		
	);
	
}


function hiliteDays (info) {
	for (var i = 0; i < info.length; i++) {
		if (info[i].type == "event") {
			var dateStr = "#" + getDateStr(info[i]);
//			alert (dateStr);
			if (!$(dateStr).hasClass("has-event")) {
				$(dateStr).addClass("has-event");
				$(dateStr + " span.ui-state-default").wrap("<a>").click(selectDay);
			}
		}
	}
}


function selectDay () {
	var id = this.parentNode.parentNode.id;
	var newYear = id.substr(0, 4);
	var newMonth = id.substr(4, 2);
	var newDay = id.substr(6, 2);

	// the - 0 is to pass it as ints
	if (window.location.href.match(/calendar\.html$/)) {
		init (null, (newDay - 0), (newMonth - 0), (newYear - 0), null);
	}
	else {
		window.location.href = basePath + "calendar.html?day=" + newDay + "&month=" + newMonth + "&year=" + newYear;
	}
}

function getDateStr (date) {
	var dateStr = date.year.toString();
	if (date.month < 10) {
		dateStr += "0" + date.month.toString();
	}
	else {
		dateStr += + date.month.toString();
	}
	if (date.day < 10) {
		dateStr += "0" + date.day.toString();
	}
	else {
		dateStr += date.day.toString();
	}
	return dateStr;
}


function loadData(info, page_index) {
	var dataHTML = "";
	count = 0;
	if (page_index == "all") {
		for (var i = 0; i < info.length; i++) {
			dataHTML += getEventHTML(info[i]);
			count++;
		}
	}
	else {
		for (var i = page_index * perpage; i < info.length && count < perpage; i++) {
			dataHTML += getEventHTML(info[i]);
			count++;
		}
	}
	if (!dataHTML) {
		dataHTML = "<p>No events were found.</p>\n";
	}
	$("#eventlist").html(dataHTML);
}


function getEventHTML(item) {
	var dataHTML = "";
	dataHTML += "<h2><span class=\"small\">";
	dataHTML += item.category;
	dataHTML += "</span><br />";
	dataHTML += "<a href=\"";
	dataHTML += item.link;
	dataHTML += "\" class=\"smboldheader\">";
	dataHTML += item.title;
	dataHTML += "</a></h2>\n<p class=\"small\">";
	dataHTML += item.description;
	dataHTML += "<br />\n";
	dataHTML += months[item.month - 1];
	dataHTML += " ";
	dataHTML += item.day;
	dataHTML += ", ";
	dataHTML += item.year;
	dataHTML += "<br /><em>\n";
	dataHTML += item.time;
	dataHTML += ", ";
	dataHTML += item.location;
	dataHTML += "</em></p>\n";
	return dataHTML;
}

function loadMixedData (items, page_index) {
	items = items.sort(sortByDay);
	items = items.slice(page_index * perpage);
	var newset = new Array();
	var count = 0;
	var dataHTML = "";
	var currMonth = new Date().getMonth() + 1;
	var currYear = new Date().getFullYear();
	while (count < items.length && count < perpage) {
		newset = getFromDate(items, null, currMonth, currYear, perpage - count, "both").sort(sortByDay);
		if (newset.length) {
			dataHTML += "<h2 class=\"boldheader\">";
			dataHTML += months[currMonth - 1];
			dataHTML += "</h2>\n";
			for (var i = 0; i < newset.length; i++) {
				dataHTML += "<p class=\"small\">";
				dataHTML += months[newset[i].month - 1];
				dataHTML += " ";
				dataHTML += newset[i].day;
				dataHTML += " <a href=\"";
				dataHTML += newset[i].link;
				dataHTML += "\">";
				dataHTML += newset[i].title;
				dataHTML += "</a></p>\n";
			}
			count += newset.length;
		}
		if (count < items.length && count < perpage && newset.length) {
			dataHTML += "<hr />\n";
		}
		if (currMonth < 12) {
			currMonth = currMonth + 1;
		}
		else {
			currMonth = 1;
			currYear = currYear + 1;
		}
	}
	$("#eventlist").html(dataHTML);
}

function loadSpotlight(item) {
	if (item != null) {
		var dataHTML = "";
		dataHTML = "<h4 class=\"boldheader\">" + months[item.month - 1] + " " + item.day + ", " + item.year + "<br />" + item.time + "<br /><a href=\"";
		dataHTML += item.link;
		dataHTML += "\">";
		dataHTML += item.title;
		dataHTML += "</a></h4>\n";
		dataHTML += "<p class=\"small\"><a href=\"";
		dataHTML += item.link;
		dataHTML += "\">more &gt;&gt;</a></p>\n";
		$("#calendarbox").html(dataHTML);
	}
	else {
		$("#calendarbox").remove();
	}
}

function loadUpcoming(info) {
	var dataHTML = "<h3 class=\"boldheader\">Upcoming Events</h3>\n";
	for (var i = 0; i < info.length; i++) {
		dataHTML += "<p class=\"small\"><a href=\"";
		dataHTML += info[i].link;
		dataHTML += "\">";
		dataHTML += info[i].title;
		dataHTML += "</a><br />\n";
		dataHTML += months[info[i].month - 1];
		dataHTML += " ";
		dataHTML += info[i].day;
		dataHTML += ", ";
		dataHTML += info[i].year;
		dataHTML += "<br />\n";
		dataHTML += info[i].time;
		dataHTML += "</p>\n";
	}
	dataHTML += '<p class="small"><a href="#" id="viewall">View all events &gt;&gt;</a></p>';
	$("#upcoming").html(dataHTML);
	$("#viewall").click(function() {
				if (window.location.href.match(/news\/calendar\.html$/)) {
			init( "all", null, null, null, "all");
		}
		else {
			window.location.href = basePath + "calendar.html?page_index=all&flag=all";
		}
		return false;
	});
}


/* date functions */

var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");

function sortByDay(a, b) {
	var x = new Date().setFullYear(a.year, a.month - 1 , a.day);
	var y = new Date().setFullYear(b.year, b.month - 1 , b.day);
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function getFromDate(items, day, month, year, num, type) {
	var newset = new Array();
	for (var i = 0; i < items.length; i++) {
		if (type == "both" || (type == "events" && items[i].type == "event")) {
			if (items[i].month == month && items[i].year == year) {
				if ((day && items[i].day == day) || !day) { 
					newset[newset.length] = items[i];
					if (num && newset.length >= num) {
						return newset;
					}
				}
			}
		}
	}
	return newset;
}

function getFromCategory(items, category) {
	var newset = new Array();
	var today = new Date();
	var thisDay = new Date();
	for (var i = 0; i < items.length; i++) {
		thisDay.setFullYear(items[i].year, items[i].month - 1, items[i].day);
		if (items[i].category == category && thisDay >= today) {
			newset[newset.length] = items[i];
		}
	}
	return newset;
}

function getUpcoming(items, type, num) {
	items = items.sort(sortByDay);
	var newset = new Array();
	var today = new Date();
	var thisDay = new Date();
//	var yearAhead = new Date();
//	yearAhead.setYear(today.getFullYear() + 1);
	for (var i = 0; i < items.length; i++) {
		if (type == "both" || (type == "events" && items[i].type == "event")) {
			thisDay.setFullYear(items[i].year, items[i].month - 1 , items[i].day);
			if (thisDay >= today) {
				newset[newset.length] = items[i];
				if (num && newset.length >= num) {
					return newset;
				}
//				else if (num == null) {
//					if (thisDay > yearAhead) {
//						return newset;
//					}
//				}
			}
		}
	}	
	return newset;
}

