$(function() {
	// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
	$( "#dialog:ui-dialog" ).dialog( "destroy" );
	
	var cur_date = new Date();
	
	var donate = $( "#donate" ),
		name1 = $( "#name1" ),
		name2 = $( "#name2" ),
		street = $( "#street" ),
		zip = $( "#zip" ),
		city = $( "#city" ),
		allFields = $( [] ).add( donate ).add( name1 ).add( name2 ).add( street ).add( zip ).add( city ),	
		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( "Length of " + n + " must be between " +
				min + " and " + max + "." );
			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 isInteger(o, n) {
		var s = o.val();
		if( s.toString().search(/^-?[0-9]+$/) == 0 )
		{
			return true;
		}
		else
		{
			o.addClass( "ui-state-error" );
			updateTips( n );
			return false;
		}
	}
	
	$( "#dialog-form" ).dialog({
		autoOpen: false,
		height: 520,
		width: 630,
		modal: true,
		buttons: {
			"spenden": function() {
				var bValid = true;
				allFields.removeClass( "ui-state-error" );

//				bValid = bValid && checkLength( name, "username", 3, 16 );
				bValid = bValid && isInteger( donate, "Die Spende muss nummerisch sein." );
//				bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );

				if ( bValid ) {
					$( "#donate_iframe" ).append( '<iframe src="https://www.kinderstiftung.de/vr-pay.php?donate=' + donate.val() + '&cur_time=' + cur_date.getTime() +'&name1=' + name1.val() +'&name2=' + name2.val() +'&street=' + street.val() +'&zip=' + zip.val() +'&city=' + city.val() +'" width="750px" height="550px" style="margin-left: -20px;"> </iframe><a href="javascript:window.print()">Seite drucken</a>');
					$( this ).dialog( "close" );
				}
			},
			"abbrechen": function() {
				window.location = "http://www.kinderstiftung.de/"
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});
	$( "#dialog-form" ).dialog( "open" );
});
