$( function() {
	$( 'form .email input' ).focus( function() {
		if( $( this ).val() == 'your name' ) this.value = '';
	} ).blur( function() {
		if( !$( this ).val() ) this.value = 'your name';
	} );
	$( '#form-add-mailname' )
		.submit( function() {
			var fields = $( this ).xForm(), valid = true;
			if( !fields.name ) {
				alert( 'Please enter your name to continue' );
				valid = false;
			} else if ( !fields.email ) {
				alert( 'Please enter your current email address' );
				valid = false;
			} else if ( !fields.mailname || fields.mailname == 'your name' ) {
				alert( 'Please select your edell email address' );
				valid = false;
			} else if ( fields.available == 'false' ) {
				alert( 'The edell email address you have selected is already in use' );
				valid = false;
			} else if ( !fields.password ) {
				alert( 'Please enter a password to continue' );
				valid = false;
			} else if ( !fields.password_confirm ) {
				alert( 'Please re-enter the password to continue' );
				valid = false;
			} else if ( fields.password != fields.password_confirm ) {
				alert( 'Your password and re-entered password are different' );
				valid = false;
			}
			return valid;
		} )
		.find( '.email input' ).keyup( function() {
			var mailname = $( this ).val();
			if( mailname ) {
				var h5 = $( '#form-add-mailname .heading h5' );
				$( h5 ).load(
					'/action/ajax-available',
					{ mailname: mailname },
					function( data ) {
						if( $( h5 ).html().indexOf( 'Available' ) > -1 ) {
							$( h5 ).attr( 'class', '' ).addClass( 'available' );
							$( '#form-add-mailname input[@name=available]' ).val( 'true' );
						} else {
							$( h5 ).attr( 'class', '' ).addClass( 'unavailable' );
							$( '#form-add-mailname input[@name=available]' ).val( 'false' );
						}
					}
				);
			} else
				$( '#form-add-mailname .heading h5' ).html( '' );
		} );
} );

$.fn.xForm = function() {
	var a = [];
	jQuery( 'input,textarea,select', this ).each( function() {
		var n = this.name, t = this.type, v = this.value;
		if( !n || this.disabled || t == 'reset' ||
			( t == 'submit' || t == 'image' || t == 'button' ) && this.form && this.form.clk != this ||
			this.tagName.toLowerCase() == 'select' && this.selectedIndex == -1 ) return;
		a[n] = ( ( t == 'checkbox' || t == 'radio' ) && !this.checked ? '0' : v );
	} );
	return a;
};
