$(function() {
	initCheckboxes('venue');
});

function initCheckboxes(id) {
	prepcheckboxes(id);
	activateCheckboxes(id);
	activateCheckAll(id);
	collectIDs(id);
}

function prepcheckboxes(id) {
	var checkboxes = $("#" + id + "_checks input:checkbox");
	var selectAll = $("#" + id + "_select_all");
	var idField = $("#" + id + "_ids");
	
	$("#" + id + "_checks input:checkbox").each(function() {
		//setting the onclick function for each checkbox
		$(this).click(function() {
			selectAll.attr('checked', false);
			collectIDs(id);
			activateCheckAll(id);
		});
	});

	//setting the onclick function for the ALL selection checkboxes
	selectAll.click(function() {
		checkboxes.attr('checked', $(this).attr('checked'));
		collectIDs(id);
	});
}

function activateCheckboxes(id) {
	var checkboxes = $("#" + id + "_checks input:checkbox");
	var results = {}
	var split;
	var query = unescape(location.search);
	
	if (query == "") {
		$("#" + id + "_select_all").click();
		checkboxes.attr('checked', true);
		return;
	}
	query = query.substring(1, query.length).split('&');
	$(query).each(function() {
		split = this.split('=');
		results[split[0]] = split[1];
	});	
	if (results["venue_ids"] != "") {
		var ids = results["venue_ids"].substring(1, results["venue_ids"].length - 1).split("','");
		if (ids.length > 0) {
			checkboxes.each(function() {
				if ($.inArray($(this).attr('value'), ids) != -1)
					$(this).attr('checked', true);
			});
		}
	} else {
		$("#" + id + "_select_all").click();
		checkboxes.attr('checked', true);
	}
}

function clearAllCheckboxes(checkboxes, idField) {
	checkboxes.attr('checked', false);
	idField.attr("value", "");
}

function collectIDs(id) {
	var checkboxes = $("#" + id + "_checks input:checkbox");
	var idField = $("#" + id + "_ids");
	
	var ids = [];
	checkboxes.each(function() {
		if ($(this).attr('checked'))
			ids.push("'" + $(this).attr('value') + "'");
	});
	idField.attr("value", ids.join(','));
	//console.log("ID Field: " + idField.attr('value'));
}

function activateCheckAll(id) {
	var checked = 0;
	var checkboxes = $("#" + id + "_checks input:checkbox");
	checkboxes.each(function() {
		if ($(this).attr('checked') == true)
			checked++;
	});
	if (checked == checkboxes.length)
		$("#" + id + "_select_all").attr('checked', 'true');
}