/* Copyright(C) 2005 Salvatore Sanfilippo <antirez@gmail.com>
 * All Rights Reserved. */

var req = null;

function tryLogin() {
    clearFields(new Array("username","pass"),new Array("badlogin"));
    if (!validate(document.f.username.value, "^[A-z0-9]+$", "La username non puo' essere vuota e non puo' contenere caratteri speciali","username")) return false;
    if (!validate(document.f.pass.value, "^.{5,}$", "La password non puo' essere vuota o piu' corta di 5 caratteri","pass")) return false;

    // Use AJAX to check if the user/password are valid.
    req = CreateXmlHttpReq(loginHandler);
    req.open("GET", "/ajax/login.php?username="+merziaEscape(document.f.username.value)+"&pass="+merziaEscape(document.f.pass.value)+"&rand="+merziaEscape(Math.random()));
    req.send(null);
}

function loginHandler() {
    if (req.readyState == 4 && req.status == 200) {
        var res = req.responseText;
        if (res.indexOf("OK:") != -1) {
            // Login success. Get the cookie from the HTTP reply and set it.
            secret = res.substring(3, res.length+1);
            if (document.f.rememberme.checked == false) {
                // Just for this session.
                setCookie("secret",secret);
            } else {
                // Set a cookie valid for the next 60 days.
                var now = new Date;
                t = now.getTime();
                now.setTime(t+(3600*24*1000*60));
                setCookie("secret",secret,now);
                //alert(a.toGMTString());
            }
	    var l = window.location.toString();
            var i = l.indexOf("?uri=");
            if (i == -1) {
                window.location = ''+document.f.username.value+'/';
            } else {
                i+=5;
		//alert(unescape(l.substring(i,l.length+1)));
                l = unescape(l.substring(i,l.length+1));
		window.location = l;
            }
        } else {
            // Login failed. Show an error.
            warnField("username");
            warnField("pass");
            showElementById("badlogin");
        }
    }
}

