$('document').ready(function(){

	/*** MOSTRA IL FORM **/	
	$("#button_accedi").live('click', function() {
		if ($("#sign_box").is(':visible')){
			$(this).attr('style','background-image:url("../images/button_attivo_barra_login.png")');
			$("#sign_box").hide();
		}
		else{
			$("#sign_box").show();
			$(this).attr('style','background-image:url("../images/button_disattivo_box.png")');
		}
	});
	
	/*** ASSOCIA IL CLICK DELL'INVIO AL CLICK SUL PULSANTE ENTRA **/
	$('#sign_box > input').keypress(function(event) {
		if(event.which == '13') {
			$("#button_entra").click();
		}
	});	  

	/*** FAI IL LOGIN **/	
	$("#button_entra").live('click', function() {
		var user = $("input[name='username']").attr('value');
		var pass = $("input[name='password']").attr('value');

		if(user != "" && pass != ""){
			$("#button_entra").replaceWith('<img id="img_ajax" src="../images/ajax-load.gif" />');
			
			$.ajax({
				type: "POST",
				url: '/index/login',
				data: {username: user, password: pass},
				success: function(html){
					if(html == -1){
						$("#img_ajax").replaceWith('<input id="button_entra" type="submit" value="Entra"/>');
						$("p[class='error']").html('Login errata');
					}
					else if(html == -2){
						$("#img_ajax").replaceWith('<input id="button_entra" type="submit" value="Entra"/>');
						$("p[class='error']").html('Errore. Riprovare');
					}
					else if(html == 1){window.open('/index/index','_self');}
				}
				,error:function(err){}
			});
		}
		else{
			$("p[class='error']").html('Compila entrambi i campi');
		}

	});
	
	/*** FAI IL LOGOUT **/	
	$("#button_esci").live('click', function() {
		window.open('/index/logout','_self');
	});
		
});
