var aGigs = {

	types: new Array(),
	locations: new Array(),
	
	init: function() {
		//event types
		$("ul#events li.event").each(function() {
			var type = $("li.type:eq(0)",this).text();
			aGigs.types.push(type);
		});
		var cleanArray = aGigs.makeUnique(aGigs.types);
		var amountArray = aGigs.getAmounts(cleanArray,aGigs.types);
		aGigs.doTypeDropdowns(cleanArray,amountArray);
		//locations
		$("ul#events li.event").each(function() {
			var location = $("li.town:eq(0)",this).text();
			aGigs.locations.push(location);
		});
		var cleanArrayL = aGigs.makeUnique(aGigs.locations);
		var amountArrayL = aGigs.getAmounts(cleanArrayL,aGigs.locations);
		aGigs.doLocationDropdowns(cleanArrayL,amountArrayL);
	},

	makeUnique: function(array) {
		var newArray = $.map(array, function(i) {
			if($(this).index(i, 0, array) < 0 ) {
				return i;
			}
		});
		return newArray;
	},

	getAmounts: function(array,oldArray) {
		var newArray2 = [];
		var newArray = $.map(array, function(i) {
			var tempArray = [];
			$(oldArray).each(function(j) {
				if (oldArray[j] == i) {
					tempArray.push(i);
				}
			});
			newArray2.push($(tempArray).length);
		});
		return newArray2;
	},
	 	
	doTypeDropdowns: function(array,amount) {
		html = "<form action=\"#\" id=\"type-form\"><p><label for=\"type-select\">Filter: </label><select name=\"event\" id=\"type-select\"><optgroup label=\"By Type:\">";
		$(array).each(function(i) {
			html += "<option value=\"" + array[i] + "\">" + array[i] + " (" + amount[i] + ")</option>"
		});
		html += "</optgroup></select></p></form>";
		$("#content h2:eq(0)").before(html);
		var form = document.getElementById("type-form");
		aGigs.activateDropdowns(array,form);
	},
	
	doLocationDropdowns: function(array,amount) {
		html = "<optgroup label=\"By location:\">";
		$(array).each(function(i) {
			html += "<option value=\"" + array[i] + "\">" + array[i] + " (" + amount[i] + ")</option>"
		});
		html += "</optgroup><optgroup label=\"============\"><option value=\"all\" selected=\"selected\">Show All (" + aGigs.types.length + ")</option></optgroup>";
		$("form#type-form select:eq(0)").append(html);
	},
	
	activateDropdowns: function(array,form) {
		$("select",form).change(function() {
			var type = $("option[@selected]",this).attr("value");
			if (type == "all") {
				$("ul#events li").show();
			} else {
				$("ul#events li").hide();
				$("ul#events li li").show();
				$("ul#events li[li[@title='" + type + "']]").show();
			}
		});
		
	}
	
}

$("#content").ready(aGigs.init);
