<?php use_helper('UrlFunctions'); ?>
<script>

acutalizarEspecialidad = function(destino,elm){
  $(destino).options.length = 1;
  var url = '<?=buildUrl('ajax/request')?>';
  var pars = 'type=getEspecialidad&nombreElm='+destino+'&value='+elm.value;
  
	var myAjax = new Ajax.Request(
                            		url, 
                            		{
                            			method: 'get', 
                            			parameters: pars, 
                            			onComplete: actualizaJSON
                            		});
}

</script>
<script>
actualizaJSON = function(request, json){
  var numeroElementos = json.length;
  for (var i = 0; i < numeroElementos; i++){
    if($(json[i][0])){
  	  switch ($(json[i][0]).tagName){
  	    case 'TD'      : Element.update(json[i][0], json[i][1]); break;
  	    case 'INPUT'   : $(json[i][0]).value=json[i][1]; break;
  	    case 'SELECT'  : 
  	      var objDDL = $(json[i][0]);
  	      if(typeof(cont) == 'undefined'){
  	        var cont = 0;
  	        objDDL.options.length = 1;
  	      }
  	      var a_contentValues = json[i][1].split("_;_");
      		var value	= a_contentValues[0];
      		var text	= a_contentValues[1];
  	      var option	= new Option(text,value);
      		try{
      			objDDL.add(option,null);
      		}catch (e){
      			objDDL.add(option,-1);
      		}
  	      cont++;
  	    break;
  	  }
    }else{
      if(json[i][0].indexOf("function") > -1){
        eval("scriptEval = "+json[i][0]);
        scriptEval();
      }
    }
  }
}
</script>
<?php

if(isset($control)){
  
  $o_ClienteBean = new ClienteBean();
  
  $o_ClienteBean->setIdMercado($IdMercado);
  $o_ClienteBean->setIdTipoNegocio($IdTipoNegocio);
  $o_ClienteBean->setTipoDocumento($tipodocumento);
  $o_ClienteBean->setDni($Dni);
  $o_ClienteBean->setNombres($Nombres);
  $o_ClienteBean->setApellidoPaterno($ApellidoPaterno);
  $o_ClienteBean->setApellidoMaterno($ApellidoMaterno);
  $nombrecompleto = $ApellidoPaterno." ".$ApellidoMaterno.", ".$Nombres;
  $o_ClienteBean->setNombreCompleto($nombrecompleto);
  $o_ClienteBean->setTelefono($Telefono);
  $o_ClienteBean->setDireccion($Direccion);
  $o_ClienteBean->setCelular($Celular);
  $o_ClienteBean->setFechaNacimiento($FechaNacimiento);
  $o_ClienteBean->setSexo($cboSexo); 
  $o_ClienteBean->setEstadoCivil($cboEstadoCivil);
  $o_ClienteBean->setEstado($cboEstado);   
  $o_ClienteBean->setFechaCreacion(date("Y-m-d H:i:s"));
  $o_ClienteBean->setUsuarioCreacion(myUser::getUser()->getUserId());
  $o_ClienteSystemClass = new ClienteSystemClass($o_ClienteBean);
  
  
  $bResult = $o_ClienteSystemClass->insertCliente($chek_documento);
  
   
  if($bResult){
    ?>
    <script language="JavaScript">
    parent.objMainTab.reqBody('<?=buildUrl('cli/list')?>','&block=001&insert=1&id=<?=$o_ClienteBean->getIdCliente()?>');
    parent.objMainTab.windowsCloseAll();
    </script>
    <?
  }else{
    $url = buildUrl('cli/add', "block=".$block."&error=1");
  }
  exit;
}

  //Mercados
  $o_ClienteSystemClass = new ClienteSystemClass(new TipoNegocioBean());
  $a_Mercado = $o_ClienteSystemClass->LoadMercadoXRol();
  
  //Tipos de Negocio
  $o_ClienteSystemClass = new ClienteSystemClass(new TipoNegocioBean());
  $a_TipoNegocio = $o_ClienteSystemClass->getTipoNegocio();

//Cargar Documento
 $o_ClienteSystemClass = new ClienteSystemClass(new DocumentoBean());
 $a_o_Documento = $o_ClienteSystemClass->getDocumento();
 
 ?>

<img src="/images/common/spacer.gif" width="10">
<table class="cuerpo" width="100%" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td height="0">
      <table border="0" cellpadding="0" cellspacing="0" width="100%">
        <tr>
          <td class="titleBody">
            <li>Cliente</li>
            <span class="subtitle"><I>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:::&nbsp;Ficha del Cliente</I></span></td>
          <td align="right" valign="baseline">&nbsp;</td>
        </tr>
      </table>
    </td>
  </tr>
    
  <tr>
    <td valign="top">
     <form id="form1" name="form1" method="POST">
      <input type="hidden" name="control" value="1">
      
        <table hspace="20px" class="marco" width="96%">
          <tr>
            <td valign="top" colspan="2">
	
              <table width="100%" border="0" cellpadding="5" cellspacing="0" style="background: #E3E9E2">
          		<tr>
    				  <td height="0">
    				  <fieldset>
    					<legend class="fielsettex"><I>Datos Generales</I></legend>
    					 <table width="100%" border="0" cellspacing="6" cellpadding="0">
							  <tr>
								<td nowrap="nowrap" width="10%" class="cabecera"><label class="label req" for="txtDniCliente" >Documento </label></td>
								<td nowrap="nowrap" width="38%"><select name="tipodocumento" id ="tipodocumento" class="combo" onchange="/*validardocumento(this.value)*/"><option value="DNI">DNI</option><option value="CEXT">CARNET EXTRNAJERIA</option></select>&nbsp;<input class="text  " type="text" autocomplete="off" name="Dni" id="Dni" maxlength="8" size="8"/><img src="/images/common/loader.gif" id="loader" style="display:none"></td><!--validate-DNI required validate-digits-->
								 <td nowrap="nowrap" width="8%" class="cabecera">&nbsp;</td>
								 <td width="12%" nowrap="nowrap" class="cabecera"><label class="label req" for="txtSexo" >Sexo</label></td>
								 <td nowrap="nowrap" width="38%">
								   <select name="cboSexo" id="cboSexo" type="text required" class="combo"> 
									  <option value="" >Seleccione</option>
									  <option value="M" >Masculino</option>
									  <option value="F" >Femenino</option>
							  		</select>
								</td>
							   </tr>
							   <tr>
								<td nowrap="nowrap" class="cabecera"><label class="label req" for="txtNombres" >Nombres </label></td>
								<td nowrap="nowrap"><input class="text required" type="text" name="Nombres" id="Nombres" size="40" maxlength="50" /></td>
								<td nowrap="nowrap" width="8%" class="cabecera">&nbsp;</td>
								 <td width="12%" nowrap="nowrap" class="cabecera"><label class="label req" for="txtEsatdoCivil" >Estado Civil</label></td>
								 <td nowrap="nowrap" width="38%">
								   <select name="cboEstadoCivil" id="cboEstadoCivil" type="text" class="combo"> 
									  <option value="" >Seleccione</option>
									  <option value="S" >Soltero</option>
									  <option value="C" >Casado</option>
									  <option value="D" >Divorciado</option>
									  <option value="V" >Viudo</option>
							  		</select>
								</td>
							  </tr>
							  <tr>
								<td nowrap="nowrap" width="12%" class="cabecera"><label class="label" for="txtApellidoPaterno">Apellido Paterno </label></td>
								<td nowrap="nowrap" width="38%"><input class="text required" type="text" name="ApellidoPaterno" id="ApellidoPaterno" /></td>
								 <td nowrap="nowrap" width="8%" class="cabecera">&nbsp;</td>
								 <td width="12%" nowrap="nowrap" class="cabecera"><label class="label req" for="txtFechaNacimiento" >F. Nacimiento</label></td>
								 <td nowrap="nowrap"><input class="text"  readonly  type="text" name="FechaNacimiento" id="FechaNacimiento" ondblclick="this.value=''" size="10"/><button type="button" onclick="return false" id="btnFechaNacimiento">...</button>
									   <script type="text/javascript">
									     document.getElementById("btnFechaNacimiento").disabled = false;
									     Calendar.setup({
									     inputField : "FechaNacimiento",
									     ifFormat : "%Y-%m-%d",
									     daFormat : "%Y-%m-%d",
									     button   : "btnFechaNacimiento"
									     });
									  </script>
								</td>
							  </tr>
							  
							  <tr>
								<td nowrap="nowrap" width="12%" class="cabecera"><label class="label" for="txtApellidoMaterno" >Apellido Materno </label></td>
								<td nowrap="nowrap" width="38%"><input class="text required" type="text" name="ApellidoMaterno" id="ApellidoMaterno"  /></td>
								<td nowrap="nowrap" width="8%" class="cabecera">&nbsp;</td>
								 <td width="12%" nowrap="nowrap" class="cabecera"><label class="label req" for="txtSueldo" >Mercado</label></td>
								 <td nowrap="nowrap"><select class="combo validate-selection " name="IdMercado" id="IdMercado" onchange="acutalizarEspecialidad('cboEspecialidad',this)" >
                  				  <option value="" > - Seleccionar - </option>
                 				  <?php foreach ($a_Mercado as $iKey => $o_MercadoBean){ ?>
                  				  <option value="<?=$o_MercadoBean->getIdMercado()?>">
                    			 <?=$o_MercadoBean->getDescripcion()?>
                   	              </option>
                  					<?php } ?>
                				</select>
               				 </td>
							  </tr>
							  <tr>
								<td nowrap="nowrap" width="12%" class="cabecera"><label class="label" for="txtDireccion">Direcci&oacute;n</label></td>
								<td nowrap="nowrap" width="38%"><textarea  name="Direccion" id="Direccion" cols="50" rows="2"></textarea></td>
								 <td nowrap="nowrap" width="12%" class="cabecera">&nbsp;</td>
								 <td width="12%" nowrap="nowrap" class="cabecera"><label class="label req" for="txtEmail" >Tipo Negocio</label></td>
								<td nowrap="nowrap"><select class="combo" name="IdTipoNegocio" id="IdTipoNegocio" >
				                  <option value="" > - Seleccionar - </option>
				                  <?php foreach ($a_TipoNegocio as $iKey => $o_TipoNegocioBean){ ?>
				                  <option value="<?=$o_TipoNegocioBean->getIdTipoNegocio()?>">
				                    <?=$o_TipoNegocioBean->getDescripcion()?>
				                  </option>
				                  <?php } ?>
				                </select>
				               </td>
							  </tr>
							  <tr>
							   <td nowrap="nowrap" width="12%" class="cabecera"><label class="label" for="txtEstado">Estado</label></td>
								 <td nowrap="nowrap" width="38%">
								    <select name="cboEstado" id="cboEstado" type="text" class="combo" onchange="acutalizarEspecialidad('cboEspecialidad',this)"/> 
									  <option value="A" >Activo</option>
									  <option value="I" >Inactivo</option>
							  		</select>
								 </td>
								 <td nowrap="nowrap" width="12%" class="cabecera">&nbsp;</td>
								  
							  </tr>
						</table>
    					</fieldset>				
    				</td>
                </tr>
    			<tr>
  				  <td height="0" width="100%">
				   
  					 <table width="100%" border="0" cellspacing="5" cellpadding="0">
  					  <tr>
  					    <td valign="top" width="50%">
  					      <fieldset>
					 		<legend class="fielsettex"><I>Otros Datos</I></legend>
  					        <table width="50%" border="0" cellspacing="3" cellpadding="0">
	  					         <tr>
									<td nowrap="nowrap" width="12%" class="cabecera"><label class="label" for="txtDireccion">Tel&eacute;fono</label></td>
									 <td nowrap="nowrap" ><input class="text" type="text" name="Telefono" id="Telefono" size="10" maxlength="15"/></td>
								  </tr>
								  <tr>
								     <td nowrap="nowrap" width="12%" class="cabecera"><label class="label" for="txtCelular">Celular</label></td>
									 <td nowrap="nowrap" ><input class="text" type="text" name="Celular" id="Celular" maxlength="15" size="10"/></td>
								  </tr>
  					        </table>
  					      </fieldset>
  					    </td>
  					    <td valign="top" width="50%">
  					      <fieldset>
					 		<legend class="fielsettex"><I>Documentos Adjuntos</I></legend>
  					        <table width="100%" border="0" cellspacing="5" cellpadding="0">
  					          <?php   
									if(is_array($a_o_Documento)){
										$i = 1;
										while(list($key,$o_Documento) = each($a_o_Documento)){
											if($i == 1){ ?>
												<tr>
											<?}?>
												<td width="4%"><input type="checkbox" name="chek_documento[]" id="chek_documento" value="<?=$o_Documento->getIdDocumento()?>"></td>
												<td><label class="label"><?=$o_Documento->getDescripcion()?></label></td>
											<?php
											if($i == 2){ 
												$i = 1;?>
												</tr>
											<?}?><?php
											$i++;
										}
									}
								?>
  					        </table>
  					      </fieldset>
  					    </td>
  					  </tr>
  				   </table>
  				   <table width="100%" border="0" cellspacing="0" cellpadding="0">
				  <tr>
					<td><img src="/images/common/spacer.gif" width="10"></td>
					 </tr>
						<tr>
						 <td align="center">
						  <input type="hidden" name="typeSubmit" id="typeSubmit">
						  <input class="button" type="submit" value="Grabar" onclick="$('typeSubmit').value='list';">
						   <input class="button" type="button" value="Cancelar" onclick="parent.objMainTab.windowsCloseAll();"/>
						  </td>
						</tr>
						<tr>
					<td height="10">&nbsp;</td>
				 </tr>
			    </table>
				</fieldset>
          		 </td>
        		</tr>
				<tr>
      			</table>
      			
     		</form>
			<script type="text/javascript">
				$("Dni").focus();
				function validardocumento(valor){
					limpiarNombres();
					if(valor == "DNI"){
						$("Dni").addClassName("validate-DNI");
						$("Dni").removeClassName("validate-CE");
						if ($('advice-validate-CE-Dni')) { $('advice-validate-CE-Dni').remove();}
						$("Dni").maxLength = 8;
						$("Dni").value ="";
						$('Nombres').readOnly 			= true;
						$('ApellidoPaterno').readOnly 	= true;
						$('ApellidoMaterno').readOnly 	= true;
						
					}
					if(valor == "CEXT"){
						$("Dni").removeClassName("validate-DNI");
						$("Dni").addClassName("validate-CE");
						if ($('advice-validate-DNI-Dni')) { $('advice-validate-DNI-Dni').remove();}
						$("Dni").maxLength = 10;
						$("Dni").value ="";
					}
					$("Dni").focus();
				}
				Validation.add('validate-CE', 'Ingrese el carnet de extranjeria.', function(v) {     
				
				
					
					var url = '<?=buildUrl('ajax/request')?>';
	  				
	
								
					var pars = 'type=validateCE&value='+v;
	  			 
				    var okdni = false;
				 	$( 'loader' ).style.display = "";
				    new Ajax.Request(url, {
				        method: 'get',
				        parameters:pars,
				        asynchronous: false,
				        onSuccess: function(transport) {
				        	
				            var obj = response = eval('(' + transport.responseText + ')');
				            
				            validateTrueEmailMsg = obj.status_desc;
				 			//alert(obj.ok);
				            if (obj.ok == '1') {
				            	if ($('advice-validate-CE-Dni')) {
					                $('advice-validate-CE-Dni').innerHTML = validateTrueEmailMsg;
					            }
				            	//alert(validateTrueEmailMsg);
								$('Nombres').readOnly 			= true;
								$('ApellidoPaterno').readOnly 	= true;
								$('ApellidoMaterno').readOnly 	= true;
				                Validation.get('validate-CE').error = validateTrueEmailMsg;
				                okdni = false;
				            } else {
								if(obj.nombres)
								{
									$('Nombres').value 			= obj.nombres;
									$('ApellidoPaterno').value 	= obj.apellido_paterno;
									$('ApellidoMaterno').value 	= obj.apellido_materno;
									$('Nombres').readOnly 			= true;
									$('ApellidoPaterno').readOnly 	= true;
									$('ApellidoMaterno').readOnly 	= true;
								}
				                okdni = true; /* return true or false */    
				            }
				            $( 'loader' ).style.display = "none";
				        },
				        onComplete: function() {
				 			//alert('complete')	
				 			
				            /**/
				        }
				    });
				 	//alert('dni'+okdni);
				    return okdni;
				});
				Validation.add('validate-email', 'Please enter a valid email address. For example johndoe@domain.com.', function(v) {     
 
				var url = '<?=buildUrl('ajax/request')?>';
  				
				var pars = 'type=validateMail&value='+v;
  			 
			    var ok = false;
			 
			    new Ajax.Request(url, {
			        method: 'get',
			        parameters:pars,
			        asynchronous: true,
			        onSuccess: function(transport) {
			        	$( 'loader' ).style.display = "";
			            var obj = response = eval('(' + transport.responseText + ')');
			            
			            validateTrueEmailMsg = obj.status_desc;
			 			//alert(obj.ok);
			            if (obj.ok === false) {
			                Validation.get('validate-email').error = validateTrueEmailMsg;
			                ok = false;
			            } else {
			                ok = true; /* return true or false */    
			            }
			        },
			        onComplete: function() {
			 			$( 'loader' ).style.display = "none";
			            if ($('advice-validate-email-email')) {
			                $('advice-validate-email-email').remove();
			            }
			 
			            if ($('advice-validate-email-email_address')) {
			                $('advice-validate-email-email_address').remove();    
			            }
			 
			            if ($('advice-validate-email-billing:email')) {
			                $('advice-validate-email-billing:email').remove();    
			            }
			 
			            if ($('advice-validate-email-shipping:email')) {
			                $('advice-validate-email-shipping:email').remove();
			            }
			 
			            if ($('advice-validate-email-_accountemail')) {
			                $('advice-validate-email-_accountemail').remove();
			            }
			        }
			    });
			 	alert('mail'+ok);
			    return ok;
			});
			
			function limpiarNombres(){
				$('Nombres').value 			= "";
				$('ApellidoPaterno').value 	= "";
				$('ApellidoMaterno').value 	= "";
				$('Nombres').readOnly 			= false;
				$('ApellidoPaterno').readOnly 	= false;
				$('ApellidoMaterno').readOnly 	= false;
				
			}
			
			//addClassName("validate-DNI")
			
			Validation.add('validate-DNI', 'Ingrese el dni.', function(v) {     
 
				
				var url = '<?=buildUrl('ajax/request')?>';
  				

							
				var pars = 'type=validateDni&value='+v;
  			 
			    var okdni = false;
			 	$( 'loader' ).style.display = "";
			    new Ajax.Request(url, {
			        method: 'get',
			        parameters:pars,
			        asynchronous: false,
			        onSuccess: function(transport) {
			        	
			            var obj = response = eval('(' + transport.responseText + ')');
			            
			            validateTrueEmailMsg = obj.status_desc;
			 			//alert(obj.ok);
			            if (obj.ok == '1') {
			            	if ($('advice-validate-DNI-Dni')) {
				                $('advice-validate-DNI-Dni').innerHTML = validateTrueEmailMsg;
				            }
			            	//alert(validateTrueEmailMsg);
							$('Nombres').readOnly 			= true;
							$('ApellidoPaterno').readOnly 	= true;
							$('ApellidoMaterno').readOnly 	= true;
			                Validation.get('validate-DNI').error = validateTrueEmailMsg;
			                okdni = false;
			            } else {
							if(obj.nombres)
							{
								$('Nombres').value 			= obj.nombres;
								$('ApellidoPaterno').value 	= obj.apellido_paterno;
								$('ApellidoMaterno').value 	= obj.apellido_materno;
								$('Direccion').value 	= obj.direccion_completa;
								$('FechaNacimiento').value 	= obj.fecha_nacimiento;
								var sexo 	= obj.sexo;
								
								var options = $$('select#cboSexo option');
                            	var len = options.length;
                            	
                            	for (var i = 0; i < len; i++) {
                            	    console.log('Option text = ' + options[i].text);
                            	    console.log('Option value = ' + options[i].value);
                            	    if(sexo == options[i].value){
                            	    	//alert("*-*rr-*-*-")
                            	    	options[i].selected = true;
                            	    }
                            	}
                            	var estado_civil 	= obj.estado_civil;
                            	var options = $$('select#cboEstadoCivil option');
                            	var len = options.length;
                            	
                            	for (var i = 0; i < len; i++) {
                            	    console.log('Option text = ' + options[i].text);
                            	    console.log('Option value = ' + options[i].value);
                            	    if(estado_civil == options[i].value){
                            	    	//alert("*-*rr-*-*-")
                            	    	options[i].selected = true;
                            	    }
                            	}
                            	
                            	
								$('Nombres').readOnly 			= true;
								$('ApellidoPaterno').readOnly 	= true;
								$('ApellidoMaterno').readOnly 	= true;
								$('FechaNacimiento').readOnly 	= true;
								
							}
			                okdni = true; /* return true or false */    
			            }
			            $( 'loader' ).style.display = "none";
			        },
			        onComplete: function() {
			 			//alert('complete')	
			 			if ($('advice-validate-digits-Dni')) { $('advice-validate-digits-Dni').remove();}
			            /**/
			        }
			    });
			 	//alert('dni'+okdni);
			    return okdni;
			});
				var valid = new Validation('form1', {immediate : true});
			</script>
			</td>
  		  </tr>
		</table>
    </td>
  </tr>
</table>
