$(document).ready(function () {
	
	$('#registrationForm a.registra').click(function (e) {
		e.preventDefault();
		// caricamento ajax
		$.get("/acsitalia/s2magazine/moduli/LOGIN_V2/registrazione/data/index.jsp?idComponente="+document.getElementById('idComponente').value+"&id_pagina="+document.getElementById('id_pagina').value+"", function(data){
			// create a modal dialog with the data
			$(data).modal({
				close: false,
				position: ["15%",],
				overlayId: 'registration-overlay',
				containerId: 'registration-container',
				onOpen: registration.open,
				onShow: registration.show,
				onClose: registration.close
			});
		});
	});
	
	$('#registrationForm input.registra_esterni').click(function (e) {
		e.preventDefault();
		// caricamento ajax
		$.get("/acsitalia/s2magazine/moduli/LOGIN_V2/registrazione/data/index.jsp?idComponente="+document.getElementById('idComponente').value+"&id_pagina="+document.getElementById('id_pagina').value+"", function(data){
			// create a modal dialog with the data
			$(data).modal({
				close: false,
				position: ["0%",],
				overlayId: 'registration-overlay',
				containerId: 'registration-container',
				onOpen: registration.open,
				onShow: registration.show,
				onClose: registration.close
			});
		});
	});
	

	$('#registrationForm a.recupera').click(function (e) {
		e.preventDefault();
		// caricamento ajax
		$.get("/acsitalia/s2magazine/moduli/LOGIN_V2/registrazione/data/form_recupera_password.jsp", function(data){
			// create a modal dialog with the data
			$(data).modal({
				close: false,
				position: ["15%",],
				overlayId: 'recover-overlay',
				containerId: 'recover-container',
				onOpen: recover.open,
				onShow: recover.show,
				onClose: recover.close
			});
		});
	});

	// preload images
	var img = ['cancel.png', 'form_bottom.gif', 'form_top.gif', 'loading.gif', 'send.png'];
	$(img).each(function () {
		var i = new Image();
		i.src = '/acsitalia/s2magazine/moduli/LOGIN_V2/registrazione/img/registration/' + this;
	});
});

var registration = {
	message: null,
	open: function (dialog) {
		// add padding to the buttons in firefox/mozilla
		if ($.browser.mozilla) {
			$('#registration-container .registration-button').css({
				'padding-bottom': '2px'
			});
		}
		// input field font size
		if ($.browser.safari) {
			$('#registration-container .registration-input').css({
				'font-size': '.9em'
			});
		}

		// dynamically determine height
		var h = 280;
		if ($('#registration-organizzazione').length) {
			h += 26;
		}
		if ($('#registration-autorizzo').length) {
			h += 22;
		}

		var title = $('#registration-container .registration-title').html();
		$('#registration-container .registration-title').html('Caricamento in corso...');
		dialog.overlay.fadeIn(200, function () {
			dialog.container.fadeIn(200, function () {
				dialog.data.fadeIn(200, function () {
					$('#registration-container .registration-content').animate({
						height: h
					}, function () {
						$('#registration-container .registration-title').html(title);
						$('#registration-container form').fadeIn(200, function () {
							$('#registration-container #registration-nome').focus();
							$('#registration-container #registration-cognome').focus();

							$('#registration-container .registration-autorizzo').click(function () {
								var autorizzo = $('#registration-container #registration-autorizzo');
								autorizzo.is(':checked') ? autorizzo.attr('checked', '') : autorizzo.attr('checked', 'checked');
							});
							$('#registration-container .registration-newsletter').click(function () {
								var newsletter = $('#registration-container #registration-newsletter');
								newsletter.is(':checked') ? newsletter.attr('checked', '0') : newsletter.attr('checked', 'checked');
							});
							$('#registration-container .registration-extranet').click(function () {
								var extranet = $('#registration-container #extranet');
								extranet.is(':checked') ? extranet.attr('checked', '0') : extranet.attr('checked', 'checked');
							});

							// fix png's for IE 6
							if ($.browser.msie && $.browser.version < 7) {
								$('#registration-container .registration-button').each(function () {
									if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
										var src = RegExp.$1;
										$(this).css({
											backgroundImage: 'none',
											filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
										});
									}
								});
							}
						});
					});
				});
			});
		});
	},
	show: function (dialog) {
		$('#registration-container .registration-send').click(function (e) {
			e.preventDefault();
			// validate form
			if (registration.validate()) {
				$('#registration-container .registration-message').fadeOut(function () {
					$('#registration-container .registration-message').removeClass('registration-error').empty();
				});
				$('#registration-container .registration-title').html('Registrazione in corso...');
				$('#registration-container form').fadeOut(200);
				$('#registration-container .registration-content').animate({
					height: '80px'
				}, function () {
					$('#registration-container .registration-loading').fadeIn(200, function () {
						$.ajax({
							url: '/acsitalia/s2magazine/moduli/LOGIN_V2/registrazione/data/index.jsp',
							data: $('#registration-container form').serialize() + '&action=send',
							type: 'post',
							cache: false,
							dataType: 'html',
							complete: function (xhr) {
								$('#registration-container .registration-loading').fadeOut(200, function () {
									$('#registration-container .registration-title').html('Operazione completata...');
									$('#registration-container .registration-message').html(xhr.responseText).fadeIn(200);
								});
							},
							error: registration.error
						});
					});
				});
			}
			else {
				if ($('#registration-container .registration-message:visible').length > 0) {
					var msg = $('#registration-container .registration-message div');
					msg.fadeOut(200, function () {
						msg.empty();
						registration.showError();
						msg.fadeIn(200);
					});
				}
				else {
					$('#registration-container .registration-message').animate({
						height: '80px'
					}, registration.showError);
				}
				
			}
		});
	},
	close: function (dialog) {
		$('#registration-container .registration-message').fadeOut();
		$('#registration-container .registration-title').html('Chiusura in corso...');
		$('#registration-container form').fadeOut(200);
		$('#registration-container .registration-content').animate({
			height: 40
		}, function () {
			dialog.data.fadeOut(200, function () {
				dialog.container.fadeOut(200, function () {
					dialog.overlay.fadeOut(200, function () {
						$.modal.close();
					});
				});
			});
		});
	},
	error: function (xhr) {
		alert(xhr.statusText);
	},
	validate: function () {
		registration.message = '';
		if (!$('#registration-container #registration-nome').val()) {
			registration.message += 'Il campo nome è obbligatorio. ';
		}
		if (!$('#registration-container #registration-cognome').val()) {
			registration.message += 'Il campo cognome è obbligatorio. ';
		}
		if (!$('#registration-container #registration-username').val()) {
			registration.message += 'Il campo username è obbligatorio. ';
		}
		if (!$('#registration-container #registration-password').val()) {
			registration.message += 'Il campo password è obbligatorio. ';
		}
		if (!$('#registration-container #registration-conferma-pwd').val()) {
			registration.message += 'Il campo conferma password è obbligatorio. ';
		}
		if (($('#registration-container #registration-password').val())!=(($('#registration-container #registration-conferma-pwd').val()))) {
			registration.message += 'Le password non coincidono. ';
		}
		var autorizzo = $('#registration-container #registration-autorizzo');
		if (!autorizzo.is(':checked')) {
			registration.message += 'Il campo autorizzo è obbligatorio. ';
		}

		var email = $('#registration-container #registration-email').val();
		if (!email) {
			registration.message += 'Il campo email è obbligatorio. ';
		}
		else {
			if (!registration.validateEmail(email)) {
				registration.message += 'Email invalida. ';
			}
		}		

		if (registration.message.length > 0) {
			return false;
		}
		else {
			return true;
		}
	},
	validateEmail: function (email) {
		var at = email.lastIndexOf("@");

		// Make sure the at (@) symbol exists and  
		// it is not the first or last character
		if (at < 1 || (at + 1) === email.length)
			return false;

		// Make sure there aren't multiple periods together
		if (/(\.{2,})/.test(email))
			return false;

		// Break up the local and domain portions
		var local = email.substring(0, at);
		var domain = email.substring(at + 1);

		// Check lengths
		if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
			return false;

		// Make sure local and domain don't start with or end with a period
		if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
			return false;

		// Check for quoted-string addresses
		// Since almost anything is allowed in a quoted-string address,
		// we're just going to let them go through
		if (!/^"(.+)"$/.test(local)) {
			// It's a dot-string address...check for valid characters
			if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
				return false;
		}

		// Make sure domain contains only valid characters and at least one period
		if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
			return false;	

		return true;
	},
	showError: function () {
		$('#registration-container .registration-message')
			.html($('<div class="registration-error">').append(registration.message))
			.fadeIn(200);
	}
};

var recover = {
		message: null,
		open: function (dialog) {
			// add padding to the buttons in firefox/mozilla
			if ($.browser.mozilla) {
				$('#recover-container .recover-button').css({
					'padding-bottom': '2px'
				});
			}
			// input field font size
			if ($.browser.safari) {
				$('#recover-container .recover-input').css({
					'font-size': '.9em'
				});
			}

			// dynamically determine height
			var h = 280;
			if ($('#recover-organizzazione').length) {
				h += 26;
			}
			if ($('#recover-autorizzo').length) {
				h += 22;
			}

			var title = $('#recover-container .recover-title').html();
			$('#recover-container .recover-title').html('Caricamento in corso...');
			dialog.overlay.fadeIn(200, function () {
				dialog.container.fadeIn(200, function () {
					dialog.data.fadeIn(200, function () {
						$('#recover-container .recover-content').animate({
							height: h
						}, function () {
							$('#recover-container .recover-title').html(title);
							$('#recover-container form').fadeIn(200, function () {
								$('#recover-container #recover-nome').focus();
								$('#recover-container #recover-cognome').focus();

								$('#recover-container .recover-autorizzo').click(function () {
									var autorizzo = $('#recover-container #recover-autorizzo');
									autorizzo.is(':checked') ? autorizzo.attr('checked', '') : autorizzo.attr('checked', 'checked');
								});
								$('#recover-container .recover-newsletter').click(function () {
									var newsletter = $('#recover-container #recover-newsletter');
									newsletter.is(':checked') ? newsletter.attr('checked', '') : newsletter.attr('checked', 'checked');
								});

								// fix png's for IE 6
								if ($.browser.msie && $.browser.version < 7) {
									$('#recover-container .recover-button').each(function () {
										if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
											var src = RegExp.$1;
											$(this).css({
												backgroundImage: 'none',
												filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
											});
										}
									});
								}
							});
						});
					});
				});
			});
		},
		show: function (dialog) {
			$('#recover-container .recover-send').click(function (e) {
				e.preventDefault();
				// validate form
				if (recover.validate()) {
					$('#recover-container .recover-message').fadeOut(function () {
						$('#recover-container .recover-message').removeClass('recover-error').empty();
					});
					$('#recover-container .recover-title').html('Recupero in corso...');
					$('#recover-container form').fadeOut(200);
					$('#recover-container .recover-content').animate({
						height: '80px'
					}, function () {
						$('#recover-container .recover-loading').fadeIn(200, function () {
							$.ajax({
								url: '/acsitalia/s2magazine/moduli/LOGIN_V2/registrazione/data/form_recupera_password.jsp',
								data: $('#recover-container form').serialize() + '&action=send',
								type: 'post',
								cache: false,
								dataType: 'html',
								complete: function (xhr) {
									$('#recover-container .recover-loading').fadeOut(200, function () {
										$('#recover-container .recover-title').html('Operazione completata...');
										$('#recover-container .recover-message').html(xhr.responseText).fadeIn(200);
									});
								},
								error: recover.error
							});
						});
					});
				}
				else {
					if ($('#recover-container .recover-message:visible').length > 0) {
						var msg = $('#recover-container .recover-message div');
						msg.fadeOut(200, function () {
							msg.empty();
							recover.showError();
							msg.fadeIn(200);
						});
					}
					else {
						$('#recover-container .recover-message').animate({
							height: '80px'
						}, recover.showError);
					}
					
				}
			});
		},
		close: function (dialog) {
			$('#recover-container .recover-message').fadeOut();
			$('#recover-container .recover-title').html('Chiusura in corso...');
			$('#recover-container form').fadeOut(200);
			$('#recover-container .recover-content').animate({
				height: 40
			}, function () {
				dialog.data.fadeOut(200, function () {
					dialog.container.fadeOut(200, function () {
						dialog.overlay.fadeOut(200, function () {
							$.modal.close();
						});
					});
				});
			});
		},
		error: function (xhr) {
			alert(xhr.statusText);
		},
		validate: function () {
			recover.message = '';
			
			if (!$('#recover-container #recover-username').val()) {
				recover.message += 'Il campo username è obbligatorio. ';
			}
			

			var email = $('#recover-container #recover-email').val();
			if (!email) {
				recover.message += 'Il campo email è obbligatorio. ';
			}
			else {
				if (!recover.validateEmail(email)) {
					recover.message += 'Email invalida. ';
				}
			}		

			if (recover.message.length > 0) {
				return false;
			}
			else {
				return true;
			}
		},
		validateEmail: function (email) {
			var at = email.lastIndexOf("@");

			// Make sure the at (@) symbol exists and  
			// it is not the first or last character
			if (at < 1 || (at + 1) === email.length)
				return false;

			// Make sure there aren't multiple periods together
			if (/(\.{2,})/.test(email))
				return false;

			// Break up the local and domain portions
			var local = email.substring(0, at);
			var domain = email.substring(at + 1);

			// Check lengths
			if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
				return false;

			// Make sure local and domain don't start with or end with a period
			if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
				return false;

			// Check for quoted-string addresses
			// Since almost anything is allowed in a quoted-string address,
			// we're just going to let them go through
			if (!/^"(.+)"$/.test(local)) {
				// It's a dot-string address...check for valid characters
				if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
					return false;
			}

			// Make sure domain contains only valid characters and at least one period
			if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
				return false;	

			return true;
		},
		showError: function () {
			$('#recover-container .recover-message')
				.html($('<div class="recover-error">').append(recover.message))
				.fadeIn(200);
		}
	};
 