(function($) {

	var unlockFields = function(form) {
		
		form.eachField(function(field){
			if (field.id != 'lastname') {
				if(field.name != 'country'){
					field.enable();
				}
				var clName = field.dom[0].className;
				if (clName.indexOf('disabled ') >= 0) {
				   
					field.dom[0].className = clName.substring(9, clName.length);
				}
			}
		});
		$('.fauxSelect:not(#joinUsFormcountryREP)').css('background-color', '#FFFFFF');                    
	};
	
	var displayLocalizedConseilleres = function(field){
		$.getJSON('/handlers/GetListConselor.aspx?cp=' + field.getValue() + '&sessionId=' + $('#sessionId').val(), function(data) {
			var items = [];
			$.each(data.data, function(key, value) {
				items.push('<li><label for="advisor' + key + '">' + value.firstname.substring(0, 1) + value.firstname.substring(1, value.firstname.length).toLowerCase() + ' ' + value.lastname.substring(0, 1) + '.  - ' + value.zipcode + ' - ' + value.town.substring(0, 1) + value.town.substring(1, value.town.length).toLowerCase() + ' - '+value.fonction+'</label><input type="radio" name="advisorInput" id="advisor' + key + '" value="' + value.id + '"/></li>');
			});
			
			var html = items.join('');
			$('#conseilleres ul').empty();
			
			if(items.length == 0){
				$('#conseilleres .title').hide();
				$('#conseilleres .error').show();
			}
			else if(items.length == 1){
				$('#advisor').val(data.data[0].id);
				$('#conseilleres label').hide();
			} else{
				
				$('#advisor').val(data.data[0].id);
				$('#conseilleres .title').show();
				$('#conseilleres .error').hide();
				$('#conseilleres ul').append(html);
				
				box.ui('form').destroy('conseilleres');
				box.ui('form').create({
					element: '#conseilleres',
					parentForm: 'joinUsForm'
				}).addReplacement().mustValidate(function(form){
					form.field('advisorInput').mustValidate(function(field){
						if(!field.isChecked()){
							return l10n.errors.required.EM_SW_43;
						} else{
							$('#advisor').val(field.getValue());
						}
					});
				});
				box.ui('form.conseilleres').field('advisorInput').check('advisor0');
			}
			
		});
	};

	box.dom(document).ready(function() {
		
		var stopSendID = false;
		/* Save the tag recruitTag */
		if ($.cookie("recruittag")) {
			if ($('#joinUsForm input[name=recruitTag]').attr('value') == "") {
				$('#joinUsForm input[name=recruitTag]').attr('value') = $.cookie('recruittag');
			}
		}
		/* is Confirmation Page */
		if(document.getElementById('joinUsForm')){

			/* Form */
			box.ui('form').addPatterns({
				//birthdate: /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/,
				birthdate: /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/,
				zip: /^[0-9]{2,5}$/,
				tel: /^[0-9]{1,100}$/
			});

			box.ui('form').create({
				element: '#joinUsForm'
			}).addReplacement().mustValidate(function(form) {

				form.field('firstname').mustValidate(function(field) {
					if (field.isEmpty()) {
						return l10n.errors.required.EM_SW_04;
					}
				});

				form.field('lastname').mustValidate(function(field) {
					if (field.isEmpty()) {
						return l10n.errors.required.EM_SW_05;
					} else if(!field.isMatching('lastname')){
						unlockFields(form);
					}
				});

				form.field('zip').mustValidate(function(field) {
					if (field.isEmpty() || !field.isMatching('zip')) {
						return l10n.errors.required.EM_SW_12;
					} else {
						displayLocalizedConseilleres(field);
					}

				});

				form.field('city').mustValidate(function(field) {
					if (field.isEmpty()) {
						return l10n.errors.required.EM_SW_13;
					}
				});

				form.field('phone').mustValidate(function(field) {
					if (field.isEmpty() || !field.isMatching('tel')) {
						return l10n.errors.required.EM_SW_14;
					}
				});
							
				form.field('email').mustValidate(function(field) {
					if (field.isEmpty()) {
						return l10n.errors.required.EM_SW_06;
					} else if (!field.isMatching('email')) {
						return l10n.errors.required.EM_SW_06;
					} else {
						if(!stopSendID){
							$.getJSON('/handlers/insertRecruit.aspx?email=' + field.getValue() + '&id=' + $('#idUser').val() + '&sessionId=' + $('#sessionId').val(), function(data) {						
								if (data.error == "") {
									$('#idUser').val(data.id);
									/*form.eachField(function(field) {
										if (field.id != 'email') {
											if(field.name != 'country'){
												field.enable();
											}
											var clName = field.dom[0].className;
											if (clName.indexOf('disabled ') >= 0) {
												// TO DO
												// remplacer le 9 par la position de la chaine disabled dans le className car clName.lastIndexOf renvoie 0 au lieu de 9...
												field.dom[0].className = clName.substring(9, clName.length);
											}
										}
									});
									$('.fauxSelect:not(#joinUsFormcountryREP)').css('background-color', '#FFFFFF');*/
								} else {
									return l10n.errors.required.EM_SW_06;
								}						
							});
						}else{
							stopSendID = false;
						}
					}
				});

				form.field('birthdate').mustValidate(function(field) {
					if (!field.isEmpty() && !field.isMatching('birthdate')) {
						return l10n.errors.required.EM_SW_17;
					}
				});

				form.field('legales').mustValidate(function(field) {
					if (field.type == "checkbox" && !field.isChecked()) {
						return l10n.errors.required.EM_SW_111;
					}
				});

				return l10n.errors.form;
			});
		}
		
		var errorCls = 'error';

		var getErrorTarget = function(field) {
			if ('radio' != field.type) {
				return field.getLabel();
			} else {
				return field.getElements().parent().parent().prev();
			}
		};

		var addErrorIcon = function(field, target) {
			var id = field.name + 'Error';
			var img = box.dom('#' + id);
			if (img.length) {
				img.attr('alt', field.getError());
			} else {
				target.append('<span id="' + id + '">' + field.getError() + '</span>');
			}
		};

		var addFieldError = function(e) {
			getErrorTarget(e.source).addClass(errorCls);
			var sourceForm = $('#' + e.id).parents('form').attr('id');
			// addErrorIcon(e.source, $('#' + sourceForm + ' div.alert .content p'));
			addErrorIcon(e.source, getErrorTarget(e.source));
		};

		var removeFieldError = function(e) {
			getErrorTarget(e.source).removeClass(errorCls);
			box.dom('#' + e.source.name + 'Error').remove();
		};

		var addFormError = function(e) {
			var id = e.source.id + 'Error';
			var msg = e.source.msg;
			var error = box.dom('#' + id);
			if (error.length) {
				error.html(msg);
			} else {
				//$('#' + e.source.id + ' div.alert').show();
			}
		};

		var removeFormError = function(e) {
			box.dom('#' + e.source.id + 'Error').remove();
		};


		box.addClick({
			id: 'btSubmit',
			deepness: 3,
			test: function(e, element) {
				return (element.nodeName.toLowerCase() == 'span' && element.className.indexOf('btSubmit') > -1);
			},
			action: function(e, element) {
				$('#joinUsForm').submit();
			}
		});

		// binding des événements
		box.bind({
			'error.form': addFormError,
			'valid.form': removeFormError,
			'error.field.text': addFieldError,
			'error.field.select': addFieldError,
			'error.field.radio': addFieldError,
			'error.field.checkbox': addFieldError,
			'valid.field.text': removeFieldError,
			'valid.field.select': removeFieldError,
			'valid.field.radio': removeFieldError,
			'valid.field.checkbox': removeFieldError
		});
		
		box.dom('#submit').click(function() {
			stopSendID = true;
		});
		
		var joinUsForm = box.ui('form.joinUsForm');
		
		var emailField = joinUsForm.field('email');
		var zipField = joinUsForm.field('zip');
		
		// unlock fields if email field is alredy filled and valid
		if(!emailField.isEmpty() && emailField.isValid()) {
			unlockFields(joinUsForm);
		}
		
		// show localized conseilleres list if zip field is alredy filled and valid
		if(!zipField.isEmpty() && zipField.isValid()) {
			displayLocalizedConseilleres(zipField);
		}

	});
	
})(jQuery);
