$(window).load(function() 
{
	function __toggle_displaygroup_hidden(obj) {
		if (obj.val() != obj.attr('show-on')) 
		{
			$('*[id|="' + obj.attr('show-id') + '"]').fadeOut('fast');
		} 
		else 
		{
			$('*[id|="' + obj.attr('show-id') + '"]').fadeIn('fast');
		}
	}
	$('select[show-id]').change(function() { __toggle_displaygroup_hidden($(this)); });
	$('select[show-id]').each(function() { __toggle_displaygroup_hidden($(this)); });
	
	
	//
	
	$('form').submit(function() {
		// check if form has id & error dialog window exists, if not, ignore
		// and always allow submit (.length == exists)
		if (!$(this).attr('id')
		    || !$('div#' + $(this).attr('id') + '-error-dialog').length)
		{
			return (true);
		}
		
		// flags error in form
		var __is_error = false;

		// go thru all labels marked as required and check if not empty
		$('label[class~="required"]').each(function() {
			var elem = $('*[name="' + $(this).attr('for') + '"]');
			if (elem.val() == '') {
				__is_error |= true;
				if (!$(this).hasClass('error')) {
					$(this).addClass('error');
				}
			} else {
				if ($(this).hasClass('error')) {
					$(this).removeClass('error');
				}
			}
		});
		
		// if error, display modal dialog
		if (__is_error) {
			$('#' + $(this).attr('id') + '-error-dialog').dialog({
				modal:   true,
				buttons: {
					'Close': function() { 
						$(this).dialog('close');
					}
				}
			});
		}
		
		// allow submit only if no errors
		return (!__is_error);
	});
});

