// Copyright (c) 2012 by Stephen C. Dewhurst

function get_datetime(file_name) {
	return file_name.substr(15, 12);
}

function get_datetime_year(datetime) {
	return datetime.substr(0, 4);
}

function get_datetime_month(datetime) {
	return datetime.substr(4, 2);
}

function get_datetime_day(datetime) {
	return datetime.substr(6, 2);
}

function get_datetime_hour(datetime) {
	return datetime.substr(8, 2);
}

function get_datetime_minute(datetime) {
	return datetime.substr(10, 2);
}

function datetime_to_day_of_week(datetime) {
	var year = parseInt(get_datetime_year(datetime), 10);
	var month = parseInt(get_datetime_month(datetime), 10);
	var day = parseInt(get_datetime_day(datetime), 10);
	var d = new Date(year, month-1, day);
	var dow = d.getDay();
	switch (dow) {
		case 0: return "Sunday";
		case 1: return "Monday";
		case 2: return "Tuesday";
		case 3: return "Wednesday";
		case 4: return "Thursday";
		case 5: return "Friday";
		case 6: return "Saturday";
	}
	return "";
}

function datetime_to_date_time(datetime) {
	var year = get_datetime_year(datetime);
	var month = get_datetime_month(datetime);
	var day = get_datetime_day(datetime);
	var hour = get_datetime_hour(datetime);
	var minute = get_datetime_minute(datetime);
	var pm = false;

	var i_hour = parseInt(hour, 10);
	var i_minute = parseInt(minute, 10);

	var time = "";

	switch (i_hour) {
	case 0:	
		if (i_minute == 0) {
			time = "midnight";
		}
		else {
			hour = "12";
			pm = false;
		}
		break;
	case 1:
	case 2:
	case 3:
	case 4:
	case 5:
	case 6:
	case 7:
	case 8:
	case 9:
	case 10:
	case 11:
		hour = i_hour.toString();
		pm = false;
		break;
	case 12:
		if (i_minute == 0) {
			time = "noon";
		}
		else {
			pm = true;
		}
		break;
	case 13:
	case 14:
	case 15:
	case 16:
	case 17:
	case 18:
	case 19:
	case 20:
	case 21:
	case 22:
	case 23:
		i_hour -= 12;
		hour = i_hour.toString();
		pm = true;
		break;
	}

	if (time == "")
		time = hour + ":" + minute + (pm ? "pm" : "am");

	return month + "/" + day + "/" + year + " at " + time;
}

function deptcode_to_deptname_long(code, dept_map) {
	for (var i = 0; i != dept_map.length; ++i) {
		if (dept_map[i][0] == code)
			return dept_map[i][1];
	}
	return "Unknown Department";
}

function deptcode_to_deptname_short(code, dept_map) {
	for (var i = 0; i != dept_map.length; ++i) {
		if (dept_map[i][0] == code)
			return dept_map[i][2];
	}
	return "Unknown";
}

function get_department_long(file, dept_map) {
	var dept = file.substr(0, 3);
	return deptcode_to_deptname_long(dept, dept_map);
}

function get_department_short(file, dept_map) {
	var dept = file.substr(0, 3);
	return deptcode_to_deptname_short(dept, dept_map);
}

function get_type(file) {
	return file.substr(13, 1);
}

function unencode_char(encoding) {
	char_encoding_map = [
	["-"	,	"_-"],
	[","	,	"_b"],
	["\""	,	"_c"],
	["'"	,	"_d"],
	["?"	,	"_e"],
	["!"	,	"_f"],
	["("	,	"_g"],
	[")"	,	"_h"],
	[":"	,	"_i"],
	[";"	,	"_j"],
	["&"	,	"_k"],
	["@"	,	"_l"],
	["$"	,	"_m"],
	["%"	,	"_n"],
	["#"	,	"_o"],
	["*"	,	"_p"],
	["["	,	"_q"],
	["]"	,	"_r"],
	["<"	,	"_s"],
	[">"	,	"_t"],
	["="	,	"_u"],
	["~"	,	"_v"],
	["^"	,	"_w"],
	["/"	,	"_x"],
	["\\"	,	"_y"],
	["|"	,	"_z"],
	["_"	,	"__"]
	];

	for (var i = 0; i != char_encoding_map.length; ++i) {
		if (char_encoding_map[i][1] == encoding) {
			return char_encoding_map[i][0];
		}
	}
	return ".";
}

// convert previously-converted text back to printable text
// Note: another php version of this function exists: maintain both!!!
function fn_to_text(fn) {
	var text = "";
	if (fn.length == 0)
		return text;

	var i = 0;
	while (i < fn.length) {
		if (fn[i] == "-") {		// hyphen back to blank
			text += " ";
			++i;
		}
		else if (fn[i] == "_") {	// underscore starts encoding
			var encoding = "_" + fn[i+1];
			var unencoded = unencode_char(encoding);
			if (unencoded == undefined)	// for IE7
				unencoded = ".";
			text += unencoded;
			i += 2;
		}
		else {				// it's POSIX
			var the_char = fn[i++];
			if (the_char == undefined)	// IE7 again
				the_char = "-";
			text += the_char;
		}
	}

	return text;
}

function process_location_for_display(loc) {
	return fn_to_text(loc);
}

function get_location(file) {
	return file.substr(27);
}

function process_linktext_for_display(linktext) {
	return fn_to_text(linktext);
}

function get_linktext(file) {
	var ltlen = parseInt(file.substr(15, 2), 10);
	return file.substr(17, ltlen);
}

function get_status(file) {
	return file.substr(14, 1);
}

function get_identifier(file) {
	return file.substr(3, 10);
}

function is_cancelled(file) {
	return get_status(file) == "x";
}

function is_changed(file) {
	return get_status(file) == "c";
}

function is_revised(file) {
	var s = get_status(file);
	return s=="1" || s=="2" || s=="3" || s=="4" || s=="5"
		|| s=="6" || s=="7" || s=="8" || s=="9";
}

function postings_comp(a, b) {
	var a_dt = get_datetime(a[1]);
	var b_dt = get_datetime(b[1]);
	if (a_dt < b_dt)
		return -1;
	if (a_dt > b_dt)
		return 1;
	return 0;
}

function postings_comp2(a, b) {
	var a_dt = get_datetime(a[1]);
	var b_dt = get_datetime(b[1]);
	if (a_dt > b_dt)
		return -1;
	if (a_dt < b_dt)
		return 1;
	return 0;
}

function document_is_post(file) {
	return get_type(file) == "p";
}

function document_is_agenda(file) {
	return get_type(file) == "a";
}

function document_is_minutes(file) {
	return get_type(file) == "m";
}

function document_is_aux(file) {
	return get_type(file) == "x";
}

function compare_datetime_to_now(datetime) {	// -1 => datetime is past, 0 => datetime is now, 1 => datetime is future
	var now = new Date();
	var nyear = now.getFullYear();
	var nmonth = now.getMonth()+1;
	var nday = now.getDate();
	var nhour = now.getHours();
	var nminute = now.getMinutes();

	var year = get_datetime_year(datetime);
	var month = get_datetime_month(datetime);
	var day = get_datetime_day(datetime);
	var hour = get_datetime_hour(datetime);
	var minute = get_datetime_minute(datetime);

	if (year > nyear) return 1;
	if (year < nyear) return -1;
	if (month > nmonth) return 1;
	if (month < nmonth) return -1;
	if (day > nday) return 1;
	if (day < nday) return -1;
	if (hour > nhour) return 1;
	if (hour < nhour) return -1;
	if (minute > nminute) return 1;
	if (minute < nminute) return -1;
	return 0;
}

function datetime_is_in_the_past(datetime) {
	return compare_datetime_to_now(datetime) === -1;
}

function datetime_is_in_the_future(datetime) {
	return compare_datetime_to_now(datetime) === 1;
}

function datetime_is_right_now(datetime) {
	return compare_datetime_to_now(datetime) === 0;
}

function get_current_meetings(f, postings) {
	for (var i = 0; i != f.length; ++i) {
		if (datetime_is_in_the_future(get_datetime(f[i][1])))	// post dir file name	
			postings.push(f[i].slice());			// meeting hasn't taken place yet
	}
	if (postings.length > 0)
		postings.sort(postings_comp);
}

function get_past_meetings(f, postings) {
	for (var i = 0; i != f.length; ++i) {
		if (datetime_is_in_the_past(get_datetime(f[i][1])))
			postings.push(f[i].slice());
	}
	if (postings.length > 0)
		postings.sort(postings_comp2);
}

function get_searched_meetings(f, postings, dept_code, start_date, end_date) {
	var start_date_string = start_date.substr(6, 4) + start_date.substr(0, 2) + start_date.substr(3, 2);
	var end_date_string = end_date.substr(6, 4) + end_date.substr(0, 2) + end_date.substr(3, 2);
	for (var i = 0; i != f.length; ++i) {
		var post = f[i][1];
		var dept = post.substr(0, 3);
		if (dept_code == dept) {
			var post_date = get_datetime(post);
			if ((post_date >= start_date_string) && (post_date <= end_date_string))
				postings.push(f[i].slice());
		}
	}
	if (postings.length > 0)
		postings.sort(postings_comp);
}

function formatPublicDocuments(postings, max, dept_map) {
	var BEGIN = "";
	var END = "";
	var ITEM_START = "<hr width=100% align=left size=1>";
	var POST_BEGIN = "";
	var POST_END = "";
	var DEPARTMENT_BEGIN = "<b>";
	var DEPARTMENT_END = "</b>";
	var LOCATION_BEGIN     = "";
	var LOCATION_END       = "";
	var DATETIME_BEGIN     = "<br><i>";
	var DATETIME_END       = "</i>";
	var AGENDA_BEGIN = "";
	var AGENDA_END = "";
	var MINUTES_BEGIN = "";
	var MINUTES_END = "";
	var AUX_BEGIN = "";
	var AUX_END = "";
	var SHOW_BEGIN = "&nbsp;<span class=\"showmore_item\"></span><div class=\"showmore_subitem\">";
	var SHOW_END = "</div>";
	var ITEM_END = "";

	var listStr = "";
	//xxxlistStr += "max = " + max + "<br>";
	try {
		if (postings.length == 0) {
			listStr = BEGIN + "There are no public meetings." + END;
		}
		else {
			//xxxlistStr += "else<br>";
			for (var i = 0; i != postings.length; ++i) {	// for each post dir
				//xxxlistStr += "i = " + i + ", length = " + postings.length + "<br>";
				if (i == max)
					break;

				var post_dir_path = postings[i][0] + "/" + postings[i][1];
				var post_dir_name = postings[i][1];

				var department =				// display info for post
					(max > 30)
					? get_department_long(post_dir_name, dept_map)
					: get_department_short(post_dir_name, dept_map);
				var location1 = get_location(post_dir_name); // hack for IE7
				var location = process_location_for_display(location1);
				var datetime = get_datetime(post_dir_name);
				var day_of_week = datetime_to_day_of_week(datetime);
				var cancelled = is_cancelled(post_dir_name);
				var changed = is_changed(post_dir_name);
				var date_time = datetime_to_date_time(datetime);

				var agenda_paths = "";
				var minutes_paths = "";
				var aux_paths = "";
				for (var j = 2; j < postings[i].length; ++j) {		// for each file in post dir
					//xxxlistStr += "&nbsp;&nbsp;j = " + j + ", length = " + postings[i].length + "<br>";
					var file = postings[i][j];			// file name
					//xxxlistStr += "&nbsp;&nbsp;file = " + file + "<br>";
					if (document_is_agenda(file)) {
						var agenda_path = post_dir_path + "/" + file;
						agenda_path = "<a href=\"" + agenda_path + "\" target=\"_blank\">agenda";
						if (is_revised(file)) {
							var s = get_status(file);
							if (s == "1")
								agenda_path += " (revised)";
							else
								agenda_path += " (revision " + s + ")";
						}
						agenda_path += "</a>";
						agenda_paths += "<br>" + agenda_path;
					}
					else if (document_is_minutes(file)) {
						var minutes_path = post_dir_path + "/" + file;
						minutes_path = "<a href=\"" + minutes_path + "\" target=\"_blank\">minutes";
						if (is_revised(file)) {
							var s = get_status(file);
							if (s == "1")
								minutes_path += " (revised)";
							else
								minutes_path += " (revision " + s + ")";
						}
						minutes_path += "</a>";
						minutes_paths += "<br>" + minutes_path;
					}
					else if (document_is_aux(file)) {
						var aux_file = file;
						var linktext = get_linktext(aux_file);
						linktext = process_linktext_for_display(linktext);
						var aux_path = post_dir_path + "/" + aux_file;
						aux_path = "<a href=\"" + aux_path + "\" target=\"_blank\">"
								+ linktext + "</a>";
						aux_paths += "<br>" + aux_path;
					}
				} // for each file in post directory
				var file_paths = agenda_paths + minutes_paths + aux_paths;

				var listLine =
					ITEM_START
					+ POST_BEGIN
					+ DEPARTMENT_BEGIN
					+ department
					+ (cancelled ? "<font color=\"red\">&nbsp;canceled</font>" : "")
					+ (changed ? "<font color=\"blue\">&nbsp;changed</font>" : "")
					+ DEPARTMENT_END
					+ DATETIME_BEGIN + date_time + DATETIME_END
					+ SHOW_BEGIN
					+ ((day_of_week == "") ? "" : (day_of_week + "<br>"))
					+ LOCATION_BEGIN + location + LOCATION_END
					+ file_paths
					+ SHOW_END
					+ POST_END
					+ ITEM_END;
				listStr += listLine;
			} // for each post dir

			listStr = BEGIN + listStr + END;
		}
	} 
	catch (e) {
	}

	return listStr;
}

function writeUpcomingPublicMeetings(publicDocumentsArray, criterion, max, dept_map) {
	var postings = new Array();
	if (criterion == "upcoming")
		get_current_meetings(publicDocumentsArray, postings);	// sorted array of valid meetings
	else if (criterion == "recent_past")
		get_past_meetings(publicDocumentsArray, postings);	// sorted array of valid meetings
	var docsStr = formatPublicDocuments(postings, max, dept_map);	// format them
	return docsStr;							// and send them back
}

function writeSearchedPublicMeetings(publicDocumentsArray, dept_code, start_date, end_date, max, dept_map) {
	//var xxxx = "<h3>publicDocumentsArray: " + publicDocumentsArray.length
	//		+ "|" + dept_code + "|" + start_date + "|" + end_date + "|" + max + "|" + dept_map.length + "</h3>";
	//return xxxx;
	var postings = new Array();
	get_searched_meetings(publicDocumentsArray, postings, dept_code, start_date, end_date);
	var docsStr = formatPublicDocuments(postings, max, dept_map);	// format them
	return docsStr;							// and send them back
}

