var Registration = {
	atLeast13: false,
	lastScreen: false,
	emailTaken: false,
	usernameTaken: false,
	
	ajaj: function(command, params, callback){
		params.ajaj = command;
		params._rand = Math.random();
		jQuery.getJSON('/register.php', params, callback);
	},
	
	Password: {
		sets: [
			'qwertyuiopasdfghjklzxcvbnm',
			'0123456789',
			'¸éöóêåíãøùçõúôûâàïðîëäæýÿ÷ñìèòüáþ³¿º´',
			',.-() ',
			'`~!@#$%^&*_=+[{]}\\|;:\'"<>/?'
		],

		getSet: function(chr){
			chr = chr.toLowerCase();
			for(var i = this.sets.length - 1; i >= 0; i--)
				for(var j = this.sets[i].length - 1; j >= 0; j--)
					if(this.sets[i].charAt(j) == chr)
						return i;
			return -1;
		},

		test: function(password){
			var leaks = 0;
			for(var i = password.length - 3; i >= 0; i--){
				var chars = [password.charAt(i), password.charAt(i + 1), password.charAt(i + 2)];
				var cSets = [this.getSet(chars[0]), this.getSet(chars[1]), this.getSet(chars[2])];
				if((chars[0] == chars[1]) && (chars[1] == chars[2])) leaks += 2;
				if((cSets[0] == cSets[1]) && (cSets[1] == cSets[2])) leaks++;
			}
			
			var usedSets = [];
			usedSets[this.sets.length] = false;
			for(var i = password.length - 1; i >= 0; i--)
				usedSets[this.getSet(password.charAt(i))] = true;
			usedSets.count = 0;
			for(var i = this.sets.length - 1; i >= 0; i--)
				if(usedSets[i]) usedSets.count += this.sets[i].length;
			if(usedSets[-1]) usedSets.count += 20;

			return {length: password.length, used: usedSets.count, leaks: leaks};
		}
	}
};

jQuery(function(){
	var $ = jQuery;
	$('#block_date_of_birth')
		.append(
			$('<p></p>')
				.append(
					$('<button type="button">Proceed &rarr;</button>').click(function(){
						var now = new Date;
						var dob = {
							year:	parseInt(this.form.elements.dob_year.value),
							month:	parseInt(this.form.elements.dob_month.value) - 1,
							date:	parseInt(this.form.elements.dob_date.value)
						};
						var dob_date = new Date(dob.year, dob.month, dob.date);
						if((dob_date.getFullYear() != dob.year) || (dob_date.getMonth() != dob.month) || (dob_date.getDate() != dob.date)){
							alert('Please enter correct date');
							return false;
						}
						Registration.atLeast13 = false;
						if(now.getFullYear() - dob.year > 13)
							Registration.atLeast13 = true;
						else if(now.getFullYear() - dob.year == 13){
							if(now.getMonth() > dob.month)
								Registration.atLeast13 = true;
							else if(now.getMonth() == dob.month)
								Registration.atLeast13 = now.getDate() >= dob.date;
						}
						$('#block_date_of_birth').hide('slow');
						if(Registration.atLeast13)
							$('#block_personal_data').show('slow');
						else
							$('#block_regular_data').show('slow');
					})
				)
		);
	
	$('#block_personal_data')
		.append(
			$('<dt class="large"></dt>')
				.append(
					$('<button type="button">&larr; Return</button>').click(function(){
						$('#block_personal_data').hide('slow');
						$('#block_date_of_birth').show('slow');
					})
				)
				.append(
					$('<button type="button">Proceed &rarr;</button>').click(function(){
						if(
							!this.form.elements.first_name.value.length ||
							!this.form.elements.last_name.value.length ||
							(!this.form.elements.gender[0].checked && !this.form.elements.gender[1].checked)
						){
							alert('Please fill in all fields!');
							return false;
						}
						$('#block_personal_data').hide('slow');
						$('#block_regular_data').show('slow');
					})
				)
		)
		.hide();

	$('#block_regular_data')
		.append(
			$('<dt class="large"></dt>')
				.append(
					$('<button type="button">&larr; Return</button>').click(function(){
						$('#block_regular_data').hide('slow');
						if(Registration.atLeast13)
							$('#block_personal_data').show('slow');
						else
							$('#block_date_of_birth').show('slow');
					})
				)
				.append(
					$('<button type="button">Proceed &rarr;</button>').click(function(){
						if(!Registration.testEmailAddress(this.form.elements.email.value)){
							alert('Please enter correct e-mail address!');
							this.form.elements.email.focus();
							return;
						}
						if(this.form.elements.email.value != this.form.elements.email2.value){
							alert('E-mail addresses do not match!');
							this.form.elements.email2.value = '';
							this.form.elements.email2.focus();
							return;
						}
						if(Registration.emailTaken){
							alert('This e-mail address is already registered! You are not allowed to register two accounts on the same e-mail address.');
							this.form.elements.email.focus();
							return;
						}
						if(!this.form.elements.password.value.length){
							alert('Please enter password!');
							this.form.elements.password.focus();
							return;
						}
						if(this.form.elements.password.value != this.form.elements.password2.value){
							alert('Passwords do not match! Please retype!');
							this.form.elements.password.value = '';
							this.form.elements.password2.value = '';
							this.form.elements.password.focus();
							return;
						}
						$('#block_regular_data').hide('slow');
						$('#block_character').show('slow');
						Registration.lastScreen = true;
					})
				)
		)
		.hide();
	
	$('#block_character > *:last-child')
		.prepend(
			$('<button type="button">&larr; Return</button>').click(function(){
				Registration.lastScreen = false;
				$('#block_character').hide('slow');
				$('#block_regular_data').show('slow');
			})
		);
	
	$('#block_character')
		.hide();
		
	$('#registration_form > [@id^="block_"] :input').keypress(function(event){
		if((event.keyCode == 13) && !Registration.lastScreen){
			$('button:last-child', $(this).parents('[@id^="block_"]')).click();
			return false;
		}
	});
	
	$('#registration_form :text, #registration_form :password')
		.keyup(function(){
			var now = (new Date()).getTime();
			this.lastTimeKeyPressed = now;
		})
		.blur(function(){
			$(this).change();
		})
	;
		
	window.setInterval(function(){
		var now = (new Date()).getTime();
		$('#registration_form :text, #registration_form :password').each(function(){
			var last = this.lastTimeKeyPressed ? this.lastTimeKeyPressed : 0;
			if(now - last > 500){
				this.lastTimeKeyPressed = now + 1e6; // just something in far future
				$(this).change();
			}
		});
	}, 300);
	
	Registration.testEmailAddress = function(address){
		return (/^[a-z0-9_\.]+@([a-z0-9\-]+\.)+[a-z0-9\-]{2,}$/i.test(address));
	}
	
	Registration.setInfo = function(id, good, messages){
		$(id)
			.text(good ? (messages[1] ? messages[1] : 'Good') : messages[0])
			.css({color: good ? '#3ec525' : '#e81780'});
		return good;
	};
	
	$('#field_username').change(function(){
		if(!this.value.length){
			Registration.setInfo('#info_username', false, ['Please enter username']);
			return;
		}
		var re5digit=/^[a-zA-Z0-9]+$/i
		if (this.value.search(re5digit)==-1){
			Registration.setInfo('#info_username', false, ['Invalid character.']);
			return;
		}
		Registration.ajaj('check_username', {username: this.value}, function(response){

			if(response.status == 'deny')
			{
				Registration.setInfo('#info_username', false, ['Bad username!']);
			}
			else
			{
				Registration.usernameTaken = response.status != 'new';
				Registration.setInfo('#info_username', !Registration.usernameTaken, ['The username is taken!']);
			}
		});
	});
	
	$('#field_email').change(function(){
		Registration.setInfo('#info_emails_match', this.value == this.form.elements.email2.value, ['E-mail addresses do not match', 'E-mail addresses match']);
		if(!this.value.length){
			Registration.setInfo('#info_email', false, ['Please enter email']);
			return;
		}
		if(!Registration.setInfo('#info_email', Registration.testEmailAddress(this.value), ['Please enter correct email']))
			return;
			
			var thisemail = this.value;
			
		Registration.ajaj('check_email', {emailer: this.value}, function(response){
			Registration.emailTaken = response.status != 'new';
			Registration.setInfo('#info_email', !Registration.emailTaken, ['The email is taken!']);
		});
	});
	
	$('#field_email2').change(function(){
		if(!Registration.setInfo('#info_emails_match', this.value == this.form.elements.email.value, ['E-mail addresses do not match', 'E-mail addresses match']))
			return;
	});
	
	$('#field_password').change(function(){
		Registration.setInfo('#info_passwords_match', this.value == this.form.elements.password2.value, ['Passwords do not match', 'Passwords match']);
		if(!this.value.length){
			Registration.setInfo('#info_password', false, ['Please enter password']);
			return;
		}
		var pwd = Registration.Password.test(this.value);
		var strong = (pwd.length >= 6) && (pwd.used > 20) && (pwd.leaks / pwd.length < 0.5);
		Registration.setInfo('#info_password', strong, ['Weak password', 'Strong password']);
	});
	
	$('#field_password2').change(function(){
		if(!Registration.setInfo('#info_passwords_match', this.value == this.form.elements.password.value, ['Passwords do not match', 'Passwords match']))
			return;
	});
	
	$('#registration_form').submit(function(){
		if(!Registration.lastScreen){
			alert('Please finish filling in the form first!');
			return false;
		}
		if(!this.elements.username.value.length){
			alert('Please enter name!');
			this.elements.username.focus();
			return false;
		}
		if(Registration.usernameTaken){
			alert('This name is taken! Please choose another one!');
			this.elements.username.focus();
			return false;
		}
		return true;
	});
}); 

