$(document).ready(function() {
	var USERNAME_PATTERN = /^\w+$/g;
	var USERNAME_PATTERN_ERROR_MESSAGE = 'Invalid username. Please note that usernames can only contain letters, numbers and an underscore; spaces and other punctuation is not allowed.'
	
	var validateUsername = $('#validateUsername');
    $('#id_username').keyup(function () {
        var t = this; 

		$(this).parents('p').prev('ul').fadeOut();

        if (this.value != this.lastValue) {
			validateUsername.removeClass('error')

			if (this.value.match(USERNAME_PATTERN) == null) {
				validateUsername.addClass('error');
				validateUsername.html(USERNAME_PATTERN_ERROR_MESSAGE);
			} else {
	            if (this.timer) clearTimeout(this.timer);
	            validateUsername.removeClass('error').html('<img src="/site_media/site_images/icons/ajax_loader.gif" height="12" width="12" style="display:inline; margin-right: 10px" /> checking availability...');
	            this.timer = setTimeout(function () {
	                $.ajax({
	                    url: '/accounts/register/check_username_availability/',
	                    data: 'username=' + t.value + "&ajax=true",
	                    dataType: 'json',
	                    type: 'post',
	                    success: function (j) {
	                        validateUsername.html(j.msg);
	                    }
	                });
	            }, 200);
			}
            this.lastValue = this.value;
        }
    });	
});
