if (typeof Podbop == 'undefined') Podbop = {};

Podbop.Matches = {
	COOKIE_NAME:     'only_matches',
	COOKIE_LIFETIME: 365,
	CHECKBOX_ID:     'only_matches',
	LIST_ID:         'events',
	NONE_ID:         'no_matches',
	NONE_MESSAGE:    'No events with MP3s found.',

	init: function() {
		var checkbox = $(Podbop.Matches.CHECKBOX_ID);
		if (checkbox) {
			addEvent(checkbox, 'onclick', Podbop.Matches.filter);
			addEvent(checkbox, 'onclick', Podbop.Matches.setCookie);

			var onlyMatches = Podbop.Matches.getCookie();
			if (onlyMatches) {
				if (! checkbox.checked) checkbox.click();

				// Filter to account for form fill on browser reload
				Podbop.Matches.filter();
			}
		}
	},
	filter: function() {
		var checkbox = $(Podbop.Matches.CHECKBOX_ID);
		var list = $(Podbop.Matches.LIST_ID);
		if (! checkbox || ! list) return;

		var events = list.getElementsByTagName('li');
		var numMatches = 0;
		for (var i = 0; i < events.length; i++) {
			var event = events[i];
			if (Element.hasClassName(event, 'event')) {
				if (Element.hasClassName(event, 'match')) {
					numMatches++;
				}
				else {
					checkbox.checked ? Element.hide(event) : Element.show(event);
				}
			}
		}

		if (numMatches == 0) {
			var p = $(Podbop.Matches.NONE_ID);
			if (checkbox.checked) {
				if (! p) {
					p = document.createElement('p');
					p.setAttribute('id', Podbop.Matches.NONE_ID);
					p.appendChild(document.createTextNode(Podbop.Matches.NONE_MESSAGE));
					list.parentNode.appendChild(p);
				}
			}
			else if (p) {
				Element.remove(p);
			}
		}
	},
	setCookie: function() {
		if (typeof Cookie == 'undefined') return;

		var checkbox = $(Podbop.Matches.CHECKBOX_ID);
		Cookie.create(Podbop.Matches.COOKIE_NAME, checkbox.checked ? 1 : 0, Podbop.Matches.COOKIE_LIFETIME);
	},
	getCookie: function() {
		if (typeof Cookie == 'undefined') return;

		var c = Cookie.read(Podbop.Matches.COOKIE_NAME);
		return c == 1 ? true : false;
	}
};

addEvent(window, 'onload', Podbop.Matches.init);
