        var tips = null;
		var allFields;
        var origLabels = [ 'Email', 'First Name', 'Last Name' ];
        var labelIDs = [ "email", "first", "last" ];
        var errorFields = [ "#mail", "#fname", "#lname" ];
        var errorInputs = [ "#email", "#firstName", "#lastName" ];
        var errorMsgSet = {
            EMPTY_EMAIL:"Email - You must provide an email address.",
            EMPTY_FIRST:"First Name - You must provide a first name.",
            EMPTY_LAST:"Last Name - You must provide a last name.",
            INVALID_EMAIL:"Email - This is not a valid e-mail address.",
            EXISTING_EMAIL:"Email - This e-mail address is already registered.",
            INVALID_FIRST:"First Name - This is not a valid name, Must begin with a letter.",
            INVALID_LAST:"Last Name - This is not a valid name, Must begin with a letter."
        };
        var formValues = { email:"", first:"", last:"" };

        var originPage = "home";

        var subname = null;
        var subemail = null;
        var justReset = false;

        // Set when error msg showing shoe subsequent typing can intelligently hide the error msg
        var errorIsSet = false;

        // Set when AJAX detects an already registered user
        var existingEmail = false;

        // Interval timer for checking completion of submit
        var checkDone = null;

        // The regular expression used to validate emails
        var emailRe = new RegExp( "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$", "g" );

        function setFormValue( field, value ) {
            formValues[ field ] = value;
        }

        function clearErrorMessage( index ) {
            $( labelIDs[ index ] ).html( origLabels[ index ] );
        }

        function clearErrorMessages() {
            for( var i = 0; i < origLabels.length; i++ ) {
                clearErrorMessage( i );
            }
        }

        function setErrorMessage( formIndex, msgName ) {
            //alert( "setErrorMessage with index " + formIndex + " and mname " + msgName + " msg " + errorMsgSet[ msgName ] );
            //$( labelIDs[ formIndex ] ).html( origLabels[ formIndex ] + " <span id=\"errormsg2\">" + errorMsgSet[ msgName ] + "</span>" );
            $( errorInputs[ formIndex ] ).addClass( "ui-state-error" );
            updateTips( errorMsgSet[ msgName ], labelIDs[ formIndex ] );
        }

        function setNameAndEmail( name, email ) {
        	//alert( "namesub " + $('.namesub').html() + " email sub " + $( '.emailsub' ).html() );
        	//alert( "Setting name " + name + " and email " + email );
        	$( '.namesub' ).html( name );
        	$( '.emailsub' ).html( email );
        }

        function flagExistingUser( addr ) {
            $.ajax( {
                type: "POST",
                url: "checkifregistered",
                data: "addr=" + addr,
                dataType: "text",
                success: function( msg ) {
                    if ( justReset ) {
                        justReset = false;
                        return;
                    }
                    existingEmail = false;
                    if ( parseInt( msg ) > 0 ) {
                        existingEmail = true;
                        //setErrorMessage( 0, 'EXISTING_EMAIL' );
                        $( "#email" ).addClass( 'ui-state-error' );
                        updateTips( "Email - This e-mail address is already registered.", "email");
                    } else {
                    	updateTips( "Email", "email", true );
                        $( "#email" ).removeClass( 'ui-state-error' );
                    }
                },
                error: function( req, err, excep ) {
                    //setErrorMsg( "Ajax error |" + err + "|" );
                },
                complete: function( req, msg ) {
                    //setErrorMsg( "Complete" );
                }
            } );
        }

        function showForm() {
        	$('#betaregstuff').dialog('open');
        }

        function showThanks() {
        	$( '#thankyoudialog' ).dialog( 'open' );
        }

		function updateTips(t,i,flag) {
		    //alert( "update tips " + tips +" with " + t + " at index |" + i + "|" );
		    tips[i].text(t);
		    //if ( !flag ) { tips[i].effect("highlight",{},1500); }
		}

		function checkLength(o,n,min,max, fieldName, sub ) {

			if ( o.val().length > max || o.val().length < min ) {
				o.addClass('ui-state-error');
				updateTips( fieldName + " - You must provide " + sub,n );
				return false;
			} else {
				return true;
			}

		}

		function checkRegexp(o,regexp,n, fieldName, sub ) {
			// alert( "Check reg exp with |" + fieldName + "|, |" + sub + "| field index " + n );
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass('ui-state-error');
				//alert( "reg exp BAD" );
				updateTips( fieldName + " - This is not a valid " + sub, n);
				return false;
			} else {
				//alert( "reg exp ok" );
				return true;
			}

		}


		// Sets up events that manage form validation actions and intelligent
        // tab/focus/blur behavior
        function setFormEvents() {
			tips = { email:$("#mail"), first:$("#fname"), last:$("#lname") };
        	//alert( "namesub " + $('.namesub').html() + " email sub " + $( '.emailsub' ).html() );

			//alert( tips['email']);
			//alert( tips['first']);
			//alert( tips['last']);
/*
			$( "#thankyoudialog").dialog({
				bgiframe: true,
				autoOpen: false,
				height: 350,
				width: 300,
				modal: true,
    			open: function() {
	    			//alert( "In open" );
	    				setNameAndEmail( subname, subemail );
	    				$( "#thankyoudialog" ).css( "visibility", "visible" );
	    			},
				buttons: {
					'Close': function() {
						$(this).dialog( 'close' );
                        window.location.href = originPage;
					}
				}
			});
*/
    		$("#betaregstuff").dialog({
    			bgiframe: true,
    			autoOpen: false,
    			height: 454,
    			width: 400,
    			modal: true,
    			open: function() {
    			tips = { email:$("#mail"), first:$("#fname"), last:$("#lname") };
		//$( ".ui-dialog-titlebar" ).css( 'display', 'none' );
$('<a href="#" id="fixhelp" class="ui-dialog-titlebar-close ui-corner-all"></a>')
.appendTo('.ui-dialog-titlebar').click(function() { alert( 'clicked' ); } );
        // do whatever you want});                     $( "#betaregform" ).attr( 'action', originPage );
	    			//alert( "In open" );
                    for( var i in formValues ) {
                        $( "#" + i ).val( formValues[ i ] );
                    }
	    			$( "#betaregstuff" ).css( "visibility", "visible" );
	    			},
    			buttons: {
    			'Submit': function() {
 //   			var first = $("#firstName");
    			var email = $("#email");
 //  			var last = $("#lastName");
    			allFields = $([]).add(email).add(first).add(last);
    					var bValid = true;
    					var emailValid = true;
    					var firstNameValid = true;
    					var lastNameValid = true;
    					allFields.removeClass('ui-state-error');
    					//tips[ 'email' ].text( "Email" );
    					//tips[ 'first' ].text( "First Name" );
    					//tips[ 'last' ].text( "Last Name" );
    					// Check validaty of Email
    					emailValid = checkLength( $("#email"),"email",1,255, "Email", "an email address." );
    	    			//emailValid = emailValid && checkRegexp( $( "#email" ),/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"email","Email*", "This is not a properly formatted email address");
    					//emailValid = emailValid && checkRegexp( $( "#email" ),/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/,"email","Email*", "This is not a properly formatted email address");
    					emailValid = emailValid && validEmail();

   					firstNameValid = checkLength( $( "#firstName" ), "first", 1, 32, "First Name", "a first name." );
    					firstNameValid = firstNameValid && checkRegexp($( "#firstName" ),/^[a-z]([0-9a-z_])*$/i, "first", "First Name", "name, Must begin with a letter.");

    					lastNameValid = checkLength( $( "#lastName" ), "last", 1, 32, "Last Name", "a last name." );
    					lastNameValid = lastNameValid && checkRegexp( $( "#lastName" ),/^[a-z]([0-9a-z_])*$/i, "last", "Last Name", "name, Must begin with a letter.");

    					if ( emailValid && firstNameValid && lastNameValid ) {	
    						$("#betaregform").submit();
    					}
    				}
    			},
    			close: function() {
    				//allFields.val('').removeClass('ui-state-error');
    				$ ( "#email" ).val('').removeClass( 'ui-state-error' );
    				$ ( "#firstName" ).val('').removeClass( 'ui-state-error' );
    				$ ( "#lastName" ).val('').removeClass( 'ui-state-error' );
				window.location.href = originPage;
    			}
    		});

        	// Forces form resetting on page load and unload

        	// Since this executes on page load this sets the focus to the e-mail field
            $( "#email" ).focus();

            $( "#doform").click( function () {
            	$('#betaregstuff').dialog('open');
            	//$( "#thankyoudialog").dialog( 'open' );
            } );

            $( "#homejump").click( function () {
            	$('#betaregstuff').dialog('open');
            	//$( "#thankyoudialog").dialog( 'open' );
            } );

            $( "#doreg").click( function () {
            	$('#betaregstuff').dialog('open');
            	//$( "#thankyoudialog").dialog( 'open' );
            } );

            $( "#doformimg" ).click( function () {
                showForm();
            } );

            $( "#presentbetareg" ).click( function() {
            	showForm();
            } );

            // Validates the submission as follows:
            // 1) Makes sure the e-mail field is non-empty else error msg
            // 2) Makes sure the e-mail field e-mail address is valid else error msg
            $("#betaregform").submit( function () {
                return true;
            } );

            // We might loose focus if a user autocompletes the email so we need to check it here
            $( "#email" ).blur( function () {
                if ( justReset ) {
                    justReset = false;
                    return;
                }
		var len = $("#email").val().length;
                if ( ( len > 0 ) && validEmail() ) {
                	var currentAddr = $( "#email" ).val();
  //              	flagExistingUser( currentAddr );
                } else if ( len == 0 ) {
		    updateTips( "Email", "email" );
		    $("#email").removeClass( 'ui-state-error' );
		}
            } );

            $( "#firstName" ).blur( function () {
            	var firstNameValid = true;
                var value = $( "#firstName" ).val();
                value = jQuery.trim( value );
                if ( value.length > 0 ) {
                    firstNameValid = firstNameValid && checkRegexp($( "#firstName" ),/^[a-z]([0-9a-z_])*$/i, "first", "First Name", "first name.");
                }
		if ( firstNameValid ) {
		    updateTips( "First Name", "first" );
		    $( "#firstName" ).removeClass( 'ui-state-error' );
		}
           } );

            $( "#lastName" ).blur( function () {
            	var lastNameValid = true;
                var value = $( "#lastName" ).val();
                value = jQuery.trim( value );
                if ( value.length > 0 ) {
                    lastNameValid = lastNameValid && checkRegexp( $( "#lastName" ),/^[a-z]([0-9a-z_])*$/i, "last", "Last Name", "last name.");
                }
		if ( lastNameValid ) {
		    updateTips( "Last Name", "last" );
		    $( "#lastName" ).removeClass( "ui-state-error" );
		}
           } );
        }
        
        // Validates an e-mail address against RFC 3696 (with the exception of hierarchical [xxx.xxx.xxx.xxx] domains)
        function validEmail () {
            var addr = $("#email").val();
            var result = addr.match( emailRe );
            result = ( result != null );
            if ( !result ) {
            	updateTips( "Email - This is not a valid email address.", "email" );
            	$( "#email" ).addClass( "ui-state-error" );
            }
            return result;
        }

