
var liveValidation;

/**
 * Initialize FB object and trigger login box
 * 
 * @param {String} [destination] The callback URL where to dispatch after logging in 
 */
function login(destination){
	var doLogin = function(response) {
		onLogin(response, destination);
	};
	FB.login(doLogin);
}

/**
 * What to do once the FB authorization finishes.
 * 
 * It basically checks if the user was authorized and redirects to
 * the specified destination.
 * 
 * @param response The FB response object
 * @param {String} [destination] The callback URL
 */
function onLogin(response, destination) {

	/*
	 * If the user is logged in there should be a session
	 */ 
	if (response.session) {
		var target = '';
		if(destination !== undefined){
			target = '?target=' + destination;
		}
		top.location.href = '/login' + target;
	}
}

/**
 * Trigger a log out on FB
 */
function logout(){
	FB.logout(function() {top.location.href='/logout';});return false;
}

/**
 * Initializes behavior for the username blur
 */
function setupUsernameValidation() {
    $('input[name=username]').keyup(function(e){
		var key = e.keyCode;
		if(key < 132 && key > 64 || key == 8 || key == 190 || key == 32){
			validateUsername();
		}
    });
    $('input[name=username]').blur(validateUsername);
}

/**
 * Throw a request to the server to make sure the username is valid
 */
function validateUsername() {
	
	$('#message').hide();
	$('#message').empty();
	
	$('#submitForm').attr("disabled", true);
    var responseImage = $('#usernameValid img');
    responseImage.attr('src', '/images/friend_indicator.gif');
    $('#usernameValid').fadeIn('fast');
    
    if (liveValidation != null) {
    	liveValidation.abort();
	}
    
    // Filters
	var filterUsername = /^[a-z0-9]{6,20}$/;
	if (!filterUsername.test($('input[name=username]').val())) {
		$('#message').html('Please choose a username between 5 and 20 characters using only letters and numbers!');
		$('#message').fadeIn('slow');
		imageSrc = '/images/invalidCheck.png';
		responseImage.attr('src', imageSrc);
    	return false;
    }
    
    liveValidation = $.get('/account/validateUsername', { username: $('input[name=username]').val() }, function(response) {
        var imageSrc = '';
        if (response) {
            imageSrc = '/images/invalidCheck.png';
            responseImage.attr('alt', response);
            $('#message').html(response);
            $('#message').fadeIn('slow');
        } else {
            imageSrc = '/images/validCheck.png';
            responseImage.attr('alt', 'valid username');
            $('#message').fadeOut('slow');
            $('#message').empty();
            $('#submitForm').removeAttr("disabled");
        }
        responseImage.attr('src', imageSrc);
    });
}

function createAccount(url){
	$('#message').hide();
	$('#message').empty();
	
	// Filters
	var filterEmail = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	
	if ($('#usernameValid img').attr('src') == '/images/invalidCheck.png') {
		$('#message').html('That username is taken. Please choose another.');
		$('#message').fadeIn('slow');
		return false;
	} else if (!filterEmail.test($('input[name=email]').val())) {
		$('#message').html('Please enter a valid e-mail address.');
		$('#message').fadeIn('slow');
		return false;
	} else if ($('select[name=gender]').val() == '') {
		$('#message').html('Please select a gender.');
		$('#message').fadeIn('slow');
		return false;
	} else if ($('input[name=city_id]').val() == '') {
		$('#message').html('Please enter a valid city.');
		$('#message').fadeIn('slow');
		return false;
	}
	
	// Create user
	$.ajax({
	   type: "POST",
	   url: "/account/createAccount",
	   data: $('#confirmationForm').serialize(),
	   dataType: "json",
	   success: function(response){
		 if (response['error']) {
			 $('#message').html(response['error']);
			 $('#message').fadeIn('slow');
			 $('#usernameValid img').attr('src', '/images/invalidCheck.png');
		 }
		// Redirect to profile
		top.location.href = '/profile';
	   }
	 });
	
	// Open facebook popup
	window.open(url, 'extendPermissions', "width=700px,height=300px,status=yes");
}