// Init Form Validation

$().ready( function() {
	
	$.validator.addMethod("cTime", 
		function(v) {
			return((v == '') || (v.match(/^(([01][0-9])|([2][0-3])):[0-5][0-9]$/)));
		},
		"No valid time");
	$.validator.addClassRules("time", { cTime: true});

	$("#duell-anmeldung").validate({
		errorElement: "label",
		errorContainer: $("#warning"),
		rules: {
			fplz: {
				required: true,
				digits: true,
				minlength: 4
			},
			fkontaktplz: {
				required: true,
				digits: true,
				minlength: 4
			},
			faktor: {
				required: true,
				min: 1
			}
		},
		errorPlacement: function(error, element) {
			if (element.attr("name") == "tnv" || element.attr("name") == "duellidee" )
				error.appendTo( element.parent("td").next("td").children("div") );
			else
				error.insertAfter(element);
		}

	});

	
	// einblenden der duell typspezifischen eingabe felder
	$('form#duell-anmeldung input[name="fduellType"]')
		.each(initDuellType)
		.click( function() {
			var n = $(this).val();
			showDuellType(n);
		 }
	);

	$('form a#submit-link').click( function() {
		
		var f = $(this).parents('form:first');
		
		if(f.validate()) f.submit();
		
		return false;
	});

	$('form input[name=l]:first').focus();
	
	$('input[name="imagefile"],input[name*="dokumentfile"]').click(function() {
		var r = $(this).siblings(':radio:first').attr('checked','checked');
		
	});
	
	$('[name*="day"]:checkbox').click( function() { 
		var n = this.id.split('day').pop();
		
		if( ! $(this).attr('checked')) {
			$('input[name*="day' + n + '"]').val('').valid();
		}
		
	});
	$('input[type="text"][name*="day"]').change(function() { 
		var n = $(this).attr('name').split('day').pop().split('_').shift();
		$('[name*="day' + n + '"]:checkbox').attr('checked', 'checked'); 
	});
	
	$('a.addDokumentUpload').click( function() {
		$('tr.dokumentUpload:hidden:first,tr.dokumentUploadName:hidden:first').show();
		
		if( $('tr.dokumentUpload:hidden').length == 0) {
			$(this).hide();
		}
	});
	
});


function initDuellType() {
	if( $(this).is(':checked') ) showDuellType($(this).val());
}
function showDuellType(n) {
	for( var i = 0; i <= 2; i++) {
		$('form#duell-anmeldung tr#fduellType_' + i)[(i == n) ? 'fadeIn' : 'hide']();
	}
	$('#tableDuell,#tableDuellHeader')[(n == 2) ? 'fadeIn' : 'hide']();
}
