$(function() {
		
		var password1 = $( "#password1" ),
                    password2 = $( "#password2" ),
			allFields = $( [] ).add( password1 ).add( password2 ),
			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( "Il campo " + n + " deve contenere da " +
					min + " a " + 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;
			}
		}

                function checkEqual( p1, p2, n ) {
			if ( p1.val() != p2.val() ) {
				p1.addClass( "ui-state-error" );
                                p2.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}
		
		$( "#dialog-form-modifica-password" ).dialog({
			autoOpen: false,
			height: 300,
			width: 350,
			modal: true,
			buttons: {
				"Modifica password": function() {
					var bValid = true;
					allFields.removeClass( "ui-state-error" );

					bValid = bValid && checkLength( password1, "Password", 6, 32 );
					bValid = bValid && checkLength( password2, "Ripeti password", 6, 32 );
					bValid = bValid && checkRegexp( password1, /^([0-9a-zA-Z,])+$/, "Caratteri permessi : a-z 0-9" );
                                        bValid = bValid && checkRegexp( password2, /^([0-9a-zA-Z,])+$/, "Caratteri permessi : a-z 0-9" );
                                        bValid = bValid && checkEqual( password1, password2, "I due campi password devono essere uguali" );
					if ( bValid ) {
						$( "#users tbody" ).append( "<tr>" +
							"<td>" + password1.val() + "</td>" +
							"<td>" + password2.val() + "</td>" +
						"</tr>" );
                                                $("#form_modifica_password").submit();
						$( this ).dialog( "close" );
					}
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});

		$( "#modifica-password" )
			.click(function() {
				$( "#dialog-form-modifica-password" ).dialog( "open" );
			});
	});
