var formValidators;

function verifyPasswords(password1, password2) {
	if (password1.value != password2.value) {
		alert('The entered passwords do not match.');
		return false;
	}
	
	return true;
}

window.addEvent('domready', function() {
	// create the character limitations
	new CharLimit({input:$('user_create_form').username, max:15});
	new CharLimit({input:"city", max:30, showMessage:false});

	formValidators = autoCreateValidators();

	$("user_create_form").addEvent("submit", function(e) {
		e = new Event(e);
		e.stop();
		
		var valid = true;
		for(var a = 0; a < formValidators.length; a++) {
			valid &= formValidators[a].test();
		}
		
		// validate and process the passwords
		if(valid) valid &= verifyPasswords($('password'), $('confirm_password'));
		
		// check the agree button
		if(valid) {
			if(!$('agree').checked) {
				alert("You must agree to the terms and conditions");
				valid = false;
			}
		}
		
		// validate the email
		if(valid) {
			if($('email').get('value') != $('confirm_email').get('value')) {
				alert('The entered emails do not match');
				valid = false;
			}
		}
		
		if(valid) {
			if($('imagestamp').get('value').length != 6) {
				alert("Please enter the six letters or digits that appear in the image");
				valid = false;
			}
		}
					
		if(!valid) return;

		$('user_create_form_submit_button').disabled = true;
		
		this.set('send', {
			onComplete:function(data) {			
				if(data.match("error")) {
					var errStr = data.substr(7);
					var errData = errStr.split("||");
				
					alert(errData[0]);
				
					$('user_create_form_submit_button').disabled = false;
				
					// the reg image is now no good... refresh with the new hash from the server
					if(errData.length > 1) {
						var newHash = errData[1];
						$('imagestamp').value = '';
						$('imagehash').value = newHash;
						$('imagereg').src = '../forum/image.php?type=regcheck&imagehash=' + newHash;
					}
				} else if(data.match("success")) {
					var form = $("user_create_form");
					form.action = BASE_URL + "login.php";
					form.submit();
				} else {
					alert("uncaught error");
				}
			}
		}).send();
	});
});

function refreshRegImage() {
	var imgHash = $('imagehash').get('value');
	new Request({
		method:'post',
		data: new Hash({'do':'imagereg', 'imagehash':imgHash}).toQueryString(),
		url: BASE_URL + 'forum/ajax.php?do=imagereg&imagehash=' + imgHash,
		onSuccess:function(data, xml) {
			var hashTag = this.response.xml.getElementsByTagName('imagehash')[0];
		
			if(hashTag) {
				var newHash = hashTag.childNodes[0].nodeValue;
				$('imagehash').value = newHash;
				$('imagereg').src = '../forum/image.php?type=regcheck&imagehash=' + newHash;
			} else {
				// then error... get the error tag
				var error = $(xml.getElementsByTagName('error')[0]).getText();
				alert(error);
			}
	}}).send();
}