$(function() {
		
		    var descrizione = $( "#descrizione_attivita" ),
                        data = $( "#datepicker_attivita" ),
			allFields = $( [] ).add( descrizione ).add( data ),
			tips = $( ".validateTips" );

		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}

		function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Campo " + n + ": minimo " +
					min + ", massimo " + max + " caratteri." );
				return false;
			} else {
				return true;
			}
		}

		function checkRegexp( o, regexp, n ) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}
		
		$( "#dialog-form-attivita" ).dialog({
			autoOpen: false,
			height: 400,
			width: 350,
			modal: true,
			buttons: {
				"Aggiungi attivita": function() {
					var bValid = true;
					allFields.removeClass( "ui-state-error" );

					bValid = bValid && checkLength( descrizione, "descrizione", 1, 130 );
                                        
                                        bValid = bValid && checkRegexp( data, /^[0-3]?[0-9]\/[01]?[0-9]\/[12][90][0-9][0-9]$/, "Immetti una data nel formato gg/mm/aaaa." );

					if ( bValid ) {
                                                $("#form_aggiungi_attivita").submit();
						$( this ).dialog( "close" );
					}
                                        
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});

		$( "#aggiungi-attivita" )
			.click(function() {
				$( "#dialog-form-attivita" ).dialog( "open" );
			});
	});
