var navegador = navigator.appName 
//if (navegador == "Microsoft Internet Explorer"){ 

//}else{ 
  //direccion=("navegador_incompatible.html") 
  //window.location=direccion;
//}

function paginaRecuperaClave(){
  location = 'login_password.php';
}

function portalWebpay(){
  w('http://webpay.softchile.cl/','950','600','Yes');
}

function solicitarPassword(){
  var Usuario = document.recupera_login.Rut_Usuario.value;
  if (Usuario.length < 10){
    alert("Ingrese su RUT");
    document.recupera_login.Rut_Usuario.focus();
  }else{
    document.recupera_login.continuar.disabled = true;
    document.recupera_login.submit();
  }
}

function popUp(file){
  ancho = '600';
  alto = '250';
  izquierda = (screen.width) ? (screen.width-ancho)/2:alto;
  arriba = (screen.height) ? (screen.height-alto)/2:ancho;
  opciones = 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width='+ancho+',height='+alto+',left=' + izquierda + ',top=' + arriba + '';
  window.open(file, 'Servicio', opciones);
}

function demo(){
  location = 'http://www.softchile.cl/';
}

function w(url, ancho, alto, barra) {
  izquierda = (screen.width) ? (screen.width-ancho)/2 : 100
  arriba = (screen.height) ? (screen.height-alto)/2 : 100
  opciones = 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=' + barra + ',resizable=0,width=' + ancho + ',height=' + alto + ',left=' + izquierda + ',top=' + arriba + ''
  window.open(url, 'Softchile', opciones);
}

function diagrama(){
 showModalDialog('esquema_tradicional.php', '', 'dialogHeight: 560px; dialogWidth: 700px; edge: Raised; center: Yes; help: No; resizable: No; status: No');
}

function checkFields( aux ){
   checkUsuarioField(aux)
}

function checkDV( cUsuario ){
  largo = cUsuario.length;
  if ( largo >= 8 )
    Usuario = cUsuario.substring(0, largo - 1);
  else
    Usuario = cUsuario.charAt(0);
    dv = cUsuario.charAt(largo-1);
    if ( Usuario == null || dv == null )
      return 0;
      var dvr = '0';
      suma = 0;
      mul  = 2;
      for (i= Usuario.length -1 ; i >= 0; i--){
        suma = suma + Usuario.charAt(i) * mul;
        if (mul == 7)
          mul = 2;
        else    
          mul++;
        }
        res = suma % 11;
        if (res==1)
          dvr = 'k';
        else if (res==0)
          dvr = '0';
        else{
          dvi = 11-res;
          dvr = dvi + "";
        }
        if ( dvr != dv.toLowerCase() ){
          return false;
        }else{
          return true;
        }
}

function checkUsuarioField(info,siguienteCasilla){
             var textoOriginal = info;
             var texto = info.value;

	var tmpstr = "";
	for ( i=0; i < texto.length ; i++ )
		if ( texto.charAt(i) != ' ' && texto.charAt(i) != '.' && texto.charAt(i) != '-' )
		tmpstr = tmpstr + texto.charAt(i);
		texto = tmpstr;
		largo = texto.length;
		if ( largo > 8 ){

		}else{
                            return false;
                          }


	var invertido = "";
	for ( i=(largo-1),j=0; i>=0; i--,j++ )
		invertido = invertido + texto.charAt(i);

	var dtexto = "";

	dtexto = dtexto + invertido.charAt(0);
	dtexto = dtexto + '-';
	cnt = 0;

	for ( i=1,j=2; i<largo; i++,j++ ){    
		if ( cnt == 3 ){
			dtexto = dtexto + '';
			j++;
			dtexto = dtexto + invertido.charAt(i);
			cnt = 1;
		}else{ 
			dtexto = dtexto + invertido.charAt(i);
			cnt++;
		}
	}

	invertido = "";
	for ( i=(dtexto.length-1),j=0; i>=0; i--,j++ )
		invertido = invertido + dtexto.charAt(i);


	if (checkDV(texto) == true){
	  siguienteCasilla.focus();
               return true;
             }else{
               alert("El Rut ingresado es incorrecto");
               textoOriginal.value = "";
               //textoOriginal.value.focus();
               return false;
             }
}


function validaLargo(){
  var Usuario = document.login.Usuario.value;
  if (Usuario.length < 10){
    alert("El Rut de Usuario es demasiado corto");
    document.login.Usuario.value = "";
    document.login.Usuario.focus();
  }
}


var xmlDoc = null ;
function validaLogin(){
  var Usuario = document.login.Usuario.value;
  var Clave = document.login.Password.value;

  if (Usuario.length < 10){
    alert("Ingrese su Rut sin puntos y con guión (XXXXXXXX-X)\nSi su rut es menor a 10 millones, anteponga el cero.");
    document.login.Usuario.focus();
  }else{
    if (Clave==''){
      alert("Ingrese su password");
      document.login.Password.focus();
    }else{
      RequestObject.open("GET","validaLogin.php?Usuario="+Usuario+"&Password="+Clave, true);   
      RequestObject.onreadystatechange = ReqChange;    
      RequestObject.send(null);
    }
  }
}



var RequestObject = false;
if (window.XMLHttpRequest) //    
RequestObject = new XMLHttpRequest();   
if (window.ActiveXObject)      
RequestObject = new ActiveXObject("Microsoft.XMLHTTP");   
function ReqChange() {   
  // Si se ha recibido la información correctamente   
  if (RequestObject.readyState==4) {     
    if (RequestObject.responseText.indexOf('invalid') == -1){     
      var msgs = RequestObject.responseText.split('|');
      if (msgs[0] == '0'){
        alert("ERROR DE ACCESO\n\nSOFTCHILE.CL no reconoce los datos ingresados.\nRevise que el RUT sea correcto y verifique su clave.\n");
        document.login.Password.value='';
        document.login.Password.focus();
      }else{
        if (msgs[0] == '4'){
          if (msgs[1] == '0'){
            alert("CUENTA EN PROCESO DE HABILITACIÓN\nEsto podría tardar hasta 48 horas, después de confirmado su pago.\n");
          }else{
            if (msgs[1] == '2'){
              var confirma = confirm("CUENTA SUSPENDIDA\n-----------------------------------------\nSu cuenta está bloqueada por Saldo Pendiente.\n¿Desea conocer su Saldo ahora?\n");
              if (confirma){
                location = 'contratar_online_buscar.php';
              }
            }else{
              if (msgs[1] == '3'){
                var confirmaCta = confirm("SU CUENTA ESTA VENCIDA\n-----------------------------------------\nPuede regularizar ahora, cancelando su Estado de Cuenta.\n¿Desea conocer el Saldo Pendiente de Pago?\n");
                if (confirmaCta){
                  location = 'contratar_online_buscar.php';
                }
              }else{
                alert("CUENTA BLOQUEADA\nFavor contáctese con nuestra Area Comercial.\n");
              }
            }
          }
          document.login.Password.value='';
          document.login.Password.focus();
        }else{
          if (msgs[0] == '3'){
            var preguntaCierre = confirm("ALERTA DE SEGURIDAD\n\nSOFTCHILE.CL no puede iniciar sesión, debido a que su cuenta está abierta.\nEsto puede deberse a que la vez anterior no cerró apropiadamente su sesión,\no bien facilitó sus claves a terceros, quienes están operando el Sistema.\n\n¿Desea forzar el cierre de la sesión actualmente abierta?");
            if (preguntaCierre){
              location = 'login_forzar_cierre.php';
            }else{
              document.login.Password.value='';
              document.login.Password.focus();
            }
          }else{
            location = 'erp/'+msgs[0];
          }
        }

      }
    }else{
        alert("Error: El Servidor esta ocupado. Por favor inténtelo más tarde.");
    }   
  }   
}   

function enviarContacto(){
  var rut = document.registro.rut;
  var nombre = document.registro.nombre;
  var telefono = document.registro.telefono;
  var ciudad = document.registro.ciudad;
  var email_demo = document.registro.email_demo;
  var producto = document.registro.producto;

  if (rutCorrecto(rut.value)==false){
    alert("El Rut es incorrecto");
    document.registro.rut.value = '';
    document.registro.rut.focus();
  }else if (nombre.value.length<5){
    alert("Ingrese su nombre");
    document.registro.nombre.focus();
  }else if (telefono.value.length<6){
    alert("Ingrese un Teléfono Fijo");
    document.registro.telefono.focus();
  }else if (ciudad.value.length<1){
    alert("Indique la ciudad");
    document.registro.ciudad.focus();
  }else if (email_demo.value.length<4){
    alert("Indique su email");
    document.registro.email_demo.focus();
  }else if (producto.value.length<3){
    alert("Seleccione la forma de contacto");
    document.registro.producto.focus();
  }else{
    document.registro.submit();
  }
}

function enviarRegistro(){
  var rut = document.registro.rut;
  var nombre = document.registro.nombre;
  var razon = document.registro.razon;
  var giro = document.registro.giro;
  var direccion = document.registro.direccion;
  var telefono = document.registro.telefono;
  var ciudad = document.registro.ciudad;
  var email_demo = document.registro.email_demo;
  var producto = document.registro.producto;
  var forma_pago = document.registro.forma_pago;

  if (nombre.value.length<5){
    alert("Ingrese su nombre");
    document.registro.nombre.focus();
  }else if (razon.value.length<5){
    alert("Ingrese la Razon Social");
    document.registro.razon.focus();
  }else if (giro.value.length<5){
    alert("Ingrese el Giro");
    document.registro.giro.focus();
  }else if (rutCorrecto(rut.value)==false){
    alert("El Rut es incorrecto");
    document.registro.rut.value = '';
    document.registro.rut.focus();
  }else if (direccion.value.length<5){
    alert("Ingrese la dirección de facturación");
    document.registro.direccion.focus();
  }else if (telefono.value.length<6){
    alert("Ingrese un Teléfono Fijo");
    document.registro.telefono.focus();
  }else if (ciudad.value.length<1){
    alert("Indique la ciudad");
    document.registro.ciudad.focus();
  }else if (email_demo.value.length<4){
    alert("Indique su email");
    document.registro.email_demo.focus();
  }else if (producto.value.length<3){
    alert("Seleccione el Plan que desea contratar");
    document.registro.producto.focus();
  }else if (forma_pago.value.length<3){
    alert("Seleccione la forma en que pagará los servicios");
    document.registro.forma_pago.focus();
  }else{
    var confirmacion = confirm("CONFIRMACION\n\nCon los datos ingresados, se generará el registro\ny enrolamiento de su empresa.\n\n¿Confirma que los datos están correctos?");
    if (confirmacion) document.registro.submit();
  }
}



function rutCorrecto(texto){
	var tmpstr = "";
	for ( i=0; i < texto.length ; i++ )
		if ( texto.charAt(i) != ' ' && texto.charAt(i) != '.' && texto.charAt(i) != '-' )
		tmpstr = tmpstr + texto.charAt(i);
		texto = tmpstr;
		largo = texto.length;
		if ( largo > 7 ){

		}else{
                            return false;
                          }


	var invertido = "";
	for ( i=(largo-1),j=0; i>=0; i--,j++ )
		invertido = invertido + texto.charAt(i);

	var dtexto = "";

	dtexto = dtexto + invertido.charAt(0);
	dtexto = dtexto + '-';
	cnt = 0;

	for ( i=1,j=2; i<largo; i++,j++ ){    
		if ( cnt == 3 ){
			dtexto = dtexto + '';
			j++;
			dtexto = dtexto + invertido.charAt(i);
			cnt = 1;
		}else{ 
			dtexto = dtexto + invertido.charAt(i);
			cnt++;
		}
	}

	invertido = "";
	for ( i=(dtexto.length-1),j=0; i>=0; i--,j++ )
		invertido = invertido + dtexto.charAt(i);


	if (checkDV(texto) == true){
               return true;
             }else{
               return false;
             }
}


function crearUsuarioDemo(){
  var rut = document.registro.rut;
  var nombre = document.registro.nombre;
  var email_demo = document.registro.email_demo;
  if (rutCorrecto(rut.value)==false){
    alert("El RUT es incorrecto");
    document.registro.rut.value = '';
    document.registro.rut.focus();
  }else if (nombre.value.length<5){
    alert("Ingrese su nombre completo");
    document.registro.nombre.focus();
  }else if (email_demo.value.length<5){
    alert("Ingrese su email");
    document.registro.email_demo.focus();
  }else{
    document.registro.submit();
  }
}


function cambiaMayusculas(destino){
    var texto = destino.value;
    destino.value = texto.toUpperCase();
}

function soloNumeros(evento){
  var key = evento.keyCode ? evento.keyCode : evento.which;
  if (key>32){
   if(key>=48 && key<= 57 || key==35 || key==36 || key==46){
    return
   }else{
    return false;
  }
 }
}

function nextCeldaLogin(siguiente){
  var siguiente;
  if (document.all)
    tecla=event.keyCode;
  else
  {
    tecla=e.which;
  }
  if (tecla==13){
    if (siguiente == 'fin'){
      validaLogin();
    }else{
      siguiente.focus();
    }
  }
}
