<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl.'/js/jquery.mask.min.js',CClientScript::POS_HEAD); 
    Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/js/fileinput.js',CClientScript::POS_END);
    Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/css/fileinput.css');
    Yii::app()->getClientScript()->registerScriptFile(Yii::app()->baseUrl.'/js/bootstrap2-toggle.js');
    Yii::app()->getClientScript()->registerCssFile(Yii::app()->baseUrl.'/css/bootstrap2-toggle.css');
?>
<?php
$this->breadcrumbs=array(
	'Creditos'=>array('index'),
	'Create',
);

$this->menu=array(
	array('label'=>'List Credito','url'=>array('index')),
	array('label'=>'Manage Credito','url'=>array('admin')),
);
?>
<h2 style="text-align: center">Solicitar pr&eacute;stamo por administrador</h2>
<?php 

$form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
	'id'=>'credito-form',
        'enableAjaxValidation' => false,
        'enableClientValidation' => true,
        'clientOptions' => array(
        'validateOnSubmit' => true,
        'validateOnChange' => true,
        'validateOnType' => true,
        ),
        'htmlOptions'=>array('enctype'=>'multipart/form-data', 'onsubmit'=>'return comparaMontos()'),
)); 
$this->widget('bootstrap.widgets.TbAlert', array(
    'block' => true, // display a larger alert block?
    'fade' => true, // use transitions?
    'closeText' => '×', // close link text - if set to false, no close link is displayed
    'alerts' => array(// configurations per alert type
        'error' => array('block' => true, 'fade' => true, 'closeText' => '×'), // success, info, warning, error or danger
        'info' => array('block' => true, 'fade' => true, 'closeText' => '×'), // success, info, warning, error or danger
    ),
));

?>
<br>
<fieldset><legend style=" font-size: 17px;"><b>Datos del solicitante</b></legend>            
<table class="table table-bordered">
        <tr>
            <td style="width: 25%"><b><?php echo $form->labelEx($model,'cedula'); ?></b></td>
            <td style="width: 25%"> 
                <div style="display:table">
                    <div style="float:left; width: 65%;">
                        <?php echo $form->textField($model,'cedula',array('maxlength'=>'10','class'=>'input-medium')); ?>
                        <?php echo  $form->error($model,'cedula') ;?>
                        
                    </div>
                    <div style="float:right;width: 35%;" >
                        <?php echo CHtml::htmlButton('Buscar <i class="icon-search"></i>', array('type'=>"button",'id'=>'btn_buscar_datos_personales','class' => 'btn btn-success icon button','onClick'=>'datosPersonalesCredito()'));	?>
                        
                    </div>
                </div>
                    <div id="mensajesSistema"  class="datosPersonales"></div>
            </td>
            <td style="width: 20%"><b>Nombres y apellidos</b></td>
            <td style="width: 30%"><div id="nombres_apellidos" class="datosPersonales"></div></td>
        </tr>
        <tr>
            <td><b>Empresa</b></td>
            <td><div id="empresa" class="datosPersonales"></div></td>
            <td><b>Unidad</b></td>
            <td><div id="unidad" class="datosPersonales"></div></td>
        </tr>
        <tr>
            <td><b>&Uacute;ltimo sueldo</b></td>
            <td><div id="sueldo" class="datosPersonales"></div></td>
            <td><b>Porcentaje de aporte</b></td>
            <td><div id="porcentaje" class="datosPersonales"></div></td>
        </tr>
        <tr>
            <td><b>Fecha de inscripci&oacute;n</b></td>
            <td><div id="fecha_inscripcion" class="datosPersonales"></div></td>
            <td><b>Estatus</b></td>
            <td><div id="estatus" class="datosPersonales"></div></td>
        </tr>
        <tr>
            <td colspan="4" id="calculadoraHaberesSocio" class="datosCredito" style="display: none"></td>
        </tr>
        
    </table>
</fieldset>
<fieldset><legend style=" font-size: 17px;"><b>Informaci&oacute;n de su &uacute;ltimo recibo de pago</b></legend>            
<table class="table table-bordered" id="datos_prestamos_calculadora">
        <tr>
            <td style="width: 25%"><b><?php echo $form->labelEx($model,'id_titulo_tipo_credito'); ?></b></td>
            <td style="width: 25%">  <?php echo $form->dropDownList($model,'id_titulo_tipo_credito',  CHtml::listData(TituloTipoCredito::model()->findAll(array('order'=>'nombre_titulo asc')), 'id', 'nombre_titulo'),
                                                                    array('prompt' => 'Seleccione ',
                                                                            'ajax' => array('type'=>'POST',
                                                                                'url'=>CHtml::normalizeUrl(array('/Comun/BusquedaTipoCreditos')), //url to call.
                                                                                'beforeSend'=>'function(xkr){'
                                                                                . ' $("#'.CHtml::activeId($model,'id_tipo_credito').'").empty();'
                                                                                . ' $("#'.CHtml::activeId($model,'id_tipo_credito').'").append(\'<option value="">...Seleccione...</option>\');'
                                                                                .'  $(".datosCredito").html("");
                                                                                    $(".detalle_capacidad_pago").remove();
                                                                                    $(".detalle_tabla_amortizacion").remove();
                                                                                    $("#mensajesSistema").html("");
                                                                                    $("#calculadoraHaberes").empty();
                                                                                    $(".afianzadora").hide();
                                                                                    $("#recibo_pago").hide(); 
                                                                                    $("#'.CHtml::activeId($model,'id_titulo_tipo_credito').'").prop("disabled", true);
                                                                                    $("#'.CHtml::activeId($model,'id_tipo_credito').'").prop("disabled", true);'
                                                                                . '}',
                                                                                'error'=>'function (xhr, ajaxOptions, thrownError) {
                                                                                    $("#'.CHtml::activeId($model,'id_titulo_tipo_credito').'").prop("disabled", false);
                                                                                    $("#'.CHtml::activeId($model,'id_tipo_credito').'").prop("disabled", false);
                                                                                }',
                                                                                'success'=>'function (data) {
                                                                                    $("#'.CHtml::activeId($model,'id_titulo_tipo_credito').'").prop("disabled", false);
                                                                                    $("#'.CHtml::activeId($model,'id_tipo_credito').'").prop("disabled", false);
                                                                                    $("#'.CHtml::activeId($model,'id_tipo_credito').'").html(data);
                                                                                }',
                                                                                'data'=>array('id_titulo_tipo_credito'=>'js:this.value','cedula'=>'js:$("#'.CHtml::activeId($model, 'cedula').'").val()'),
                                                                            ))); ?><br>
                                        <?php echo $form->error($model,'id_titulo_tipo_credito'); ?></td>
            <td style="width: 20%"><?php echo $form->labelEx($model,'id_tipo_credito'); ?></td>
            <td style="width: 30%"><?php echo $form->dropDownList($model,'id_tipo_credito',  CHtml::listData(TipoCredito::model()->findAll(array('condition'=>'publicar = TRUE AND id_titulo_tipo_credito=:id_titulo_tipo_credito','order'=>'descripcion asc',
                                                                                                                                                'params'=>array(':id_titulo_tipo_credito'=>(int)$model->id_titulo_tipo_credito))), 'id', 'descripcion'),
                                                                    array('onchange'=>'tipoCreditoCaracteristica()','prompt' => 'Seleccione ')); ?><br>
                                        <?php echo $form->error($model,'id_tipo_credito'); ?></td>
        </tr>
        
        <tr>
            <td colspan="4" id="calculadoraHaberes" class="datosCredito" style="display: none"></td>
        </tr>
        <tr>
            <td colspan="3"><b>Monto máximo permitido</b></td>
            <td><div id="monto_sugerido" class="datosPersonales datosCredito"></div></td>
        </tr>
        <?php if($post ==  true && count($modelCapacidadPago)>0){ ?>
                <tr class="detalle_capacidad_pago">
                    <td colspan="2"><b>Descripci&oacute;n</b></td>
                    <td><b>Asignaci&oacute;n</b></td>
                    <td><b>Deducciones</b></td>
                </tr>

                <?php   foreach ($modelCapacidadPago as $key => $value) {?>
                    <tr class="detalle_capacidad_pago">
                        <td colspan="2"><b><?php echo $value->nombre_concepto; ?></b></td>
                        <td><?php echo ($value->asignacion)?' Bs.' .$form->textField($value,"[$key]monto",array('style'=>'text-align:right','onChange'=>'calcularCapacidadPago();' ,'class'=>'span2 campo_asignacion')):""; ?><br>
                        <?php echo ($value->asignacion)?$form->error($value,"[$key]monto"):""; ?></td>
                        <td><?php echo (!$value->asignacion)?' Bs.' .$form->textField($value,"[$key]monto",array('style'=>'text-align:right','onChange'=>'calcularCapacidadPago();','class'=>'span2 campo_deduccion')):""; ?><br>
                        <?php echo (!$value->asignacion)?$form->error($value,"[$key]monto"):""; ?></td>
                    </tr>
                <?php }
           
                if(count($modelCapacidadPago)>0){?>
                    <tr class="detalle_capacidad_pago">
                        <td colspan="2"><b>Totales</b></td>
                        <td style="text-align: left"><div id="total_asignacion" class="campo_asignacion"></div></td>
                        <td style="text-align: left"><div id="total_deducciones" class="campo_deduccion"></div></td>
                    </tr>
                   <?php }?>

                   <?php  foreach (Credito::model()->findAll('idasociado=:idasociado',array(':idasociado'=>$model->idasociado)) as $key => $value) {?>            
                        <tr class="detalle_capacidad_pago">
                            <td colspan="2">Cuota mensual del prestamos "<b><?php echo $value->idTipoCredito->descripcion; ?></b>"</td>
                            <td></td>
                            <td style="text-align: left" class="monto_haberes_comprometido">Bs. <?php echo Yii::app()->format->number($value->cuota_pagar) ?></td>

                        </tr>
                    <?php } ?>
                            <tr class="detalle_capacidad_pago">
                        <td><b>Sueldo integral</b></td>
                        <td><div id="sueldo_integral"></div></td>
                        <td><b>33% del descunto integral</b></td>
                        <td><div id="porcentaje_sueldo"></div></td>
                    </tr>
                            <tr class="detalle_capacidad_pago">
                        <td><b>Monto total comprometido mensual</b></td>
                        <td><div id="total_prestamos"></div></td>
                        <td><b>% en pr&eacute;stamos mensual</b></td>
                        <td><div id="porcentaje_total_prestamos"></div></td>
                    </tr>
                            <tr class="detalle_capacidad_pago">
                        <td><b>Monto disponible para comprometer hasta el 33%</b></td>
                        <td><div id="total_disponible"></div></td>
                        <td><b>% del monto disponible</b></td>
                        <td><div id="porcentaje_total_disponible"></div></td>
                    </tr>
                <?php }?>
        
    </table>
    <table class="table table-bordered" id="recibo_pago" style ="display:<?php echo ($post)?"block":"none"?>">
        <tr>
            <td style="width: 25%"><b><?php echo $form->labelEx($model,'nombre_recibo_pago'); ?></b></td>
            <td style="width: 75%"> 	<?php echo $form->fileField($model,'nombre_recibo_pago',array('class'=>'file file-loading','data-show-caption'=>true)); ?>
                                        <?php echo $form->error($model,"nombre_recibo_pago"); ?>
            </td>
        </tr>
    </table>

</fieldset>
<fieldset><legend style=" font-size: 17px;"><b>Datos del préstamo</b></legend>            
<table class="table table-bordered" id="datos_prestamos">
        <tr>
            <td style="width: 25%"><b><?php echo $form->labelEx($model,'cuenta'); ?> </b></td>
            <td style="width: 25%"> 
                <?= $form->dropDownList($model,'cuenta',
                        CHtml::listData(AsociadoCuentaBanco::model()->with(['idBanco','idAsociado'])->together(true)->findAll([
                                    'select'=>"t.cuenta_bancaria AS id, \"idBanco\".descripcion ||''|| (CASE WHEN cuenta_corriente = true THEN 'Cuenta Corriente' ELSE 'Cuenta de Ahorro' END)||' '|| \"t\".cuenta_bancaria as cuenta_bancaria",
                                    'condition'=>'cedula=:cedula AND id_estatus=1 AND t.blnborrado = false',
                                    'params'=>[':cedula'=>$model->cedula]]),'id','cuenta_bancaria'),['style'=>"width:90%",'prompt'=>'-- SELECCIONE EL NUMERO DE CUENTA BANCARIO --']);
                    ?><br>                  
                <?php echo $form->error($model,'cuenta');?>

            </td>
            <td style="width: 30%"><?php echo $form->labelEx($model,'fecha_solicitud') ;?></td>
            <td style="width: 20%"><?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
                                        'model' => $modelSeguimientoCredito,
                                        'attribute' => 'fecha_registro',
                                        'value' => $modelSeguimientoCredito->fecha_registro,
                                        'language' => 'es',
                                        'htmlOptions' => array('readonly' => "readonly", 'class' => 'input-xlarge'),
                                        //additional javascript options for the date picker plugin
                                        'options' => array(
                                            'autoSize' => true,
                                            // 'defaultDate'=>$model->fechanacimiento,
                                            //'dateFormat'=>'yy-m-d',
                                            'dateFormat' => 'dd-mm-yy',
                                            'buttonImage' => Yii::app()->baseUrl . '/images/calendar.png',
                                            'buttonImageOnly' => true,
                                            'buttonText' => 'Fecha',
                                            'selectOtherMonths' => true,
                                            'showAnim' => 'slide',
                                            'showButtonPanel' => true,
                                            'showOn' => 'button',
                                            'changeMonth' => 'true',
                                            'changeYear' => 'true',
                                            'maxDate'=> "+0D",
                                        ),
                                    ));
                              ?>
                              <?php echo $form->error($modelSeguimientoCredito,'fecha_registro') ;?></td>
        </tr>
        <tr>
            <td><b><?php echo $form->labelEx($model,'id_tipo_cobro'); ?> </b></td>
            <td> 
                <?= $form->dropDownList($model,'id_tipo_cobro',
                        CHtml::listData(TipoCobro::model()->findAll(['order'=>"descripcion",]),'id','descripcion'),['style'=>"width:90%",'prompt'=>'-- SELECCIONE EL TIPO DE COBRO --']);
                    ?><br>                  
                <?php echo $form->error($model,'id_tipo_cobro');?>

            </td>
            <td>
                    ¿Cuotas manuales? <?= $form->checkBox($model,"cuotas_manuales",
                  array('data-toggle'=>'toggle',
                      'data-onstyle'=>"success", 'data-offstyle'=>"danger",
                      'data-on'=>"<b>Si</b> <i class=\"icon-ok-sign\"></i>",
                      'data-off'=>"<b>No</b> <i class=\"icon-remove\"></i>")
                  );?>
                    <div id="numero_cuotas" style="display: <?= $model->cuotas_manuales? 'block':'none'?>"><br>
                      <?php echo $form->textfield($model,'numero_cuotas') ;?>
                      <?php echo $form->error($model,'numero_cuotas') ;?>
                        
                    </div>
                      
            </td>
            <td>  <?= $form->labelEx($model,"omitir_evaluacion_capacidad_pago")?><?= $form->checkBox($model,"omitir_evaluacion_capacidad_pago",
                  array('data-toggle'=>'toggle',
                      'data-onstyle'=>"success", 'data-offstyle'=>"danger",
                      'data-on'=>"<b>Si</b> <i class=\"icon-ok-sign\"></i>",
                      'data-off'=>"<b>No</b> <i class=\"icon-remove\"></i>")
                  );?>
            </td>
        </tr>
        <tr>
            <td><?= $form->labelEx($model,"omitir_monto_maximo_permitido")?> </td>
            <td>  <?= $form->checkBox($model,"omitir_monto_maximo_permitido",
                  array('data-toggle'=>'toggle',
                      'data-onstyle'=>"success", 'data-offstyle'=>"danger",
                      'data-on'=>"<b>Si</b> <i class=\"icon-ok-sign\"></i>",
                      'data-off'=>"<b>No</b> <i class=\"icon-remove\"></i>")
                  );?>
            </td>
            <td style="width: 20%"><div class="desicionCuotasEspeciales" style="display:<?php echo ($modelPermitirCuotasEspeciales!=0)?"block":"none"?>">Calcular con cuotas especiales</div></td>
            <td style="width: 30%"><div class="desicionCuotasEspeciales" style="display:<?php echo ($modelPermitirCuotasEspeciales!=0)?"block":"none"?>"> <?php echo $form->radioButtonList($model, 'generar_tabla_cuotas_especiales', array(
                                                        '1'=>'SI',
                                                        '0'=>'NO', 
                                                       )); ?></div></td>
        </tr>
        <tr id="bloqueo_anticipado_prestamos">
            <td>Bloqueo anticipado de préstamos</td>
            <td>
                <?= $form->checkBox($model, 'bloqueo_anticipado_prestamos', [
                    'data-toggle' => 'toggle',
                    'data-onstyle' => "success",
                    'data-offstyle' => "danger",
                    'data-on' => "<b>Si</b> <i class=\"icon-ok-sign\"></i>",
                    'data-off' => "<b>No</b> <i class=\"icon-remove\"></i>",
                    'style' => 'width: 50px; height: 20px;',
                ]); ?>
            </td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td style="width: 25%"><b><?php echo $form->labelEx($model,'monto_credito'); ?></b></td>
            <td style="width: 25%"> 
                <div style="display:table">
                    <div style="float:left; width: 60%;" class="input-append">
                        <?php echo  $form->textfield($model,'monto_credito',array('style'=>'text-align:right','readOnly'=>((!$model->isNewRecord)?'readOnly':NULL))) ;?>

                        <?php echo CHtml::htmlButton('<i class="icon-ok-sign"></i>&nbsp;&nbsp;<b>Calcular</b>', [
                            'type' => "button",
                            'id' => 'btn_calcular',
                            'class' => 'btn btn-success icon button',
                            'onClick' => 'buscarTablaAmortizacion()'
                        ]) ?>
                        
                    </div>
                    <div style="width: 100%;" >
                        
                        <?php echo  $form->error($model,'monto_credito') ;?>
                        
                    </div>
                </div>


            </td>
            <td><b class="afianzadora" style="display: <?= ($model->id_afianzadora!='')?'block':'none'?>">Afianzadora:</b></td>
            <td><div class="afianzadora" style="display: <?= ($model->id_afianzadora!='')?'block':'none'?>"><?= $form->dropDownList($model,'id_afianzadora',
                        CHtml::listData(Afianzadora::model()->findAll(['order'=>"descripcion",]),'id','descripcion'),['style'=>"width:90%",'prompt'=>'-- SELECCIONE LA AFIANZADORA --']);
                    ?></div></td>
        </tr>
    </table>
</fieldset>
<div id="error_submit"></div>



    <div id='detalle_tsabla_amortizacion'></div>
     <div class="form-actions"  style="text-align: center">
        <?php $this->widget('bootstrap.widgets.TbButton', array(
			'buttonType' => 'submit',
			'type' => 'success',
            'icon'=>'icon-ok',
			'label' => 'Solicitar préstamo',
            'htmlOptions' => ['id' => 'btn_registrar'],
    ));?>
</div>

<?php $this->endWidget(); ?>
<?php 
    Yii::app()->clientScript->registerScript('tablaAmortizacion1', '
    $(document).on("ready", function (e) {
        $("#bloqueo_anticipado_prestamos").hide();
    });

        var monto_haberes_socio = 0;
           
        function consultarTablaAmortizacionPost(){
            
            calcularCapacidadPago();
            datosPersonalesCredito();
            buscarTablaAmortizacion();
        }
        
	var datosPostDatos = '.(($postDatos)?1:0).';	
        function datosPersonalesCredito(){
            var cedula = $("#'.CHtml::activeId($model,"cedula").'").val();
            if(!datosPostDatos){
            
                $("#'.CHtml::activeId($model,'id_titulo_tipo_credito').'").empty();
                $("#'.CHtml::activeId($model,'id_titulo_tipo_credito').'").append(\'<option value="">...Seleccione...</option>\');
                $("#'.CHtml::activeId($model,'id_tipo_credito').'").empty();
                $("#'.CHtml::activeId($model,'id_tipo_credito').'").append(\'<option value="">...Seleccione...</option>\');
            }
            $("#'.CHtml::activeId($model,'cuenta').'").val("");  
            $("#'.CHtml::activeId($model,'cuenta').'").empty(); 
            $("#'.CHtml::activeId($model,'cuenta').'").append(\'<option value="">- SELECCIONE EL NUMERO DE CUENTA BANCARIO --</option>\'); 
            if($.isNumeric(cedula)&& cedula>6){
                $.ajax({
                        url:"'.CController::createUrl('/Comun/DatosPersonalesPrestamos').'",
                        cache: false,
                        type: "POST",
                        dataType: "json",
                        data: ({cedula:cedula}),
                        beforeSend: function(xkr){
                            $(".datosPersonales").html("");
                            $("#mensajesSistema").html("");
                            $("#error_submit").html("");
                            
                            $("#btn_buscar_datos_personales").prop("disabled", true);
                            $(".datosPersonales").html(`<div style="text-align: center;"><i class="fa fa-spinner fa-spin" style="font-size:29px;"></i></div>`);
                            
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            $(".datosPersonales").html("");
                            $("#btn_buscar_datos_personales").prop("disabled", false);
                        },
                        success: function(data){

                            $("#btn_buscar_datos_personales").prop("disabled", false);
                            $(".datosPersonales").html("");
                                if(data.error==0) {
                                    $("#nombres_apellidos").html(data.nombres_apellidos);
                                    $("#empresa").html(data.empresa);
                                    $("#unidad").html(data.unidad);
                                    $("#sueldo").html("Bs. "+data.sueldo);
                                    $("#porcentaje").html(data.porcentaje);
                                    $("#fecha_inscripcion").html(data.fecha_inscripcion);
                                    $("#estatus").html(data.estatus);  
                                    if(!datosPostDatos){
                                        buscarCuentaBanco(cedula);
                                        $("#'.CHtml::activeId($model,'id_titulo_tipo_credito').'").append(data.titulos_tipo_prestamos);                                  
                                    }
                                    
                                                                      
                                }
                                else{
                                    $("#mensajesSistema").html(data.mensajeError);
                                    $(".datosCredito").html("");
                                    $(".detalle_tabla_amortizacion").remove();
                                    $("#recibo_pago").hide(); 
                                    $(".detalle_capacidad_pago").remove();
                                    $("#calculadoraHaberes").empty();
                                }
                        }
                });
                datosPostDatos= 0;
        }
        else{
            $(".datosCredito").html("");
            $(".detalle_capacidad_pago").remove();
            $(".detalle_tabla_amortizacion").remove();
            $(".datosPersonales").html("");
            $("#mensajesSistema").html("");                        
            $(".desicionCuotasEspeciales").hide();
        }

    };
    var datosPost = '.(($post)?1:0).';
    function tipoCreditoCaracteristica(){
        var cedula=$("#'.Chtml::activeId($model,'cedula').'").val();
        var idTipoCredito  = $("#'.CHtml::activeId($model,'id_tipo_credito').'").val();
        var idTituloTipoCredito  = $("#'.CHtml::activeId($model,'id_titulo_tipo_credito').'").val();
        $("#calculadoraHaberes").empty();
        if(cedula != "") {
            if(idTituloTipoCredito != "") {
    			if ($.isNumeric(cedula) && cedula>6) {
    				if (idTipoCredito != "") {
    					$.ajax({
                            url:"'.CController::createUrl('TipoCreditoCaracteristica').'",
                            cache: false,
                            type: "POST",
                            dataType: "json",
                            data: ({cedula:cedula,idTipoCredito:idTipoCredito}),
                            beforeSend: function(xkr){
                                    $(".datosCredito").html("");
                                    if(!datosPost){
                                        $(".detalle_capacidad_pago").remove();
                                    }
                                    monto_haberes_socio = 0;
                                    //datosPost=0;
                                    $(".detalle_tabla_amortizacion").remove();
                                    $("#mensajesSistema").html("");
                                    $("#recibo_pago").hide();
                                    $(".desicionCuotasEspeciales").hide();
                                    $("#error_submit").html("");
                                    $("#calculadoraHaberes").empty();
                                    $("#'.CHtml::activeId($model,'id_titulo_tipo_credito').'").prop("disabled", true);
                                    $("#'.CHtml::activeId($model,'id_tipo_credito').'").prop("disabled", true);
                                    $("#calculadoraHaberes").show();
                                    $("#calculadoraHaberes").html(`<div style="text-align: center;"><i class="fa fa-spinner fa-spin" style="font-size:29px;"></i></div>`);
                                    $("#bloqueo_anticipado_prestamos").hide();
                                },
                                error : function (xhr, ajaxOptions, thrownError) {
                                    $("#'.CHtml::activeId($model,'id_titulo_tipo_credito').'").prop("disabled", false);
                                    $("#'.CHtml::activeId($model,'id_tipo_credito').'").prop("disabled", false); 
                                    $("#calculadoraHaberes").hide();
                                    $("#calculadoraHaberes").html("");
                                    $("#bloqueo_anticipado_prestamos").hide();
                                },
                                success: function(data){
                                    $("#calculadoraHaberes").hide();
                                    $("#calculadoraHaberes").html("");
                                    $("#'.CHtml::activeId($model,'id_titulo_tipo_credito').'").prop("disabled", false);
                                    $("#'.CHtml::activeId($model,'id_tipo_credito').'").prop("disabled", false);
                                if(data.error == 0) {
                                    $("#btn_registrar").prop("disabled", false);
                                    $("#btn_calcular").prop("disabled", false);
                                    $("#monto_sugerido").html(data.monto_sugerido);
                                    if(!datosPost){
                                       $("#datos_prestamos_calculadora").append(data.detalle_capacidad_pago);
                                    }
                                    if(data.mostrar_recibo_pago==1){
                                        $("#recibo_pago").show();
                                    }

                                    $("#calculadoraHaberes").empty();
                                    $("#calculadoraHaberes").show();
                                    $("#calculadoraHaberes").html(data.calculadoraHaberes);

                                    datosPost=0;
                                    porcentaje_capacidad_pago = data.porcentajeCapacidadPago;

                                    monto_haberes_socio = data.monto_haberes_socio;

                                    if(data.mostrar_afinazadoras == 1)$(".afianzadora").show();
                                     $("#'.Chtml::activeId($model, 'id_tipo_cobro').'").val(data.id_tipo_cobro);
                                    // ejecutamos el evento change()
                                    $("#'.Chtml::activeId($model, 'id_tipo_cobro').'").change();
                                    if(data.permitirDesicionCuotasEspeciales == 1) {
                                        $(".desicionCuotasEspeciales").show();
                                    }

                                    if (data.bloqueo_anticipado_prestamos) {
                                        $("#bloqueo_anticipado_prestamos").show();
                                    } else {
                                        $("#bloqueo_anticipado_prestamos").hide();
                                    }
                                } else {
                                    $("#btn_registrar").prop("disabled", true);
                                    $("#btn_calcular").prop("disabled", true);
                                    $("#calculadoraHaberes").empty();
                                    $("#calculadoraHaberes").show();
                                    $("#calculadoraHaberes").html(data.mensajeError);
                                }
                            }
    					});
    				} else {
                        $(".datosCredito").html("");
                        $(".detalle_capacidad_pago").remove();
                        $(".detalle_tabla_amortizacion").remove();
                        $(".desicionCuotasEspeciales").hide();
    				}
    			} else {
    				alert("Cédula debe ser un número o mayor de 6 caracteres");
                    $(".datosCredito").html("");
                    $(".detalle_capacidad_pago").remove();
    			}
            }
        } else {
            $(".datosCredito").html("");
            $(".detalle_capacidad_pago").remove();
            $(".detalle_tabla_amortizacion").remove();
            $("#mensajesSistema").html("");
        }
    }
    
function buscarCuentaBanco(idasociado){    
      datas="ci="+idasociado;
        $.ajax({
                type: \'POST\',
                url: \''.Yii::app()->createAbsoluteUrl("/Comun/BuscarCuentaBanco").'\',
                data:datas,
                beforeSend: function(xkr){
                    $("#'.CHtml::activeId($model,'cuenta').'").empty(); 
                    $("#'.CHtml::activeId($model,'cuenta').'").append(\'<option value="">- SELECCIONE EL NUMERO DE CUENTA BANCARIO --</option>\'); 
                            },
      success:function(data) {
        $("#'.CHtml::activeId($model,'cuenta').'").html(data);return false;
      },
      error: function(data) { // if error occured
        alert("Ha ocurrido un error , Contacte con el administrador");
      },
      dataType:\'html\'
    });
    
  

    }
 function buscarTablaAmortizacion(){
        var cedula=$("#'.Chtml::activeId($model,'cedula').'").val();
        var idTipoCredito  = $("#'.CHtml::activeId($model,'id_tipo_credito').'").val();
        var montoCredito  = $("#'.CHtml::activeId($model,'monto_credito').'").val();
        var numeroCuotas  = $("#'.CHtml::activeId($model,'numero_cuotas').'").val();
        var omitirEvaluacion  = $("#'.CHtml::activeId($model,'omitir_evaluacion_capacidad_pago').'").prop(\'checked\')?1:0;
        var omitirMaximo  = $("#'.CHtml::activeId($model,'omitir_monto_maximo_permitido').'").prop(\'checked\')?1:0;
        var generar_cuotas_especiales  = $(\'input:radio[name="Credito[generar_tabla_cuotas_especiales]"]:checked\').val();
        var id_afianzadora  =  $("#'.CHtml::activeId($model,'id_afianzadora').'").val();
        var bloqueo_anticipado = $("#'.CHtml::activeId($model,'bloqueo_anticipado_prestamos').'").prop(\'checked\') ? 1 : 0;

        if(id_afianzadora =="")
           id_afianzadora =0;

        var capacidad_pago = 0;
        if ( $("#total_disponible").length ) {
            var capacidad_pago = $("#total_disponible").html();
            capacidad_pago = capacidad_pago.trim();
            capacidad_pago = capacidad_pago.replace("Bs. ", "");
            capacidad_pago = capacidad_pago.replace("&nbsp;", "");
            capacidad_pago = capacidad_pago.replace(/\./g,"").replace(/,/g,".");
        }
        
        if(numeroCuotas!= "" ){
            if(!$.isNumeric(numeroCuotas) && numeroCuotas<1){
                alert("El valor debe ser un numero entero");
                return false
            }
        }
        $(".detalle_tabla_amortizacion").remove();    
        if(($.isNumeric(capacidad_pago) && capacidad_pago>0)||omitirEvaluacion ==1) {
        
            if(cedula!="" && $.isNumeric(cedula) && cedula>6) { 
                if(idTipoCredito!=""){
                    $.ajax({
                            url:"'.CController::createUrl('tablaAmoritzacionAdministrador').'",
                            cache: false,
                            type: "POST",
                            dataType: "json",
                            data: ({
                                idTipoCredito,
                                montoCredito,
                                cedula,
                                capacidad_pago,
                                generar_cuotas_especiales,
                                monto_haberes_socio,
                                numeroCuotas,
                                omitirEvaluacion,
                                omitirMaximo,
                                id_afianzadora,
                                bloqueo_anticipado
                            }),

                            beforeSend: function(xkr){
                                $(".detalle_tabla_amortizacion").remove();
                                $("#error_submit").html("");
                                $("#datos_prestamos").append(
                                        `<tr id = "cargando-tabla-amortizacion">
                                            <td colspan="4">
                                                <div style="text-align: center;">
                                                    <i class="fa fa-spinner fa-spin" style="font-size:29px;"></i>
                                                </div>
                                            </td>
                                        </tr>`
                                 ); 
                                $("#btn_calcular").prop("disabled", true);

                            },
                            error: function (xhr, ajaxOptions, thrownError) {
                                $("#btn_calcular").prop("disabled", false);
                                 $("#cargando-tabla-amortizacion").remove();
                            },
                            success: function(data){
                                $("#btn_calcular").prop("disabled", false);
                                $("#cargando-tabla-amortizacion").remove();
                                    if(data.error==0) {                                
                                        $("#datos_prestamos").append(data.encabezado_tabla_amoritzacion);
                                        $("#btn_registrar").prop("disabled", false);                                        

                                    }
                                    else{
                                        var html = "<tr class=\"detalle_tabla_amortizacion\">\
                                                        <td colspan=\"4\">"+data.mensajeError+"</td>\
                                                    </tr>";
                                        if(data.mensajeError!="")
                                            $("#datos_prestamos").append(html); 
                                    }
                            }
                    });
                }
                else{                                            
                    $(".datosCredito").html("");
                    $(".detalle_capacidad_pago").remove();
                    $(".detalle_tabla_amortizacion").remove();
                }
            }
            else{
                $(".datosCredito").html("");
                $(".detalle_capacidad_pago").remove();
                $(".detalle_tabla_amortizacion").remove();
            }
        }
        else{
            var html = "<tr class=\"detalle_tabla_amortizacion\">\
                        <td colspan=\"4\"><div class=\"alert alert-warning\"><i class=\"icon-info-sign\"></i>El asociado no posee capacidad de pago para solictar préstamo</div></td>\
                        </tr>";
            $("#datos_prestamos").append(html); 
        }
    };
	var globalDeducciones = 0;
	var globalAsignaciones = 0;
	var porcentaje_sueldo = 0;
	var porcentaje_capacidad_pago = 0.33;
    function calcularCapacidadPago(){
        globalAsignaciones =0;
        $(".campo_asignacion").each(
            function(index, value) {
                var numero = $(this).val();
                numero = numero.replace(/\./g,"").replace(/,/g,".");							
                if($.isNumeric(numero)){						
                    globalAsignaciones = globalAsignaciones +  eval(numero);
                }	
                else
                    $(this).val(0);
        });

        $("#total_asignacion").html("Bs. "+convertNumberFloatZero(globalAsignaciones)) ;
        $("#sueldo_integral").html("Bs. "+convertNumberFloatZero(globalAsignaciones)) ;
        porcentaje_sueldo = globalAsignaciones.toFixed(2)*porcentaje_capacidad_pago;
        $("#porcentaje_sueldo").html("Bs. "+convertNumberFloatZero(porcentaje_sueldo)) ;       
    
        globalDeducciones =0;
        $(".campo_deduccion").each(
            function(index, value) {
                var numero = $(this).val();
                numero = numero.replace(/\./g,"").replace(/,/g,".");							
                if($.isNumeric(numero)){						
                    globalDeducciones = globalDeducciones +  eval(numero);						
                }
                else
                    $(this).val(0);
            });
        
        $("#total_deducciones").html("Bs. "+globalDeducciones.toFixed(2)) ;		
            $(".monto_haberes_comprometido").each(function(){
                var numero = $(this).html();
                numero = numero.trim();
                numero = numero.replace("Bs. ", "");
                numero = numero.replace("&nbsp;", "");
                numero = numero.replace(/\./g,"").replace(/,/g,".");
                globalDeducciones = globalDeducciones +  eval(numero);	
            });
            $("#total_deducciones").html("Bs.  "+convertNumberFloatZero(globalDeducciones)) ;
            $("#total_prestamos").html("Bs.  "+convertNumberFloatZero(globalDeducciones)) ;

            calculadorHaberes();		
        }
	
	function calculadorHaberes(){
            if(globalAsignaciones>0){
                var porcentaje_total_prestamos = (globalDeducciones.toFixed(2) *100/eval(globalAsignaciones));
                $("#porcentaje_total_prestamos").html(convertNumberFloatZero(porcentaje_total_prestamos)+"%") ;

                var monto_total_disponible = eval(porcentaje_sueldo)-globalDeducciones.toFixed(2);
                $("#total_disponible").html("Bs. "+convertNumberFloatZero(monto_total_disponible)) ;

                var porcentaje_total_disponible = (porcentaje_capacidad_pago*100)-porcentaje_total_prestamos.toFixed(2);
                $("#porcentaje_total_disponible").html(convertNumberFloatZero(porcentaje_total_disponible)+"%") ;
            }
	}

    function comparaMontos(){
        
        var m_credito = $("#'.CHtml::activeId($model,'monto_credito').'").val();
        m_credito = eval(m_credito.replace(/\./g,"").replace(/,/g,"."));

        var m_financiar = $("#monto_financiar").html();
        m_financiar = m_financiar.trim();
        m_financiar = m_financiar.replace(" Bs.", "");
        m_financiar = eval(m_financiar.replace(/\./g,"").replace(/,/g,"."));

        if (m_credito !== m_financiar) {
            $("#error_submit").html("<span class=\"help-inline error\">Debe dar click en el boton <b>Calcular</b>, para generar la nueva tabla!</span>");
            return false;
        }else{

            $("#error_submit").html("");
            return true;
        }

        //return false;
    }
        



  function convertNumberFloatZero(number){
	if(!$.isNumeric(number)){
		return \'NaN\';
	}
	var numberFloat = number.toFixed(3);
	var splitNumber = numberFloat.split(".");
	var cNumberFloat = number.toFixed(2);
	var cNsplitNumber = cNumberFloat.split(".");
	var lastChar = splitNumber[1].substr(splitNumber[1].length - 1);
	if(lastChar > 0 && lastChar < 5){
		cNsplitNumber[1]--;
	}
	return Number(splitNumber[0]).toLocaleString(\'es\').concat(\',\').concat(cNsplitNumber[1]);
  }
        
        $(\'.campo_asignacion\').mask(\'#.##0,00\', {reverse: true});
        $(\'.campo_deduccion\').mask(\'#.##0,00\', {reverse: true});
        $(\'#'.CHtml::activeId($model,'monto_credito').'\').mask(\'#.##0,00\', {reverse: true});

	',CClientScript::POS_HEAD);
	Yii::app()->clientScript->registerScript('tablaAmortizacion2','
        $("#'.CHtml::activeId($model,'cuotas_manuales').'").change(function(){
            if($(this).prop(\'checked\')){
                $("#numero_cuotas").show("slow");
            }
            else
                $("#numero_cuotas").hide("slow");
        });
			$(document).ready(function() {
                            $(\'.campo_asignacion\').mask(\'#.##0,00\', {reverse: true});
                            $(\'.campo_deduccion\').mask(\'#.##0,00\', {reverse: true});
                            
                            $("form").keypress(function(e) {
                                if (e.which == 13) {
                                    return false;
                                }
                            });
                            if($("#'.Chtml::activeId($model,'cedula').'").val()!=""){
                                    consultarTablaAmortizacionPost();
                            }

                            $("#btn_registrar").prop("disabled", true);
                            $("#error_submit").html("");
			});
	');

?>
