////
//functions
function isValidEmail(str) {
  return  (str.indexOf("@") > 0);
}

function pretty(str){
  str = str.replace(/_/g, ' ');
  return ucwords(str);
}

function ucwords (str) {
  // http://kevin.vanzonneveld.net
  // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // +   improved by: Waldo Malqui Silva
  // +   bugfixed by: Onno Marsman
  // *     example 1: ucwords('kevin van zonneveld');
  // *     returns 1: 'Kevin Van Zonneveld'
  // *     example 2: ucwords('HELLO WORLD');
  // *     returns 2: 'HELLO WORLD'
 
  return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase( ); } );
}


/////
//main
$(document).ready(function() {
  
    jQuery('#birthday-submit').click(function(){
	var min_year = Date.parse('-13years');
	//.toString('dddd, MMMM d, yyyy'));
	var month = parseInt(jQuery('#month').val());
	var day = parseInt(jQuery('#day').val());
	var year = parseInt(jQuery('#year').val());


	if((!month)||(!day)||(!year)){
	  alert('Please fill in all the fields for your birthday');
	  return 1;
	}
	birthday = Date.parse(month+'/'+'/'+day+'/'+year);
	if(birthday < min_year){
	  jQuery('#whiteout-regions').css('display', 'none');
	  jQuery('input').removeAttr('disabled');
	  jQuery('select').removeAttr('disabled');
	  jQuery('#signup-button').click(function(){
	      ///////
	      //Begin validation
	      //////

	      fields_to_check = new Array ('first_name', 'last_name',
					   'email_address', 'confirm_email_address', 'postal_country');
	      
	      //check all fields to make sure they are filled in
	      for(key in fields_to_check){
		if(jQuery('#'+fields_to_check[key]).val()==''){
		  alert('Please fill in '+pretty(fields_to_check[key]));
		  return 0;
		}
	      }
	      //email addresses match?
	      if(jQuery('#email_address').val()!=jQuery('#confirm_email_address').val()){
                if(jQuery('#email_address').val()!=''){
                  alert('Email addresses must match');
                  return 0;
                }
	      }
	      //is email valid
	      if(!isValidEmail(jQuery('#email_address').val())){
		alert('Invalid email address');
		return 0;
	      }



	      ///////
	      //End validation (passed all cases)
	      //////
	      document.email_signup.submit();
            });
	}else{
	  window.location.href = '?invalid_age=1';
	}
      });
  });

