/* Author: Michael C Gorman <http://michaelcgorman.net/> for Milestones Early Learning Center & Preschool

*/

$(window).load(function(){$(".bg, .cols").setAllToMaxHeight();});

function json_request(url) {
	var script_tag = document.createElement("script");
	script_tag.setAttribute("src", url);
	document.getElementsByTagName("head")[0].appendChild(script_tag);
}

function contains(arr, srch_obj) {
	var arr_count = arr.length;
	for(var i = 0; i < arr_count; i++) {
		if(arr[i] === srch_obj) {
			return true;
		}
	}
	return false;
}

var facebook_photos = function() {
	//faux-globals... change as desired
	var g_discard_album_names = ["Profile Pictures"];
	var g_max_pic_count = 4;
	var g_album_ids = [];
	var g_display_tag = document.getElementsByTagName("body")[0];
	
	function sort_by_create_date(obj_a, obj_b) {
		return obj_a.created_time < obj_b.created_time;
	}
	
	function get_albums_from_page(page_id, display_element) {
		if(display_element) {
			g_display_tag = display_element;
		}
		var api_url = "http://graph.facebook.com/" + page_id + "/albums/?fields=id,name&callback=facebook_photos.filter_albums";
		json_request(api_url);
	}
	
	function filter_albums(albums) {
		var album_objs = albums.data;
		var album_count = album_objs.length;
		for(var i = 0; i < album_count; i++) {
			if(!contains(g_discard_album_names, album_objs[i].name)) {
				g_album_ids.push(album_objs[i].id);
			}
		}
		
		get_pictures_from_albums(g_album_ids);
	}
	
	function get_pictures_from_albums(album_ids) {
		var api_url = "http://graph.facebook.com/photos?ids=";
		var album_count = album_ids.length;
		if(album_count >= 1) {
			api_url += album_ids[0];
		}
		for(var i = 1; i < album_count; i++) {
			api_url += "," + album_ids[i];
		}
		api_url += "&fields=name,picture,link&callback=facebook_photos.filter_pictures&limit="+g_max_pic_count;
		json_request(api_url);
	}
	
	function filter_pictures(albums) {
		var picture_objs = [];
		var album_count = g_album_ids.length;
		var album_id;
		var album_obj;
		var album_picture_count = 0;
		
		for(var i = 0; i < album_count; i++) {
			album_id = g_album_ids[i];
			if(albums[album_id] && albums[album_id].data) {
				album_obj = albums[album_id].data;
				album_picture_count = album_obj.length;
	
				for(var j = 0; j < album_picture_count; j++) {
					picture_objs.push(album_obj[j]);
				}
			}
		}
		
		display_pictures(picture_objs.sort(sort_by_create_date).slice(0, g_max_pic_count));
	}
	
	function display_pictures(picture_objs) {
		var picture_count = picture_objs.length;
		
		for(var i = 0; i < picture_count; i++) {
			display_picture(picture_objs[i]);
		}
	}
	
	function display_picture(picture_obj) {
		var picture_tag = document.createElement("img");
		var append_tag = picture_tag;
		if(picture_obj.picture) {
			picture_tag.setAttribute("src", picture_obj.picture);
		}
		if(picture_obj.name) {
			picture_tag.setAttribute("alt", picture_obj.name);
			picture_tag.setAttribute("title", picture_obj.name);
		}
		if(picture_obj.link) {
			var link_tag = document.createElement("a");
			link_tag.setAttribute("href", picture_obj.link);
			link_tag.appendChild(picture_tag);
			append_tag = link_tag;
		}
		
		if(g_display_tag.tagName == "UL" || g_display_tag.tagName == "OL") {
			var list_item_tag = document.createElement("li");
			list_item_tag.appendChild(append_tag);
			g_display_tag.appendChild(list_item_tag);
		}
		else {
			g_display_tag.appendChild(append_tag);
		}
	}
	
	return {
		get_albums_from_page:get_albums_from_page,
		filter_albums:filter_albums,
		filter_pictures:filter_pictures
	}
}();

if(document.getElementById("facebook-photos")) {
	facebook_photos.get_albums_from_page("148790931817304", document.getElementById("facebook-photos"));
}




// code for programs.html

/**
 * Adds a leading zero to a single-digit number.	Used for displaying dates.
 */
function padNumber(num) {
	if (num <= 9) {
		return "0" + num;
	}
	return num;
}

/**
 * Uses Google data JS client library to retrieve a calendar feed from the
 * specified URL.	 The feed is controlled by several query parameters and a
 * callback function is called to process the feed results.
 *
 * @param {string} calendarUrl is the URL for a public calendar feed
 * 
 * TODO: automatically figure out the year
 */	 
function loadCalendar(calendarUrl) {
	var service = new 
	   google.gdata.calendar.CalendarService('gdata-js-client-samples-simple');
	var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
	query.setOrderBy('starttime');
	query.setSortOrder('ascending');
	query.setSingleEvents(true);
	query.setMinimumStartTime(
	         google.gdata.DateTime.fromIso8601('2010-09-01T00:00:00.000-05:00')
	);
	query.setMaximumStartTime(
	         google.gdata.DateTime.fromIso8601('2011-09-01T00:00:00.000-05:00')
	);

	service.getEventsFeed(query, listEvents, handleGDError);
}

/**
 * Callback function for the Google data JS client library to call when an error
 * occurs during the retrieval of the feed.	 Details available depend partly
 * on the web browser, but this shows a few basic examples. In the case of
 * a privileged environment using ClientLogin authentication, there may also
 * be an e.type attribute in some cases.
 *
 * @param {Error} e is an instance of an Error 
 */
function handleGDError(e) {
	document.getElementById('jsSourceFinal').setAttribute('style', 
			'display:none');
	if (e instanceof Error) {
		/* alert with the error line number, file and message */
		alert('Error at line ' + e.lineNumber +
					' in ' + e.fileName + '\n' +
					'Message: ' + e.message);
		/* if available, output HTTP error code and status text */
		if (e.cause) {
			var status = e.cause.status;
			var statusText = e.cause.statusText;
			alert('Root cause: HTTP error ' + status + ' with status text of: ' + 
						statusText);
		}
	} else {
		alert(e.toString());
	}
}

/**
 * Callback function for the Google data JS client library to call with a feed 
 * of events retrieved.
 *
 * Creates an unordered list of events in a human-readable form.	This list of
 * events is added into a div called 'events'.	The title for the calendar is
 * placed in a div called 'calendarTitle'
 *
 * @param {json} feedRoot is the root of the feed, containing all entries 
 */ 
function listEvents(feedRoot) {
	var entries = feedRoot.feed.getEntries();
	var monthElements = getMonths();
	
	/* loop through each event in the feed */
	var len = entries.length;
	for (var i = 0; i < len; i++) {
		var entry = entries[i];
		var title = entry.getTitle().getText();
		var startDateTime = null;
		var startJSDate = null;
		var times = entry.getTimes();
		if (times.length > 0) {
			startDateTime = times[0].getStartTime();
			startJSDate = startDateTime.getDate();
		}
		var entryLinkHref = null;
		if (entry.getHtmlLink() != null) {
			entryLinkHref = entry.getHtmlLink().getHref();
		}
		var dateString = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
		if (!startDateTime.isDateOnly()) {
			dateString += " " + startJSDate.getHours() + ":" + 
					padNumber(startJSDate.getMinutes());
		}
		
		var eventElement = document.createElement('div');

		eventElement.appendChild(
		                    document.createTextNode(dateString + ' - ' + title)
		);

		monthElements[startJSDate.getMonth()].appendChild(eventElement);
	}
}

function getMonths() {
	var months = new Array(12);
	var monthHash = [
		{num: 8, name: 'September'},
		{num: 9, name: 'October'},
		{num: 10, name: 'November'},
		{num: 11, name: 'December'},
		{num: 0, name: 'January'},
		{num: 1, name: 'February'},
		{num: 2, name: 'March'},
		{num: 3, name: 'April'},
		{num: 4, name: 'May'},
		{num: 5, name: 'June'},
		{num: 6, name: 'July'},
		{num: 7, name: 'August'}
	];
	
	var events_container = document.getElementById('programs_events');
	var container;
	
	for(var i = 0; i < monthHash.length; i++) {
		if(i % 3 == 0) {
			container = document.createElement('div');
			container.className = "monthRow";
			events_container.appendChild(container);
		}
		var currentMonth = months[monthHash[i].num] =
		                                     document.createElement('article');
		var monthName = document.createElement('h1');
		monthName.innerHTML = monthHash[i].name;

		currentMonth.className = "grid_3 " + ((i%3 == 0) ? "alpha ":"") + ((i%3 == 2) ? "omega ":"") + monthHash[i].name.toLowerCase();

		currentMonth.appendChild(monthName);
		container.appendChild(currentMonth);
	}
	
	return months;
}

if(false && document.getElementById("programs_events")) {
	loadCalendar('http://www.google.com/calendar/feeds/b1h00mtnc5jn8cvk1okqdgicfg@group.calendar.google.com/public/full?alt=json');
}


/*$('.admin textarea').autoResize({
	// On resize:
	onResize : function() {
		$(this).css({opacity:0.8});
	},
	// After resize:
	animateCallback : function() {
		$(this).css({opacity:1});
	},
	// Quite slow animation:
	animateDuration : 300,
	// More extra space:
	extraSpace : 40
}).trigger('change');

$('.admin textarea').change(function(){
	var url = "update.php";
	var data = {
		file: $(this).attr('name'),
		content: $(this).val()
	};
	$.post(url,data);
}); */

