// PRODUCCION
var url = '..';
var urlLogin = 'https://web.sedeb2b.com';
var proyecto = 'Businessmail';
// TEST
//var url = '../..';
//var urlLogin = '../..';
//var proyecto = 'EdiwinViewerV3';

var urlFaqs = 'http://web.sedeb2b.com/ayuda';
var sedeb2b = 'Sedeb2b';
var primera = true;
var idioma = '';

var _OP_OBTENER_SERVIDORES = 1;

var _OP_LISTADO_PUBLICADORESBM = 1;

var _OP_OLVIDO_PASSWORD = 3;
var _OP_MOSTRAR_OLVIDO_PASSWORD = 4;
var _OP_OLVIDO_USUARIO = 5;


function cargaDatosLogin(){
  var urlOrigen = window.location.href;
  var index = urlOrigen.indexOf('?');
  if (index != -1 ){
    var parametros = urlOrigen.substring(index + 1,urlOrigen.length)
    parametros = parametros.split('&');
    for (var i=0; i<parametros.length; i++){
      var param = parametros[i].split('=');
      var nombreParam = param[0];
      if (nombreParam == 'usuario'){
        if (document.getElementById('usuario')){
          document.getElementById('usuario').value = param[1];
        }
      } else if (nombreParam == 'password'){
        if (document.getElementById('password')){
          document.getElementById('password').value = param[1];
        }
      }
    }
  }
}

function faqs(idioma){
  var urlFaqs_ = urlFaqs + '/' + idioma + '/faqs/index.htm';
  openwindow(urlFaqs_, 'ventana');
}


function ValidateRespuesta(){
  var respuesta = document.getElementById("respuesta").value;
  if(respuesta == ''){
    alert(Text7);
    return false;
  }
  var file = url + '/' + proyecto + '/password.Ejecutar?op='+_OP_OLVIDO_PASSWORD+'&web=1&dominio=businessmail&tipocliente=businessmail&idioma=' + idioma + '&respuesta=' + respuesta;
  xmlReq = getXMLGET(file, self.responseHandlerCuerpo);
}



function Cancelar(){
  cargaTexto('home');
}

function redireccion(lang){
  if (lang=='es') window.location.href = "../ES/index.htm";
  else if (lang=='en') window.location.href = "../EN/index.htm";
  else if (lang=='fr') window.location.href = "../FR/index.htm";
  else if (lang=='pt') window.location.href = "../PT/index.htm";
  else if (lang=='it') window.location.href = "../IT/index.htm";
  else window.location.href = "../ES/index.htm";
  idioma = lang;
}

function seleccionar(){
  var elem = document.getElementById("version");
  var lang = elem.options[elem.selectedIndex].value;
  redireccion(lang);
}


function detectaResolucion(){
  document.getElementById("resolucion").value = screen.width + 'x' + screen.height + ',' + screen.availWidth + 'x' + screen.availHeight;
}
 
function openwindow(url, windowName) {
  var options = 'scrollbars=yes,resizable=yes,status=no,toolbar=no,menubar=no,location=no';
  options += ',width=' + screen.availWidth + ',height=' + screen.availHeight;
  options += ',screenX=0,screenY=0,top=0,left=0';
  var win = window.open(url, windowName, options);
  win.focus();
  return win;
}

function processkeypress(e){
  if(window.Event) var whichCode = e.which;
  else var whichCode = event.keyCode;
  if(whichCode == 13) {
    Login();
    return true;
  }
}

function validaUsuario(usuario){
  if ((usuario == null) || (usuario == '')){
    alert(Text0);
    return false;
  }
  return true;
}

function validaPassword(password){
  if ((password == null) || (password == '')){
    alert(Text1);
    return false;
  }
  return true;
}



function Login(idioma) {
  if (!validaUsuario(document.getElementById("usuario").value)){
    return false;
  }
  if (!validaPassword(document.getElementById("password").value)){
    return false;
  }

  if (primera) {
    primera = false;
    if ((document.getElementById("trGrupoLogin").style.display == 'none')){
      var file = url + '/' + proyecto + '/inicio?op='+_OP_OBTENER_SERVIDORES+'&funcion=obtenServidores&dominio=businessmail&tipocliente=businessmail';
      var xmlReq = xmlHTTPRequestObject();
      xmlReq.open( "GET", file, false );
      xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded; ");
      xmlReq.send("");
      gridInicioHandler(xmlReq);
    } else {
      if (document.getElementById("servidor").value == ''){
        alert(Text3);
        primera = true;
        return;
      } else { 
        Login2(idioma);
      }
    }
  } else {
    alert(Text4 + '\n' + Text5);
  }
}


function Login2(idioma){

  try {detectaResolucion();} catch(e){ }

  document.forms['form1'].target='ventana';
  document.forms['form1'].method='get';
  document.forms['form1'].action = urlLogin + '/' + proyecto + '/login';
 
  openwindow('', 'ventana')
  document.forms['form1'].submit();

  document.getElementById("usuario").value = '';
  document.getElementById("password").value = '';
  document.getElementById("trGrupoLogin").style.display = 'none';
  primera = true;
  return ;
}

function ListadoPublicadores(idioma) {
  var file = url + '/' + sedeb2b + '/publicadoresBM?op='+_OP_LISTADO_PUBLICADORESBM+'&idioma=' + idioma;
  xmlReq = getXMLGET(file, self.responseHandlerCuerpo);
}

function accesoCuenta() {
  var file = './accesoCuenta.htm';
  xmlReq = getXMLGET(file, self.responseHandlerCuerpo);
}

function cargaTexto(fileName) {
  if (document.getElementById("login").innerHTML == ""){
    cargaLogin();
  }
  var file = './' + fileName + '.htm';
  xmlReq1 = getXMLGET(file, self.responseHandlerTexto);
}

function cargaLogin() {
  var file = './login.htm';
  xmlReq2 = getXMLGET(file, self.responseHandlerLogin);
}

function cargaCuerpo(url) {
  xmlReq = getXMLGET(url, self.responseHandlerCuerpo);
}

function responseHandlerTexto(){
  try{
    if (xmlReq1){
      if (xmlReq1.readyState == 4) {
        if (xmlReq1.status == 200) {
          try{
            document.getElementById("cuerpo").innerHTML = "";
            document.getElementById("textoCuerpo").innerHTML = xmlReq1.responseText;
          } catch(e){
//            alert(e.message);
          }
        }
      }
    }
  } catch(e){}
}

function responseHandlerLogin(){
  try{
    if (xmlReq2){
      if (xmlReq2.readyState == 4) {
        if (xmlReq2.status == 200) {
          try{
            document.getElementById("login").innerHTML = xmlReq2.responseText;
          } catch(e){
//            alert(e.message);
          }
        }
      }
    }
  } catch(e){}
}

function responseHandlerCuerpo(){
  try{
    if (xmlReq){
      if (xmlReq.readyState == 4) {
        if (xmlReq.status == 200) {
          try {
		  	try {
				var DOMDoc = xmlReq.responseXML;
				var funcion = xmlGetElementContent_(DOMDoc, 'funcion');
				var estado = xmlGetElementContent_(DOMDoc, 'estado');
				if (funcion == 'olvidoPassword') {
					if (estado == 1) {
						var contenido = xmlGetElementContent_(DOMDoc, 'contenido');
						alert(contenido);
						cargaTexto('home');
					} else if (estado == 0) {
						var msj = xmlGetElementContent_(DOMDoc, 'mensaje');
						alert(msj);
					}
					primera = true;
					return;
				} else if (funcion == 'olvidoUsuario') {
					if (estado == 1) {
						var contenido = xmlGetElementContent_(DOMDoc, 'contenido');
						alert(contenido);
						cargaTexto('home');
					} else if (estado == 0) {
						var msj = xmlGetElementContent_(DOMDoc, 'mensaje');
						alert(msj);
					}
					primera = true;
					return;
				}
			} catch (e) {
				
			}

			document.getElementById("login").innerHTML = "";
			document.getElementById("textoCuerpo").innerHTML = "";
			document.getElementById("cuerpo").innerHTML = xmlReq.responseText;	
			primera = true;

          } catch(e){
            alert(e.message);
          }
        }
      }
    }
  } catch(e){}
}

function responseHandlerPassword(){
  try{
    if (xmlReq){
      if (xmlReq.readyState == 4) {
        if (xmlReq.status == 200) {
          try{
            document.getElementById("login").innerHTML = "";
            document.getElementById("textoCuerpo").innerHTML = "";
            var DOMDoc = xmlReq.responseXML;
            var funcion = xmlGetElementContent_(DOMDoc,'funcion');
            if (funcion == 'olvidoPassword') {
                var estado = xmlGetElementContent_(DOMDoc,'estado');
                if (estado == 0) {
					var msj = xmlGetElementContent_(DOMDoc, 'mensaje');
					alert(msj);
					//document.getElementById("cuerpo").innerHTML = msj;
                } else if (estado == 1){
				    cargaCuerpo(url + '/' + proyecto + '/admin/password/FormOlvidoPassword.jsp');
				}
            }
            primera = true;
          } catch(e){
//            alert(e.message);
          }
        }
      }
    }
  } catch(e){}
}


//================================================================================

function cambiaServidor(combo){
  document.getElementById("servidor").value = combo.options[combo.selectedIndex].value;
}

function cargaCombo(listaServidores, grupo){
  var combo = document.getElementById(grupo);
  var grupos = listaServidores.split(",");
  combo.options.length = 0;
  var tamanyo = grupos.length + 1;
  combo.options.length = tamanyo;
  for(var i=0; i<grupos.length; i++){
    combo.options[i].text = grupos[i];
    combo.options[i].value = grupos[i];
  }
  combo.options[tamanyo - 1].text = ' ';
  combo.options[tamanyo - 1].value = ' ';
  combo.options.selectedIndex = tamanyo - 1;
}


function olvidoPassword(idioma) {
    olvidoPasswordV3(idioma);
}


function olvidoPasswordV2(idioma) {
  var usuario = document.getElementById("usuario").value;
  if (!validaUsuario(usuario)){
    return false;
  }
  var servidor = document.getElementById("servidor").value;
  if (servidor == null){
    servidor = '';
  }

  var file = url + '/' + proyecto + '/password.Ejecutar?op='+_OP_MOSTRAR_OLVIDO_PASSWORD+'&web=1&dominio=businessmail&tipocliente=businessmail&usuario=' + usuario + '&idioma=' + idioma + '&servidor=' + servidor;
  xmlReq = getXMLGET(file, self.responseHandlerPassword);
}


function olvidoPasswordV3(idioma){
  var usuario = document.getElementById("usuario").value;
  if (!validaUsuario(usuario)){
    return false;
  }

  if (primera) {
    primera = false;
    if ((document.getElementById("trGrupo1").style.display == 'none')){
      var file = url + '/' + proyecto + '/inicio?op='+_OP_OBTENER_SERVIDORES+'&funcion=olvidoPassword&dominio=businessmail&tipocliente=businessmail';
      var xmlReq = xmlHTTPRequestObject();
      xmlReq.open( "GET", file, false );
      xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded; ");
      xmlReq.send("");
      gridInicioHandler(xmlReq);
    } else {
      if (document.getElementById("servidor").value == ''){
        alert(Text3);
        primera = true;
        return;
      } else { 
        olvidoPasswordV2(idioma);
      }
    }
  } else {
    alert(Text4 + '\n' + Text5);
  }
}

function olvidoUsuario(idioma) {
  if (!validaEmail(document.getElementById("email"))){
    return false;
  }

  if (primera) {
    primera = false;
    if ((document.getElementById("trGrupo2").style.display == 'none')){
      var file = url + '/' + proyecto + '/inicio?op='+_OP_OBTENER_SERVIDORES+'&funcion=olvidoUsuario&dominio=businessmail&tipocliente=businessmail';
      var xmlReq = xmlHTTPRequestObject();
      xmlReq.open( "GET", file, false );
      xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded; ");
      xmlReq.send("");
      gridInicioHandler(xmlReq);
    } else {
      if (document.getElementById("servidor").value == ''){
        alert(Text3);
        primera = true;
        return;
      } else { 
        olvidoUsuario2(idioma);
      }
    }
  } else {
    alert(Text4 + '\n' + Text5);
  }
}

function olvidoUsuario2(idioma){
  var email = document.getElementById("email").value;
  var servidor = document.getElementById("servidor").value;
  var file = url + '/' + proyecto + '/password.Ejecutar?op='+_OP_OLVIDO_USUARIO+'&web=1&dominio=businessmail&tipocliente=businessmail&email=' + email + '&idioma=' + idioma + '&servidor=' + servidor;
  xmlReq = getXMLGET(file, self.responseHandlerCuerpo);
}


function gridInicioHandler(xmlReq){
  try{
  if (xmlReq){
    if (xmlReq.readyState == 4) {
      if (xmlReq.status == 200) {
        try{
          var DOMDoc = xmlReq.responseXML;
          var estado = xmlGetElementContent_(DOMDoc,'estado');
          if (estado == 1) {
            var funcion = xmlGetElementContent_(DOMDoc,'funcion');
            if (funcion == 'olvidoPassword'){
              olvidoPasswordV2(idioma);
              return;
            } else if (funcion == 'olvidoUsuario'){
              olvidoUsuario2(idioma);
              return;
            } else { //funcion=='obtenServidores' desde el Login
              Login2(idioma);
              return;
            }
          } else if (estado == 2) {//Formato nuevo DOMINIO.GRUPO=X (1 solo servidor)
            var listaServidores = xmlGetElementContent_(DOMDoc,'contenido');
            document.getElementById("servidor").value = listaServidores;
            var funcion = xmlGetElementContent_(DOMDoc,'funcion');
            if (funcion == 'olvidoPassword'){
              olvidoPasswordV2(idioma);
              return;
              return;
            } else if (funcion == 'olvidoUsuario'){
              olvidoUsuario2(idioma);
              primera = true;
              return;
            } else { //funcion=='obtenServidores' desde el Login
              Login2(idioma);
              primera = true;
              return;
            }
          } else if (estado == 3) {//Formato nuevo DOMINIO.GRUPO=X (varios servidores)
            var listaServidores = xmlGetElementContent_(DOMDoc,'contenido');
            var funcion = xmlGetElementContent_(DOMDoc,'funcion');
            if (funcion == 'olvidoPassword'){
              cargaCombo(listaServidores, 'grupo1');
              document.getElementById("trGrupo1").style.display = '';  //Es lo mismo que borrar el 'none'
              document.getElementById("trGrupo2").style.display = 'none';
              primera = true;
              return;
            } else if (funcion == 'olvidoUsuario'){
              cargaCombo(listaServidores, 'grupo2');
              document.getElementById("trGrupo2").style.display = '';  //Es lo mismo que borrar el 'none'
              document.getElementById("trGrupo1").style.display = 'none';
              primera = true;
              return;
            } else { //funcion=='obtenServidores' desde el Login
              cargaCombo(listaServidores, 'grupoLogin');
              document.getElementById("trGrupoLogin").style.display = '';  //Es lo mismo que borrar el 'none'
              primera = true;
              return;
            }
          } else {
            var msj = xmlGetElementContent_(DOMDoc,'mensaje');
            alert(msj);
            primera = true;
          }
        } catch(e){
          alert(e.message);
          primera = true;
        }

      } else {//Se ha producido un error en la llamada
        alert(Text6);
        primera = true;
      }
    }
  }
  } catch(e){primera = true;}
}
