/* -----------------------------------------------------------------------
   Fuel Industries
   Register Javascript
----------------------------------------------------------------------- */

if ( typeof AGA === "undefined" ) { var AGA = {}; }

$(document).ready(function()
{
   AGA.register.init();  
   keepalive();
});

AGA.register = {
   
   init: function()
   {
      // validation
      $('#fieldUsername').blur( function(){ AGA.validator.username( $(this), $(this).val() ); } );
      
      $('#fieldPassword').blur( function(){ AGA.validator.password( $(this), $(this).val() ); } );
      $('#fieldPasswordc').blur( function(){ AGA.validator.confirm_password( $('#fieldPassword'), $('#fieldPasswordc'), $('#fieldPassword').val(), $('#fieldPasswordc').val() ); } );

      $('#fieldParentEmail').blur( function(){ AGA.validator.email( $(this), $(this).val() ); } );
      $('#fieldAgree').blur( function(){ AGA.validator.agree( $(this), $(this).val() ); } );

      $('#form-registration').submit( this.form_submit );
		$('#form-parent-registration').submit( this.form_parent_submit );
		
      // other
      $('#register-main .field').focus( this.set_field_style );
      $('#register-main .field').blur( this.unset_field_style );

		$('#promobtn').click( function()
		{
			$('#promocodebox').slideDown('slow');
			$(this).hide();
		});
		
   },
   
   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 );
		if (valid) valid = AGA.validator.username( $('#fieldUsername'), $('#fieldUsername').val(), false, false );
		if (valid) valid = AGA.validator.password( $('#fieldPassword'), $('#fieldPassword').val(), false );
      if (valid) valid = AGA.validator.confirm_password( $('#fieldPassword'), $('#fieldPasswordc'), $('#fieldPassword').val(), $('#fieldPasswordc').val(), false );
      if (valid) valid = AGA.validator.email( $('#fieldParentEmail'), $('#fieldParentEmail').val(), false );
		if (valid) valid = AGA.validator.agree( $('#fieldAgree'), $('#fieldAgree:checked').val(), false );
		
      if( AGA.validator.has_errors() )
      {
         AGA.messenger.summon( AGA.validator.errors[0], 'error' );
         return false;
      }  
        AGA.process_registration.sendform( $('#selectMonth').val(), $('#selectDay').val(), $('#selectYear').val(), 
        		$('#fieldUsername').val(), $('#fieldPassword').val(), $('#fieldPasswordc').val(), $('#fieldParentEmail').val(), $('#fieldAgree:checked').val(), $('#selectCountry').val() );
		return false;
   },
	
   form_parent_submit: function()
   {
      AGA.validator.clear_errors();
      var valid = AGA.validator.email( $('#fieldParentEmail'), $('#fieldParentEmail').val(), false );
		if (valid) valid = AGA.validator.password( $('#fieldPassword'), $('#fieldPassword').val(), false );
      if (valid) valid = AGA.validator.confirm_password( $('#fieldPassword'), $('#fieldPasswordc'), $('#fieldPassword').val(), $('#fieldPasswordc').val(), false );
		if (valid) valid = AGA.validator.agree( $('#fieldAgree'), $('#fieldAgree:checked').val(), false );
		
      if( AGA.validator.has_errors() )
      {
         AGA.messenger.summon( AGA.validator.errors[0], 'error' );
         return false;
      }  
		
		return true;
   }
   
};

AGA.validator = {
   
	errors: [],
	current_username: '',
	
   rules: 
   {
      birthday: { 
         'main': 'Please select a valid <strong>Birthday</strong>.',
         'checkdate': 'This is not a valid <strong>Birthday</strong>. Please try again.'
      },
      username: { 
         'main': 'You need a <strong>Username</strong>, please fill in the Username field.',
         'numbers': 'Your <strong>Username</strong> cannot contain more than <strong>4 numbers</strong>.',
         'length': 'This <strong>Username</strong> is too long. It cannot be longer then <strong>20 characters</strong>.',
         'short': 'This <strong>Username</strong> is too short. It needs to be at least <strong>6 characters long</strong>.',
         'taken': 'Sorry, this <strong>Username</strong> is taken. Please try a new name.',
         'invalid': '<strong>Usernames</strong> must consist of letters and numbers.',
         'badword': 'This <strong>Username</strong> is unacceptable. Please don\'t use bad words.',
         'taken': 'Sorry, this <strong>Username</strong> is taken. Please try a new name.'
      },
      password: { 
         'main': 'This is not a valid <strong>Password</strong>. Please try again.',
         'short': 'This <strong>Password</strong> is too short. It must be at least <strong>4 characters long</strong>.',
         'confirm': 'Your <strong>Password</strong> and <strong>Confirm Password</strong> do not match. Please try again.'
      },
      email: { 
         'main': 'This is not a valid <strong>E-mail Address</strong>. Please try again.'
      },
      agree: { 
         'main': 'You must agree to the <strong>Terms of Service / Privacy Policy</strong> to register.'
      },
      promocode: { 
         'main': 'This is not a valid <strong>Promo Code</strong>. <br /> If you do not have a Promo Code, please <strong>leave this field blank</strong>.',
         'used': 'This <strong>Promo Code</strong> has already been used.'
      }
   },
	
   set_error: function( field, msg, throwit )
   { 
		if( throwit !== false ) throwit = true
		
      this.errors.push( msg );
      field.addClass('fail').removeClass('pass');
		
      if( throwit === true )
      { 
         this.throw_error( msg );
      }
		else
		{
			field.focus();
		}
		
      return false;
   },
   
   set_pass: function( field )
   { 
      field.addClass('pass').removeClass('fail');
      //AGA.messenger.hide(); 
      return true; 
   },
   
   throw_error: function( msg ){ AGA.messenger.summon( msg, 'error' ); },
   
   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.short, 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 );
      }
   },
   
   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( $('#agreeterms .fields'), this.rules.agree.main, throwit );
      }
      return this.set_pass( field );
   },
   
   promocode: function( field, promocode, throwit )
   {
      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;
		

		
		$.ajax({
			type: "GET",
			url: "/services/register_account.php",
			data: dataString,
			cache: false,
			success: function(response) {
			    
			    if (response.length > 0) {
			    	/* show activate box */
			    	$('#overlay_hidden #regaccountbox').after(response);
			    	AGA.overlay.load_window( $('#main'), $('#overlay_hidden #activatebox') );
			    } else {
			    	/* we shouldn't be here as input validation is done before submit */
		    	    AGA.overlay.load_window( $('#main'), $('#overlay_hidden #regaccountbox') );
			    }
		    },
		    error: function (XMLHTTPRequest, textStatus, errorThrown ){
					 alert( "Unable to contact server. textStatus=" + textStatus + " errorThrown=" + errorThrown );
		    },
		    complete: function (XMLHTTPRequest, textStatus) {
		    }
		});
	}
};

