var lang = [];
lang['empty'] = 'pole je prázdné';
lang['empty_checkbox'] = 'Vyberte alespoň jednu možnost - ';
lang['invalid_email'] = 'neplatný email';

$(document).ready(function() {

	$('form.validate').bind('submit', function(){
		var valid = true;
		var errors = [];
		var checkboxes = [];
		
		$('input.req:not(:checkbox), textarea.req', $(this)).each(function(){
			if($(this).val().length == 0){
				valid = false;
				errors.push({
					label: $(this).prev('label').html(),
					error: 'empty'
				});
			}	
		});
		
		$('input.reqCheckbox:checkbox', $(this)).each(function(){
			var name = $(this).attr('name');
			if($('input.reqCheckbox[name="'+name+'"]:checked').length == 0){
				valid = false;
				if(!checkboxes[name]){
					var h2 = $(this).prevAll('h2');
					var label = h2.find('span').length > 0 ? h2.find('span').html() : h2.html();
					errors.push({
						label: label,
						error: 'empty_checkbox'
					});
					checkboxes[name] = true;
				}
			}
		});
		
		var email = $('input[name=email]', $(this));
		if(email && !validEmail(email.val())){
			valid = false;
			errors.push({
				label: email.prev('label').html(),
				error: 'invalid_email'
			});
		}
		
		if(errors.length > 0){
			var errors_html = '';
			$.each(errors, function(i, obj){
				if(obj.error != 'empty_checkbox'){
					errors_html += '<div><strong>'+obj.label+'</strong> '+lang[obj.error]+'</div>';
				}else{
					errors_html += '<div>'+lang[obj.error]+' <strong>'+obj.label+'</strong></div>';
				}
			});
			
			$(this).find('.errors').remove();
			$(this).prepend('<div class="errors">'+errors_html+'</div>');
		}
		
		return valid;
	});
	
});

function validEmail(str){
	var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	return filter.test(str);
}