function Filters() {
	this._currentFilters = new Array();
}

Filters.prototype._currentFilters;

Filters.prototype.addCategory = function(category) {
	this._currentFilters.push(category);
	this._currentFilters.sort();
};

Filters.prototype.removeCategory = function(category) {
	this._currentFilters = $.grep(this._currentFilters,function(value) {
			return value != category;
		}
	);
};

Filters.prototype.getCategories = function() {
	return this._currentFilters;
};

Filters.prototype.hasCategory = function(category) {
	var stringOfArray = this._currentFilters.toString();
	if (stringOfArray.search(category) != -1) {return true;};
	return false;
};

var filters = new Filters();

function getCategory (node) {
	return node.parent().attr('id');
};

function initFilterEvents () {
	$("table li").each(function() {
		var show = false;
		var classes = $(this).attr("class").split(",");
		for (i=0; i<classes.length; i++) {
			(filters.hasCategory(classes[i])) ? show = true : show = show;
		}
		(show == true) ? $(this).show() : $(this).hide();
	});
}

function initFilters() {
	var address = document.location.toString();
	if (address.match('categories')) {
		$("#content-section-nav li a.checked").each(function(index) {
			filters.addCategory(getCategory($(this)));
		});
		initFilterEvents();
	} else {
		var categories = getCookie('filter');
		
		$("#content-section-nav li a").each(function(index) {
			
			if (categories != null) {
				if (categories.search($(this).parent().attr("id")) != -1) {
					$(this).removeClass("unchecked");
					$(this).addClass("checked");
					filters.addCategory(getCategory($(this)));
				} else {
					$(this).removeClass("checked");
					$(this).addClass("unchecked");
					filters.removeCategory(getCategory($(this)));
				};
			} else {
				if ($(this).hasClass('unchecked') == false ) {
					$(this).addClass("checked");
				}
				
				filters.addCategory(getCategory($(this)));;
			}
			
		});
	}
	$("li ul li:has(ul)").addClass("expandable");
	$('.expandable ul').hide();
}

function expandFilter() {
	$(".expandable").click(function() {
		if ($(this).hasClass("expanded")) {
			// These callbacks MUST be anonymous, otherwise they are called too soon
			$(this).children('ul').slideUp('normal', function() {resizeBody();});
			$(this).removeClass("expanded");
		} else {
			$(this).addClass("expanded");
			$(this).children('ul').slideDown('normal', function() {resizeBody();});
		}
		return false;
	});
	
	$('.expandable').find('a:first').click(function() {
		var parent = $(this);
		parent.parent().find('ul li a').each(function() {
			if (parent.hasClass("checked")) {
				$(this).removeClass("checked");
				$(this).addClass("unchecked");
				filters.removeCategory(getCategory($(this)));
			} else {
				$(this).removeClass("unchecked");
				$(this).addClass("checked");
				filters.addCategory(getCategory($(this)));
			}
		});
		return false;
	});
}

function checkboxes() {
	$("#checkall").click(function() {
		if ($(this).hasClass('unchecked')) {
			$("#content-section-nav li a").each(function () {
				$(this).removeClass("unchecked");
				$(this).addClass("checked");
				filters.addCategory(getCategory($(this)));
			});
		} else {
			$("#content-section-nav li a").each(function () {
				$(this).removeClass("checked");
				$(this).addClass("unchecked");
				filters.removeCategory(getCategory($(this)));
			});
		}
		filterEvents();
	});
	
	$("#content-section-nav li a").click(function() {
		if ($(this).attr("id") != "checkall") { 
			if ($(this).hasClass("unchecked"))
			{
				$(this).removeClass("unchecked");
				$(this).addClass("checked");
				filters.addCategory(getCategory($(this)));
			} else {
				$(this).removeClass("checked");
				$(this).addClass("unchecked");	
				filters.removeCategory(getCategory($(this)));
			}
		}
		return false;
	});
	
}

function filterEvents () {
	$('#content-section-nav li a').click(function() {
		// Act on the event
		$('table li').each(function(index) {
			var found = false;
			// if the li category does not exist within filters, hide it!
			// don't forget multiple categories
		
			// gets the classes and splits them into an array
			var classes = $(this).attr("class").split(",");
			
			// see if any of the classes exist within the currently checked filters
			for (var i=0; i < classes.length; i++) {
				if (filters.hasCategory(classes[i])) {
					found = true;
				};
			};
			if (found) {
				$(this).show();
			} else {
				$(this).hide();
			};
		});
		updateRssFilter();
		setCookie();
	});
}

function updateRssFilter() {
	$('#calendar-rss a').attr('href', '/calendar/rss/'+getIds());
	$('#ical-url').attr('value', 'http://rowlandhall.org/calendar/ical/'+getIds());
	$('#ical-url').bind('click',function(){$('#ical-url').select()})

}

function changeMonth() {
	// Next Month Link
	$('.next_month a').click(function() {
		var path = $(this).attr('href');
		path = path.split('/categories:');
		$(this).attr('href', path[0]+'/'+getIds());
	});
	
	// Previous Month Link
	$('.previous_month a').click(function() {
		var path = $(this).attr('href');
		path = path.split('/categories:');
		$(this).attr('href', path[0]+'/'+getIds());
	});
	
	// Form 
	$('#content-main form .go').click(function() {
		$('#content-main form .categories').attr('value',getIds());
	});
}

function getIds () {
	var ids = [];
	if (typeof( window[ 'addl_ids' ] ) != "undefined")ids.push(addl_ids);
	$('#content-section-nav li a[@class=checked]').each(function(index) {
		ids.push($(this).parent().attr('id').replace(/cat/, ''));
	});
	
	// Strips out blank items in the array
	var length = ids.length;
	for (var i=0; i < length; i++) {
		if (ids[i] == '') {
			ids.splice(i, 1);
		};
	};
	
	ids.join(',');
	
	// Builds the link, if there are no categories, it uses 2 to not confuse the system
	if (ids.length > 0) {
		ids = 'categories:' + ids;
	} else {
		ids = 'categories:2';
	};
	
	return ids;
}

/**
 * Sets cookie to remember calendar filter state
 */
function setCookie() {
	var checkedString = "";
	var checkedArray = new Array();
	var i = 0;
	
	// Goes through checked checkboxes and adds them to an array to put in a cookie
	$('#content-section-nav li a').each(function(index) {
		if ($(this).attr("class") == "checked") {
			checkedArray[i] = $(this).parent().attr("id");
			i++;
		};
		checkedString = checkedArray.join("|");
	});
	
	var date = new Date();
	date.setTime(date.getTime()+(7*24*60*60*1000*365)); // Cookie will last for 7 years
	var expires = date.toGMTString();
	
	// Set cookies for both calendar paths, some browsers need this
	document.cookie = "filter="+checkedString+"; expires="+expires+"; path=/calendar;";
}

/**
 * Gets the cookie
 * @param {String} c_name Name of the cookie we are looking for
 * @returns String of contents if cookie is found, otherwise NULL
 */
function getCookie(c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) {
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} else {
			return null;
		}
	}
}

/**
 * Shows/Hides events based on what's in the cookie
 */
function loadFromCookie() {
	var categories = getCookie('filter');
	
	
	if (categories != null) {
		var categoriesArray = categories.split("|");
		$('table li').each(function(index) {
			var found = false;
			// if the li category does not exist within filters, hide it!
			// don't forget multiple categories

			// gets the classes and splits them into an array
			var classes = $(this).attr("class").split(",");

			// see if any of the classes exist within the currently checked filters
			for (var i=0; i < classes.length; i++) {
				if (categories.search(classes[i]) != -1) {
					found = true;
				};
			};
			if (found) {
				$(this).show();
			} else {
				$(this).hide();
			};
		});
	}
}

$(document).ready(function(){
	initFilters();
	expandFilter();
	checkboxes();
	filterEvents();
	$('.expandable').removeClass('expanded');
	updateRssFilter();
	changeMonth();
	loadFromCookie();
});

function resizeBody() {
	if ($('#content-outer').height() < $('#content-section').height()) {
		$('#content-outer').height($('#content-section').height()+'px');
	} else {
		$('#content-outer').height('auto');
	};
}


