// JavaScript Document
// crea l'oggetto per la comunicazione AJAX con il server
// compatibile con tutti i browser che supportano AJAX
function crea_http_req() {
	var req = false;
	if (typeof XMLHttpRequest != "undefined")
		req = new XMLHttpRequest();
	if (!req && typeof ActiveXObject != "undefined") {
		try {
			req=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				req=new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				try {
					req=new ActiveXObject("Msxml2.XMLHTTP.4.0");
				} catch (e3) {
					req=null;
				}
			}
		}
	}

	if(!req && window.createRequest)
		req = window.createRequest();

	if (!req) alert("Il browser non supporta AJAX");

	return req;
}

// l'oggetto per comunicare con il server
var http_req = crea_http_req();

// invia i dati del form al server
function login(error) {
	var username = document.getElementById("username").value;
	var password = document.getElementById("password").value;
	var percorso = document.getElementById("percorso_login").value;
	
	var passed = validatePassword(password, {
		length:   [4, Infinity],
		badWords: ["password", "prova", "test"],
		badSequenceLength: 4
	});
	
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;	// check email
	
	var errorMsg = '';
	var error_css = "compile_error";
	
	if(!validateEmail(username)){
		errorMsg += '- e-mail\n';
		addClass(document.getElementById("username"), error_css);
		document.getElementById("username").style.color="#FFF";
	}
	
	if(!passed){
		errorMsg += '- password\n';
		addClass(document.getElementById("password"), error_css);
		document.getElementById("password").style.color="#FFF";
	}
	
	if(errorMsg != ''){
		errorMsg = error + ':\n\n' + errorMsg;
		//alert(errorMsg);
		var login_resp = document.getElementById("login_resp");
		login_resp.style.display = "block";
		return false;
	}
	
	var dati_post = "username=" + username + "&password=" + password;
	http_req.onreadystatechange = gestisci_risposta;
	http_req.open('POST', percorso + 'login.php', true);
	http_req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	http_req.setRequestHeader("Content-length", dati_post.length);
	http_req.setRequestHeader("Connection", "close");
	http_req.send(dati_post);
}

// recupero e gestisco la risposta inviata dal server
function gestisci_risposta() {
	if(http_req.readyState == 4) {
		var esito = http_req.responseText;
		var login_resp = document.getElementById("login_resp");
		switch (esito) {
		  case '1': // username non presente nel sistema
			login_resp.style.display = "block";
			//alert('username non presente nel sistema');
		  break;

		  case '2': // password errata
			login_resp.style.display = "block";
			//alert('password errata');
		  break;

		  case '3':  // username o password non inserite
			login_resp.style.display = "block";
			//alert('username o password non inserite');
		  break;

		  case '4':  // login effettuato correttamente
			window.location.reload();
			//alert('login effettuato correttamente');
		  break;

		  default: // Risposta del server non riconosciuta
			login_resp.style.display = "block";
			//alert('Risposta del server non riconosciuta: ' + esito);
		}
	}
}


function hasClass(target, theClass){
	var pattern = new RegExp("(^| )" + theClass + "( |$)");
	if(pattern.test(target.className)){
		return true;
	}
	return false;
}

function addClass(target, theClass){
	if (!hasClass(target, theClass)){
		if (target.className == ""){
			target.className = theClass;
		} else {
			target.className += " " + theClass;
		}
	}
}


/// funzione per validazione password

function validatePassword (pw, options) {
	// default options (allows any password)
	var o = {
		lower:    0,
		upper:    0,
		alpha:    0, /* lower + upper */
		numeric:  0,
		special:  0,
		length:   [0, Infinity],
		custom:   [ /* regexes and/or functions */ ],
		badWords: [],
		badSequenceLength: 0,
		noQwertySequences: false,
		noSequential:      false
	};

	for (var property in options)
		o[property] = options[property];

	var	re = {
			lower:   /[a-z]/g,
			upper:   /[A-Z]/g,
			alpha:   /[A-Z]/gi,
			numeric: /[0-9]/g,
			special: /[\W_]/g
		},
		rule, i;

	// enforce min/max length
	if (pw.length < o.length[0] || pw.length > o.length[1])
		return false;

	// enforce lower/upper/alpha/numeric/special rules
	for (rule in re) {
		if ((pw.match(re[rule]) || []).length < o[rule])
			return false;
	}

	// enforce word ban (case insensitive)
	for (i = 0; i < o.badWords.length; i++) {
		if (pw.toLowerCase().indexOf(o.badWords[i].toLowerCase()) > -1)
			return false;
	}

	// enforce the no sequential, identical characters rule
	if (o.noSequential && /([\S\s])\1/.test(pw))
		return false;

	// enforce alphanumeric/qwerty sequence ban rules
	if (o.badSequenceLength) {
		var	lower   = "abcdefghijklmnopqrstuvwxyz",
			upper   = lower.toUpperCase(),
			numbers = "0123456789",
			qwerty  = "qwertyuiopasdfghjklzxcvbnm",
			start   = o.badSequenceLength - 1,
			seq     = "_" + pw.slice(0, start);
		for (i = start; i < pw.length; i++) {
			seq = seq.slice(1) + pw.charAt(i);
			if (
				lower.indexOf(seq)   > -1 ||
				upper.indexOf(seq)   > -1 ||
				numbers.indexOf(seq) > -1 ||
				(o.noQwertySequences && qwerty.indexOf(seq) > -1)
			) {
				return false;
			}
		}
	}

	// enforce custom regex/function rules
	for (i = 0; i < o.custom.length; i++) {
		rule = o.custom[i];
		if (rule instanceof RegExp) {
			if (!rule.test(pw))
				return false;
		} else if (rule instanceof Function) {
			if (!rule(pw))
				return false;
		}
	}

	// great success!
	return true;
}


function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}

function validateEmail(email) {
	var email = trim(email);                        // value of field with whitespace trimmed off
	var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
	var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
	var errore_mail = 0;
	
	if (email == "") {
		errore_mail = 1;//alert("vuoto");
    } else if (!emailFilter.test(email)) {              //test email for illegal characters
		errore_mail = 1;//alert(email);
    } else if (email.match(illegalChars)) {
		errore_mail = 1;//alert("match");
    }
	
	if(errore_mail == 0){
		return true;
	} else {
		return false;
	}
	
}