/*************************************************************************************
 * Functions On Load		                                                         *
 *************************************************************************************/
            
//Hide the submit button
$(document).ready( function(){
		dontAskForUrl();
});

function askForUrl(){
	$('#myURL').show();
	$('#myURL').find('input[type=text]').attr('disabled', false);
}
function dontAskForUrl(){
	$('#myURL').hide();
	$('#myURL').attr('disabled', 'disabled');	
}
/*************************************************************************************
 * Form Response Functions                                                           *
 *************************************************************************************/

//Changes class if field is selected
function imSelected(input_obj){
	input_obj.className='active';
}

//Changes class if field is no longer selected
function imNotSelected(input_obj){
	//Do not change class if the input has a status of valid or invalid already
	if(input_obj.className != 'invalid' && input_obj.className != 'valid'){
		input_obj.className='inactive';	
	}
}

//Changes class if field is invalid!
function imInvalid(input_obj, myIcon){
	input_obj.className="invalid";
	//display icon of failure
	if(myIcon){
		displayFailureImage(myIcon);
	}
	birdReactGrouchy();
	hideSubmit();
}

//Changes class if a field is valid
function imValid(input_obj, myIcon){
	input_obj.className="valid";
	//dispaly icon of success
	if(myIcon){
		displaySuccessIcon(myIcon);
	}
	birdReactHappy();
	check_form_status();
}

//Display the success image
function displaySuccessIcon(myID){
	myID.className='green_check';
}

//Display the failure image
function displayFailureImage(myID){
	myID.className='red_error';
}

//Limit Characters in fields
function fly_limit_chars(input_obj, limitNumber){
	if (input_obj.value.length > limitNumber){
		input_obj.value = input_obj.value.substring(0,limitNumber);
	}			
}


/*************************************************************************************
 * Bird Response Functions                  				                         *
 *************************************************************************************/

//Change bird's text bubble
function formBirdSpeak(myString){
	document.getElementById('form_errors').innerHTML = myString;
}

//Change the bird to the happy version
function birdReactHappy(){
	$('img.login_bird').stop().animate({
        opacity: 1
    }, 250);
}

//Change the bird to the confused version
function birdReactGrouchy(){
	//$('img.login_bird').fadeOut("slow");
	$('img.login_bird').stop().animate({
        opacity: 0
    }, 250);
}

/*************************************************************************************
 * Functions to validate form elements "on the fly" before the form is ever submit.  *
 *************************************************************************************/

//Name Field -- Letters, numbers and spaces and underscores
function fly_validate_name(input_obj){
	var myIcon = document.getElementById('name_td');
	var myName = input_obj.value;
	var nameRegExp = /^(?=.*[^\W_])[\w ]*$/;
	var isValidName = nameRegExp.test(myName);

	if(isValidName){
		imValid(input_obj, myIcon);
		formBirdSpeak('');
		
	}else{
		imInvalid(input_obj, myIcon);
		formBirdSpeak('Lark can\'t pronounce your name! Please don\'t use any funny characters.');
	}
}

//Email Field -- Check DB
function fly_validate_email(input_obj){
	var myIcon = document.getElementById('email_td');
	var myEmail = input_obj.value;
	var emailRegExp  =
		/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i ;
	var isEmailValid =  emailRegExp.test(myEmail);		
	if(isEmailValid){
		$("#form_errors").removeClass().addClass('message_checking').text('Checking database...').fadeIn("slow");
				$.get("ajax/join.php",{ uname: myEmail } ,function(data)
		        {
				  if(data == 1) //if email is there
				  {
				  	$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
					{ 
				  		imInvalid(input_obj, myIcon);
						//document.getElementById('email_td').className='red_error';
				  		formBirdSpeak('This email has already registered! <a href=login.php>Log in here</a>!');
						});		
		          }
				  else // if the email is not there
				  {
				  	$("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
					{ 
				  		imValid(input_obj, myIcon);
						formBirdSpeak('');
					});
				  }
		        });
	}else{
		imInvalid(input_obj, myIcon);
		formBirdSpeak('That doesn\'t look like a valid email address to me!');
	}
}

//Email Field -- No Db Check
function fly_is_valid_email(input_obj){
	var myIcon = document.getElementById('email_td');
	var myEmail = input_obj.value;
	var emailRegExp  =
		/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i ;
	var isEmailValid =  emailRegExp.test(myEmail);		
	if(isEmailValid){
		imValid(input_obj, myIcon);
		formBirdSpeak('');
	}else{
		imInvalid(input_obj, myIcon);
		formBirdSpeak('That doesn\'t look like a valid email address to me!');
	}
}



//Initial Password Selection
function fly_validate_pass(input_obj){
	var myIcon = document.getElementById('pass_td');
	var myPass = input_obj.value;
	
	var passRegExp  =
			/((?=.*\d)(?=.*[a-zA-Z])).{6,12}/;
				
	var isPassValid =  passRegExp.test(myPass);		

	//Clear the retype password field either way
	if(document.getElementById('retype_password')){
		document.getElementById('retype_password').className = "inactive";
		document.getElementById('retype_password').value = "";
		document.getElementById('pass2_td').className = "input_response";
	}
	
	if(isPassValid){
		imValid(input_obj, myIcon);
		//document.getElementById('pass_td').className='green_check';
		formBirdSpeak('');
	}else{
		imInvalid(input_obj, myIcon);
		//document.getElementById('pass_td').className='red_error';
		formBirdSpeak('Your password must be between 6-12 characters and contain at least one number!');
	}
}

//Password Retyped Field
function fly_validate_matching_pass(input_obj){
	var myIcon = document.getElementById('pass2_td');
	//Get our two password values
	var myPass = input_obj.value;
	var myOtherPass = document.getElementById('password');

	//If our first password attempt is empty or was invalid, display error
	if(myOtherPass.value == "" || myOtherPass.className=="invalid"){
		formBirdSpeak('Your password must be between 6-12 characters and contain at least one number!');		
	}
	//Otherwise, proceed to check
	else{
		if(myPass != myOtherPass.value){
			imInvalid(input_obj, myIcon);
			//document.getElementById('pass2_td').className='red_error';
			formBirdSpeak('The passwords you have entered do not match!');
		}
		else{
			imValid(input_obj, myIcon);
			//document.getElementById('pass2_td').className='green_check';
			formBirdSpeak('');		
		}	
	}
}

//basically just validates that you've typed something
function fly_validate_message(input_obj){
	var myIcon = document.getElementById('message_td');
	var myMessage = input_obj.value;
	if(myMessage.length > 10){
		imValid(input_obj, myIcon);
		formBirdSpeak('');	
	}else{
		imInvalid(input_obj, myIcon);
		formBirdSpeak('Please elaborate a little more with your message!');
	}
}

/*************************************************************************************
 * Check the status of the form  													*
 *************************************************************************************/

function check_form_status(){
	var formReady = true;
	//Check all the inputs and see if the class is set to valid
    var allInputs = $(":input");
    allInputs.each(function(){
    	if( $(this).attr('class') != 'valid' && $(this).attr('class') != 'submitButton' && $(this).attr('class') != 'form_submit'){
    		formReady = false;
    	}
    });
    if(formReady == true){
    	displaySubmit();
    }
}

/*************************************************************************************
 * Submit Form																		*
 *************************************************************************************/

function displaySubmit(){
	$('.submitButton').hide();
	$('.submitButton').fadeIn('slow');
	$('.submitButton').attr('disabled', false);
}

function hideSubmit(){
	$('.submitButton').attr('disabled', 'disabled');	
}
