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


<script src="<?php echo Constantes::ROOT_DIR_APP?>/web/hc/code/highcharts.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();
  
}
function visualizar(id){
	$(id).show();
}
function ocultar(id){
	$(id).hide();
}
exportFindControl = function(action){
  strFormSerialize = returnQueryStringForm();
  executeFind(strFormSerialize, action);
}

executeFind = function(str, action){
  if(typeof(action) == 'undefined'){
	  url = "<?=buildUrlComplet('rep.php/uti/gridu_tabla', "block=".$block)?>";
	}else{
	  switch (action){
	    case 'excel': parent.objMainTab.reqBody('<?=buildUrl('uti/excel')?>','001&'+str); break;
        case 'pdf': parent.objMainTab.reqBody('<?=buildUrl('uti/pdf')?>','001&'+str); break;	    
	  }
	  
	  return;
	}
  //str = str + '&block=001';
  url = "<?=buildUrlComplet('mnt.php/uti/gridu_tabla', "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('uti/gridu_tabla', "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=getSucursales&nombreElm';
			new Ajax.Request(url2, {
			  method: 'get', 
              parameters: pars, 
			  onComplete: function(response) {
			    graficarSucursales(response);
			  }
			});
			
			//Obtener el xml de las sucursales x fecha
			var pars = $('form1').serialize();
			var url2 = '<?=buildUrl('ajax/request')?>';
  			pars = pars+'&type=sucursalesxTiempo&nombreElm';
			new Ajax.Request(url2, {
			  method: 'get', 
              parameters: pars, 
			  onComplete: function(response) {
			    graficarSucursalesxFecha(response);
			  }
			});
			
			//Obtener el xml de las mercados x sucursal
			var pars = $('form1').serialize();
			var url2 = '<?=buildUrl('ajax/request')?>';
  			pars = pars+'&type=mercadosSucursales&nombreElm';
			new Ajax.Request(url2, {
			  method: 'get', 
              parameters: pars, 
			  onComplete: function(response) {
			    graficarMercadosSucursales(response);
			  }
			});
			
			//Obtener el xml de las sucursales x
			var pars = $('form1').serialize();
			var url2 = '<?=buildUrl('ajax/request')?>';
  			pars = pars+'&type=mercadosSucursalesxTiempo&nombreElm';
			new Ajax.Request(url2, {
			  method: 'get', 
              parameters: pars, 
			  onComplete: function(response) {
			    graficarMercadosSucursalesxFecha(response);
			  }
			});
			
}



actualizarSucursalesxTiempo = function(){
  var cboSucursalFiltro = '';
  if($('cboSucursalFiltro')) cboSucursalFiltro = $('cboSucursalFiltro').value;
  
  var parsform = $('form1').serialize();
  var url = '<?=buildUrl('ajax/request')?>';
  var pars = 'type=sucursalesxTiempo&cboSucursalFiltro='+cboSucursalFiltro+'&'+parsform;
  new Ajax.Request(url, {
			  method: 'get', 
              parameters: pars, 
			  onComplete: function(response) {
			    graficarSucursalesxFecha(response.responseText);
			  }
			});
	
}

actualizarMercadosxTiempo = function(object){
  var cboSucursalFiltroMxT = '';
  if($('cboSucursalFiltroMxT')) cboSucursalFiltroMxT = $('cboSucursalFiltroMxT').value;
  var cboMercadoFiltro = $('cboMercadoFiltro').value;
  var parsform = $('form1').serialize();
  var url = '<?=buildUrl('ajax/request')?>';
  var pars = 'type=mercadosSucursalesxTiempo&cboMercadoFiltro='+object.value+'&cboSucursalFiltroMxT='+cboSucursalFiltroMxT+'&'+parsform;
  new Ajax.Request(url, {
			  method: 'get', 
              parameters: pars, 
			  onComplete: function(response) {
			    graficarMercadosSucursalesxFecha(response);
			  }
			});
	
}

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;
}
loadMeses = function(){
  $('cboPeriodoInicial').options.length = 1;
 
  value = $('cboAnio').value;
  var url = '<?=buildUrlComplet('rep.php/ajax/request')?>';
  var pars = 'type=getMeses&nombreElm=cboPeriodoInicial&value='+value;
  
	var myAjax = new Ajax.Request(
                            		url, 
                            		{
                            			method: 'get', 
                            			parameters: pars, 
                            			onComplete: actualizaJSON
                            		});
                            		
 
   
}
loadMesesFinal = function(){
  
  $('cboPeriodoFinal').options.length = 1;
  value = $('cboAnioFinal').value;
 
                            		
  var url = '<?=buildUrlComplet('rep.php/ajax/request')?>';
  var pars = 'type=getMeses&nombreElm=cboPeriodoFinal&value='+value;
  
	var myAjax = new Ajax.Request(
                            		url, 
                            		{
                            			method: 'get', 
                            			parameters: pars, 
                            			onComplete: actualizaJSON
                            		});
   
}

function graficarSucursales(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;
	//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);
		
	Highcharts.chart('chartdiv_sucursales', {
		chart: {
	        type: 'pie',
	        options3d: {
	            enabled: true,
	            alpha: 3,
	            beta: 25
	        }
	    },
		lang: {
	        
	        printChart:"Imprimir Imagen",
	        downloadPNG:"Descargar Imagen en PNG"
	        
	    },
		
	        exporting: {
	            filename: 'export_xlsx_example',
	            buttons: {
	                contextButton: {
	                    enabled: true,
	                    menuItems: [
						{
	                        text: 'Exportar PNG',
	                        onclick: function() {
	                            this.exportChart({
	                                type: 'image/png'
	                            });
	                        }
	                    }, {
	                        text: 'Exportar PDF',
	                        onclick: function() {
	                            this.exportChart({
	                                type: 'application/pdf'
	                            });
	                        }
	                    }]
	                }
	            }
	     
	            
	        },
		title: {
			text: TextTitulo
		},
		subtitle: {
			text: TextSubTitulo
		},
	    credits: {
	        enabled: false
	    },
	    tooltip: {
	        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
	    },
	    plotOptions: {
	       pie: {
	            allowPointSelect: true,
	            cursor: 'pointer',
	            depth: 35,
	            dataLabels: {
	                enabled: true,
	                format: '{point.name}'
	            }
	        }
	    },    
			series: 
			[{
		        type: 'pie',
		        data: data
		    }]
	})       
		
		
       
}
function graficarSucursalesxFecha(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('chartdiv_sucursales_x_tiempo', {
		chart: {
	        type: 'column',
	        options3d: {
	            enabled: true,
	            alpha: 3,
	            beta: 25,
	            depth: 70
	        }
	    },
		lang: {
	              
	        viewFullscreen:"Ver en pantalla completa",
	        printChart:"Imprimir Imagen",
	        downloadPNG:"Descargar Imagen en PNG"
	    },
		
	        exporting: {
	            filename: 'export_xlsx_example',
	            buttons: {
	                contextButton: {
	                    enabled: true,
	                    menuItems: [
						{
	                        text: 'Exportar PNG',
	                        onclick: function() {
	                            this.exportChart({
	                                type: 'image/png'
	                            });
	                        }
	                    }, {
	                        text: 'Exportar PDF',
	                        onclick: function() {
	                            this.exportChart({
	                                type: 'application/pdf'
	                            });
	                        }
	                    }]
	                }
	            },
	            csv: {
	                // dateFormat: '%Y%m'
	            }
	        },
		title: {
			text: TextTitulo
		},
		subtitle: {
			text: TextSubTitulo
		},
		xAxis: {
			categories: TextCategories,
			labels: {
	            skew3d: true,
	            style: {
	                fontSize: '16px'
	            }
	        }
		},
		yAxis: {
			/*min: 10,*/
			title: {
				text: TextTiuloYAxis
			}
		},
	    credits: {
	        enabled: false
	    }/*,
		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
			}
		}*/
	    ,
	    plotOptions: {
	        column: {
	            depth: 25
	        }
	    },    
			series: objects
		})  
		
		/*
     	var chart1 = new FusionCharts("<?php echo Constantes::ROOT_DIR_APP?>/web/tools/Charts/Column3D.swf", "ChartId", "540", "380", "0", "0");
     	chart1.addParam("WMode", "Transparent");
     	chart1.setDataXML(xml);
     	chart1.render("chartdiv_sucursales_x_tiempo");
    	
   */
       
}


function graficarMercadosSucursales(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;
	//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);
		
	Highcharts.chart('chartdiv_mercados_x_sucursales', {
		chart: {
	        type: 'pie',
	        options3d: {
	            enabled: true,
	            alpha: 3,
	            beta: 25
	        }
	    },
		lang: {
	       
	        viewFullscreen:"Ver en pantalla completa",
	        printChart:"Imprimir Imagen",
	        downloadPNG:"Descargar Imagen en PNG"
	      
	    },
		
	        exporting: {
	            filename: 'export_xlsx_example',
	            buttons: {
	                contextButton: {
	                    enabled: true,
	                    menuItems: [
						{
	                        text: 'Exportar PNG',
	                        onclick: function() {
	                            this.exportChart({
	                                type: 'image/png'
	                            });
	                        }
	                    }, {
	                        text: 'Exportar PDF',
	                        onclick: function() {
	                            this.exportChart({
	                                type: 'application/pdf'
	                            });
	                        }
	                    }]
	                }
	            }
	        },
		title: {
			text: TextTitulo
		},
		subtitle: {
			text: TextSubTitulo
		},
	    credits: {
	        enabled: false
	    },
	    tooltip: {
	        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
	    },
	    plotOptions: {
	       pie: {
	            allowPointSelect: true,
	            cursor: 'pointer',
	            depth: 35,
	            dataLabels: {
	                enabled: true,
	                format: '{point.name}'
	            }
	        }
	    },    
			series: 
			[{
		        type: 'pie',
		        data: data
		    }]
	})
	
		/*	
	   	var chart1 = new FusionCharts("<?php echo Constantes::ROOT_DIR_APP?>/web/tools/Charts/Pie3D.swf", "ChartId", "540", "380", "0", "0");
     	chart1.addParam("WMode", "Transparent");
     	chart1.setDataXML(xml);
     	chart1.render("chartdiv_mercados_x_sucursales");
    	
		*/   
       
}
function graficarMercadosSucursalesxFecha(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('chartdiv_mercados_x_sucursales_x_tiempo', {
		chart: {
	        type: 'column',
	        options3d: {
	            enabled: true,
	            alpha: 3,
	            beta: 25,
	            depth: 70
	        }
	    },
		lang: {
	      
	        viewFullscreen:"Ver en pantalla completa",
	        printChart:"Imprimir Imagen",
	        downloadPNG:"Descargar Imagen en PNG"
	    },
		
	        exporting: {
	            filename: 'export_xlsx_example',
	            buttons: {
	                contextButton: {
	                    enabled: true,
	                    menuItems: [
						{
	                        text: 'Exportar PNG',
	                        onclick: function() {
	                            this.exportChart({
	                                type: 'image/png'
	                            });
	                        }
	                    }, {
	                        text: 'Exportar PDF',
	                        onclick: function() {
	                            this.exportChart({
	                                type: 'application/pdf'
	                            });
	                        }
	                    }]
	                }
	            },
	            csv: {
	                // dateFormat: '%Y%m'
	            }
	        },
		title: {
			text: TextTitulo
		},
		subtitle: {
			text: TextSubTitulo
		},
		xAxis: {
			categories: TextCategories,
			labels: {
	            skew3d: true,
	            style: {
	                fontSize: '16px'
	            }
	        }
		},
		yAxis: {
			/*min: 10,*/
			title: {
				text: TextTiuloYAxis
			}
		},
	    credits: {
	        enabled: false
	    }/*,
		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
			}
		}*/
	    ,
	    plotOptions: {
	        column: {
	            depth: 25
	        }
	    },    
			series: objects
		}) 
     	
	/*
	var chart1 = new FusionCharts("<?php echo Constantes::ROOT_DIR_APP?>/web/tools/Charts/Column3D.swf", "ChartId", "540", "380", "0", "0");
     	chart1.addParam("WMode", "Transparent");
     	chart1.setDataXML(xml);
     	chart1.render("chartdiv_mercados_x_sucursales_x_tiempo");
    	
   */
       
}



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

function actualizarMercadosxSucusales(valor){
	//Obtener el xml de las mercados x sucursal
	//alert('--');
	var pars = $('form1').serialize();
	var pars = pars+'&cboSucursalFiltro='+valor;
	var url2 = '<?=buildUrl('ajax/request')?>';
		pars = pars+'&type=mercadosSucursales&nombreElm';
	new Ajax.Request(url2, {
	  method: 'get', 
      parameters: pars, 
	  onComplete: function(response) {
	    graficarMercadosSucursales(response);
	  }
	});
}

function actualizarMercadosxTiempo(op){
	if(op == '1'){
		
		var cboSucursalFiltroMxT = '';
		var destino = 'cboMercadoFiltro';
		if($('cboSucursalFiltroMxT')) cboSucursalFiltroMxT= $('cboSucursalFiltroMxT').value;
		$('cboMercadoFiltro').options.length = 0;
	  	var url = '<?=buildUrlComplet('mnt.php/ajax/request')?>';
	  	var pars = 'type=getMercado&nombreElm='+destino+'&value='+cboSucursalFiltroMxT;
	  
		var myAjax = new Ajax.Request(
	                            		url, 
	                            		{
	                            			method: 'get', 
	                            			parameters: pars, 
	                            			onComplete: function (response, json){
	                            				actualizaJSON(response, json);
	                            				 actualizarGraficoMercadoxTiempo();
	                            			}
	                            		});
		
	}else{
		actualizarGraficoMercadoxTiempo();
	}
	
}

function actualizarGraficoMercadoxTiempo(){
	var cboSucursalFiltroMxT = '';
	var cboMercadoFiltro = '';
	if($('cboSucursalFiltroMxT')) cboSucursalFiltroMxT= $('cboSucursalFiltroMxT').value;
	if($('cboMercadoFiltro')) cboMercadoFiltro= $('cboMercadoFiltro').value;
	
	//Obtener el xml de las sucursales x
	var pars = $('form1').serialize();
	var pars = pars+'&cboMercadoFiltro='+cboMercadoFiltro;
	var pars = pars+'&cboSucursalFiltro='+cboSucursalFiltroMxT;
	var url2 = '<?=buildUrl('ajax/request')?>';
		pars = pars+'&type=mercadosSucursalesxTiempo&nombreElm';
	new Ajax.Request(url2, {
	  method: 'get', 
      parameters: pars, 
	  onComplete: function(response) {
	    graficarMercadosSucursalesxFecha(response);
	  }
	});
}
</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
//Carga los Mercado
$o_ClienteSystemClass = new ClienteSystemClass(new TipoNegocioBean());
$a_Mercado = $o_ClienteSystemClass->LoadMercadoXRol();

if( myUser::getUser()->getRoleId() == "sys.res"){
	$idAdministrador = myUser::getUser()->getIdColaborador();
}


$o_SucursalBean = new SucursalBean();
if($idAdministrador)$o_SucursalBean->setIdAdministrador($idAdministrador);
$o_SucursalDP = new SucursalDP($o_SucursalBean);
$a_Sucursal = $o_SucursalDP->select();



/*
$o_SucursalBean = new SucursalBean();
$o_SucursalBL = new SucursalBL();
$a_Sucursal = $o_SucursalBL->busquedaSucursal($o_SucursalBean);

*/


$o_CrUtilidadFN = new CrUtilidadFN();
$a_anios = $o_CrUtilidadFN->getAnios();

$anio_def = date('Y');
$mes_def = date('m');

$periodo_def =$anio_def."-".$mes_def; 

$a_periodos = $o_CrUtilidadFN->getMeses($anio_def);

//Carga los Mercado
$o_ClienteSystemClass = new ClienteSystemClass(new TipoNegocioBean());
$a_Mercado = $o_ClienteSystemClass->LoadMercadoXRol();



$fecha =date('Y-m-d')
?>

<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;Utilidad de Prestamos</li></td>
          
        </tr>
      </table>
      <table class="marco" width="100%">
        <tr>
          <td align="center" valign="top"  width="33%" class="marco">
            	 <table border="0" cellpadding="3" cellspacing="0">
            	 	<tr>
						<td width="12%" height="26" nowrap="nowrap" class="cabecera"><label class="label" for="txtNombre">Zona</label></td>
					</tr>
					<tr>
						<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);"/> 
									<option value="" > - Seleccionar - </option>
									<?php foreach ($a_Sucursal as $iKey => $o_SucursalBean){ ?>
									<option value="<?=$o_SucursalBean->getIdSucursal()?>">
									  <?=$o_SucursalBean->getDescripcion()?>
									</option>
									<?php } ?> 
							  </select>
						</td>
					</tr>
					<tr>
						<td width="12%" height="26" nowrap="nowrap"><label class="label" for="txtNombre">Mercado</label></td>
						<td width="10%" nowrap="nowrap">
								 <select name="cboMercado" id="cboMercado" type="text" class="combo"  onchange="acutalizarRepresentante('cboRepresentante',this);"/> 
									<option value="" > - Seleccionar - </option>
								</select>
						</td>
					</tr>
					<tr>
						<td width="12%" height="26" nowrap="nowrap"><label class="label" for="txtNombre">Representante</label></td>
						<td width="10%" nowrap="nowrap">
							 <select name="cboRepresentante" id="cboRepresentante" type="text" class="combo"/> 
								<option value="" > - Seleccionar - </option>
							</select>
					  </td>
					 
					</tr>
					<tr>
						<td width="12%" height="26" nowrap="nowrap" class="cabecera"></td>
					</tr>
				</table>
          </td>
          <td  width="33%" class="marco">
          		<table border="0" cellpadding="3" cellspacing="0">
          			<tr>
						<td width="12%" height="26" nowrap="nowrap" class="cabecera" colspan="5"><label class="label" for="txtNombre">Tiempo</label></td>
					</tr>
          			<tr>
						<td colspan="5"><input type="radio" name="tiempo" value="1" checked onclick="javascript:visualizar('tiempoPeriodo');ocultar('tiempoFecha');"><label class="label" for="txt">Periodo  </label>
								
						</td>
					</tr>
					<tr  id="tiempoPeriodo" >
					  		
						 <td width="9%" height="26" nowrap="nowrap"><label class="label" for="txt"></label>
								</td>
						 <td width="9%" height="26" nowrap="nowrap"><label class="label" for="txt">Desde</label></td>
							<td nowrap="nowrap"><label class="label" for="txtNombre">
								<select name="cboAnio" id="cboAnio" type="text" class="combo" onchange="loadMeses(this.value)"/> 
									<option value="" >Seleccione </option>
										<?php foreach ($a_anios as $key => $val){ ?>
										<option value="<?=$val?>" <?if($val == $anio_def) echo " selected "?>>
										  <?=$val?>
										</option>
										<?php } ?> 
								 </select>
								 <select name="cboPeriodoInicial" id="cboPeriodoInicial" type="text" class="combo" /> 
									<option value="" >Seleccione</option>
									<?php foreach ($a_periodos as $key => $val){ ?>
										<option value="<?=$val?>" <?if($val == $periodo_def) echo " selected "?>>
										  <?=$val?>
										</option>
									<?php } ?> 
								</select>
							</td>
							
						 <td width="9%" height="26" nowrap="nowrap"><label class="label" for="txtDni">Hasta</label></td>
						 <td nowrap="nowrap">
						 	<select name="cboAnioFinal" id="cboAnioFinal" type="text" class="combo" onchange="loadMesesFinal()"/> 
									<option value="" >Seleccione </option>
										<?php foreach ($a_anios as $key => $val){ ?>
										<option value="<?=$val?>" <?if($val == $anio_def) echo " selected "?>>
										  <?=$val?>
										</option>
										<?php } ?> 
							 </select>
						 	 <select name="cboPeriodoFinal" id="cboPeriodoFinal" type="text" class="combo"/> 
									<option value="" > - Seleccionar - </option>
									<?php foreach ($a_periodos as $key => $val){ ?>
										<option value="<?=$val?>" <?if($val == $periodo_def) echo " selected "?>>
										  <?=$val?>
										</option>
									<?php } ?> 
							</select>
						 </td>
							
							
					</tr>
					<tr>
						<td colspan="5"><input type="radio" name="tiempo" value="2" onclick="javascript:visualizar('tiempoFecha');ocultar('tiempoPeriodo');"><label class="label" for="txt">Fecha</label>
						</td>
					</tr>
					<tr id="tiempoFecha" style="display:none">
					  	 <td></td> 
						 <td width="9%" height="26" nowrap="nowrap"><label class="label" for="txt">Desde</label></td>
							<td nowrap="nowrap"><input class="text" type="text" ondblclick="this.value=''" size="8" maxlength="10" name="txtFechaInicial" id="txtFechaInicial" value='<?=$fecha?>' />&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="9%" height="26" nowrap="nowrap"><label class="label" for="txtDni">Hasta</label></td>
						 <td nowrap="nowrap">&nbsp;<input class="text" type="text" ondblclick="this.value=''" size="8" maxlength="10" name="txtFechaFinal" id="txtFechaFinal" 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>
							
					</tr>
				</table>
          </td>
           <td class="marco">
          		<table   border="0" cellpadding="3" cellspacing="0">
          			<tr>
						<td  height="26" nowrap="nowrap" class="cabecera"><label class="label" for="txtNombre">Prestamos</label></td>
					</tr>
					<tr>
						<td><input type="radio" name="opfechavencimiento" value="" checked="checked"><label class="label" for="txt">Todos</label>
						</td>
					</tr>
					<tr>
						<td><input type="radio" name="opfechavencimiento" value="<" ><label class="label" for="txt">Cancelado antes de la Fecha de Vencimiento</label>
						</td>
					</tr>
					<tr>
						<td><input type="radio" name="opfechavencimiento" value="="><label class="label" for="txt">Cancelado en la Fecha de Vencimiento</label>
						</td>
					</tr>
					<tr>
						<td><input type="radio" name="opfechavencimiento" value=">"><label class="label" for="txt">Cancelado despues de la Fecha de Vencimiento</label>&nbsp;&nbsp;<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);
    $('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 
  
}
?>