// JavaScript Document
var login = {
	initialize: function(){
		this.menuItem = $('a_login'),
		this.slide = $('login');
	},
	
	apri: function(){
		if (!this.slide.visible()){
			this.slide.slideDown({ duration: 0.5, queue:'end' });
			this.menuItem.changeClassNames('yellow','white');
		}
		return this;
	},
	
	chiudi: function(){
		if (this.slide.visible()){
			this.slide.slideUp({ duration: 0.5, queue:'end' });
			this.menuItem.changeClassNames('white','yellow');
		}
		return this;
	},
	
	toggle: function(){
		registra.chiudi();
		passw.chiudi();
		
		this.apri().chiudi();
		return false;
	}
}

var passw = {
	initialize: function(){
		this.menuItem = $('a_passw'),
		this.slide = $('passw');
	},
	
	apri: function(){
		if (!this.slide.visible()){
			this.slide.slideDown({ duration: 0.5, queue:'end' });
			this.menuItem.changeClassNames ('yellow','white');
		}
		return this;
	},
	
	chiudi: function(){
		if (this.slide.visible()){
			this.slide.slideUp({ duration: 0.5, queue:'end' });
			this.menuItem.changeClassNames ('white','yellow');
		}
		return this;
	},
	
	toggle: function(){
		registra.chiudi();
		login.chiudi();
		
		this.apri().chiudi();
		return false;
	}
}

function logout(){
	var url = "/login/logout.php";
	//Effect.BlindUp('usermenu'); //il menu sparisce
	//Effect.BlindDown('usermenu', { queue: 'end' }); //il menu ricompare
	$('usermenu').innerHTML += '&nbsp;<span><img src="/Immagini/loadingroller.gif" alt="Logging out" border="0"></span>';
  new Ajax.Updater("usermenu", url, { 
																			method: 'get',
																			onComplete : function(){
	
						setTimeout("window.location.reload()",1000);
													
																			}
																			});
	$('loading').innerHTML = "";

}

	function startCallback(i) {
		// make something useful before submit (onStart)
		img = document.createElement("img");
			img.setAttribute("src","/Immagini/loadingroller.gif");
			img.setAttribute("alt","loading");
			img.setAttribute("title","Loading");
		document.getElementById("loading").innerHTML='';
		document.getElementById('loading').appendChild(img);

		//document.getElementById('loading').innerHTML = '<img src="/Immagini/loading.gif" alt="loading" title="Loading" />';
		return true;
	}
	function completeCallback(response, i) {
		// make something useful after (onComplete)
		//document.getElementById('nr').innerHTML = parseInt(document.getElementById('nr').innerHTML) + 1;
		Eimg = document.createElement("img");
		if(response == "error"){
			Eimg.setAttribute("src","/Immagini/error2.jpg");
			Eimg.setAttribute("alt","error!");
			Eimg.setAttribute("title","Error");
			Eimg.setAttribute("align","absbottom");
		//document.getElementById('loading').innerHTML = '<img src="/Immagini/error.jpg" alt="error!" title="Error" />';
		}else{
			Eimg.setAttribute("src","/Immagini/ok4.png");
			Eimg.setAttribute("alt","loaded");
			Eimg.setAttribute("title","Loaded");
			Eimg.setAttribute("align","absbottom");
			//document.getElementById('loading').innerHTML = '<img src="/Immagini/loaded.gif" alt="loaded" title="Loaded" />';
			//Effect.BlindUp('usermenu', { queue: 'end' }); //il menu sparisce
			document.getElementById('usermenu').innerHTML = '<span style="color:#FFCC00">Ciao <strong>'+response+'</strong>';
			//Effect.BlindDown('usermenu', { queue: 'end' }); //il menu ricompare
			setTimeout("Effect.SlideUp('login')",1000);
	
			setTimeout("window.location.reload()",1500);
	
		}
		document.getElementById("loading").innerHTML="";
		document.getElementById('loading').appendChild(Eimg);
	}
	function startCallback2(i) {
		// make something useful before submit (onStart)
		img = document.createElement("img");
			img.setAttribute("src","/Immagini/loadingroller.gif");
			img.setAttribute("alt","loading");
			img.setAttribute("title","Loading");
		document.getElementById("password").innerHTML='';
		document.getElementById('password').appendChild(img);

		//document.getElementById('loading').innerHTML = '<img src="/Immagini/loading.gif" alt="loading" title="Loading" />';
		return true;
	}
	function completeCallback2(response, i) {
		// make something useful after (onComplete)
		//document.getElementById('nr').innerHTML = parseInt(document.getElementById('nr').innerHTML) + 1;
		Eimg = document.createElement("img");
		if(response.indexOf('error') > -1){
			Eimg.setAttribute("src","/Immagini/error2.jpg");
			Eimg.setAttribute("alt","error!");
			Eimg.setAttribute("title","Error");
			Eimg.setAttribute("align","absbottom");
			document.getElementById('usermenu').innerHTML = '<span style="color:#008000">Non &egrave; stata trovata alcuna corrispondenza nel database</span>&nbsp;&nbsp;&nbsp;&nbsp;' + document.getElementById('usermenu').innerHTML;
		//document.getElementById('loading').innerHTML = '<img src="/Immagini/error.jpg" alt="error!" title="Error" />';
		}else{
			Eimg.setAttribute("src","/Immagini/ok4.png");
			Eimg.setAttribute("alt","loaded");
			Eimg.setAttribute("title","Loaded");
			Eimg.setAttribute("align","absbottom");
			//document.getElementById('loading').innerHTML = '<img src="/Immagini/loaded.gif" alt="loaded" title="Loaded" />';
			//Effect.BlindUp('usermenu', { queue: 'end' }); //il menu sparisce
			document.getElementById('usermenu').innerHTML = '<span style="color:#008000">La tua password &egrave; stata inviata nella tua mailbox</span>&nbsp;&nbsp;&nbsp;&nbsp;' + document.getElementById('usermenu').innerHTML;
			//Effect.BlindDown('usermenu', { queue: 'end' }); //il menu ricompare
			setTimeout("Effect.SlideUp('passw')",1000);

		}
		document.getElementById("password").innerHTML="";
		document.getElementById('password').appendChild(Eimg);
	}
	
	var node = function(){};
	
	function registrati() {
		registra.apri();
	}
 	var registra = { 
		initialize: function(){
			this.lastCall = {},
			this.lastValue = {},
			this.STARTCOUNT = 3,
								
			this.comands = {
				12:    'CAPS_LOCK',
				16:    'SHIFT',
				17:    'CTRL',
				18:    'ALT',
				20:    'MAIUSC',
				27:    'ESC',
				33:    'SCROLL_KEYS (PAGE UP)',
				34:    'SCROLL_KEYS (PAGE DOWN)',
				35:    'SCROLL_KEYS (PAGE END)',
				36:    'SCROLL_KEYS (PAGE HOME)',
				37:    'ARROW_KEYS (LEFT)',
				38:    'ARROW_KEYS (UP)',
				39:    'ARROW_KEYS (RIGHT)',
				40:    'ARROW_KEYS (DOWN)',
				91:		 'CMD LEFT (WINDOWS = ?)',
				93:    'CMD RIGHT (WINDOWS = ?)'
			},
						
			this.menuItem = $('a_registrati'), this.popup = $('registrati');
						
			this.form = $('registratiform');
			this.email = $(this.form['f_ind_e']), this.user = $(this.form['user']), this.password = $(this.form['password']), this.password2 = $(this.form['password2']),
				this.privacy = $(this.form['informativa_privacy']),
				this.emailExists = $(this.form['email_exists']), this.userExists = $(this.form['user_exists']);

			Builder.dump(node);
			this.caricamento = node['img'] ({
						src   : '/Immagini/loadingroller.gif',
						align : 'absbottom'
			});		
			
		},
		
		privacy: function(){
			var width = 800;
			var height = 600;
			var top = (screen.availHeight-height)/2;
			var left = (screen.availWidth-width)/2;
			window.open('/login/privacy.php','Privacy','width='+width+',height='+height+',top='+top+',left='+left+',resizable=0,location=0');
		},
	
		count: function (time, v) {
			if(time <= 0) {
				this.lastCall[v] = 0;
				return 0;
			}
			this.lastCall[v] = time;
			var timeout = "this.count(0,'"+v+"')";
			setTimeout(timeout,time*1000);
		},
		
		request: function(options){
			Object.complete(options || { }, {
					positiveResponse: '',
					negativeResponse: ''
			});
			var content = new Ajax.Request('/login/login.php',{
				registra: this,			
				
				onCreate: function() {
					Object.extend(this, this.registra);
					//emailAlert.update (this.caricamento);
					this.lastCall[options.v] = this.STARTCOUNT;
				},
									
				parameters: {
					'request': options.v,
					'text':    eval('$F(this.'+options.v+')')
				},
				
				onComplete: function(transport) {
					Object.extend(this, this.registra);
					if (parseInt(transport.responseText) == 0){
						alertMessage = node['span'] ({
							style: 'color:#66ff66'
						},options.positiveResponse);
						eval('this.'+options.v+'Exists.value = 0');
					//	this.count(this.STARTCOUNT,options.v);
					} else if (parseInt(transport.responseText) == 1){
						alertMessage = node['span'] ({
							style: 'color:#ff9966'
						}, options.negativeResponse);
						eval('this.'+options.v+'Exists.value = 1');
					//	this.lastCall[options.v] = 0;
					}	else {
						alertMessage = node['span'] ({
							style: 'color:#ffff66'
						}, transport.responseText);
						eval('this.'+options.v+'Exists.value = 0');
						this.lastCall[options.v] = 0;
					}
					
					options.alert.update(alertMessage);
					
					this.enable();
				}
			})
	},
		
		reset: function(options){
			//this.lastCall[options.v] = null;
			options.alert.cancel(true);
		},
		
		_email: function() {			
			var emailAlert = $('email_alert'), emailAlertMessage,
				email = $F(this.email);
						
			if (!this.email.present()){
				this.reset({
					v: 'email',
					alert: emailAlert
				})
				return;
			}
			
			if (!email.match(/^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\.[a-z]{2,3}$/)) {
				emailAlertMessage = node['span']({ style: 'color:#ffff66'}, 'L&rsquo;indirizzo e-mail inserito non &egrave; corretto');
				emailAlert.update(emailAlertMessage);
			} else 
				this.request({
					v: 'email',
					alert: emailAlert,
					positiveResponse: 'e-mail <strong>disponibile</strong>',
					negativeResponse: 'e-mail <strong>non disponibile</strong>'
				});
		},

		_user: function() {			
			var userAlert = $('user_alert'), userAlertMessage, 
				user = $F(this.user);
						
			if (!this.user.present()){
				this.reset({
					v: 'user',
					alert: userAlert
				})
				this.enable();
				return;
			}
			
			if (!user.match(/[\w*\s*-?!?]/) && user.match(/[^\d+]/)) {
				if(user.match(/[^\d+]/))
					userAlertMessage = node['span']({ style: 'color:#ffff66; font-size:12px'}, 'il <b>nick name</b> deve cominciare con una lettera');
				else 
					userAlertMessage = node['span']({ style: 'color:#ffff66; font-size:12px'}, 'il <b>nick name</b> pu&ograve; essere composto solo da <b>lettere e numeri</b>');
					
				userAlert.update(userAlertMessage);
			} else 
				this.request({
					v: 'user',
					alert: userAlert,
					positiveResponse: 'nick name <strong>disponibile</strong>',
					negativeResponse: 'nick name <strong>non disponibile</strong>'
				});
		},

		_password: function() {			
		//	alert('passwording');
			var passwordAlert = $('password_alert'), passwordAlertMessage,
				password = $F(this.password), passwordCheck = $F(this.password2);
						
			if (!this.password.present()) {
				this.reset({
					v: 'password',
					alert: passwordAlert
				});
				this.enable();
				return;
			}
		
			var security = password.security('string');
			passwordAlertMessage = node['span']('Sicurezza password: ',
				node['span']({
					style: 'color: ' + security['color'] + ''
				}, security['message'])										
			);
			passwordAlert.update(passwordAlertMessage);
			
			this._password2();
		},

		_password2: function(){
			var passwordAlert = $('password2_alert'), passwordAlertMessage,
			password = $F(this.password), passwordCheck = $F(this.password2);
						
			if (!this.password2.present() || password == passwordCheck) {
				this.reset({
					v: 'password2',
					alert: passwordAlert
				});
				this.enable();
				return;
			}
		
			if (password != passwordCheck) {
				var posDiffer = password.differ(passwordCheck);
				if (password.length >= passwordCheck.length) {
					if (posDiffer > passwordCheck.length)
						passwordAlertMessage = node['span']({ style: 'color:#ffff66'}, '&nbsp;');
					else if (posDiffer == passwordCheck.length && passwordCheck.length > 2) 
						passwordAlertMessage = node['span']({ style: 'color:#ffff66'}, 'La password non corrisponde dall&rsquo;<b>ultima</b> cifra');
					else if (posDiffer == passwordCheck.length - 1 && passwordCheck.length > 3)
						passwordAlertMessage = node['span']({ style: 'color:#ffff66'}, 'La password non corrisponde dalla <b>penultima</b> cifra');
					else if (posDiffer < 100)
						passwordAlertMessage = node['span']({ style: 'color:#ffff66'}, 'La password non corrisponde dalla <b>' + posDiffer.toCardinalString('f') + '</b> cifra');
					else
						passwordAlertMessage = node['span']({ style: 'color:#ffff66'}, 'La password non corrisponde dalla cifra <b>' + posDiffer + '</b>');
					passwordAlert.update(passwordAlertMessage);
				} else {
					if (posDiffer == passwordCheck.length && passwordCheck.length > 2) 
						passwordAlertMessage = node['span']({ style: 'color:#ffff66'}, 'La password non corrisponde dall&rsquo;<b>ultima</b> cifra');
					else if (posDiffer == passwordCheck.length - 1 && passwordCheck.length > 3)
						passwordAlertMessage = node['span']({ style: 'color:#ffff66'}, 'La password non corrisponde dalla <b>penultima</b> cifra');
					else if (posDiffer < 100)
						passwordAlertMessage = node['span']({ style: 'color:#ffff66'}, 'La password non corrisponde dalla <b>' + posDiffer.toCardinalString('f') + '</b> cifra');
					else
						passwordAlertMessage = node['span']({ style: 'color:#ffff66'}, 'La password non corrisponde dalla cifra <b>' + posDiffer + '</b>');
					passwordAlert.update(passwordAlertMessage);
				}
			}
			
			this.enable();
		},
		
		first: function (v, e){
			if (!Object.isNumber (this.lastCall[v])){
				this.lastCall[v] = 0;
				this.check(v, e, true);
			} else
				this.check(v, e);
		},
		
		check: function (v, e, force){
			
			var keycode = window.event ? window.event.keyCode : !e ? 0 : e.which ? e.which : e.charCode;
			if(this.comands[keycode]) return;
													
			if (!Object.isUndefined(v)) {	
				if(v.indexOf('password') > -1){
					this.lastCall[v] = 0;
				}
							
				if (Object.isNumber(this.lastCall[v])){
					if ($F(eval('this.' + v)) != this.lastValue[v] || force){
						eval('this._' + v + '()'); 																					//es: this._email();
						this.lastValue[v] = $F(eval('this.' + v));											
					}
				}
			} else {
				this.enable();
			}
		},
	
		apri: function (){
			login.chiudi();
			passw.chiudi();
			
			if (this.popup.visible()) return false;
			
			this.resize().appear();
			this.menuItem.changeClassNames ('yellow','white');
			return false;
		},
		
		enable: function(){
			var invia = $(this.form['invia']), 
				enable = true, b = {};

			b['email'] = this.email.present() && $F(this.email).match(/^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\.[a-z]{2,3}$/) && !parseInt(this.emailExists.value);
			b['user'] = this.user.present() && $F(this.user).match(/[\w*\s*-?!?]/) && $F(this.user).match(/[^\d+]/) && !parseInt(this.userExists.value);
			b['password'] = this.password.present() && ($F(this.password) == $F(this.password2));
			b['privacy'] = this.privacy.checked;
	
			$H(b).each(function (check) {
				enable = check.value ? enable : false;
			});
			if(enable){
				invia.disabled = false;
			}else{
				invia.disabled = true;
			}
		},
		
		resize: function (){
			var w = screen.availWidth  * 2/3,
					h = screen.availHeight * 2/3,
					l = (screen.availWidth  - w) / 2,
					t = (screen.availHeight - h) / 2;
					
			this.popup.style.width  = ( ( w / screen.availWidth ) * 100) + '%';
			this.popup.style.height = ( ( h / screen.availHeight) * 100) + '%';
			this.popup.style.left   = ( ( l / screen.availWidth ) * 100) + '%';
			this.popup.style.top    = ( ( t / screen.availHeight) * 100) + '%';
			return this.popup;
		},
		
		chiudi: function (){
			if(this.popup.visible()){
				this.popup.fade();
				this.menuItem.changeClassNames ('white','yellow');
			}
			return true;
		}
	};

	document.observe("dom:loaded", function() {
		registra.initialize();
		login.initialize();
		passw.initialize();
		
		setInterval(function(){
				var found = false, start = false;								 
				$A($$('div.switch')).each(function(element){		
						if ($(element).visible())	{							
							start = true;
							new Effect.SlideUp(element, { queue: 'front'})		
						} else if (!found && start) {
							new Effect.SlideDown(element, { queue: 'end'});		
							found = true;
						}
				});
				if (!found) {
					$A($$('div.switch')).each(function(element){		
						 if (!found && !$(element).visible()) {
								new Effect.SlideDown(element, { queue: 'end'});		
								found = true;
						 }
					});
				}
		}, 10000);	
	});