var calcPorcentaje = true;
function formatoNumero (numero, destino) {
	destino.val(formatear_numero(numero, 2));
}


function formatoRut() {

	$("#rut_aux").val(formatear_numero($("#rut").val(),0) + "-" + $("#dv").val().toUpperCase());
}
/* ------------------------------------------- */

function formateaRut(e) {

        VRut = $("#rut_aux").val();
	if (!ValidarRut(VRut)) {
		alert("Rut no es valido");
		$("#rut_aux").val("");
		return false;
	}

	var rutv = trim(VRut);
	var dveri = rutv.charAt(rutv.length-1)
        tmpstr = "";
	for ( i=0; i < rutv.length-1 ; i++ ) {
        	if ( rutv.charAt(i) != ' ' && rutv.charAt(i) != '.' && rutv.charAt(i) != '-' )
        		tmpstr = tmpstr + rutv.charAt(i);
	}
	$("#rut").val(tmpstr);
	$("#dv").val(dveri);
	$("#rut_aux").val(formatear_numero(tmpstr,0) + "-" + dveri.toUpperCase());
	return true;
}

function formatear_numero(numero, totDec){

	var nroFormateado = '';
	var band = 0;
	var indDec = (totDec > 0);
	var contDec = 0;
	var decimales = "";
	var extras = "";

	for (i=0; i<totDec; decimales+="0",i++);

	i=0;
	if(numero.charAt(i)=="-"){
		band++;
		i++;
	}

	while ( i < numero.length && (numero.charAt(i) != "," && numero.charAt(i) != ".") ) {
		nroFormateado += numero.charAt(i);
		i++;
	}

	nroFormateado = formato_miles(nroFormateado);
	if (numero.charAt(i) == ","|| numero.charAt(i) == "." ) i++;

	if (indDec) {
		if (i < numero.length ) {
			while ( i < numero.length && contDec <= totDec ) {
				extras += numero.charAt(i);
				i++; 
				contDec++;
			}
		}
		if (nroFormateado.length == 0)  nroFormateado = '0';
		decimales = extras + decimales;
		nroFormateado += "," + decimales.substring(0, totDec);
	}
	if(band>0){
		nroFormateado = "-" + nroFormateado;
	}
	return nroFormateado;
}

function formato_miles(texto) {
	var invertido = "";
	var i=0, j=0;
	var cnt=0;
	var etexto = new String("");
	var dtexto = new String(texto);
	var largo=0;

	 largo = dtexto.length;
	for ( i=largo; i>=0 ; i--)
		if (dtexto.charAt(i) >= "0" && dtexto.charAt(i) <= "9")
			etexto = etexto + dtexto.charAt(i);
	largo = etexto.length;
	dtexto = "";
	for ( i=0; i <= largo; i++ ) {
		if ( cnt == 3 ) {
			if (i!= largo)
				dtexto = dtexto + '.';
			dtexto = dtexto + etexto.charAt(i,1);
			cnt = 1;
		} else {
			dtexto = dtexto + etexto.charAt(i,1);
			cnt++;
		}
	}
	etexto="";
	for ( i=dtexto.length; i>=0 ; i--)
		etexto = etexto + dtexto.charAt(i,1);
	return (etexto);
}


function d2Number(numero) {
    	var band = 0;	
	var salida = "";

	i = 0;
	if(numero.charAt(i)=="-"){
		band++;
		i++;
	}

	for (; i< numero.length; i++) {
		if (numero.charAt(i) == "." ) {
			salida += ",";
		}
		if (numero.charAt(i) == "." ) {
			continue;
		}
		salida += numero.charAt(i);
	}
	if(band>0){
		salida = "-" + salida;
	}
	return salida;
}

function toNumber(numero) {

	var band = 0;	
	var salida = "";

	i = 0;
	if(numero.charAt(i)=="-"){
		band++;
		i++;
	}

	for (; i< numero.length; i++) {
		if (numero.charAt(i) == "." ) {
			continue;
		}
		if (numero.charAt(i) == "," ) {
			salida += ".";
			continue;
		}
		salida += numero.charAt(i);
	}
	if(band>0){
		salida = "-" + salida;
	}
	return salida;
}

/*************************************************************/
  /* trim()                                                    */
  /*************************************************************/
	function trim(s)
	{
		var l=0; var r=s.length -1;
		while(l < s.length && s[l] == ' ') { l++; }
		while(r > l && s[r] == ' ') { r-=1; }
		if (l==0 && r==s.length)
			return s;
		else
			return s.substring(l, r+1);
	}


/************************************************************/
/* ValidarRut                                             	*/
/************************************************************/

  function ValidarRut(VRut)
  {

    if (trim(VRut) == "") return false;

    var tmpstr = "";
    var rutv = trim(VRut);
    var dveri = rutv.charAt(rutv.length-1)

    for ( i=0; i < rutv.length-1 ; i++ ) {
        //if ( rutv.charAt(i) != ' ' && rutv.charAt(i) != '.' && rutv.charAt(i) != '-' && rutv.charAt(i) !="k" && rutv.charAt(i) != "K" )
        if ( rutv.charAt(i) != ' ' && rutv.charAt(i) != '.' && rutv.charAt(i) != '-' )
          tmpstr = tmpstr + rutv.charAt(i);
	}
    var largo = tmpstr.length;
    var num_error = 0;
    var suma = 0;

    for (i=0; i < largo ; i++ ) {
       if ( tmpstr.charAt(i) !="0" && tmpstr.charAt(i) != "1" && tmpstr.charAt(i) !="2" && tmpstr.charAt(i) != "3" && tmpstr.charAt(i) != "4" && tmpstr.charAt(i) !="5" && tmpstr.charAt(i) != "6" && tmpstr.charAt(i) != "7" && tmpstr.charAt(i) !="8" && tmpstr.charAt(i) != "9")
          num_error++;
	}
    if (num_error == 0) {

      var l = largo;
      var mult = 2;
      for (var i=l-1; i>=0; i--) {
        var car=parseInt(tmpstr.charAt(i));
        suma += car * mult;
        mult++;
        if (mult == 8) {
          mult = 2;
        }
     }

     var resto = 11 - (suma % 11);
     if ((resto == dveri) || ((resto == 10) && ((dveri == 'k') || (dveri == 'K'))) || ((resto == 11) && (dveri == 0))) {
        return true;
     } else {
        return false;
     }
    } else {
    return false;
    }
  }  

  
  function date2int(s) {
	var sdia = s.substr(0,2);
	var smes = s.substr(3,2);
	var sano = s.substr(6,4);

	var intdate = parseInt(sano + "" + smes + "" + sdia);
	return intdate;
}

function calculaFinanciamiento() {

	porc = '';

	try {
		mtoPropiedad = parseFloat($("#mtoPropiedad").val());
		mtoCredito = parseFloat($("#mtoCredito").val());
		if (eval(mtoPropiedad) > 0 && eval(mtoCredito) > 0) 
			porc = (mtoCredito / mtoPropiedad) * 100;

	} catch (error) {
	}
	$("#financiamiento").val(formatear_numero(new String(porc), 2));
    calcPorcentaje = false;
}


function calculaPorcentajeTrue(e) {
    tecla = (document.all) ? e.keyCode : e.which;
    if (permitido(tecla)) return;
    calcPorcentaje = true;
}
function calculaPorcentaje(e) {

    if (!calcPorcentaje) {
        return
    }
    mtoPropiedad = 0;
    mtoCredito = 0;
    porc = 0;
	try {
            mtoPropiedad = parseFloat($("#mtoPropiedad").val());
            mtoCredito = parseFloat($("#mtoCredito").val());

            if (mtoPropiedad == 0 && mtoCredito == 0) {
              return;
            }

            porc = parseFloat($("#financiamiento").val());
            if (porc == 0) {
              return;
            }

            if (mtoPropiedad > 0) {
                mtoCredito = (porc / 100) * mtoPropiedad;
                $("#monto_uf_aux").val(formatear_numero(new String(mtoCredito), 2));
                formato ($("#monto_uf_aux"), $("#mtoCredito"));
                toUF($("#mtoCredito"), $("#monto_uf_pes"))
            } else {
                mtoPropiedad = (porc / 100) / mtoCredito;
                $("#valor_propiedad_aux").val(formatear_numero(new String(mtoPropiedad), 2));
                formato ($("#valor_propiedad_aux"), $("#mtoPropiedad"));
                toUF($("#mtoPropiedad"), $("#valor_propiedad_pes"))
            }
            calculaContado()
	} catch (error) { }
	
}


function formato(origen, destino) {

	destino.val(toNumber(origen.val()));
	origen.val(formatear_numero(destino.val(), 2));
}

function formatoPropNumero(e) {
	formato ($("#valor_propiedad_aux"), $("#mtoPropiedad"));
}

function formatoPorcentaje(e) {
        $("#financiamiento").val(formatear_numero($("#financiamiento").val(), 2));
}

function formatoCreditoNumero(e) {
	formato ($("#monto_uf_aux"), $("#mtoCredito"));
}

function formatoSeguro(e) {
	formato ($("#monto_seguro_aux"), $("#mtoSeguro"));
}

var digitos = "0123456789.,";

function isNumero(obj, mensaje) {

	for (i=0; i < obj.value.length; i++) {
          dig = obj.value.charAt(i);
          if (digitos.indexOf(dig) == -1) {
                if (mensaje != "") {
			alert("El campo " + mensaje + " debe ser númerico");
			obj.value = '';
			obj.focus(); 
                }
                return false;
          }
	}
	return true;
}

var patronTexto = /[A-Za-zñÑ\s]/;
var patronMail = /[A-Za-zñÑ@.]/;
var patronDigito = /[0-9.,]/;
var patronRut = /[0-9\-.kK]/;
var patronEMail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;


function permitido (codigo) {
  return (codigo == 0 || codigo == 8);
}

function validaTexto (e) {
  tecla = (document.all) ? e.keyCode : e.which;
  if (permitido(tecla)) return true;
  return patronTexto.test(String.fromCharCode(tecla));
}

function validaRut (e) {
  tecla = (document.all) ? e.keyCode : e.which;
  if (permitido(tecla)) return true;
  return patronRut.test(String.fromCharCode(tecla));
}

function validaMail (e) {
  tecla = (document.all) ? e.keyCode : e.which;
  if (permitido(tecla)) return true;
  return patronMail.test(String.fromCharCode(tecla)) || patronDigito.test(String.fromCharCode(tecla));
}

function validaDigito (e) {
  tecla = (document.all) ? e.keyCode : e.which;
  if (permitido(tecla)) return true;
  return patronDigito.test(String.fromCharCode(tecla));
}

function isMailValido(texto) {
  return patronEMail.test(texto);
}

function valNumero(caja) {
    
    return eval(toNumber(contenido(caja))) > 0;
}

function contenido(caja) {
    return trim($("#" + caja).val());
}

function simular() {

        if (contenido("nombre")  == "") {
            alert("Debe ingresar el nombre");
            return false;
        }
        if (contenido("rut_aux")  == "") {
            alert("Debe ingresar el rut");
            return false;
        }
        if (contenido("fono_celular")  == "" && contenido("fono_fijo")  == "") {
            alert("Debe indicar al menos un fono de contacto");
            if (contenido("fono_celular")  != "") {
                if (!isNumero(contenido("fono_celular"))) {
                    alert("El numero del fono celular solo puede ser numérico");
                }
            }
            if (contenido("fono_fijo")  != "") {
                if (!isNumero(contenido("fono_fijo"))) {
                    alert("El numero del fono fijo solo puede ser numérico");
                }
            }
            return false;
        }
        
        if (contenido("email")  != "") {
          if (!isMailValido(contenido("email"))) {
            alert("Dirección de correo no es válida.");  
            return false;
          }
        }
        if (!valNumero("valor_propiedad_aux")) {
            alert("Debe indicar el valor de la propiedad");
            return false;
        }
        if (!valNumero("monto_uf_aux")) {
            alert("Debe indicar el valor del crédito");
            return false;
        }
        if (eval(contenido("mtoCredito")) < eval(contenido("minimoCredito"))) {
		alert("El monto del credito debe ser mayor a U.F " + contenido("minimoCredito"));
		return false;
	}
        if (eval(contenido("mtoPropiedad")) < eval(contenido("minimoPropiedad"))) {
		alert("El monto de la propiedad debe ser mayor a U.F " + contenido("minimoPropiedad"));
		return false;
	}        
        if (isNaN($("input[@name='propiedad']:checked").val())) {
            alert("Debe indicar el tipo de propiedad");
            return false;
        }
        if (isNaN($("input[@name='dfl2']:checked").val())) {
            alert("Debe especificar el estado DFl2");
            return false;
        }
        
        var porcentaje = 0;
        if ($("#objetivo").val() == 1) {
            porcentaje = eval(contenido("maximoPorcentajeVivienda"));
        } else {
            porcentaje =eval(contenido("maximoPorcentajeGeneral"));
        }
        
	if (eval(toNumber(contenido("financiamiento"))) > porcentaje) {
		alert("El % de financiamiento no puede superar el " + porcentaje + "%");
		return false;
	}
        
        $("form:first").attr("action","/laraucana/simulacion.do?method=calculo");
        $("form:first").attr("target","");
	$("form:first").submit();
        return true;
}
