$(function(){
	form = $('#regform');
	$('input[name=username]', form).focus();
	form.bind("submit", function(e) {
		//username check...
		var username = $.trim( $('input[name=username]', form).val() );
		if( username == '' ) {
			form_error('username', 'Please fill in the username field!');
			return false;
		}
		if( username.length < 3){
			form_error('username', "Too short username! It must contain at least 3 symbols.");
			return false;
		}
		if( !is_valid_str(username) ){
			form_error('username', "Username must contain only [a-zA-Z0-9_] symbols!");
			return false;
		}
		//check password...
		var password = $.trim( $('input[name=password]', form).val() );
		if( password == '' ) {
			form_error('password', "Please, fill in the password field!");
			return false;
		}
		if( password.length < 5){
			form_error('password', "Too short password! It must contain at least 5 symbols.");
			return false;
		}
		if( !is_valid_password(password) ){
			form_error('password', "The following characters are allowed in your password: a-z, A-Z, 0-9, _ and common punctuation characters.");
			return false;
		}
		var passwordconf = $.trim( $('input[name=passwordconf]', form).val() );
		if( password != passwordconf ) {
			$('input[name=passwordconf]').val('');
			form_error('passwordconf', "The password and the retyped passwords do not match! Please, retype the password once again.");
			return false;	
		}
		//check email...
		var email = $.trim( $('input[name=email]', form).val() );
		if( !email ) {
			form_error('email', "Please fill in the email field!");
			return false;
		}
		if( !is_valid_email(email) ) {
			form_error('email', "Invalid email adress!");
			return false;
		}
		//check captcha
		var ccode = $.trim( $('input[name=ccode]', form).val() );
		if( ccode == '' ) {
			form_error('ccode', "Please, enter the code from image!");
			return false;	
		}

		return true;
	});
	
	$("#cupdater").bind("click", function(e) {
		var rnd = Math.floor( Math.random()*10000 );
		$("#sequre_img").attr('src', '/get_captcha/?' + rnd);
		$('input[name=ccode]', form).val('').focus();
		return false;
	});
	
	
});


function is_valid_str(str) {
	return ( str.match(/[^a-zA-Z0-9_]/) ) ? false : true;
}
function is_valid_password(str) {
	return ( str.match(/[^a-zA-Z0-9_.?:;!,'"]/) ) ? false : true;
}
function is_valid_email(str) { 
	return str.match(/^(\w|-|\d|_)+(\.(\w|-|\d|_)+)*@(\w|-|\d)+(\.(\w|-|\d)+)+$/);
}

