$(function(){
	$('form > *:even').addClass('alt');
	$('tbody tr:even').addClass('alt');
	$('thead input').click(function(){
		$(this).parents('thead').siblings('tbody').find('input').each(function(){
			if ($(this).is(':checked')) $(this).attr('checked', false);
			else $(this).attr('checked', true);
		});
	});
	
	/* Uploads */
	$('.upload').parent().prettyPhoto({
		showTitle: false
	});
	
	/* Custom Fields */
	var $fields = $('#fields', '#custom_fields');
	$('#js_save_custom_field').click(function(){
		var key = $('#js_custom_key').val(),
			value = $('#js_custom_value').val();
		
		if (key && value) {
			var $field = $('<div class="field"><div class="left"><input type="text" name="custom_key[]" class="custom_key" value="' + key + '" /><input type="submit" class="button custom_delete" value="Delete" /></div><textarea name="custom_value[]" class="custom_value" rows="3" cols="30">' + value + '</textarea></div>').css({ display: 'none' });
			
			$field.prependTo($fields).fadeIn();
			$('#js_custom_key').val('');
			$('#js_custom_value').val('');
		}
		
		return false;
	});
	$('.custom_delete').live('click', function(){
		$(this).parents('.field').fadeOut('normal', function(){
			$(this).remove();
		});
		
		return false;
	});
	
	function makeSlug(text) {
		return $.trim($.trim(text.toLowerCase().replace(/[^a-z0-9-]/g, ' ')).replace(/\s+/g, '-').replace(/-+/g, '-'));
	}
	
	$('.slug').each(function(){
		var  $this = $(this),
			$holder = $('.slughere');
		
		$this.keyup(function(){
			$holder.val(makeSlug($this.val()));
		});
	});
	
	$('.delete').click(function(){
		var $this = $(this);
		
		if (confirm('Are you sure you want to delete this ' + $this.parents('tr').attr('class').replace(' alt', '') + '?')) {
			$.ajax({
				type: 'GET',
				url: $this.attr('href'),
				async: true,
				success: function(){
					$this.parents('tr').children('td').animate({
						backgroundColor: '#fbc7c7'
					}, 'fast', function(){
						$(this).animate({
							backgroundColor: '#fff',
							opacity: 'hide'
						}, 'slow');
					});
				}
			});
		}
		
		return false;
	});
	
	/* Comment Approve/Unapprove */
	$('.status').click(function(){
		var $this = $(this),
			type = $this.attr('class').replace('status ', '');
		
		$.ajax({
			type: 'GET',
			url: $this.attr('href'),
			async: true,
			success: function(){
				if (type == 'unapprove') {
					$this.parents('tr').children('td').animate({
						backgroundColor: '#fff568'
					}, 'fast', function(){
						$(this).animate({
							backgroundColor: '#fff',
							opacity: 'hide'
						}, 'slow');
					});
				} else {
					$this.parents('tr').children('td').animate({
						backgroundColor: '#dafda5'
					}, 'fast', function(){
						$(this).animate({
							backgroundColor: '#fff',
							opacity: 'hide'
						}, 'slow');
					});
				}
			}
		});
		
		return false;
	});

});