$(function(){
	$('.datepicker').datepicker();
	$('.inner', '.filters ').hide();

	$('h2', '.filters').each(function(){
		$(this).html('<a href="#show_filters">'+ $(this).html() +'&darr;</a>');
	});

	$("a[href$='show_filters']").click(function(){
		$('.inner', '.filters ').toggle();
		return false;
	})

	$("a[href$='select_all']").click(function(){
		var $col = $(this).parent('p').parent('div');
		var $inputs = $('input', $col);
		$inputs.attr('checked', true);
		return false;
	})

	$("a[href$='select_none']").click(function(){
		var $col = $(this).parent('p').parent('div');
		var $inputs = $('input', $col);
		$inputs.attr('checked', false);
		return false;
	})
	
	$(".list").link();
	
	$('input.clear').click(function(){
		$('#search_term').attr('value', '');
	})
	
	$('.volunteer_flags input').change(function(){
		$form = $(this).closest('form');
		$.post($form.attr('action'), {'flags_id' : $(this).val(),'checked' : $(this).attr('checked')})
	});
	
	$('.baptism_archive input').change(function(){
		$form = $(this).closest('form');
		$.post($form.attr('action'), {'ajax':true, 'checked' : $(this).attr('checked')})
		
		if($(this).attr('checked'))
		{
			$(this).closest('tr').addClass('archived');
		}
		else
		{
			$(this).closest('tr').removeClass('archived');
		}
	});
	
	$(':input[maxchars]')
		.bind('keyup', function(e){
			var key = e.which;
			var $count = $('.character-count', $(this).closest('p'));

			if(key >= 33 || key == 13 || key == 8)
			{
				var maxchars = $(this).attr('maxchars');
				var currentchars = $(this).val().length;

				$count.text(currentchars + ' of ' + maxchars);
	
				if(currentchars >= maxchars > 0) {
					e.preventDefault();
					$count.css({'color':'red'})
				}	else {
					$count.css({'color':null})
				}
			}
		})
		.autoResize({
	    animate : false,
	    limit: 350,
	    extraSpace: 0
		});
})

$.fn.link = function() {
	$('tbody tr', this).each(function(){
		var id = $('td:first a', this).attr('href');
		if(id && id != '')
		{
			$(this)
				.mouseover(function(){
					$(this).css('cursor', 'pointer');
					window.status = id;
				})
				.click(function(){
					window.location = id;
				})
				.mouseout(function(){
					window.status = '';
				})
		}
	})
}


