var userName = '';

function OnLoad(user, password)
{
  if (user) {  // Login desde otra página
    var loginParams =  "sistemaid=" + gPrintmaxSistemaId + "&login=" + user + "&passwd=" + password;

    $('body').css('display', 'none');
    $.get(gPrintmaxComprobarLogin, loginParams, function(xml) {
      PeticionLoginCompletado(xml);
    });
  }
  else
    document.getElementById('printmax_username').focus();
}


function checkComprobarLogin(e)
{
	if (e.keyCode == 13)
		comprobarLogin(document.getElementById('printmax_username').value, document.getElementById('printmax_passwd').value);
}


function comprobarLogin(login,passwd)
{
	//var loginURL = "comprobarlogin.php";
	var loginURL = gPrintmaxComprobarLogin;
	var loginParams =  "sistemaid=" + gPrintmaxSistemaId + "&login=" + login + "&passwd=" + hex_md5(passwd);

	$("#notificacionError").html("");
	$("#notificacionEstado").html("(comprobando)");
  userName = login;

  $.get(loginURL, loginParams, PeticionLoginCompletado);
}

function PeticionLoginCompletado(respuestaXML)
{
	//Comprobamos si ha finalizado XmlHttpRequests
	$("#notificacionEstado").html('');
	var lId = 0;
	var lUser = "";
	var lSession = "";
	var lItem;

	lXml = $(respuestaXML.documentElement);

  if (lXml.find('status').text() == 'offline') {
    $("#notificacionError").html("Sitio no disponible en estos momentos, disculpe las molestias.");
  }
  else {
    lItem = lXml.find('userdata');
    lId   = lItem.find('userid').text();
    lUser = lItem.find('username').text();

    lSession = lItem.find("session").text();
    if (lId > 0)
    {
      $("#loginaceptado").html("Bienvenido " + lUser);
      setCookieLT("printmax_loginid", lId, gPrintmaxDuracionSesion*60);
      setCookieLT("printmax_loginuser", lUser, gPrintmaxDuracionSesion*60);
      setCookieLT("printmax_session", lSession, gPrintmaxDuracionSesion*60);
      setCookieLT("printmax_asist_id", lItem.find("assistantid").text(), gPrintmaxDuracionSesion*60);
      setCookieLT("printmax_asist_name", lItem.find("assistantfirstname").text(), gPrintmaxDuracionSesion*60);
      setCookieLT("printmax_asist_email", lItem.find("assistantemail").text(), gPrintmaxDuracionSesion*60);

      window.location = gPrintMaxStartPage;
    }
    else {
      delCookie("printmax_loginid");
      delCookie("printmax_loginuser");
      delCookie("printmax_session");
      $("#notificacionError").html("Usuario o contraseña erróneos");

      $('body').css('display', 'inherit');  // Por si llega de otra página
    }
  }
}
