var can_register = true;

function submitSignup () 
{ 
	// Perform additional age-gate check on submit
	if ( document.cookie.length > 0 ) {
		var start = document.cookie.indexOf( 'ya2ydrsat' );
		if ( start >= 0 ) {
			$('#too_young').css('color', 'red').slideDown();
			can_register = false;
		}
	}
	
	if (!can_register)
	{
		$('#too_young').css('color', 'red').slideDown();
		return false;
	}

	// Confirm the user's age > 14
	birthdate = Date.UTC($('#birth_date_year').val(),
			     $('#birth_date_month').val(),
			     $('#birth_date_day').val());
	today = new Date();
	age = Math.floor( ( ( today - birthdate ) / 1000 ) / ( 60 * 60 * 24 * 365 ) );

	if (age < 14 || isNaN( age ) )
	{
		var expires = new Date( );
		expires.setTime( today.getTime( ) + ( 60 * 60 * 24 * 1000 ) );
		document.cookie = 'ya2ydrsat=true;expires=' + expires.toGMTString( );
		
		$('#too_young').css('color', 'red').slideDown();
		return false;
	}	


	// Validate the email
	var email = $( '#subscriber_email' ).val( ).trim( );
	var email_regex = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/i;
	if ( 0 == email.length || !email_regex.test( email ) )
	{
		$('.newsletter_error').hide();
		$('#invalid_email').css('color', 'red').slideDown();
		return false;
	}

	// Did they accept the terms and conditions?
	if ( !$terms_of_use.attr( 'checked' ) ) {
		$( '.newsletter_error' ).hide();
		$( '#must-accept-terms' ).css( 'color', 'red' ).slideDown( );
		return false;
	}

	$.ajax( { 
		type: 'get',
		url: '/community/newsletter/subscribe',
		data: $( '#newsletter-form' ).serialize( ),
		success: function ( data ) { 
			$('.newsletter_error').hide();
			$('#subscribe_success' ).css('font-weight', 'bold').show( );
			$(':input').clearForm();
		},
		error: function ( ) { 
			$('#oops_error').show( );
			$(':input').clearForm();
		}		
	} );

	return false;
}

$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

// Clear the email input box on blur/focus
$( function ( ) { 
	$( '#subscriber_email' ).focus( function ( ) { 
		if ( 'Enter Email' == $( this ).val( ) )
			$( this ).val( '' );
	} );	

	$( '#subscriber_email' ).blur( function ( ) { 
		if ( 0 == $( this ).val( ).trim( ).length )
			$( this ).val( 'Enter Email' );
	} );	
	
	if ( document.cookie.length > 0 ) {
		var start = document.cookie.indexOf( 'ya2ydrsat' );
		if ( start >= 0 ) {
			can_register = false;
		}
	}
	
} );

