<?php use_helper('UrlFunctions'); ?>
<script src="<?php echo Constantes::ROOT_DIR_APP?>/web/hc/code/highstock.src.js"></script>
<script src="<?php echo Constantes::ROOT_DIR_APP?>/web/hc/code/highcharts-3d.js"></script>
<script src="<?php echo Constantes::ROOT_DIR_APP?>/web/hc/code/modules/data.js"></script>
<script src="<?php echo Constantes::ROOT_DIR_APP?>/web/hc/code/modules/exporting.js"></script>
<script src="<?php echo Constantes::ROOT_DIR_APP?>/web/hc/code/modules/export-data.js"></script>
<script>
findControl = function(){
  
  concatValueStr();
  
}

exportFindControl = function(action){
  strFormSerialize = returnQueryStringForm();
  executeFind(strFormSerialize, action);
}

executeFind = function(str, action){
  if(typeof(action) == 'undefined'){
	  url = "<?=buildUrl('vta/grid', "block=".$block)?>";
	}else{
	  switch (action){
	    case 'excel': parent.objMainTab.reqBody('<?=buildUrl('rcd/excel')?>','001&'+str); break;
	    case 'pdf': parent.objMainTab.reqBody('<?=buildUrl('rcd/pdf')?>','001&'+str); break;	    
	    case 'pdf_supervisor': parent.objMainTab.reqBody('<?=buildUrl('rcd/pdf_supervisor')?>','001&'+str); break;	    
	    case 'pdf_moroso': parent.objMainTab.reqBody('<?=buildUrl('rcd/pdf_moroso')?>','001&'+str); break;
	  }
	  
	  return;
	}
  //str = str + '&block=001';
  url = "<?=buildUrl('vta/grid', "block=".$block)?>";
	var myAjax  = new Ajax.Updater(
                                	"resultGrtid",
                                	url,
                                	{
                                		asynchronous:	true,
                                		method			: 'get',
                                		parameters	: str,
                                		evalScripts	: true,
                                		onLoading   : cargandoImagenSerch(),
                                		onComplete	: function(){
                                			//objMainTab.showMenu();
                                		}
                                	});
}

concatValueStr = function(){
  strFormSerialize = returnQueryStringForm();
  if(arguments[0]){
    strFormSerialize += '&'+arguments[0];
  }
  executeFind(strFormSerialize);
}

function returnQueryStringForm(){
  cadenaFormulario = $('form1').serialize();
             var posicion = new Array();
             var a_pars = new Array();
             var miArray = new Array();
             posicion=[];
             a_pars=[];
             miArray=[];
             miArray = cadenaFormulario.split('&');
             x=0;
             for (i = 0; i < miArray.length; i++){
            	   posicion[i] = miArray[i].indexOf('=');
            	   if(typeof(miArray[i-1])!='undefined'){
            				if(miArray[i].substring(posicion[i],0)== miArray[i-1].substring(posicion[i-1],0) ){
           					 porcion = miArray[i].substring((1+posicion[i]));
           					 a_pars[x-1]+='@'+porcion;
           				}else{
          					 a_pars[x]= miArray[i];
         					 x++;
          				}
          		}else{
          			 a_pars[x]= miArray[i];
          			  x++;
          		}
           }
  cadenaFormulario = a_pars.join('&');
  cadenaFormulario += '&id_form=frmFindFedu';
  return(cadenaFormulario);
}

function cargandoImagenSerch(){
	//disabledWin.setPathImage('/images/common/progress.gif');
	disabledWin.show(true,true,'resultGrtid');
}

</script>
<script>
findControl = function(){
  var valid = new Validation('form1', {immediate : true});
  var result = valid.validate();
 
  if(result){
	  var pars = $('form1').serialize();
	  
		disabledWin.setPathImage('/images/common/progress.gif');
		disabledWin.show(true,true,'resultGrtid');
	  
		url = "<?=buildUrl('vta/grid', "block=".$block)?>";
		var myAjax  = new Ajax.Updater(
		"resultGrtid",
		url,
		{
			asynchronous:	true,
			method		: 'get',
			parameters	: pars,
			evalScripts	: true,
			onLoading		: function(){
				//$('contentMenu').innerHTML = $('messageLoadMenu').innerHTML;
			},
			onComplete	: function(){
				request();
			}
		});
  }
  
}

function request(){
	//Obtener el xml de las sucursales
	var pars = $('form1').serialize();
	var url2 = '<?=buildUrl('ajax/request')?>';
	pars = pars+'&type=getPrestamosxMercadosxTiempo&nombreElm';
	new Ajax.Request(url2, {
	  method: 'get', 
	  parameters: pars, 
	  onComplete: function(response) {
		GraficarMercadoxTiempo(response);
	  }
	});
};	

deleteRegistro = function(id,codigo){
  //buildUrl('rcd/delete/id/'block=001'
  if(confirm("�Esta seguro de eliminar la ficha del docente con codigo : "+codigo+ " ?")){
      //objMainTab.reqBody('<? //=buildUrl('rcd/add')?>','block=001&delete=1&id='+id);   
      parent.objMainTab.reqBody('<?=buildUrl('rcd/delete')?>','&delete=1&cod=jj&id='+id);
  }
  
}

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
                            		});
}
acutalizarMercado = function(destino,elm){
  $(destino).options.length = 1;
  var url = '<?=buildUrlComplet('mnt.php/ajax/request')?>';
  var pars = 'type=getMercado&nombreElm='+destino+'&value='+elm.value;
  
	var myAjax = new Ajax.Request(
                            		url, 
                            		{
                            			method: 'get', 
                            			parameters: pars, 
                            			onComplete: actualizaJSON
                            		});
   //$('cboRepresentante').length = 1;
}

</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();
      }
    }
  }
}

function GraficarMercadoxTiempo(response){
	
	    graficarMercadosxFecha(response);
	  
}

function graficarMercadosxFecha(originalRequest){
  
	
	data = originalRequest.responseText;
	data = data.evalJSON(true);
	
	
	var objects =[];
	console.log(data.titulo);
	var TextTitulo = data.titulo;
	var TextSubTitulo = data.subtitulo;
	var TextTiuloYAxis = data.tiuloyaxis;
	var TextCategories = data.categories;
	console.log(TextCategories);
	
	const it = (obj, tabSize = 0) => {
		var objects =[];
		for (let k in obj) {
			const v = obj[k];
			if (Object.prototype.toString.call(v) === '[object Object]') {
			 
			  objects.push(v);
			  it(v, tabSize + 1);
			} else {
			 
			}
			
		}
	return objects;
	};
	data = data.datos;
	objects = it(data);
	
	console.log(objects);

	console.log('-------------------');
	
	//alert('****');
	Highcharts.chart('container', {
		chart: {
			type: 'bar',
			options3d: {
	            enabled: true,
	            alpha: 3,
	            beta: 25,
	            depth: 70
	        }
		},
		title: {
			text: TextTitulo
		},
		subtitle: {
			text: TextSubTitulo
		},
		xAxis: {
			/*categories: ['Africa', 'America', 'Asia', 'Europe', 'Oceania','Otro','Otro 1','Otro 2','Otro 3','Otro 4','Otro 5','Otro 6'],*/
			categories: TextCategories,
			title: {
				text: null
			},
			max: 4,
			scrollbar: {
				enabled: true
			},
			tickLength: 0
		},
		colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#9900CC', '#64E572', '#FF9655', '#FFF263', '#6AF9C4', '#000000'],
		yAxis: {
			min: 0,
			title: {
				text: 'Monto Total',
				align: 'high'
			},
			labels: {
				overflow: 'justify'
			}
		},
		tooltip: {
			valueSuffix: ' '
		},
		plotOptions: {
			bar: {
				dataLabels: {
					enabled: true
				}
			}
		},
		legend: {
			layout: 'vertical',
			align: 'right',
			verticalAlign: 'top',
			x: -40,
			y: 10,
			floating: true,
			borderWidth: 1,
			backgroundColor:
				Highcharts.defaultOptions.legend.backgroundColor || '#FFFFFF',
			shadow: true
		},
		credits: {
			enabled: false
		},
		series: objects
		/*
		series: [{
			name: 'Year 1800',
			data: [107, 31, 635, 203, 2,16,35,16,35,35,3500,15000]
		}, {
			name: 'Year 1900',
			data: [133, 156, 947, 408, 6, 18, 36, 18, 36, 36, 3600, 750]
		}, {
			name: 'Year 2000',
			data: [814, 841, 3714, 727, 31,20, 37,20, 37, 3700, 3900,700]
		}, {
			name: 'Year 2016',
			data: [1216, 1001, 4436, 738, 40,22, 105,22, 105, 1000, 10000,100]
		}, {
			name: 'Year 2017',
			data: [1216, 1001, 4436, 738, 40,22, 105,22, 105, 10000, 5000,20000]
		}]
		*/
	});
     	      
}
</script>

<?php
$fecha = date('Y-m-d');
$fecha1 = date('Y-m-d',strtotime($fecha.' -7 days'));
//Carga los Mercado
$o_ClienteSystemClass = new ClienteSystemClass(new TipoNegocioBean());
$a_Mercado = $o_ClienteSystemClass->LoadMercadoXRol();

$o_SucursalSystemClass = new SucursalSystemClass(new ColaboradorBean());
$a_Colaborador = $o_SucursalSystemClass->getColaborador();

$idAdministrador = myUser::getUser()->getIdColaborador();

//echo $idAdministrador;

$o_SucursalBean = new SucursalBean();
if($idAdministrador && myUser::getUser()->getRoleId() == "sys.res")$o_SucursalBean->setIdAdministrador($idAdministrador);
if($idAdministrador && myUser::getUser()->getRoleId() == "sys.sup"){
    $o_ColaboradorBean_Temp = new ColaboradorBean();
	$o_ColaboradorBean_Temp->setIdColaborador(myUser::getUser()->getIdColaborador()); 
	$o_ColaboradorBL_Temp = new ColaboradorBL();
	$o_ColaboradorBeanResult = $o_ColaboradorBL_Temp->busquedaColaborador($o_ColaboradorBean_Temp);
	$idAdministrador = $o_ColaboradorBeanResult[0]->getIdPadre();
    $o_SucursalBean->setIdAdministrador($idAdministrador);
    $ok_sel = 0;
}elseif(myUser::getUser()->getRoleId() == "sys.ope"){
	$o_ColaboradorBean_Temp = new ColaboradorBean();
	$o_ColaboradorBean_Temp->setIdColaborador(myUser::getUser()->getIdColaborador()); 
	$o_ColaboradorBL_Temp = new ColaboradorBL();
	$o_ColaboradorBeanResult = $o_ColaboradorBL_Temp->busquedaColaborador($o_ColaboradorBean_Temp);
	$idAdministrador = $o_ColaboradorBeanResult[0]->getIdPadre();
    $o_SucursalBean->setIdAdministrador($idAdministrador);
}
$o_SucursalDP = new SucursalDP($o_SucursalBean);
$a_Sucursal = $o_SucursalDP->select();
if(myUser::getUser()->getRoleId() == "sys.ope"){
	$idSucursal = $a_Sucursal[0]->getIdSucursal();
	$a_Sucursal = null;
}
if(is_array($a_Sucursal)){
    //print_r($a_Sucursal);
    
   $idSucursal = $a_Sucursal[0]->getIdSucursal();
  
    
    $o_SuccursalMercadoBN = new SucursalMercadoBean();
    $o_SuccursalMercadoBN->setIdSucursal($idSucursal);
   
    $o_SuccursalMercadoDP = new SucursalMercadoDP($o_SuccursalMercadoBN);
    $a_o_SuccursalMercado = $o_SuccursalMercadoDP->select();
    foreach($a_o_SuccursalMercado as $key => $o_SuccursalMercado){
        $a_ids_mercado[] = $o_SuccursalMercado->getIdMercado();
    }
    //print_r($a_ids_mercado);
    
    if(!is_array($a_ids_mercado)) $a_ids_mercado[] = 9999;
    $o_MercadoBN = new MercadoBean();
    $o_MercadoBN->setIdMercados($a_ids_mercado);
   
    $o_MercadoDP = new MercadoDP($o_MercadoBN);
    $a_Mercado = $o_MercadoDP->select();
   
}

//Tipo de Docentes
//$o_DocenteSystemClass = new DocenteSystemClass(new TipoDocenteBean());
//$a_TipoDocente = $o_DocenteSystemClass->getTipoDocente();

//echo $idSucursal."----";
?>

<img src="/images/common/spacer.gif" width="10">
<table class="cuerpo" style="background: #E3E9E2" width="99%" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td valign="top">
      <form name="form1" id="form1" method="POST">
      <table border="0" cellpadding="0" cellspacing="0" width="100%">
        <tr>
          <td class="titleBody"><li>&nbsp;&nbsp;Venta del Asesor</li></td>
          <td align="right" valign="baseline">
           
          </td>
        </tr>
      </table>
      <table class="marco" width="100%">
        <tr>
          <td align="center" valign="top">
            <table width="100%" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td width="100%" valign="top" >
                  <table class="SubCabecera" width="100%" border="0" cellpadding="0" cellspacing="0">
                    <tr>
                       <td valign="top" >
                          <table class="SubCabecera"  width="33%" border="0" cellpadding="3" cellspacing="0">
                           <tr>
								<td width="8%" height="26" nowrap="nowrap" class="cabecera"><label class="label" for="txtNombre">F.&nbsp;Inicial</label></td>
								<td nowrap="nowrap"><input class="text" type="text" name="txtFechaInicial" ondblclick="this.value=''" id="txtFechaInicial" size="10" readonly value="<?=$fecha1?>"/>&nbsp;<button type="button" onclick="return false" id="btnFechaInicial">...</button></td>
								  <script type="text/javascript">
										document.getElementById("txtFechaInicial").disabled = false;
										Calendar.setup({
										  inputField : "txtFechaInicial",
										  ifFormat : "%Y-%m-%d",
										  daFormat : "%Y-%m-%d",
										  button   : "btnFechaInicial"
										});
									</script>
								  <td width="8%" height="26" nowrap="nowrap" class="cabecera"><label class="label" for="txtNombre">F.&nbsp;Final</label></td>
								  
								  <td nowrap="nowrap"><input class="text" type="text" ondblclick="this.value=''" name="txtFechaFinal" id="txtFechaFinal" size="10" readonly value="<?=$fecha?>"/>&nbsp;<button type="button" onclick="return false" id="btnFechaFinal">...</button></td>
								  <script type="text/javascript">
										document.getElementById("txtFechaFinal").disabled = false;
										Calendar.setup({
										  inputField : "txtFechaFinal",
										  ifFormat : "%Y-%m-%d",
										  daFormat : "%Y-%m-%d",
										  button   : "btnFechaFinal"
										});
									</script>
                               <?php if(myUser::getUser()->getRoleId() <> "sys.ope"){?>
                                <td width="12%" height="26" nowrap="nowrap"><label class="label" for="txtNombre">Sucursal</label></td>
        						<td width="10%" nowrap="nowrap">
        							<select name="cboSucursal" id="cboSucursal" type="text" class="combo" onchange="acutalizarMercado('cboMercado',this);"/> 
        									<?php if($ok_sel == 1){?><option value="" > - Seleccionar - </option><?php } ?>
        									<?php foreach ($a_Sucursal as $iKey => $o_SucursalBean){ ?>
        									<option value="<?=$o_SucursalBean->getIdSucursal()?>">
        									  <?=$o_SucursalBean->getDescripcion()?>
        									</option>
        									<?php } ?> 
        							  </select>
        						</td>    
        					    <?php } 
								if(myUser::getUser()->getRoleId() == "sys.ope"){?><input type="hidden" name="cboSucursal" id="cboSucursal" value="<?=$idSucursal?>"><?php }?>
                           	    <td width="12%" height="26" nowrap="nowrap" class="cabecera"><label class="label" for="txtNombre">Mercado</label></td>
	                            <td width="10%" nowrap="nowrap">
		                      	 <select name="cboMercado" id="cboMercado" type="text" class="combo"/>
								   <option value="" > - Seleccionar - </option>	
			                       <?php foreach ($a_Mercado as $iKey => $o_MercadoBean){ ?>
			                        <option value="<?=$o_MercadoBean->getIdMercado()?>">
			                          <?=$o_MercadoBean->getDescripcion()?>
			                        </option>
			                        <?php } ?> 
								 </select>
	                           </td>
								

									<td width="12%" height="26" nowrap="nowrap" class="cabecera"><label class="label" for="txtNombre">Tipo</label></td>
									<td width="10%" nowrap="nowrap">
									 <select name="cboTipo" id="cboTipo" type="text" class="combo"/> 
									   
										<option value="R">NORMAL</option>
										<option value="F">REFINANCIADO</option>
										
									 </select>
								   </td>
								   <td width="12%" height="26" nowrap="nowrap" class="cabecera"><label class="label" for="txtNombre">Estado</label></td>
									<td width="10%" nowrap="nowrap">
									 <select name="cboEstado" id="cboEstado" type="text" class="combo"/> 
									   
										<option value="P">Pendiente</option>
										<option value="C">Cancelado</option>
										
									 </select>&nbsp;<input class="button" type="button" value="Buscar" onclick="findControl();"/>
								   </td>
									</tr>
									  </table>
								   </td>
								   
                       
                    </tr>
                  </table>
                </td>
                </tr>   
			 
            </table>
          </td>
        </tr>
      </table>
       
      </form>
      <div id="resultGrtid">
      </div>
	  
    </td>
  </tr>
</table>


<?php
if(isset($insert)){
  ?>
  <script>
    elementLoad.show(undefined,"Se inserto la ficha satisfactoriamente.");
    setTimeout("elementLoad.hide()",5000);
    $('IdPrestamo').value = "<?=$id?>";
    //$('cboEstadoPrestamo').value = "<?=$cboEstadoPrestamo?>";
    //$('cboMercado').value = "<?=$cboMercado?>";
    
    
    findControl();
  </script>
  <?php
}
if(isset($update)){
  ?>
  <script>
    elementLoad.show(undefined,"Se actualizo la ficha satisfactoriamente.");
    setTimeout("elementLoad.hide()",5000);
    $('IdPrestamo').value = "<?=$id?>";
   
    findControl();
  </script>
  <?php
}
if(isset($delete)){
  ?>
  <script>
    elementLoad.show(undefined,"Se elimino la ficha satisfactoriamente.");
    setTimeout("elementLoad.hide()",5000);
    $('IdPrestamo').value = "<?=$id?>";
    
    findControl();
    
  </script>
  <?php 
  
}
?>