<?php use_helper('UrlFunctions'); ?>
<script src="/hc/code/highcharts.js"></script>
<script src="/hc/code/modules/data.js"></script>
<script src="/hc/code/modules/exporting.js"></script>
<script src="/hc/code/modules/export-data.js"></script>
<script>
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>
acutalizarRepresentante = function(destino,elm){
  $(destino).options.length = 1;
  var url = '<?=buildUrlComplet('mnt.php/ajax/request')?>';
  var pars = 'type=getRepresentante&nombreElm='+destino+'&value='+elm.value;
  
	var myAjax = new Ajax.Request(
                            		url, 
                            		{
                            			method: 'get', 
                            			parameters: pars, 
                            			onComplete: actualizaJSON
                            		});
}

</script>

<script>
findControl = function(){
  
  concatValueStr();
  
}
exportFindControl = function(action){
  strFormSerialize = returnQueryStringForm();
  executeFind(strFormSerialize, action);
}
executeFind = function(str,action){ 
  
  if(typeof(action) == 'undefined'){
	  url = "<?=buildUrl('resumdiario/grid', "block=".$block)?>";
	}else{
	  switch (action){
	    case 'excel': parent.objMainTab.reqBody('<?=buildUrl('resumdiario/excel')?>','001&'+str); break;
	    //case 'pdf': parent.objMainTab.reqBody('<?=buildUrl('resumdiario/pdfsemn')?>','001&'+str); break;	    
	  }
	  
	  return;
	}
  
  //str = str + '&block=001';
  //url = "<?//=buildUrl('rcp/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);
}
showTesis= function(id){
  parent.objMainTab.modalDialog('<?=buildUrl('resumdiario/show',"block=001")?>/id/'+id,{title:'Detalle Tesis',width:800,height:450});
}
function cargandoImagenSerch(){
	//disabledWin.setPathImage('/images/common/progress.gif');
	disabledWin.show(true,true,'resultGrtid');
}

function abrirVentana(IdSucursal,campo){
	cadenaFormulario = $('form1').serialize();
	parent.objMainTab.modalDialog('<?=buildUrl('resumdiario/show/id/1');?>/Idsucursal/'+IdSucursal+'/Campo/'+campo+'/parametros/'+cadenaFormulario,{title:'Grafico',width:1110,height:500})
}

function abrirVentanaDetail(IdSucursal,Fecha,IdMercado,campo){
	cadenaFormulario = $('form1').serialize();
	parent.objMainTab.modalDialog('<?=buildUrl('resumdiario/showdetail/id/1');?>IdsucursalD/'+IdSucursal+'/FechaD/'+Fecha+'/IdMercadoD/'+IdMercado+'/Campo/'+campo+'/parametros/'+cadenaFormulario,{title:'Grafico',width:1110,height:500})
}

</script>
<script>
findControl = function(){
  
  var pars = $('form1').serialize();
  
	disabledWin.setPathImage('/images/common/progress.gif');
	disabledWin.show(true,true,'resultGrtid');
  
	url = "<?=buildUrl('resumdiario/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(){
			//objMainTab.showMenu();
			//objMainTab.showMenu();
			datastart = '';
			dataend = '';


			var url = "http://localhost/hc/p_json.php";
			var pars = $('form1').serialize();
			//var pars = 'startDate=' + datastart + '&endDate=' + dataend;
			var pars = pars;

			var myAjax = new Ajax.Request(
				url, 
				{
					method: 'post', 
					evalJSON: 'force',
					requestHeaders:
					{
						Accept: 'application/json'
					},
					parameters: pars, 
					onComplete: showResponse
				});
		}
	});
  
}

function showResponse(originalRequest)
{
	//put returned XML in the textarea
	//alert(originalRequest);
	
	
	//data = JSON.parse(originalRequest.responseText);
	
	/*
	data = originalRequest.responseText;
	$("container").innerHTML = data;
	data = JSON.parse(data);
	*/
	data = originalRequest.responseText;
	data = data.evalJSON(true);
	
	//data = originalRequest.responseJSON;
	//data = Object.evalJSON(data)
	//data = JSON.parse(data);
		
	//data = data.evalJSON(true);

	//var data = '{ "name": "Violet", "occupation": "character" }'.evalJSON();
	//$("container").innerHTML = data;
	
	/* Otra alternativa que funciona
	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;
	//alert("****");
	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]') {
			  //console.log(`${k}:`);
			  //console.log(v);
			  objects.push(v);
			  it(v, tabSize + 1);
			} else {
			  //console.log(`${'\t--'.repeat(tabSize)}${k}: ${v}`);
			}
			//objects.push(obj);
		}
	return objects;
	};
	data = data.datos;
	objects = it(data);
	
	console.log(objects);
	
	//alert("****");
	/*
	var datos = [{
		name: 'Name',
		data: objects      
	}];
	*/     
		
	Highcharts.chart('container', {
		chart: {
		type: 'column'
	},
	lang: {
        downloadCSV:"Descarga CSV",       
        viewFullscreen:"Ver en pantalla completa",
        printChart:"Imprimir Imagen",
        downloadPNG:"Descargar Imagen en PNG",
        downloadXLS:"Descargar valores en Excel"
    },
	
        exporting: {
            filename: 'export_xlsx_example',
            buttons: {
                contextButton: {
                    enabled: true,
                    menuItems: [{
                        text: 'Exportar XLSX',
                        onclick: function() {
                            this.downloadXLS();
                        }
                    }, {
                        text: 'Exportar CSV',
                        onclick: function() {
                            this.downloadCSV();
                        }
                    }, {
                        text: 'Exportar PNG',
                        onclick: function() {
                            this.exportChart({
                                type: 'image/png'
                            });
                        }
                    }, {
                        text: 'Exportar PDF',
                        onclick: function() {
                            this.exportChart({
                                type: 'application/pdf'
                            });
                        }
                    }]
                }
            },
            csv: {
                // dateFormat: '%Y%m'
            },
            xlsx: {
                worksheet: {
                    autoFitColumns: true,
                    categoryColumnTitle: 'Month',
                    dateFormat: 'yyyy-mm',
                    name: 'Export XLSX Test'
                },
                workbook: {
                    fileProperties: {
                        Author: "File Author",
                        Company: "File Company",
                        CreatedDate: new Date(Date.now())
                    }
                }
            }
        },
	title: {
		text: TextTitulo
	},
	subtitle: {
		text: TextSubTitulo
	},
	xAxis: {
		categories: TextCategories,
		crosshair: true
	},
	yAxis: {
		min: 0,
		title: {
			text: TextTiuloYAxis
		}
	},
	tooltip: {
		headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
		pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
			'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
		footerFormat: '</table>',
		shared: true,
		useHTML: true
	},
	plotOptions: {
		column: {
			pointPadding: 0.2,
			borderWidth: 0
		}
	},    
		series: objects
	})                          
	
	
}


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

acutalizarSemana = function(destino,elm){
	
  $(destino).options.length = 1;
  var url = '<?=buildUrl('ajax/request')?>';
  var pars = 'type=getSemana&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

   //Cargar al Colaborador

if(myUser::getUser()->getIdPadre() && myUser::getUser()->getIdPadre() != "A"){
	
  	$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();
 }elseif(myUser::getUser()->getIdPadre() == "A"){
 	  
 	//Todos los Padres Rol actualmente sys.gen y sys.view
 	//SIN FILTRO
 }else{
 	if(myUser::getUser()->getRoleId() == "sys.res"){
  		$idAdministrador = myUser::getUser()->getIdColaborador();
 	}else{
 		$o_ColaboradorBean_Tem1 = new ColaboradorBean();
  		$o_ColaboradorBean_Tem1->setIdColaborador(myUser::getUser()->getIdColaborador());
  		$o_ColaboradorDP_Tem1 = new ColaboradorDP($o_ColaboradorBean_Tem1); 
  		$a_Colaborador = $o_ColaboradorDP_Tem1->select();
 	}
 }

$o_SucursalBean = new SucursalBean();
if(myUser::getUser()->getRoleId() == "sys.res"){
	$o_SucursalBean->setIdAdministrador(myUser::getUser()->getIdColaborador());
	
}
$o_SucursalBL = new SucursalBL();
$a_Sucursal = $o_SucursalBL->busquedaSucursal($o_SucursalBean); 
if(myUser::getUser()->getRoleId() == "sys.res"){
	$IdSucursal = $a_Sucursal[0]->getIdSucursal();
	$o_SucursalMercadoBean = new SucursalMercadoBean();
	$o_SucursalMercadoBean->setIdSucursal($IdSucursal);
	$o_SucursalMercadoDP = new SucursalMercadoDP($o_SucursalMercadoBean);
	$a_o_SucursalMercadoDP = $o_SucursalMercadoDP->select();
	
	foreach ($a_o_SucursalMercadoDP as $key => $o_SucursalMercadoDP){
		$a_idsmercado[] = $o_SucursalMercadoDP->getIdMercado();
	}
	
	$o_MercadoBean = new MercadoBean();
	$o_MercadoBean->setIdMercados($a_idsmercado);
	$o_MercadoDP = new MercadoDP($o_MercadoBean);
	$a_Mercado = $o_MercadoDP->select();
	
	
}

//echo $idAdministrador;
if($idAdministrador){
	$o_ColaboradorBean = new ColaboradorBean();
	$o_ColaboradorBean->setIdPadre($idAdministrador);
	
	$o_colaborador = new ColaboradorBean();
	$o_colaborador->setIdPadre($idAdministrador);
	
	$o_CapitalInicialSystemClass = new CapitalInicialSystemClass($o_colaborador);
	$a_Colaborador = $o_CapitalInicialSystemClass->getColaborador();
	
	$o_SucursalBean = new SucursalBean();
	$o_SucursalBean->setIdAdministrador($idAdministrador);
	$o_SucursalBL = new SucursalBL();
	$a_o_sucursal = $o_SucursalBL->busquedaSucursal($o_SucursalBean);
	//----------------------------------------------------
	
	$IdSucursal = $a_o_sucursal[0]->getIdSucursal();
	
	$o_BalanceDia = new BalanceDiaBean();
	$o_BalanceDia->setIdSucursal($IdSucursal);
	$o_BalanceDia->setIdAdministrador($idAdministrador);
	
	$o_BalanceDiaDP = new BalanceDiaDP($o_BalanceDia);
	$fecha = $o_BalanceDiaDP->ObtenerDiaAbierto();

}else{
	
}

//Obtener el Periodo Actual 
$txtFechaFinal = date('Y-m-d');
$txtFechaInicial = date('Y-m-d',strtotime($txtFechaFinal.' -7 days'));;

$o_BalanceDia = new BalanceDiaBean();

$o_BalanceDiaTempo = new BalanceDiaDP($o_BalanceDia);

$periodoActual = $o_BalanceDiaTempo->ObtenerUltimoPeriodo();


$a_periodosHabiles = $o_BalanceDiaTempo->ObtenerPeriodosHabiles();
$a_semanasHabiles = $o_BalanceDiaTempo->ObtenerSemanasHabiles($periodoActual);
	
?>

<img src="/images/common/spacer.gif" width="10">
<table class="cuerpo"  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;Resumen Diario</li></td>
          <td align="right" valign="baseline">
            <img src="/images/common/buttons/btnExcel.gif" title="Exportar a Excel" onClick="exportFindControl('excel');" style="cursor:pointer"/>
          </td>
        </tr>
      </table>
      <table class="marco" width="100%" style="background: #E3E9E2">
        <tr>
          <td align="center" valign="top">
            <table width="100%" border="0" cellspacing="0" cellpadding="0">
              <tr>
               
								<?php if(myUser::getUser()->getRoleId() == "sys.gen" || myUser::getUser()->getRoleId() == "sys.view" || myUser::getUser()->getRoleId() == "sys.res") {?>
	                            <td width="12%" height="26" nowrap="nowrap" class="cabecera"><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(myUser::getUser()->getRoleId() != "sys.res"){?>
							 	            	<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>
								<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"  onchange="acutalizarRepresentante('cboColaborador',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>
		                       	<?php } ?> 
	                     <td width="15%"  nowrap="nowrap" class="cabecera"><label class="label" for="txtFecha">Representante</label></td>
                         <td nowrap="nowrap"><select class="combo validate-selection " name="cboColaborador" id="cboColaborador"  >
                          	<?php if(myUser::getUser()->getRoleId() != "sys.ope"){?>
							 	  <option value="" > - Seleccionar - </option>
							<?php } ?> 
                          <?php foreach ($a_Colaborador as $iKey => $o_ColaboradorBean){ ?>
                           <option value="<?=$o_ColaboradorBean->getIdColaborador()?>">
                           <?=$o_ColaboradorBean->getNombreCompleto()?>
                           </option>
                          <?php } ?>
                        </select>
		                 </td>
                    
                
              </tr>
			  <tr>
			  <td width="9%" height="26" nowrap="nowrap" class="cabecera"><label class="label" for="txt">Fecho Desde</label></td>
              <td nowrap="nowrap"><input class="text" type="text" ondblclick="this.value=''" size="10" maxlength="10" name="txtFechaInicial" id="txtFechaInicial" value='<?php echo $txtFechaInicial;?>' /><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="9%" height="26" nowrap="nowrap" class="cabecera"><label class="label" for="txtDni">Fecha Hasta</label></td>
              <td nowrap="nowrap"><input class="text" type="text" ondblclick="this.value=''" size="10" maxlength="10" name="txtFechaFinal" id="txtFechaFinal" value='<?php echo $txtFechaFinal;?>'/><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>
			    <td align="right" style="vertical-align:top"><input class="button" type="button" value="Buscar" onclick="findControl();"/></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);
    $('txtivnid').value = "<?=$cod?>";
    findControl();
  </script>
  <?php
}
if(isset($update)){
  ?>
  <script>
    elementLoad.show(undefined,"Se actualizo la ficha satisfactoriamente.");
    setTimeout("elementLoad.hide()",5000);
    $('txtivnid').value = "<?=$cod?>";
    findControl();
  </script>
  <?php
}
if(isset($delete)){
  ?>
  <script>
    elementLoad.show(undefined,"Se elimino la ficha satisfactoriamente."); 
    findControl();
  </script>
  <?php 
  
}
?>