function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function formatoNumero (numero, destino) {
        if (numero == 0) {
            destino.val('');
            return;
        }
	destino.val(formatear_numero(numero, 2));
}

/* ------------------------------------------- */

function formatear_numero(numero, totDec){

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

        if (numero == '0' || numero == 0) {
            return '';
        }
	for (i=0; i<totDec; decimales+="0",i++);

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

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

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

	if (indDec) {
		if (i < intput.length ) {
			while ( i < intput.length && contDec <= totDec ) {
				extras += intput.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;

        if (texto == '0') {
            return '';
        }
	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 toNumber(numero) {

	var band = 0;	
	var salida = "";
        var intput = new String(numero);
        
        if (trim(numero) == "") {
            return "0";
        }
	i = 0;
	if( intput.charAt(i)=="-" ){
		band++;
		i++;
	}

	for (; i< intput.length; i++) {
		if (intput.charAt(i) == "." ) {
			continue;
		}
		if (intput.charAt(i) == "," ) {
			salida += ".";
			continue;
		}
		salida += intput.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);
	}

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());
          mtoContado = parseFloat($("#mtoContado").val());
          mtoCredito = parseFloat($("#mtoCredito").val());

          if (mtoPropiedad == 0 && mtoCredito == 0)  {
              return;
          }
          if (eval(mtoPropiedad) > 0 && eval(mtoCredito) > 0) {
                  porc = roundNumber((mtoCredito / mtoPropiedad) * 100,2);
                  $("#porc").val(porc);
        }
          $("#financiamiento").val(formatear_numero(new String(porc), 2));
	} catch (error) {
            $("#financiamiento").val(" ");
	}
asignadividendos();	
}

function calculaContado(e) {
    mtoPropiedad = 0;
    mtoCredito = 0;
    mtoContado = 0;

    mtoPropiedad = parseFloat($("#mtoPropiedad").val());
    mtoContado = parseFloat($("#mtoContado").val());
    mtoCredito = parseFloat($("#mtoCredito").val());
    
    if (mtoPropiedad == 0)  {
        return;
    }

    if (mtoContado > 0)  {
        mtoCredito =  roundNumber(mtoPropiedad - mtoContado,2);
        $("#monto_uf_aux").val(formatear_numero(new String(mtoCredito), 2));
        $("#mtoCredito").val(mtoCredito);
        toUF($("#mtoCredito"), $("#monto_uf_pes"))
    }
}

function calculaCredito(e) {
    mtoPropiedad = 0;
    mtoCredito = 0;
    mtoContado = 0;

    mtoPropiedad = parseFloat($("#mtoPropiedad").val());
    mtoContado = parseFloat($("#mtoContado").val());
    mtoCredito = parseFloat($("#mtoCredito").val());

    if (mtoPropiedad == 0)  {
        return;
    }

    if (mtoCredito > 0)  {
      mtoContado =  roundNumber(mtoPropiedad - mtoCredito,2);
      $("#monto_ctdo_aux").val(formatear_numero(new String(mtoContado), 2));
      $("#mtoContado").val(mtoContado);
      toUF($("#mtoContado"), $("#monto_ctdo_pes"))
    }
}

function calculaPorcentaje(e) {

    mtoPropiedad = 0;
    mtoCredito = 0;
    porc = 0;
    try {
        mtoPropiedad = parseFloat($("#mtoPropiedad").val());
        mtoContado = parseFloat($("#mtoContado").val());
        mtoCredito = parseFloat($("#mtoCredito").val());
//alert('En calculaPorcentaje : ' + mtoPropiedad);
        if (mtoPropiedad == 0 && mtoCredito == 0) {
            return;
        }
        resp = parseFloat($("#porc").val());
        porc = parseFloat(toNumber($("#financiamiento").val()));
        if (porc == 0) {
          return;
        }
        
        if (resp == porc) {
            return;
        }
        if (mtoPropiedad > 0) {
            mtoCredito = roundNumber((porc / 100) * mtoPropiedad,2);
            $("#monto_uf_aux").val(formatear_numero(new String(mtoCredito), 2));
            formato ($("#monto_uf_aux"), $("#mtoCredito"));
            toUF($("#mtoCredito"), $("#monto_uf_pes"))
            calculaCredito();
            $("#financiamiento").val(formatear_numero(porc,2));
        } else {
            mtoPropiedad = roundNumber((porc / 100) / mtoCredito,2);
            $("#valor_propiedad_aux").val(formatear_numero(new String(mtoPropiedad), 2));
            formato ($("#valor_propiedad_aux"), $("#mtoPropiedad"));
            toUF($("#mtoPropiedad"), $("#valor_propiedad_pes"))

        }
        
    } catch (error) { }
}

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

function toUF(origen, destino) {
    destino.val(formatear_numero(parseFloat(origen.val()) * parseFloat($("#valorUF").val())));
}



function calcula_uf()
{
    var vpp = document.getElementById('valor_propiedad_pes');
    var mcp = document.getElementById('monto_ctdo_pes')
    var vps = document.getElementById('monto_uf_pes');
    var por = document.getElementById('financiamiento');
    var vup = document.getElementById('valor_propiedad_aux');
    var mcu = document.getElementById('monto_ctdo_aux');
    var vus = document.getElementById('monto_uf_aux');
    var uf = document.getElementById('valor_uf');

var divisor;
//alert(uf.value);
    //Formateo
    vup.toString().replace(".", ",");
    mcu.toString().replace(".", ",");
    vus.toString().replace(".", ",");



    vpp.value = roundNumber(val_DesFormateaNumero(vpp.value),0);
    mcp.value = roundNumber(val_DesFormateaNumero(mcp.value),0);
    vps.value = roundNumber(val_DesFormateaNumero(vps.value),0);

    vup.value = val_DesFormateaNumero(vup.value);
    mcu.value = val_DesFormateaNumero(mcu.value);
    vus.value = val_DesFormateaNumero(vus.value);

    por.value = roundNumber(val_DesFormateaNumero(por.value),0);

    //Verifica valores numericos.

    vpp.value = (isNaN(vpp.value)?0:vpp.value);
    mcp.value = (isNaN(mcp.value)?0:mcp.value);
    vup.value = (isNaN(vup.value)?0:vup.value);
    vps.value = (isNaN(vps.value)?0:vps.value);
    mcu.value = (isNaN(mcu.value)?0:mcu.value);
    vus.value = (isNaN(vus.value)?0:vus.value);
    por.value = (isNaN(por.value)?0:por.value);
//alert('vup ' + vup.value + 'mcu ' + mcu.value + 'vus ' + vus.value + 'uf.value ' + uf.value);
    vup.value = roundNumber((toNumber(vpp.value) / parseFloat($("#valorUF").val())), 2)
    mcu.value = roundNumber((toNumber(mcp.value) / parseFloat($("#valorUF").val())), 2)
    vus.value = roundNumber((toNumber(vps.value) / parseFloat($("#valorUF").val())),2)

//alert('vup ' + vup.value + 'mcu ' + mcu.value + 'vus ' + vus.value);

    if(vup.value == 0)
        divisor = 1;
    else
        divisor = vup.value;

    por.value = roundNumber(((vus.value * 100)/divisor),2);

    //Formateo
    vpp.value = val_FormateaNumero(vpp.value);
    mcp.value = val_FormateaNumero(mcp.value);
    vup.value = val_FormateaNumero(vup.value);
    vps.value = val_FormateaNumero(vps.value);
    mcu.value = val_FormateaNumero(mcu.value);
    vus.value = val_FormateaNumero(vus.value);
    por.value = val_FormateaNumero(por.value);

/*    if(toNumber(vpp.value) > 0){
    formatoPropNumero();
}
    if(toNumber(vps.value) > 0){
        formatoCreditoNumero();
        calculaCredito();
    }
    
    if(toNumber(mcp.value) > 0){
        formatoContadoNumero();
        calculaContado();
    }



calculaFinanciamiento();
*/
}
function calcula_prop(){
   formatoPropNumero();
   calculaFinanciamiento();
}

function calcula_cont(){
   formatoContadoNumero();
   calculaContado();
   calculaFinanciamiento();
}

function calcula_cred(){
   formatoCreditoNumero();
   calculaCredito();
   calculaFinanciamiento();
}

function formatoPropNumero(e) {
    if ($("#valor_propiedad_aux").val() == "") return;
    formato ($("#valor_propiedad_aux"), $("#mtoPropiedad"));
    toUF($("#mtoPropiedad"), $("#valor_propiedad_pes"))
}


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

function formatoCreditoNumero(e) {

    if ($("#monto_uf_aux").val() == "") return;
    formato ($("#monto_uf_aux"), $("#mtoCredito"));
    toUF($("#mtoCredito"), $("#monto_uf_pes"))
}

function formatoContadoNumero(e) {
    if ($("#monto_ctdo_aux").val() == "") return;
    formato ($("#monto_ctdo_aux"), $("#mtoContado"));
    toUF($("#mtoContado"), $("#monto_ctdo_pes"))	
}

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 (tecla == 13) {
        sgte = $('#'+e.currentTarget.id).attr('sgte');
        if (sgte != '') {
            $('#'+e.currentTarget.id)[0].blur();
            $('#' + sgte).focus();
            
        }
        return true;
    }*/
    if (!permitido(tecla)) {
        if (!patronDigito.test(String.fromCharCode(tecla))) {
            return false;
        }
    }
    limpiaResultado();
    return true;
}

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

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

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

function d2Number(numero) {
    	var band = 0;	
	var salida = "";
        var input = new String(numero);
	i = 0;
	if (input.charAt(i)=="-"){
		band++;
		i++;
	}

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


/***********************  Limpia Montos ************************/

function limpiaMontosPropiedad(e) {
    tecla = (document.all) ? e.keyCode : e.which;
    if (tecla == 13 || e.keyCode == 9) {
        return;
    }
    if ($("#mtoPropiedad").val() != '0') {
        $("#valor_propiedad_pes").val('');
        $("#monto_ctdo_aux").val('');
        $("#monto_ctdo_pes").val('');
        $("#monto_uf_aux").val('');
        $("#monto_uf_pes").val('');
        $("#financiamiento").val('');

        $("#mtoPropiedad").val('0');
        $("#mtoCredito").val('0');
        $("#mtoContado").val('0');
        $("#porc").val('0');
    }
}

/************************************************************/
/* ValidarRut                                             	*/
/************************************************************/
function ValidarRut(VRut) {

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

  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 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 cambiarPlazos() {
    var plazosMH = new Array(8,10,12,15,20,25,30);
    var plazosMU = new Array(15,20,25,30);
    var value = $("#plazo").val();
    $("#plazo").empty();
    var tmp = ($("#producto").val() != 20)?plazosMH:plazosMU;
    for (x = 0; x < tmp.length; x++)
        $("#plazo").append('<option value="' + tmp[x] + '">' + tmp[x] + ' años</option>');
    if (value != "") $("#plazo").val(value);
}

function cambiaProducto() {
    cambiarPlazos();
    if ($("#producto").val() != 20) {
        $("#graciaReal").attr('disabled',false);
        $("#gracia").attr('disabled',false);
        $("#segCesantia").attr('checked',true);
        $("#seguroDsInv").attr('disabled',false);
    } else {
        $("#graciaReal").val(0);
        $("#graciaReal").change();
        $("#gracia").attr('disabled',true);
        $("#graciaReal").attr('disabled',true);
        $("#segCesantia").attr('checked',false);
        $("#seguroDsInv").attr('checked',false);
        $("#seguroDsInv").attr('disabled',true);
    }
    limpiaResultado();
}
