var dependencies_array;
var passed_validation = false;

var terms_viewed = false;
var privacy_policy_viewed = false;

var country_id = null;
var country_question_id = 220;

var lastClick = 0;
var currentClick;
var clickDelay = 3000;			


// We want to proxy a submit to the validation service before submitting it
$('#questions_active').submit(function( e ){

	// Remove the signup errors
	$('.signup_error').detach();
	
	if( !passed_validation )
	{
			// Stop the form from submitting
		e.preventDefault();
	
		// Validate the form
		$.post(
			'?do_validate=true',
			$("#questions_active").serialize(),
			validate
		);		
	}
	else
	{
		passed_validation = false;
		return true;
	}

	
});

// Setup the dependancies
var dependencies = $('#deps_json');
if( dependencies )
{
	dependencies_array = $.parseJSON( dependencies.html() );
}

// Attach the onchange handler to any selects in the form
$('#questions_active select').each(function(){
	$(this).change(onchangeHandler);
});

// Make sure that the user has read the terms and conditions before agreeing it
$('#q_999992').click(function(){
	if( !terms_viewed )
	{
		alert('You must read the Terms and Conditions before agreeing to them');
		$('#q_999992').removeAttr('checked');
	}
});

// Flag that the affiliate has read the terms and conditions
$('#termsLink').click(function( e ){
	e.preventDefault();
	terms_viewed = true;
	
	window.open(termsURL, 'terms', 'scrollbars=yes, resizable=yes, width=600, height=400' );
});


// Make sure that the user has read the privacy policy before agreeing to it
$('#q_999993').click(function(){
	if( !privacy_policy_viewed )
	{
		alert('You must read the Privacy Policy before agreeing to it');
		$('#q_999993').removeAttr('checked');
	}
});

// Flag that the affiliate has read the Privacy Policy
$('#privacyLink').click(function( e ){
	e.preventDefault();
	privacy_policy_viewed = true;
	
	window.open(privacyURL, 'terms', 'scrollbars=yes, resizable=yes, width=600, height=400' );
});


/**
 * Send an AJAX response to the validation service. If the response is 'OK', then submit the form, otherwise display the error messages
 **/
function validate( response )
{
	if( response == 'OK' )
	{
		passed_validation = true;
		$("#questions_active").submit();
	}
	else
	{
		// Reset the captcha
		$("#q_999999").val('');
		var errors = eval( response );
		
		// Attach the error messages
		for( i=0; i < errors.length; i++ )
		{
			var error = "<div class='signup_error'>" + errors[i].message + "</div>";
			var question_id = errors[i].idquestion;
			
			$( '#qcon_' + question_id ).append( error );
		}
	}
}

/**
 * Handle a user selecting an option from the drop down
 *
 * (Nest children if necessary)
 * 
 **/
function onchangeHandler( e )
{
	var element = e.target;
	var question_id = element.name.replace('q_', '');
	var value = element.value;

	// We need to store the country ID globally, so that we are able to pass it to the verifyphone script	
	if(question_id == country_question_id)
	{
		country_id = value;
	}

	// Grab the question container
	var container = $('#qcon_' + question_id );
	var question_pool = $('#question_pool');
	
	// Grab any children
	var children = dependencies_array[ question_id + '_' + value ];
	
	// Grab the child container ( or instantiate it if necessary )
	var child_question_container = $('#qcon_' + question_id + ' ul');
	if( child_question_container.length == 0 )
	{
		child_question_container = $("<ul></ul>");
		container.append( child_question_container );
	}
	
	// Add the existing children back to the question pool
	child_question_container.children().each(function(){
		question_pool.append( $(this) );
	});
	
	// Add the childrent to the container
	if(children)
	{
		for( i=0; i< children.length; i++ )
		{
			var child_id = '#qcon_' + children[i];
			var child_element = $(child_id);
			
			child_element.change(onchangeHandler);
			child_question_container.append( child_element );
		}
	}
}

/**
 * Trigger Phone validation
 **/
function handlePhoneCallback( e )
{
	element = $('#' + e.replace('q_', 'question_') );
	
	if( element.length < 1 || element.val() == '' || element.val() == undefined )
	{
		alert('You must enter a phone number first');
		return false;
	}
	
	if( country_id == null )
	{
		alert('You must select a country first');
		return false;
	}
	
	var u = gup('u');
	var v = gup('v');
	var url = '/signup/verifyphone?u='+u+'&v='+v+'&phone='+encodeURIComponent(element.val())+'&country='+country_id;
	
	// This ensures users can only spawn one phone verification window every 3 seconds.
	// This will stop users from double clicking the number, and sending 2 PINs.
	// This would cause issues, as the phone verification system would send 2 PINs, but the 2nd call wouldn't interrupt the 1st one,
	// so PIN #2 would be saved in the phoneverification class, while PIN #1 would be read out to the user.
	currentClick = new Date().getTime();
	if( (currentClick - lastClick) >= clickDelay )
	{
		window.open(url,'Neverblue','width=600,height=600');
	}
	lastClick = currentClick;
}



function gup( name )
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
	{
		return "";	
	}
    else
	{
		return results[1];	
	}
}

