$(function() {	
	register_season_callbacks();
	
	var empty_upload_image_field = $('.upload_image:last').clone();
	$('#add_upload_image_field').click(function() {
		$(this).parents('small').before(empty_upload_image_field.clone());
		$(this).parents('small').before('<br />');
		
		var images = $("#images input");
		
		if (images.length == 7) {
			$(this).hide();
		}
	});
	
	$('#add-sperrung-button').click(function() {
		$(this).hide();
		$('#add-sperrung').show();
		$('#sperrung-von').focus();
	});
	
	$('#add-sperrung input[type=text]').focus(function() {
		var elm = this;
		$(elm).css('background-color', '#f99');
		$(elm).addClass('active');
		$('#calendar-big tbody td').css('cursor', 'pointer');
		$('#calendar-big tbody td').click(function() {
			$(elm).val($(this).attr('title'));
			$('#calendar-big tbody td:not(.not-in-this-month)').unbind();
			$(elm).css('background-color', '#fff');
			$(elm).removeClass('active');
			
			var next = $($(elm).nextAll('input')[0]);
			if (next.is('input[type=submit]') || next.val() == '') {
				next.focus();
			}
		});
	});
	
	ajaxify_calendar_links();
});

function ajaxify_calendar_links() {
	$('#calendar-big .nav a').each(function() {
		var href = $(this).attr('href');
		$(this).attr('href', 'javascript: void(0);');
		$(this).click(function() {
			$('#calendar-big').load(href + '&ajax=1 #calendar-big', function(){
				ajaxify_calendar_links();
				$('#add-sperrung .active').focus();
			});
		});
	});
}

function register_season_callbacks() {
	$('.add-season').each(function() {
		var tr = $(this).parents('tr');
		var empty_season = tr.clone();

		tr.parents('table').find('.delete-season').unbind();
		tr.parents('table').find('.delete-season').click(function() {
			$(this).parents('tr').remove();
		});
		
		$(this).unbind();
		$(this).click(function() {
			$(this).parents('table').append(empty_season);
			$(this).removeClass('add-season');
			$(this).addClass('delete-season');
			$(this).text('del');
			
			register_season_callbacks();
		});
	});
}

