$.fn.removeCol = function(col){
    if(!col){ col = 1; }
    $('tr td:nth-child('+col+'), tr th:nth-child('+col+')', this).remove();
    return this;
};

$(function() {
	var logged_in = $('#menu div.logout').length;

	$('div.reply a').click(function() {
		$('#parent_id').val($(this).attr('data-id'));
	});

	$('#form.register').validate({
		rules: { password2: { equalTo: "#form.register input[name=password]" } }		
	});

	$('#form.forgot').validate();

	$('#add_comment').validate();

	$('#form.add_story').validate({
		errorPlacement: function() { },
   		rules: {
			body: {
				required: true,
				maxlength: 2000
			}
		}
	});
	$('#form.add_story').find('textarea').keyup(function() {
		var used = $(this).val().length;
		if(used > 2000) {
			$(this).val($(this).val().substr(0, 2000));
			used = 2000;
		}
		$('span.chars span').text(used);
	});

	$('div.votes a').click(function() {
		return true;
		if(!logged_in) {
			alert('You must be logged in to rate a story!');
			return false;
		}
	});

	$('#my_account form.edit').validate();
	$('#my_account form.change_password').validate({
		rules: { password2: { equalTo: "#my_account form.change_password input[name=password]" } }	
	});

	var $scaffold = $('#main.scaffold');

	if($scaffold.length == 1) {
		$.each(['Body','Password','Key'], function() {
			var th = $scaffold.find('th:contains(' + this + ')');
			if(th.length > 0) {
				var x = th.closest('tr').find('th').index(th);
				th.closest('table').removeCol(x+1);
			}
		});
		$scaffold.find('a:contains(Comment Count)').text('Comments');
		$scaffold.find('th:contains(Comment Count)').text('Comments');
	}

	$('#sort_by').change(function() {
		var $form = $(this).closest('form');
		$form.find('input.category_id').val($('#category_filter').val());
		$form.find('input.search').val($('#search input.text').val());
		$form.submit();
	});

	$('#category_filter').change(function() {
		var $form = $(this).closest('form');
		$form.find('input.sort_by').val($('#sort_by').val());
		$form.find('input.search').val($('#search input.text').val());
		$form.submit();
	});

	$('#search').submit(function() {
		$(this).find('input.sort_by').val($('#sort_by').val());
		$(this).find('input.category_id').val($('#category_filter').val());
	});

	if($('#flashMessage').length == 1) {
		setTimeout(function() {
			$('#flashMessage').fadeOut('slow');
		}, 5000);
	}

	$('div.admin a.delete').click(function() {
		return confirm('Are you sure you wish to remove this story?');
	});
});