<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl.'/js/jquery.mask.min.js',CClientScript::POS_HEAD); ?>


<h3><center>Solicitud de Montepio</center></h3>

<div class="alert alert-info"><i class="icon-info-sign"></i> Solo se pueden generar solicitudes de montepio para asociados con estatus <strong>"FALLECIDO"</strong>.</div>

<?php
    foreach(Yii::app()->user->getFlashes() as $key => $message) {
        echo '<div class="alert alert-' . $key . '">' . $message . "</div>\n";
    }
?>
	
	<?php
	$form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
			'id'=>'solicitudmp-form',
			'type' => 'horizontal',
	        'enableAjaxValidation' => false,
	        'enableClientValidation' => true,
	        'clientOptions' => array(
	        'validateOnSubmit' => true,
	        'validateOnChange' => true,
	        'validateOnType' => true,
        ),
	    'htmlOptions' => array('onsubmit' => 'return verificarCheckbox()'),
		));
	?>
	<br>
	<fieldset>  <!--Datos del asociado-->
		<legend style=" font-size: 17px;"><b>Datos del asociado</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 class="input-append">
					<?php echo $form->textField($model,'cedula',array('maxlength'=>'10')); ?>
					<?php $this->widget('bootstrap.widgets.TbButton',
			        	array(
							'buttonType' => 'button',
							'type' => 'primary',
				            'icon'=>'icon-search icon-white',
							'htmlOptions' => array(
											'onclick' => 'findData()',
											'id' => 'btn-datos',
											),
						)
			    	);?>
					<!--<button class="btn btn-primary" id="btn-datos" type="button" onclick="findData()">Buscar</button>-->
				</div>
	             
	                                    <div id="mensajesSistema"  class="datosPersonales"></div>
	                                    <?php echo $form->error($model, "cedula"); ?></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><b>Fecha de fallecimiento</b></td>
	            <td><div id="fecha_fallece" class="datosPersonales"></div></td>
	            <td><b>Fecha l&iacute;mite para Solicitud</b></td>
	            <td><div id="fecha_limite" class="datosPersonales"></div></td>
	        </tr>
	        <tr>
	            <td colspan="4" id="calculadoraHaberesSocio" class="datosCredito" style="display: none"></td>
	        </tr>	        
	    </table>
	</fieldset> <!--fin datos del beneficiario-->
	<div id="diverror"></div>
	<div id="mensaje_flimite"></div>


	<div id="solicitud_cargada">
		<div id="nobenef"></div>   <!--formulario de registro de beneficiario-->
		<br>

		<div>
			<?php $this->widget('bootstrap.widgets.TbButton',
				        	array(
								'buttonType' => 'button',
								'type' => 'primary',
					            'icon'=>'icon-plus icon-white',
					            'label' => 'Nuevo Beneficiario',
								'htmlOptions' => array(
												'onclick' => 'mostrarForm()',
												'id' => 'btn-bnf',
												),
							)
			);?>
			<!--<button class="btn btn-primary" id="btn-bnf" type="button" onclick="mostrarForm()">Registrar Beneficiario</button>-->
		</div>

		<br>
		<div class="cargarbnf" id="form-bnf">
			<fieldset>
				<legend>Nuevo Beneficiario</legend>

				<table class="table table-bordered ">
					<tr>

						<td style="width: 25%"><?php echo $form->labelEx($modelBeneficiario,'cedula'); ?></td>
						<td style="width: 25%"><?php echo $form->textField($modelBeneficiario,'cedula'); ?></td>

						<td style="width: 25%"><?php echo $form->labelEx($modelBeneficiario,'nombre'); ?></td>
						<td style="width: 25%"><?php echo $form->textField($modelBeneficiario,'nombre'); ?></td>
					</tr>

					<tr>
						<td style="width: 20%"><?php echo $form->labelEx($modelBeneficiario,'apellido'); ?></td>
						<td style="width: 30%"><?php echo $form->textField($modelBeneficiario,'apellido'); ?></td>

						<td style="width: 25%"><?php echo $form->labelEx($modelBeneficiario,'parentesco'); ?></td>
						<td style="width: 25%"><?php echo $form->dropDownList($modelBeneficiario,'parentesco',
																CHtml::listData(Parentesco::model()->findAll(),'idparentesco', 'descripcion'),
																	array('prompt'=>'Seleccione',)); ?></td>
					</tr>

					<tr>
						<td style="width: 20%"><?php echo $form->labelEx($modelBeneficiario,'fecha'); ?></td>
						<td style="width: 30%" colspan="3">
							<?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
		                                        'model' => $modelBeneficiario,
		                                        'attribute' => 'fecha',
		                                        'value' => $modelBeneficiario->fecha,
		                                        'language' => 'es',
		                                        'htmlOptions' => array('readonly' => "readonly", 'class' => 'input-xlarge', 'id'=>'fnacimiento'),
		                                        //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' => 'Escoger fecha',
		                                            'selectOtherMonths' => true,
		                                            'showAnim' => 'slide',
		                                            'showButtonPanel' => true,
		                                            'showOn' => 'button',
		                                            'changeMonth' => 'true',
		                                            'changeYear' => 'true',
		                                            'yearRange' => "1900:+nn",
		                                            'maxDate'=> "+0D",
		                                        ),
		                                    ));
		                              ?>
		                              <?php echo $form->error($modelBeneficiario,'fecha') ;?></td>
					</tr>
				</table>
				<div id="msgerror"></div>

			<?php $this->widget('bootstrap.widgets.TbButton',
				        	array(
								'buttonType' => 'button',
								'type' => 'primary',
					            'icon'=>'icon-ok icon-white',
					            'label' => 'Guardar Beneficiario',
								'htmlOptions' => array(
												'onclick' => 'guardarBeneficiario()',
												'id' => 'btn-benf',
												),
							)
			);?>
			<!--<button class="btn btn-primary" id="btn-benf" type="button" onclick="guardarBeneficiario()">Guardar Beneficiario</button>-->



			</fieldset>
		</div> <!--fin formulario de registro de beneficiario-->
		
		<br>
		<div id="msgtbl"></div>
		<div class="beneficiarios"></div> <!--Tabla de beneficiarios-->
		<div class="nocheck"></div>
		<div class="grid-benef">
			<fieldset>
	                <legend>Beneficiarios</legend>    
					
					
	                <?php  $this->widget('ext.selgridview.BootSelGridView', array(
	                	'type' => 'bordered',
	                    'id'=>'beneficiarios-grid',
	                    'dataProvider'=>$modelBeneficiario->searchBenefid($modelAsociado->idasociado),
	                    'selectableRows'=> 10,

	                    'columns'=>array(
	                            array(
	                            'id'=>'seleccion',
	                            'class' => 'CCheckBoxColumn',
	                            ),

	                            
	                            array('header'=>'Nombre','value'=>'($data->nombre)'),
	                            array('header'=>'Apellido','value'=>'($data->apellido)'),
	                            array('header'=>'Cédula','value'=>'($data->cedula)'),
	                            array('header'=>'Parentesco','value'=>'($data->parent->descripcion)'),


	                            array(
					                'class'=>'bootstrap.widgets.TbButtonColumn',
					                'deleteConfirmation' => '¿Desea eliminar este registro?',
					                'template' => '{delete}',
					                'buttons' => array(
					                    'delete' => array('label' => 'Eliminar',
					                        'url' => 'Yii::app()->controller->createUrl("/Beneficiario/Delete",array("id"=>$data->idbeneficiario))',
					                    ),
					                )
					            )
	                    ),
	                    )); ?>
	            </fieldset>
		<br>
		<div id="check-error"></div>

	    <?php if(Yii::app()->user->hasFlash('error')):?>
	    	<div class="alert alert-error">
	        	<i class="icon-remove"></i> <?php echo Yii::app()->user->getFlash('error'); ?>
	    	</div>
		<?php endif; ?>
		</div>
		<br>
		<fieldset>
			<legend>Solicitante</legend>
			<div id="solicitante">
				<?php echo $form->labelEx($model,'Solicitante'); ?>
				<?php echo $form->dropDownList($model,'id_beneficiario', CHtml::listData(Beneficiario::model()->findAll(), 'id', 'nombre'), array('prompt' => 'Seleccione ')); ?>
			</div>
		</fieldset>
		<br>

		<div class="form-actions"  style="text-align: center">
		        <?php $this->widget('bootstrap.widgets.TbButton',
		        	array(
						'buttonType' => 'submit',
						'type' => 'success',
			            'icon'=>'icon-ok',
						'label' => 'Realizar solicitud',
						'htmlOptions' => array(
										'onclick' => 'verificarCheckbox()',
										'id' => 'btn_regSolicitud',
										),
					)
		    	);?>
		
		</div>
	</div>

<?php $this->endWidget(); ?>

<br>	

<?php Yii::app()->clientScript->registerScript('datosSolicitud', '

	$(document).ready(function(){
	
		$("#form-bnf").hide();
		$("#btn-bnf").hide();
		$(".grid-benef").hide();
		$("#solicitud_cargada").hide();

		$("form").keypress(function(e) {
                                if (e.which == 13) {
                                    return false;
                                }
                            });

	});


	//muestra el formulario de registro de beneficiario
	function mostrarForm(){

		$("#form-bnf").toggle("slow");
	}

	
	//crear el nuevo beneficiario para el asociado cargado
	function guardarBeneficiario(){
		
		var cedula = $("#'.CHtml::activeId($modelBeneficiario, 'cedula').'").val();
		var nombre = $("#'.CHtml::activeId($modelBeneficiario, 'nombre').'").val();
		var apellido = $("#'.CHtml::activeId($modelBeneficiario, 'apellido').'").val();
		var parentesco = $("#'.CHtml::activeId($modelBeneficiario, 'parentesco').'").val();
		var fecha = $("#fnacimiento").val();
		var cedulaAsociado = $("#'.CHtml::activeId($model, 'cedula').'").val();
		
		 
		if (cedula!== "" && nombre!== "" && apellido!== "" && parentesco!== "") {

			
			$.ajax({

                    url:"'.CController::createUrl('Recdatos').'",
                    cache: false,
                    type: "POST",
                    dataType: "json",
                    data: ({cedula:cedula, nombre:nombre, apellido:apellido, parentesco:parentesco,cedulaAsociado:cedulaAsociado, fecha:fecha}),
					beforeSend: function(xkr){
							$("#msgtbl").html("");
							$("#msgerror").html("");
							$("#check-error").html("");
							$("#nobenef").html("");

							$("#'.CHtml::activeId($model,'id_beneficiario').'").empty();
        					$("#'.CHtml::activeId($model,'id_beneficiario').'").append(\'<option value="">...Seleccione...</option>\');
					},

                    success: function(data){
                        if (data.error==0) {
                            
                            $(".msgtbl").html("Registro Exitoso");
                           	$("#'.CHtml::activeId($modelBeneficiario, 'cedula').'").val("");
                           	$("#'.CHtml::activeId($modelBeneficiario, 'nombre').'").val("");
                           	$("#'.CHtml::activeId($modelBeneficiario, 'apellido').'").val("");
                           	$("#'.CHtml::activeId($modelBeneficiario, 'parentesco').'").val("");
                           	$("#fnacimiento").val("");
							$("#form-bnf").hide("0200");
							
							//actualiza el Combobox de solicitantes
							$("#'.CHtml::activeId($model,'id_beneficiario').'").append(data.bnfs);
							$("#nobenef").html(data.msg_combo);

							//actualiza la grilla
							$.fn.yiiGridView.update(\'beneficiarios-grid\');

                        }
                        else{
							$("#msgerror").html(data.msgerror);
                        }                        
                    }
            });
		
		}else{

			$("#msgtbl").html("");
			$("#msgerror").html("");
		}
	}

	//consultar datos de la cedula del asociado introducida
	function findData(){

                var cedula = $("#'.CHtml::activeId($model,'cedula').'").val();
                var tipo_sol = 1;

                var benef =  '.(($modelBeneficiario->idbeneficiario!='')?$modelBeneficiario->idbeneficiario:0).';

                $("#'.CHtml::activeId($model,'id_beneficiario').'").empty();
                $("#'.CHtml::activeId($model,'id_beneficiario').'").append(\'<option value="">...Seleccione...</option>\');


                if ($.isNumeric(cedula) && cedula>6) {					

                        $.ajax({

                                url:"'.CController::createUrl('FindData').'",
                                cache: false,
                                type: "POST",
                                dataType: "json",
                                data: ({cedula:cedula, tipo:tipo_sol}),
                                beforeSend: function(xkr){
                                        $(".datosPersonales").html("");
                            			$("#mensajesSistema").html("");
                            			$("#nobenef").html("");
                            			$(".beneficiarios").html("");
                            			$("#form-bnf").hide(1000);
										$(".grid-benef").hide();
                            			$("#diverror").hide();
                            			$("#check-error").html("");
                                           
                                        },

                                success: function(data){
                                    
                                    if(data.error==0) {

                                    	var registrado = data.registrado;

										if (registrado == 1) {
												
											$("#diverror").html(data.flash);
					                        $("#diverror").show();
					                        $("#solicitud_cargada").hide(0500);
					                        $("#mensaje_flimite").html("");

										}else{
                                    	
	                                    	var ruta ="'.Yii::app()->createAbsoluteUrl("montepio/solicitud/solicitud_mp").'";

	                                    	var flimite = data.fecha_limite_sol;

                                            $("#nombres_apellidos").html(data.nombre_apellido);
		                                    $("#empresa").html(data.empresa);
		                                    $("#unidad").html(data.unidad);
		                                    $("#sueldo").html("Bs. "+data.sueldo);
		                                    $("#porcentaje").html(data.porcentaje);
		                                    (data.fecha_inscripcion!==null)?$("#fecha_inscripcion").html(data.fecha_inscripcion):$("#fecha_inscripcion").html("NO REGISTRADA");
		                                    $("#fecha_fallece").html(data.fecha_fallece);
		                                    $("#fecha_limite").html(flimite);
		                                    
		                                    $("#estatus").html(data.estatus);
		                                    $("#nobenef").html(data.nobenef);
											
											if (data.esconder == 0) {
													
												if (registrado == 0) {
														
													$("#diverror").html("");
					                                $("#diverror").hide();
					                                $("#solicitud_cargada").show(0500);
					                                $("#btn-bnf").show(0500);
					                                $("#mensaje_flimite").html("<span class=\"help-inline success\">"+data.mensaje_flimite+"</span>");
												}
												
											}else if(data.esconder == 1){

												$("#solicitud_cargada").hide(0500);
												$("#diverror").html("");
												$("#mensaje_flimite").html("<span class=\"help-inline error\">"+data.mensaje_flimite+"</span>");				
											}
										}
										
										$("#'.CHtml::activeId($model,'id_beneficiario').'").append(data.bnfs);

		                                $.fn.yiiGridView.update(\'beneficiarios-grid\',{type:\'GET\', url:ruta,data:\'cedula=\'+cedula}); 
	                                    $(\'#beneficiarios-grid\').selGridView(\'addSelection\', [benef]);

		                                if ($("#nobenef").html !== "") {

			                                $(".grid-benef").show();

		                                }else{
												
											$(".grid-benef").hide();
		                                }
		                                                                 
                                    }
                                    else{
										$("#mensajesSistema").html(data.mensajeError);
										$("#calculadoraHaberes").hide();
										$("#btn-bnf").hide(0500);
										$(".grid-benef").hide();

										if (data.mensaje_flimite == "") {
 											
 											$("#mensaje_flimite").html("");

 										}else{

 											$("#mensaje_flimite").html("<span class=\"help-inline error\">"+data.mensaje_flimite+"</span>");
										}
                                	}
                                }

                        	});
                }
                else{

                	$("#mensajesSistema").html("");
                	$("#diverror").html("<span class=\"help-inline error\">El campo cédula no puede estar vacío!.</span>");

                }
	}

    //comprobacion de seleccion de checkboxes de la tabla de beneficiarios cargados
	function verificarCheckbox(){

		var checkbox = $("#beneficiarios-grid").selGridView("getAllSelection");
		var filas = $(".items tbody tr td").length;
		var sol_combo = $("#'.CHtml::activeId($model,'id_beneficiario').'").focus();
		var solicitante = $("#'.CHtml::activeId($model,'id_beneficiario').'").val();

		//console.log(solicitante);
		//return false;

		if (filas === 1) {				
		
			$("#check-error").html("<span class=\"help-inline error\"><strong>Debe cargar un beneficiario antes de realizar una solicitud!</strong></span>");
			return false;
			
		}else if(filas > 1){

			if(filas > 1 && checkbox == ""){
			
				$("#check-error").html("<span class=\"help-inline error\"><strong>Debe seleccionar al menos un beneficiario de la lista para procesar la solicitud!</strong></span>");
				return false;

			}else if (filas >1 && checkbox > 0) {
			
				if (solicitante == "") {
				
					$("#check-error").html("<span class=\"help-inline error\"><strong>Debe seleccionar al beneficiario solicitante!</strong></span>");

					return false;

				}else if (solicitante > 0) {
				
					$("#check-error").html("");
					return true;
				}
			}
		}
	}

',CClientScript::POS_HEAD); ?>