(function(){
    var h2 = document.querySelector('h2');
     
    var spanUsername = document.querySelector('span');
	var spanEmail = document.getElementsByTagName('span')[1];
	
	var usernameField = document.forms[0].elements[0];
	var emailField = document.forms[0].elements[1];
	
	var spanUsernamePattern = new RegExp('unique');
	var emailPattern = /[a-z0-9]+@[a-z0-9]+\.[a-z]+/i;
	
	var btn = document.querySelector('button');
	btn.disabled = true;
	
	var request = new XMLHttpRequest();
	
	function buttonWatcher(){
	    if(emailPattern.test(emailField.value) && usernameField.value != ''){
		    btn.disabled = false;
		}
		else{
		    btn.disabled = true;
		}
	}
	function sendData(){
	    if(spanUsernamePattern.test(spanUsername.innerText)){
		    request.onreadystatechange = function(){
			    if(request.readyState == 4 && request.status == 200)

			}
			request.open('POST', 'registration.php', false);
			request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
			request.send("username=" + usernameField.value + "&email=" + emailField.value);
		}
		else{
		    alert('Username is already taken');
			usernameField.focus();
		}
	}
	
	usernameField.addEventListener('keyup', buttonWatcher, false);
	usernameField.addEventListener('keypress', buttonWatcher, false);
	emailField.addEventListener('keyup', buttonWatcher, false);
	emailField.addEventListener('keypress', buttonWatcher, false);
	btn.addEventListener('click', sendData, false);
	
	
})();
{
				    h2.innerText = request.responseText;
					usernameField.value = '';
					emailField.value = '';
					spanUsername.innerHTML = '';
					spanEmail.innerHTML = '';
					btn.disabled = true;
				}