function Validate (form) {
	var req_fields = $(form).find(".required");
	var valid = true;

	$(form).find("input,select,textarea").removeClass('left_blank');
	
	for (i=0; i<req_fields.length; i++) {
		var field_name = $(req_fields[i]).attr('name');
		
		if ($(req_fields[i]).val() == '') {
			$(req_fields[i]).addClass('left_blank');
			valid = false;
		}
	}
	
	if (valid == false) {
		DisplayError("You left a required field blank");
	}
	
	return valid;
}

function DisplayError (text) {
	if (text) $("#error").html(text);
	$("#error").animate({ opacity: 1.0 }, 0).slideDown(200).animate({ opacity: 1.0 }, 3000).animate({ opacity: 0 }, 1000).slideUp();
}

function DisplayMessage (text) {
	if (text) $("#error").html(text);
	$("#message").animate({ opacity: 1.0 }, 0).slideDown(200).animate({ opacity: 1.0 }, 1000).animate({ opacity: 0 }, 1000).slideUp();
}

function ShowLists (tab,show_only) {
	// user is on home page, i.e. no "show only" menu
	if (show_only === undefined || show_only == '') {
		show_only = "all";
	}
	// if the user just searched, tab will be blank
	if (tab == '') tab = 'all';
	// if the user just searched, tab will be blank
	if (show_only == '') tab = 'all';
	// hide all rows
	$("#mailing_lists tr[class!='header']").hide();
	// show rows matching current tab
	if (tab == "all") {
		$("#mailing_lists tr").show();
	}
	else {
		$("#mailing_lists tr").each(function() {
			if ($(this).hasClass(tab)) {
				$(this).show();
			}
		});
	}
	// show rows matching current "show only" filter
	if (show_only != "all") {
		$("#mailing_lists tr").each(function() {
			if (!$(this).hasClass(show_only) && !$(this).hasClass('header')) {
				$(this).hide();
			}
		});
	}
	// store current "show only" value as a session var
	$.post('/action.php', { action: 'set_current_filter', show_only: show_only });
}

function SetCurrentList (id) {
	$.post('/action.php', { action: 'set_current_list', tab: id });
}

$(document).ready(function() {
	// hide the drop-down menus if the user clicks outside it
	$(document).click(function() {
		$('#mailing_list_menu').slideUp(200);
	    $("#services_menu").slideUp(200);
	});
	$("#mailing_list_button").click(function(e){
	    e.stopPropagation();
	    $("#services_menu").slideUp(200);
	});
	$("#services_button").click(function(e){
	    e.stopPropagation();
	    $("#mailing_list_menu").slideUp(200);
	});
	
	// attach click events to "states" selectors
	if ($('table#states').length > 0) {
		$('table#states td').click(function() {
			$(this).toggleClass('selected');
			var checkbox = $(this).find("input");
			checkbox.attr('checked',!checkbox.attr('checked'));
		});
	}
});
