/*# Metadata ################################### Header v.2
# $URL: http://gt-nas-1/svn/gamebase.frontend/trunk/xsl_gamebase/_stargames/landingpages/data/v01/validate.js $
# $Rev: 3317 $
# $Date: 2011-06-16 13:11:54 +0200 (Do, 16 Jun 2011) $
# $Author: bszil $
### TOC ###################################################
#
### Description ###########################################
# 
# formvalidation of register form with nicknamecheck for availability
#
#########################################################*/
var nickAvailable = false;//nick available
var nickChecked = false;//nick checked for availability
var validateWhat = 'form';//validation of one formfield only or the whole form is running

$(window).addEvent('domready', function() {
	$('nick')
		.addClass('nickCheck')
		.addClass('nickUniqueCheck');
	$('email').addClass('emailCheck');
	$$(	
	   $('pass'),
	   $('pass_conf')
	).addClass('passCheck');
	
	$('pass_conf').addClass("validate-match matchInput:'pass'"); 
	$('agb').addClass('agbCheck');
	$('securecode').addClass('securecodeCheck');
	
	
	$('pass').addEvent('blur', function () {
		if ($('pass_conf').get('value').length > 0) {
			$('pass_conf').fireEvent('change');
		}
		//if first passwordfield is changed after allready filled second password field fire change event of second password field for checking the match again 
	});
	

	fnValidator = new FormValidator('fnRegister', {
		scrollToErrorsOnSubmit: false,
		stopOnFailure: true,
		evaluateFieldsOnChange: true,
		evaluateFieldsOnBlur: false,
		onElementFail: function(element, rulesArray) {
			$("mistakes_wrapper").setStyle('display', 'block')
			rulesArray.each(function (item) {
				if ($(item)) {
					$(item).setStyle('display', 'list-item');
				}
			})
			//hidden Error-list-elements have the ID of their validation rule, example: failed rule is 'xyzcheck' -> show $('xyzcheck')
		},
		onElementPass: function (element) {
			var passedClasses = element.className.split(' ');
			passedClasses.each(function (item) {
				if ($(item)) {
					$(item).setStyle('display', 'none');
				}
			});
			if (!$("mistakes_wrapper").getElements('li').getStyle('display').contains('list-item')) {
				$("mistakes_wrapper").setStyle('display', 'none');
			}//if no error element is visible anymore hide the whole Error-wrapper
		},
		evaluateOnSubmit: true,
		serial: true,
		
		onElementValidate: function () {
			validateWhat = 'field';//save the last validation, its always 'field' but overwritten immedialy with 'form' on formValidate, if its a whole form validation
		},
		
		onFormValidate: function (passed, form, evt) {
			validateWhat = 'form';//whole form validation(on submit or on enter)
			if (passed && nickChecked && nickAvailable) {
				form.submit();
			}
		}
	});
		
	fnValidator.addAllThese([
		['nickUniqueCheck', {
			test: function (element) {
				if (!(/^[A-Za-z0-9_]{3,13}$/).test(element.get('value'))) {
					if ($('divNick')) {
						$('divNick').dispose();//remove it if all good
					}
					$('nickUniqueCheck').setStyle('display', 'none');
					return true;
					//no validation for unique nick if nickcheck isn't passed, on validation of the whole form all rules are checked, if the username doesnt fit or is empty the availibilty is not interesting
				} else {
					if (!nickChecked) {//if nickfield is not checked yet
						checkNick(element, $('nickUniqueCheck'), fnValidator);
						fnValidator.stop();//stop validation here and continue if the request of checknick() is complete
						return true;
					} else {
						return nickAvailable;//return of the global variable for holding the nickcheckstatus, set by the checkNick Function
					}
				}
			}
		}],
		['nickCheck', {
			test: function (element) {
				return (/^[A-Za-z0-9_]{3,13}$/).test(element.get('value'));
			}
		}],
		['emailCheck', {
			test: function (element) {
				return (/^[\w-]+(?:\.[\w-]+)*@\w(?:[\w-]+\.)+[a-zA-Z]{2,7}$/).test(element.get('value'));
			}
		}],
		['passCheck', {
			test: function (element) {
				return (/^.{5,128}/).test(element.get('value'));
			}
		}],
		['securecodeCheck', {
			test: function (element) {
				return (element.get('value').length == 6);
			}
		}],
		['agbCheck', {
			test: function (element) {
				return element.get('checked');
			}
		}]
	]);
	
	$('fnRegister').addEvent('submit', function (evt) {
		evt.stop();//block submitting
	});
		
	$('nick').addEvent('change', function (evt) {
		nickAvailable = false;
		nickChecked = false;
	});//reset if the content of the nickfield changed
});

function setAlternateNick(nickname) {
	if (Browser.Engine.trident5) {
		fnValidator.start();//IE7 needs starthelp here, no questions please *confused*
	}
	$('nick')
		.set('value', nickname)
		.fireEvent('change');//force revalidation
}

//sample: checkNick($('nick'), $('nickUniqueCheck'), fnValidator);
function checkNick(formField, errorHolder, validator) {
		new Request.JSONP({
		url: DOTNETAPPFOLDER + '/CheckNick',
		data: {
			xpf: 'gen',
			nick: formField.get('value')
		},
		onComplete: function (data) {
			var divNick = 'divNick';
			var availableNick = data["isavailable"];
			if (availableNick == 0) {
				if (!$(divNick)) {
					var divNick = new Element('div', {
						id: divNick
					});//div for holding alternative nicknames list
					divNick.inject(errorHolder, 'bottom');
				} else {
					$(divNick).empty();//empty the alternative names div
				}
				var dlTag = new Element('dl', {
					id: 'nickContainer'
				});
				dlTag.inject(divNick);
				
				data["alternates"].each(function (item) {
					var ddTag = new Element('dd');
					var aTag = new Element('a', {
						text: item,
						href: Browser.Engine.trident5 ? "javascript:setAlternateNick('" + item + "');void(0);" : "javascript:;",
						onclick: "setAlternateNick(this.get('text'))"
					});
					aTag.inject(ddTag);
					ddTag.inject(dlTag);
				})
				errorHolder.setStyle('display', 'list-item');
				nickAvailable = false;
			} else {
				if ($(divNick)) {
					$(divNick).dispose();//remove it if all good
				}
				nickAvailable = true;//set global nick available variable
			}
			nickChecked = true;//set global nick checked variable
			validator.start();//continue validation of field or whole form now
			if (validateWhat == 'field') {
				validator.validateField(formField);
			} else {
				validator.validate();	
			}
		}
	}).send();
}

