if (!NovartisVaccines) {
	var NovartisVaccines = {};
}

NovartisVaccines.RegistrationForm = Class.create({
	injectMandatoryMarkers: function () {
		var template = $('um-reg-form-mandatory').cloneNode(true);
		template.removeAttribute('id');
		
		this.mandatoryFields.each(function (n) {
			n.appendChild(template.cloneNode(true));
		});
	},

	extendClickToLabel: function () {
		$$('form.um-reg-form label > input[type="checkbox"]', 'form.um-reg-form label > input[type="radio"]').each(function (input) {
			this.applyFormBlocksConditionalFiltering(input);
			
			Event.observe(input.up('label'), 'click', function (ev) {
				if (Event.element(ev).nodeName === 'LABEL') {
					Event.stop(ev);
					input.checked = input.type === 'radio' ? true : !input.checked;
				}
				
				this.applyFormBlocksConditionalFiltering(input);
			}.bind(this));
		}.bind(this));
	},
	
	applyFormBlocksConditionalFiltering: function (input) {
		var conditionalPart = {
			'true': 	$(input.name + '-checked'),
			'false':	$(input.name + '-not-checked')
		};

		var cont = conditionalPart[input.checked];		
		if (cont) {
			cont.show();
			cont
				.select('td.um-reg-form-mandatory + td > input')
				.findAll(function (n) {
					return n.value == 'N/A';
				})
				.each(function (n) {
					n.value = '';
				});
		}
		
		cont = conditionalPart[!input.checked];
		if (cont) {
			cont.hide();
			cont
				.select('td.um-reg-form-mandatory + td > input')
				.findAll(function (n) {
					return !n.value;
				})
				.each(function (n) {
					n.value = 'N/A';
				});
		}
	},
	
	injectLoginValidator: function () {
		$$('form.um-reg-form input[name="login"]').each(function (field) {
			Event.observe(field, 'blur', function (ev) {
				field.value = field.value.strip();
				if (field.value.length > 0 && field.value !== field._checkedValue) {
					field.disable();
					field._checkedValue = field.value;
					
					new Ajax.Request('/um/' + NovartisVaccines.context + '/check-login', {
						parameters: {
							login: field.value
						},
						onComplete: function (tr) {
							field.enable();
							console.debug('done');
						},
						onSuccess: function (tr) {
							var res = tr.responseText.evalJSON();
							console.debug(res);
							this.displayUsedLogin(field, !!res.exists);
						}.bind(this),
						onFailure: function (tr) {
							console.debug('failure');
						},
						onException: function (tr, e) {
							console.debug('exception');
							console.log(e);
						}
					});
				}
			}.bind(this));
		}.bind(this));
	},
	
	displayUsedLogin: function (field, exists) {
		var n		= field.up('td').previous('td');
		var msg	= n.down('p');
		if (!exists) {
			if (msg) {
				msg.parentNode.removeChild(msg);
			}
			field._invalid = false;
		} else {
			if (!msg) {
				msg = $(Builder.node('p', { className: 'um-reg-form-missing' }));
				n.appendChild(msg);
			}
			msg.update("La login scelta non e` disponibile");
			field._invalid = true;
			field.enable();
			field.focus();
		}
	},
	
	injectValidators: function () {
		$$('form.um-reg-form').each(function (form) {
			Event.observe(form, 'submit', function (ev) {
				var doSubmit = true;
				
				Event.stop(ev);
				
				this.mandatoryFields.each(function (n) {
					if (n.nodeName === 'TD') {
						var field = null;
						if (n.next('td').down('input') && !n.next('td').down('input').disabled) {
							field = n.next('td').down('input');
						}
						if (n.next('td').down('select') && !n.next('td').down('select').disabled) {
							field = n.next('td').down('select');
						}
						
						field.value	= field.value.strip();
						if (field.value.length == 0 || field._invalid) {
							// missing
							n.addClassName('um-reg-form-missing');
							doSubmit = false;
						} else {
							n.removeClassName('um-reg-form-missing');
						}
					}
				}.bind(this));
				
				['password', 'email'].each(function (type) {
					var f1 = 'um-reg-form-' + type;
					var f2 = 'um-reg-form-confirm-' + type;
					
					if ($F(f1).length > 0) {
						var pass = true;
						if ($F(f1) !== $F(f2)) {
							// different
							pass			= false;
							doSubmit	= false;
						}
				
						if (type === 'email' && pass && !$F(f1).match(/^.+@.+\..+$/)) {
							pass			= false;
							doSubmit	= false;
						}
						
						[$(f1), $(f2)].each(function (n) {
							n = n.up('td').previous('td');
							if (pass) {
								n.removeClassName('um-reg-form-missing');
							} else {
								n.addClassName('um-reg-form-missing');
							}
						}.bind(this));
					}
				}.bind(this));

				var agree = form.select('td.um-reg-terms-agreement input').first();
				if (agree) {
					if (agree.checked) {
						agree.up('td').removeClassName('um-reg-form-missing');
					} else {
						doSubmit = false;
						agree.up('td').addClassName('um-reg-form-missing');
					}
				}
				
				$$('form.um-reg-form td.um-reg-form-console')[0].update(
					doSubmit ? '' : 'Mancano alcuni campi obbligatori o i valori inseriti non sono validi.');
					
				if (doSubmit) {
					form.submit();
				}
			}.bind(this));
		}.bind(this));
	},
	
	setupServerSentErrors: function () {
		try {
			var f = NovartisVaccines.registrationFields;
			NovartisVaccines.registrationFields = f.length == 0 || f === '(none)' ?
				null : f.unescapeHTML().evalJSON();
		} catch (e) {
			console.error(e);
		}
	
		if (NovartisVaccines.registrationFields) {
			var o = NovartisVaccines.registrationFields;
			
			if (o.errors) {
				var fields	= $$('form.um-reg-form')[0].getElements();
				o.fields		= $H(o.fields);
				
				fields.each(function (f) {
					if (f.type === 'text' || f.type === 'password' || f.nodeName === 'SELECT') {
						f.value = o.fields.get(f.name);
					} else if (f.type === 'checkbox') {
						f.checked = !!o.fields.get(f.name);
					} else if (f.type === 'radio') {
						f.checked = o.fields.get(f.name) == f.value;					
					}
					
					if (o.errors.indexOf(f.name) != -1) {						
						if (f.name === 'login') {
							this.displayUsedLogin(f, true);
						} else {
							f.up('td').previous('td').addClassName('um-reg-form-missing');
						}
					} 
				}.bind(this));
				
				$$('form.um-reg-form td.um-reg-form-console')[0].update('Mancano alcuni campi obbligatori o i valori inseriti non sono validi.');
			}
		}
	},
	
	_addSelectOption : function (
									el,
									optionVal,
									optionDescr
			) {
		var optNew = document.createElement('option');
		optNew.text = optionDescr;
		optNew.value = optionVal;
		try {
			el.add(optNew, null); // standards compliant; doesn't work in IE
		}
		catch(ex) {
			el.add(optNew); // IE only
		}
	},
	
	_emptySelect: function (el) {
		while (el.length > 0) {
			el.remove(0);
		}
	},
	
	_autoLoadCombo : function (
								baseValues,
								defaultIndexValue,
								el,
								elControllers
			) {
		
		var loadElements = function () {
			//empty
			this._emptySelect(el);
			
			//defaultValues
			baseValues.each(function (val) {
				this._addSelectOption(el,val.value,val.descr);
			}.bind(this));
			el.selectedIndex=defaultIndexValue;
			
			var parametersObj = {
					select: el.name
			};
			if (elControllers) {
				elControllers.each(function (controller) {
					parametersObj[controller.name] = controller.value;
				});
			}
			
			el.hide();
			el.next('div.selectLoading').show();
			
			new Ajax.Request('/um/' + NovartisVaccines.context + '/loadSelect', {
				parameters: parametersObj,
				onSuccess: function (tr) {
					var res = tr.responseText.evalJSON();
					//console.debug(res);
					if (res.opts) {
						res.opts.each(function (option) {
							this._addSelectOption(el,option.val,option.descr);
						}.bind(this));
					}
					el.fire("registration:reloaded");
				}.bind(this),
				onComplete: function () {
					if (!el.disabled) {
						el.show();
					}
					el.next('div.selectLoading').hide();
				},
				onFailure: function (tr) {
					console.debug('failure');
				},
				onException: function (tr, e) {
					console.debug('exception');
					console.log(e);
				}
			});
		}.bind(this);
		
		//loading
		if (elControllers) {
			if (elControllers[0]) {
				elControllers[0].observe('change', function () {
					loadElements();
				});
				
				elControllers[0].observe('registration:reloaded', function () {
					loadElements();
				}.bind(this));
			}
		} else {
			loadElements();
		}

		
	},
	
	_statoEsteroVsItalian : function (	el,
										valueChoice,
										differentEls,
										equalEls) {
		
		var f = function () {
			var v_equalEls = differentEls;
			var v_differentEls = equalEls;
			if (el.value === valueChoice) {
				v_equalEls = equalEls;
				v_differentEls = differentEls;
			}
			v_equalEls.each(function (e) {
				e.enable();
				e.show();
			});
			v_differentEls.each(function (e) {
				e.disable();
				e.hide();
			});
		};
		
		el.observe('change', f);
		f();
	},
	
	initialize: function () {
		if ($$('select[name=zip]').size() > 0) {
		this._autoLoadCombo([
		                     	{	value : '',
		                     		descr : '--'}
		                     ],
		                     0,
		                     $$('select[name=zip]').first(),
		                     [	
		                      	$$('select[name=city]').first(),
		                      	$$('select[name=state]').first()
		                     ]);
		}
		if ($$('select[name=city]').size() > 0) {
		this._autoLoadCombo([
		                     	{	value : '',
		                     		descr : '--'}
		                     ],
		                     0,
		                     $$('select[name=city]').first(),
		                     [$$('select[name=state]').first()]);
		}
		if ($$('select[name=state]').size() > 0) {
		this._autoLoadCombo([
		                     	{	value : '',
		                     		descr : '--'},
		                     	{	value : 'Stato estero',
			                     	descr : 'Stato estero'},
			                    {	value : '',
			                     	descr : '--'}
		                     ],
		                     0,
		                     $$('select[name=state]').first());
		}
		if ($$('select[name=state]').size() > 0) {
		this._statoEsteroVsItalian(	$$('select[name=state]').first(), 
									"Stato estero",
									[$$('select[name=city]').first(),
									 $$('select[name=zip]').first()],
									[$$('input[name=city]').first(),
									 $$('input[name=zip]').first()]);
		}
		
		this.mandatoryFields = $$('form.um-reg-form .um-reg-form-mandatory');
		
		this.injectMandatoryMarkers();
		this.extendClickToLabel();
		this.injectLoginValidator();
		this.injectValidators();
		
		this.setupServerSentErrors();
	}
});

Event.observe(window, 'load', function () {
	window.regForm = new NovartisVaccines.RegistrationForm();
});
