// JavaScript Document
	$(document).ready(function(){
	var username_available=false;
	$("#register_username").focus(); // set focus to username on entry
	//$("#submit_button").attr("disabled","disabled");   // disable the submit button until . . .
	$("#captcha_button").attr("disabled","disabled");    // disable the submit button until . . .
				
	$("#register_username").blur(function(){
            // wait until focus moves away from this textarea
			var initial_username_length;
			var adjusted_username_length;
			var text_in;
			var chars_regex=/[^a-zA-Z0-9]/g;
			var first_alpha_regex=/^[a-zA-Z]/;
			var username_error=false;
			//var alphaExp = /^[a-zA-Z\ ]+$/;
			
			text_in=$("#register_username").val();
			if(!text_in.match(first_alpha_regex)) username_error=true; // first char not a letter
			initial_username_length=$("#register_username").val().length;
			text_in=text_in.replace(chars_regex,'');
		   $("#register_username").val(text_in); // set new value
           adjusted_username_length = $("#register_username").val().length; 
			//console.log("firstCharError %s, initial length %s, length now %s ",username_error,initial_username_length,adjusted_username_length);
			
		    //$("#username_message").empty(); 
		    //$("#username_message").addClass('error');
			
			if(username_error==false && adjusted_username_length==initial_username_length && (adjusted_username_length > 4 && adjusted_username_length<15)){
				// name is ok
				 $("#username_message").removeClass();
				 $("#username_message").addClass('ok');
				 $("#username_help").empty(); 
				
			}
			else{
				  $("#username_feedback").empty(); // clear ajax message area
				  $("#username_help").empty();     // clear help area
				  $("#username_message").empty();  // clear message icon
				  $("#username_message").addClass('error');
				  $("#username_help").append('5 to 15 characters long, using a-z, A-Z and 0-9, starting with a letter'); 
			}

        });
// ------------------------------------------------------------------------------;
$("#register_username").focus(function(){
            // cleanup on focus
				 $("#username_message").removeClass();
				 $("#username_help").empty(); 
				 $("#username_feedback").empty(); // clear ajax message area
				 $("#username_message").empty();  // clear message icon


        });
// ------------------------------------------------------------------------------;
// check username when focus moves away; but only if username is OK!

$("#register_username").blur(function(){
	
	var first_alpha_regex=/^[a-zA-Z]/;
	//console.log('Current username textbox contains: ',$("#register_username").val());
	//console.log('first character test',(!$("#register_username").val().match(first_alpha_regex)));
	//console.log('length <=4',$("#register_username").val().length<=4);
	//console.log('length >15',$("#register_username").val().length>15);
	if((!$("#register_username").val().match(first_alpha_regex)) || ($("#register_username").val().length<=4) || ($("#register_username").val().length>15) ) 
	{ //console.log('There was no need to check the username, it did not meet the criteria');
	  // give user feedback in the feedback area
		$("#username_feedback").removeClass().addClass('feedback_error').text('usename error');
		return;
	}// don't bother checking if username criteria not met
 //remove all the class add the messagebox classes and start fading
 $("#username_feedback").removeClass().addClass('messagebox').text('checking . . .');
 //check the username exists or not from ajax
 $.post("/register/username_checker.php",{ user_name:$(this).val() } ,function(data)
 {
  if(data!='yes') //if username not avaiable
  {
	  username_available=false;
      $("#username_feedback").fadeTo(200,0.1,function() //start fading the messagebox
   {
    //add message and change the class of the box and start fading
    $(this).html('not available').addClass('messageboxerror').fadeTo(900,1);
   });
  }
  else
  {
   $("#username_feedback").fadeTo(200,0.1,function()  //start fading the messagebox
   {
    //add message and change the class of the box and start fading
	username_available=true;
    $(this).html('available').addClass('messageboxok').fadeTo(900,1);
   });
  }
 });
 
});
// ------------------------------------------------------------------------------;	

// check password field for minimum length

$("#register_password").blur(function(){
	// minimum length 8 characters
	var password;
	var chars_regex=/[^a-zA-Z0-9]/g;
	password=$("#register_password").val();
	password=password.replace(chars_regex,'');
	$("#register_password").val(password);
	var password_length=$("#register_password").val().length;
	
	if(password_length <8 || password_length >15 ){
		$("#password_message").empty();
		$("#password_message").addClass('error');
		$("#password_help").empty();
		$("#password_help").append('minimum 8 maximum 15 characters, using a-z, A-Z and 0-9');
	}
	else{
		$("#password_message").removeClass();
		$("#password_message").addClass('ok');
		$("#password_help").empty(); 
	}
});
// ------------------------------------------------------------------------------;
// check password confirm field matches password
$("#register_password_confirm").blur(function(){
	// minimum length 8 characters
	var password;
	password=$("#register_password").val();
	var password_confirm=$("#register_password_confirm").val();
	
	if(password!= password_confirm){
		$("#password_confirm_message").empty();
		$("#password_confirm_message").addClass('error');
		$("#password_confirm_help").empty();
		$("#password_confirm_help").append('passwords don\'t yet match');
	}
	else{
		$("#password_confirm_message").removeClass();
		$("#password_confirm_message").addClass('ok');
		$("#password_confirm_help").empty();
		//$("#password_confirm_help").append('passwords match');

	}
});
// ------------------------------------------------------------------------------;
// check all fields completed and terms agreed before submit button becomes available
// remember that all this checking gets done again server side
$("#register_email").blur(function(){
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	if($('#register_email').val().match(emailExp)){
		// email address ok
		$("#email_message").removeClass();
		$("#email_message").addClass('ok');
		$("#email_help").empty(); 
	}
	else{
		// suspect email address
		$("#email_message").empty();
		$("#email_message").addClass('error');
		$("#email_help").empty();
		$("#email_help").append('please use a valid email address');
	}
  
});





// ------------------------------------------------------------------------------;
// user may have gone back, so check as each field blurs
$("#register_password").blur(function(){
	check_inputs();
});
$("#register_password_confirm").blur(function(){
	check_inputs();
});
$("#register_email").blur(function(){
	check_inputs();
});

// look at the checkboxes as they are clicked
$("#terms_0").click(function(){
	check_inputs();
});
$("#terms_1").click(function(){
	check_inputs();
});
$("#terms_2").click(function(){
	check_inputs();
});

function check_inputs(){
	// performs validation of all fields as final check before exposing captcha and submit button
	var agree=$("#terms_0").is(":checked");
	var no_filesharing=$("#terms_1").attr("checked");
	var one_account=$("#terms_2").attr("checked");
	//console.log('agree terms', agree);
	//console.log('no_filesharing', no_filesharing);
	//console.log('one_account', one_account);
	
	if(agree && no_filesharing && one_account){
		if($("#register_password").val() == $("#register_password_confirm").val()){
			if($("#register_password").val().length >=8 && $("#register_password").val().length<16){
				var chars_regex=/[^a-zA-Z0-9]/g;
				var first_alpha_regex=/^[a-zA-Z]/;
				var username=$("#register_username").val(); // not enought, also needs to check status
				var username_length=username.length;        // see usename_available too
				var checked_username=username.replace(chars_regex,'');
				var checked_length=checked_username.length;
				if(username.match(first_alpha_regex) && username_length==checked_length){
					var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
					if($('#register_email').val().match(emailExp)) {
						if(username_available==true){
							//$("#submit_button").removeAttr("disabled"); // enable submit button later
							// show captcha div
							$("#captcha").show();
							$("#captcha_button").removeAttr("disabled");
						}
					}
				}
			}
			
		}
	}
	else{
		$("#submit_button").attr("disabled","disabled"); // disable submit button
	}
};

// reCpatcha stuff
$("#captcha_button").click(function validateCaptcha(){

    challengeField = $("input#recaptcha_challenge_field").val();
    responseField = $("input#recaptcha_response_field").val();
    //alert(challengeField);
    //alert(responseField);
    //return false;
	 $("#captchaStatus").removeClass().addClass('messagebox').text('checking . . . thank you for your patience');

    var reCaptcha_response = $.ajax({
    type: "POST",
    url: "/register/ajax_recaptcha.php",
    data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
    async: false
    }).responseText;
    
    if(reCaptcha_response == "success"){
         $("#captchaStatus").empty();
		 $("#captchaStatus").removeClass().addClass('ok');
		 $("#captchaStatus").append("Looks like you are human"); // message
		 $("#captcha_button").hide(); // remove button
         Recaptcha.destroy(); // prevent resubmission
		 $("form:first").submit(); // send that data for server-side processing
		 
    }
    else{
        $("#captchaStatus").empty();
		$("#captchaStatus").removeClass().addClass('error');
	    $("#captchaStatus").append("Your answer was not correct. Please try again");
        Recaptcha.reload();
        //return false;
    }

});

// end reCaptcha stuff

	}
	
	);