/* -----------------------------------------------------------------------
   Fuel Industries
   Register Javascript
----------------------------------------------------------------------- */

if ( typeof AGA === "undefined" ) { var AGA = {}; }

$(document).ready(function()
{
   AGA.register.init();  
   keepalive();
});

AGA.register = {
   
   init: function()
   {
      // validation
      $('#fieldUsername').change( function(){ AGA.validator.username( $(this), $(this).val() ); } );
      $('#fieldPassword').change( function(){ AGA.validator.password( $(this), $(this).val() ); } );
      $('#fieldPasswordc').change( function(){ AGA.validator.confirm_password( $('#fieldPassword'), $('#fieldPasswordc'), $('#fieldPassword').val(), $('#fieldPasswordc').val() ); } );

      $('#fieldParentEmail').change( function(){ AGA.validator.email( $(this), $(this).val() ); } );
      $('#fieldParentEmailc').change( function(){ AGA.validator.confirm_email( $('#fieldParentEmail'), $('#fieldParentEmailc'), $('#fieldParentEmail').val(), $('#fieldParentEmailc').val() ); } );
      $('#fieldAgree').change( function(){ AGA.validator.agree( $(this), $(this).val() ); } );

      $('#registerform').submit( this.form_submit );
		
   },
   
   set_field_style: function(){ $(this).addClass('focused'); },
   unset_field_style: function(){ $(this).removeClass('focused'); },
   
   form_submit: function()
   {
      AGA.validator.clear_errors();
      var valid = AGA.validator.birthday( $('#selectMonth, #selectDay, #selectYear'), $('#selectMonth').val(), $('#selectDay').val(), $('#selectYear').val(), false );      
	  valid = valid | (AGA.validator.username( $('#fieldUsername'), $('#fieldUsername').val(), false, false ));
	  valid = valid | (AGA.validator.password( $('#fieldPassword'), $('#fieldPassword').val(), false ));
      valid = valid | (AGA.validator.confirm_password( $('#fieldPassword'), $('#fieldPasswordc'), $('#fieldPassword').val(), $('#fieldPasswordc').val(), false ));
      valid = valid | (AGA.validator.email( $('#fieldParentEmail'), $('#fieldParentEmail').val(), false ));
      valid = valid | (AGA.validator.agree( $('#fieldAgree'), $('#fieldAgree:checked').val(), false ));
		
      if( AGA.validator.has_errors() )
      {
    	 /* AGA.splashOverlay.load_window( $('#main'), $('#overlay_hidden #regaccountbox') ); */
         return false;
      }
      
      if ($('#fieldAgree:checked').val() == undefined) {
    	  $agree = 0;
      } else {
    	  $agree = 1;
      }
      
      AGA.process_registration.sendform( $('#selectMonth').val(), $('#selectDay').val(), $('#selectYear').val(),
        		$('#fieldUsername').val(), $('#fieldPassword').val(), $('#fieldPasswordc').val(), $('#fieldParentEmail').val(), $agree, $('#selectCountry').val() );

      $('#regaccountbox div.birthday .select').removeClass('pass'); /* clean up the class */
      return false;
   }   
};

AGA.validator = {
   
	errors: [],
	current_username: '',
	
   rules: 
   {
      birthday: { 
         'main': 'Please select a valid <strong>Birthday</strong>.',
         'checkdate': 'This is not a valid <strong>Birthday</strong>.'
      },
      username: { 
         'main': 'You need a <strong>Username</strong>.',
         'numbers': 'Cannot contain more than <strong>4 numbers</strong>.',
         'length': 'Cannot be longer then <strong>20 characters</strong>.',
         'short': 'Needs be at least <strong>6 characters long</strong>.',
         'taken': 'This <strong>Username</strong> is taken.',
         'invalid': '<strong>Usernames</strong> must consist of letters and numbers.',
         'badword': '<strong>Username</strong> is unacceptable.'
      },
      password: { 
         'main': 'This is not a valid <strong>Password</strong>.',
         'shorts': 'It must be at least <strong>4 characters long</strong>.',
         'confirm': '<strong>Confirm Password</strong> do not match.'
      },
      email: { 
         'main': 'This is not a valid <strong>E-mail Address</strong>.',
		 'confirm': '<strong>Email Address</strong> does not match.'
      },
      agree: { 
         'main': 'You must agree to the <strong>Terms of Service / Privacy Policy</strong> to register.'
      }
   },
	
   set_error: function( field, msg, throwit )
   { 

	      this.errors.push( msg );
	      field.addClass('fail').removeClass('pass');
			
		  field.focus();
		  field.siblings("div.error").html(msg).show();

      return true;
   },
   
   set_pass: function( field )
   { 
	      field.addClass('pass').removeClass('fail');
	      field.siblings("div.error").hide();

      return true; 
   },

   set_email: function( field )
   {
		field.addClass('pass').removeClass('fail');
		field.siblings("div.error").hide();
		
		return true;
   },
   
   throw_error: function( msg ){ return; },
   
   has_errors: function(){ return ( this.errors.length !== 0 ); },
   clear_errors: function(){ this.errors = []; },
   
   birthday: function( field, month, day, year )
   {
      if( !month.match( /^[0-9]{2}$/ ) || !day.match( /^[0-9]{2}$/ ) || !year.match( /^[0-9]{4}$/ ) )
      {
         return this.set_error( field, this.rules.birthday.main, false );
      }
      return this.set_pass( field );
   },
   
   username: function( field, username, throwit, ajax )
   {
      var num_matches = username.match( /[0-9]/gi );
      
      if( username.length == 0 )
      {
         return this.set_error( field, this.rules.username.main, throwit );
      }
      
      if( num_matches !== null && num_matches.length > 4 )
      {
         return this.set_error( field, this.rules.username.numbers, throwit );
      }
      
      if( username.length > 20 )
      {
         return this.set_error( field, this.rules.username.length, throwit );
      }
      
      if( username.length < 6 )
      {
         return this.set_error( field, this.rules.username.short, throwit );
      }
      
      if( !username.match( /^[a-zA-Z0-9]+$/ ) )
      {
         return this.set_error( field, this.rules.username.invalid, throwit );
      }
		
		if( this.current_username != username )
		{
			var result = '';
			
			$.ajax(
			{
				url: "/www/register/modules/username_check.php", 
				data: { username: username },
				async: false,
				success: function( response )
				{
					result = response;
				}
			});
			
			if( result == 'badword' )
			{
				return this.set_error( field, this.rules.username.badword, throwit );
			}
			
			if( result == 'duplicate' )
			{
				return this.set_error( field, this.rules.username.taken, throwit );
			}
		}
		
		this.current_username = username;
		return this.set_pass( field );
		
   },
   
   password: function( field, password, throwit )
   {
      if( password.length == 0 )
      {
         return this.set_error( field, this.rules.password.main, throwit );
      }
      if( password.length < 4 )
      {
         return this.set_error( field, this.rules.password.shorts, throwit );
      }
      return this.set_pass( field );
   },
   
   confirm_password: function( field1, field2, password1, password2, throwit )
   {
      if( password1.length != 0 )
      {
         if( password1 != password2 )
         {
            return this.set_error( field2, this.rules.password.confirm, throwit );
         }
         return this.set_pass( field2 );
      }
   },

   confirm_email: function( field1, field2, email1, email2, throwit )
   {
		if ( email1.length != 0 )
		{
			if ( email1 != email2 )
			{
				return this.set_error( field2, this.rules.email.confirm, throwit );
			}
			return this.set_email( field2 );
		}
   },
   
   email: function( field, email, throwit )
   {
      if( !email.match( /^[a-zA-Z0-9]+[_a-zA-Z0-9-]*(\.[_a-zA-Z0-9-]+)*@[A-Za-zöäüÖÄÜ0-9]+(-[A-Za-zöäüÖÄÜ0-9]+)*(\.[A-Za-zöäüÖÄÜ0-9-]+)*(\.[A-Za-z]{2,6})$/ ) )
      {
         return this.set_error( field, this.rules.email.main, throwit );
      }
      return this.set_pass( field );
   },
   
   agree: function( field, agree, throwit )
   {
      if( agree == undefined || agree === null )
      {
         return this.set_error( field, this.rules.agree.main, throwit );
      } else {
    	  return this.set_pass( field );
      }
   }

};

AGA.process_registration = {
	sendform: function(selectMonth, selectDay, selectYear, fieldUsername, fieldPassword, fieldPasswordc, fieldParentEmail, fieldAgree, selectCountry)
	{		
		var dataString = 'newAccount=true'
		+ '&selectMonth=' + selectMonth 
		+ '&selectDay=' + selectDay
		+ '&selectYear=' + selectYear
		+ '&fieldUsername=' + fieldUsername
		+ '&fieldPassword=' + fieldPassword
		+ '&fieldPasswordc=' + fieldPasswordc
		+ '&fieldParentEmail=' + fieldParentEmail
		+ '&fieldAgree=' + fieldAgree
		+ '&selectCountry=' + selectCountry;
		
		/*alert(dataString);*/

		
		$.ajax({
			type: "POST",
			url: "/services/register_account_splash.php",
			data: dataString,
			cache: false,
			success: function(response) {
			    //alert('reg response = ' + response);
			    
			    if (response.length > 0) {
			    	
			    	/* show activate box */
			    	$('#overlay_hidden').children('#regaccountbox').after(response);
			    	
			    	if ($('#overlay').length > 0) {
				    	/* regular webpage */
			    		AGA.overlay.load_window( $('#main'), $('#overlay_hidden #activatebox') );
			    		//alert('after overlay load_window');
			    	} else {
			    		/* splash page */
			    		AGA.splashOverlay.load_window( $('#main'), $('#overlay_hidden #activatebox') );
			    	}
			    } else {
			    	/* we shouldn't be here as input validation is done before submit */
		    	    AGA.splashOverlay.load_window( $('#main'), $('#overlay_hidden #regaccountbox') );
			    }
		    },
		    error: function (XMLHTTPRequest, textStatus, errorThrown ){
					 /*alert( "Unable to contact server. textStatus=" + textStatus + " errorThrown=" + errorThrown );*/
		    },
		    complete: function (XMLHTTPRequest, textStatus) {
		    }
		});
	},
	
	resendemail: function() 
	{
		var action = $('#resendaction').val();
		var uid = $('#resenduserid').val();
		var uname = $('#resendusername').val();
		var activation = $('#resendactivation').val();
		var email = $('#resendemail').val();
		
		var dataString = 'resendaction=' + action
			+ '&resenduserid=' + uid 
			+ '&resendusername=' + uname
			+ '&resendactivation=' + activation
			+ '&resendemail=' + email;	
		
		/*alert(dataString);*/
		
		$.ajax({
			type: "POST",
			url: "/services/resend_account_activation_email_splash.php",
			data: dataString,
			cache: false,
			success: function(response) {		    
			    /** if (response.length > 0) { 
			    	alert('error=' + response);
			     } else {
			    	alert('email sent');
			    } **/
		    },
		    error: function (XMLHTTPRequest, textStatus, errorThrown ){
					 /*alert( "Unable to contact server. textStatus=" + textStatus + " errorThrown=" + errorThrown );*/
		    },
		    complete: function (XMLHTTPRequest, textStatus) {
		    }
		});	
		
		return false;
	}
};

