<script>

	//-------------------------Chat-----------------------------------

	function openForm() {
	    document.getElementById("myForm").style.display = "block";
	}

	function llenaListaChat(){

		$('#chatSel').append("<option value='1'>Juanito</option>");
		$('#chatSel').append("<option value='2'>Pepe</option>");
		$('#chatSel').append("<option value='3'>Pedro</option>");
		$('#chatSel').append("<option value='4'>Paco</option>");
		$('#chatSel').append("<option value='5'>Jason</option>");

		$('select').formSelect();

	}

	function closeForm() {
	    document.getElementById("myForm").style.display = "none";
	}

	//-------------------------Chat-----------------------------------

	// var a = document.getElementById('idioma');
	// if(a.value == "es"){
	// 	<?php if (defined("BANDERA_ES")) {?>
	// 		document.getElementById('banderaPais').innerHTML = '<span class="flag-icon flag-icon-<?php echo BANDERA_ES; ?>"></span>&nbsp;';
	// 	<?php } else {?>
	// 		document.getElementById('banderaPais').innerHTML = '<span class="flag-icon flag-icon-mx"></span>&nbsp;';
	// 	<?php }?>
	// }else{
	// 	document.getElementById('banderaPais').innerHTML = '<span class="flag-icon flag-icon-um"></span>&nbsp;';
	// }

	var banderaMaestra = true;
	var banderaMaestra2 = true;
	var labels = [traducirFrase("Agentes esperando"), traducirFrase("Agentes pausados"), traducirFrase("Agentes en llamada cortada"), traducirFrase("Agentes calificando"),
	traducirFrase("Agentes en llamada")
	];
	var agentes = [];
	var dataLine2 = [];
	var llamadas = [];
	var agentesInCall = [];
	var llamadasSonando = [];
	var llamadasEntrantes = [];
	var llamadasSalientes = [];
	var flagInfo2 = false;
	var datasets = [];
	var count = 0;
	var datasethistorico=[];
	function addLineChartData(chart, label, data,horagod) {
		chart.data.labels.push(label);
		for (var i = 0; i < chart.data.datasets.length; i++) {
			chart.data.datasets[i].data.push((data[i]));
		}
		chart.update();
	}


	function addLineChartDataW(chart, label, data) {

		//alert("entro, label: "+label);

		var tiempo = new Date().getTime();
		for (var i = 0; i < chart.series.length; i++) {


			chart.series[i].addPoint({
				x:  tiempo,
				y:  parseInt(data[i])
			});

		}

		//alert(superTiempo);

		//chart.xAxis[0].setExtremes(superTiempo, tiempo);

	}


	function addHistoricData(chart,fecha, data){
		var tiempo=new Date(fecha*1000).getTime();
		for(var i=0;i<chart.series.length;i++){
			chart.series[i].addPoint({
				x:  tiempo,
				y:  parseInt(data[i])
			},false);
		}
	}
	function addLineChartDataW2(chart, label, data) {

		var tiempo = new Date().getTime();

		//alert("entro, dataLength: "+chart.series.length);

		for (var i = 0; i < chart.series.length-1; i++) {

			/*chart.series[i].addPoint({
				x:  label,
				y:  data[i]
			});*/

			chart.series[i].addPoint({
                    x:  tiempo,
                    y:  parseInt(data[i])
                });

		}

		chart.xAxis[0].setExtremes(superTiempo, tiempo);

	}

	function addRadarChartData(chart, data, label) {
		chart.data.datasets[0].data = data;
		chart.update();
		if (label != null) chart.data.labels = label;
	}

	function limpiaAgentes() {
		$('.barrita').show();
		for (var i = 0; i < radarChart.data.datasets.length; i++) {
			radarChart.data.datasets[i].data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
				0, 0, 0, 0
			];
		}
		for (var i = 0; i < pieChart.data.datasets.length; i++) {
			pieChart.data.datasets[i].data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
				0, 0, 0
			];
		}
		for (var i = 0; i < barChart.data.datasets.length; i++) {
			barChart.data.datasets[i].data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
				0, 0, 0
			];
		}
		for (var i = 0; i < lineChart.data.datasets.length; i++) {
			lineChart.data.datasets[i].data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
				0, 0, 0, 0
			];
		}

	}

	function trae_historico(){
		var url= 'homeAdmin/dameHistorico';
		$.ajax({
			url:url,
			type: "POST",
			dataType: "text",
			async: "true",
			success: function (resp) {
				var data=JSON.parse(resp);
				for (const fecha in data) {
					var dataS =[ data[fecha]['agents_waiting'],
							data[fecha]['agents_paused'],
							data[fecha]['agents_in_dead_calls'],
							data[fecha]['agents_in_dispo'],
							data[fecha]['agents_in_calls']
					];
					$etiqueta=data[fecha]['etiqueta'];
					data[fecha]['real']+=' UTC';
					addHistoricData(lineChart2, fecha, dataS);
				}
				lineChart2.redraw();
			}
		})
	}
	function limpiaCampanas() {}

	function refrescaBloqueAgentes() {
		var url = "<?php echo MODULOS; ?>homeAdmin/dameInfo";
		if ($("#campanaAgentes").val() != -1) {
			url = "usuarios/getInfoAgents";
		}
			let archived=document.getElementById("archived").checked?1:0;
		var parametros = {
			campana: $("#campanaAgentes").val(),
			archived:archived
		};
		if (banderaMaestra) {
			banderaMaestra = false;
			$.ajax({
				url: url,
				type: "POST",
				data: parametros,
				dataType: "text",
				cache: false,
				async: true,
				success: function (resp) {
                    cargaGraficasCuadritos();
					var data = JSON.parse(resp);
					banderaMaestra = true;
					if (data.Estado == 'ok') {
						refrescaGrafica0(data);
						var dataS = [data.agents_waiting,
							data.agents_paused,
							data.agents_in_dead_calls,
							data.agents_in_dispo,
							data.agents_in_calls
						];
						addRadarChartData(radarChart, dataS, null);
						addRadarChartData(pieChart, dataS, null);
						addRadarChartData(barChart, dataS, null);
						lineChart.data.labels.shift();
						for (var i = 0; i < lineChart.data.datasets.length; i++) {
							lineChart.data.datasets[i].data.shift();
						}
						var tiempo=fixedDate();
						addLineChartData(lineChart, data.hora, dataS);
						addLineChartDataW(lineChart2, data.hora, dataS);
						$('.barrita').hide();

					} else {
						M.toast({
							html: data.Descripcion
						});
					}
				},
				error: function (data) {
					banderaMaestra = true;
				}
			});
		}

	}

	var running = false;
	var primeraVez = true;
	var seriesOptions = [];
	var dataE = [];
	time = fixedDate();
	var i ;
	for (i = -99; i <= 0; i += 1) {
		dataE.push([
			time + i * 1000,
			0
		]);
	}

	function refrescaBloqueCampanas(recrea, ) {
		if (!running) {
			if (recrea) {
				$('.barrita').show();
			}
			primeraVez = false;
			var url = "<?echo MODULOS; ?>campanasHome/dameInfoCampa";
			let archived=document.getElementById("archived").checked?1:0;
			var parametros = {
				campana: $("#campanaCampanas").val(),
				lista: $("#listaCampanas").val(),
				archived:archived
			};
			if (banderaMaestra2) {
				banderaMaestra2 = false;
				$.ajax({
					url: url,
					type: "POST",
					data: parametros,
					async: true,
					cache: false,
					dataType: "text",
					success: function (resp) {

                        //cargaGraficasCuadritos();
						var data = JSON.parse(resp);
						if (data.Estado == 'ok') {
							if (data.estados != undefined) {
								var dataS = [];
								var label = [];
								for (var i = 0; i < data.estados.length; i++) {
									label[i] = data.estados[i].nombre;
									dataS[i] = data.estados[i].cuantos;
								}
								if (recrea) {
									creaTest(label, dataS, data.HORA);
								} else {
									addRadarChartData(radarChart1, dataS, null);
									addRadarChartData(pieChart1, dataS, null);
									addRadarChartData(barChart1, dataS, null);
									lineChart1.data.labels.shift();
									for (var i = 0; i < lineChart1.data.datasets.length; i++) {
										lineChart1.data.datasets[i].data.shift();
									}

									//addLineChartData(lineChart1, data.HORA, dataS);

								}
							} else {
                                if(cualEstaActivo ==2){
                                    M.toast({
                                        html: traducirFrase('No hay datos disponibles')
                                    });
                                }
								lineChart1 = new Chart(lineCanvas1, {
									type: "line",
									data: {
										labels: [i18n.gettext("No hay datos disponibles")],
										datasets: [{
											label: i18n.gettext("No hay datos disponibles"),
											backgroundColor: myColors,
											borderColor: "rgb(3, 40, 68)",
											data: [0]
										}]
									},
									options: {
										maintainAspectRatio: false,
										scales: {
											yAxes: [{
												display: true,
												ticks: {
													min: 0,
													suggestedMax: 30
												}
											}]
										},
										onClick:function()
										{

										}
									}
								});


								radarChart1 = new Chart(radarCanvas1, {
									type: "radar",
									data: {
										labels: [i18n.gettext("No hay datos disponibles")],
										datasets: [{
											label: i18n.gettext("No hay datos disponibles"),
											backgroundColor: myColors,
											borderColor: "rgb(3, 40, 68)",
											data: [0]
										}]
									},
									options: {
										maintainAspectRatio: false,
										responsive: true,
										onClick:function()
										{

										}
									}
								});
								pieChart1 = new Chart(pieCanvas1, {
									type: "pie",
									data: {
										labels: [i18n.gettext("No hay datos disponibles")],
										datasets: [{
											data: [0],
											backgroundColor: myColors,
											borderColor: "rgb(3, 40, 68)"
										}]
									},
									options: {
										maintainAspectRatio: false,
										responsive: true,
										onClick:function()
										{

										}
									}
								});
								barChart1 = new Chart(barCanvas1, {
									type: "horizontalBar",
									data: {
										labels: [i18n.gettext("No hay datos disponibles")],
										datasets: [{
											label: i18n.gettext("No hay datos disponibles"),
											data: [0],
											backgroundColor: myColors,
											borderColor: "rgb(3, 40, 68)"
										}]
									},
									options: {
										maintainAspectRatio: false,
										responsive: true,
										onClick:function()
										{

										}
									}
								});

							}

							$('.barrita').hide();

						} else {
							M.toast({
								html: data.Descripcion
							});
						}
						banderaMaestra2 = true;
					},
					error: function (data) {
						console.log(data);
						banderaMaestra2 = false;
					}
				});
			}
		}
	}

	function refrescaGrafica0(datos) {
		$("#agentes_logueados").html(datos.agents_logged_in);
		$("#agentes_en_llamada").html(datos.agents_in_calls);
		$("#llamadas_activas").html(datos.llamadas_activas);
		$("#llamadas_sonando").html(datos.llamadas_sonando);
		$("#llamadas_entrantes").html(datos.llamadasEntrantes);
		$("#llamadas_salientes").html(datos.agents_in_calls - datos.llamadasEntrantes);
		agentes.push(datos.agents_logged_in);
		agentesInCall.push(datos.agents_in_calls);
		llamadas.push(datos.llamadas_activas);
		if (agentes.length >= 19) {
			agentes = agentes.slice(1, agentes.length + 1);
		}
		if (agentesInCall.length >= 19) {
			agentesInCall = agentesInCall.slice(1, agentesInCall.length + 1);
		}
		if (llamadas.length >= 19) {
			llamadas = llamadas.slice(1, llamadas.length + 1);
		}
		llamadasSonando.push(datos.llamadas_sonando);
		if (llamadasSonando.length >= 19) {
			llamadasSonando = llamadasSonando.slice(1, llamadasSonando.length + 1);
		}
		llamadasEntrantes.push(datos.llamadasEntrantes);
		if (llamadasEntrantes.length >= 19) {
			llamadasEntrantes = llamadasEntrantes.slice(1, llamadasEntrantes.length + 1);
		}
		llamadasSalientes.push(datos.agents_in_calls - datos.llamadasEntrantes);
		if (llamadasSalientes.length >= 19) {
			llamadasSalientes = llamadasSalientes.slice(1, llamadasSalientes.length + 1);
		}

		$("#clients-bar").sparkline(agentes, {
			type: 'bar',
			height: '25',
			barWidth: 7,
			barSpacing: 4,
			barColor: '#b2ebf2',
			negBarColor: '#81d4fa',
			zeroColor: '#81d4fa',
		});
		$("#profit-tristate").sparkline(llamadas, {
			type: 'line',
			width: '100%',
			height: '25',
			lineWidth: 2,
			lineColor: '#E1D0FF',
			fillColor: 'rgba(255, 255, 255, 0.2)',
			highlightSpotColor: '#E1D0FF',
			highlightLineColor: '#E1D0FF',
			minSpotColor: '#00bcd4',
			maxSpotColor: '#4caf50',
			spotColor: '#E1D0FF',
			spotRadius: 4
		});
		$("#sales-compositebar").sparkline(agentesInCall, {
			type: 'bar',
			height: '25',
			barWidth: 7,
			barSpacing: 4,
			barColor: '#b2ebf2',
			negBarColor: '#81d4fa',
			zeroColor: '#81d4fa',
		});
		$("#invoice-line").sparkline(llamadasSonando, {
			type: 'line',
			width: '100%',
			height: '25',
			lineWidth: 2,
			lineColor: '#E1D0FF',
			fillColor: 'rgba(233, 30, 99, 0.4)',
			highlightSpotColor: '#E1D0FF',
			highlightLineColor: '#E1D0FF',
			minSpotColor: '#f44336',
			maxSpotColor: '#4caf50',
			spotColor: '#E1D0FF',
			spotRadius: 4,
		});
		$("#inbound-line").sparkline(llamadasEntrantes, {
			type: 'line',
			width: '100%',
			height: '25',
			lineWidth: 2,
			lineColor: '#E1D0FF',
			fillColor: 'rgba(233, 30, 99, 0.4)',
			highlightSpotColor: '#E1D0FF',
			highlightLineColor: '#E1D0FF',
			minSpotColor: '#f44336',
			maxSpotColor: '#4caf50',
			spotColor: '#E1D0FF',
			spotRadius: 4,
		});
		$("#outbound-line").sparkline(llamadasSalientes, {
			type: 'line',
			width: '100%',
			height: '25',
			lineWidth: 2,
			lineColor: '#E1D0FF',
			fillColor: 'rgba(233, 30, 99, 0.4)',
			highlightSpotColor: '#E1D0FF',
			highlightLineColor: '#E1D0FF',
			minSpotColor: '#f44336',
			maxSpotColor: '#4caf50',
			spotColor: '#E1D0FF',
			spotRadius: 4,
		});

	}

	var flagShida = false;
	var flagShida1 = false;
    var cualEstaActivo = 1;
	var PrimeroHist = 0;
	function cargarCampanas() {
		if (!flagShida) {
			flagShida = true;
			$.ajax({
				url: "/<?=RUTA_MAESTRA;?>/index.php/campanas/getCampaignsSelect ",
				type: "POST",
				async: true,
				cache: false,
				dataType: "text",
				success: function (result) {
					flagShida = false;
					var res = JSON.parse(result);
					if (res.Estado == 'ok') {
						var Anterior = $("#campanaAgentes").val();
						var Texto = "<option value='-1' " + ("-1" == Anterior ? "selected='selected'" : "") +
							"><div class='white-text'>"+i18n.gettext("Todas las campañas")+"</div></option>";
						$("#campanaAgentes").html("");
						var Otro = "";
						var otroAnterior = $("#campanaCampanas").val();
						$("#campanaCampanas").html("");
						for (var i = 0; i < res.Campanas.length; i++) {
							Texto += "<option value='" + res.Campanas[i].campaign_id + "' " + (res.Campanas[i].campaign_id == Anterior ?
									"selected='selected'" : "") + "><span style='color:black;'>" + res.Campanas[i].campaign_name +
								"</span></option>";
							Otro += "<option value='" + res.Campanas[i].campaign_id + "' " + (res.Campanas[i].campaign_id == otroAnterior ?
									"selected='selected'" : "") + "><span style='color:black;'>" + res.Campanas[i].campaign_name +
								"</span></option>";
						}
						$("#campanaAgentes").html(Texto);
						$("#campanaCampanas").html(Otro);
						cargarListas();

						if(PrimeroHist == 0){

							consultaCampa(1);
							PrimeroHist = 1;

						}

					} else {
						M.toast({
							html: res.Descripcion
						});
					}
				},
				error: function (data) {
					console.log(data);
				}
			});
		}
	}
	function fixedDate(){
		let time = new Date()
		time.setUTCHours(time.getHours())
		return time.getTime()
	}
	function cargarListas() {
		if (!flagShida1) {
			flagShida1 = true;
			$.ajax({
				url: "/<?=RUTA_MAESTRA;?>/index.php/listas/getListsSelect ",
				type: "POST",
				data: {
					campana: $("#campanaCampanas").val()
				},
				async: true,
				cache: false,
				dataType: "text",
				success: function (result) {
					flagShida1 = false;
					var res = JSON.parse(result);
					if (res.Estado == 'ok') {
						var Anterior = $("#listaCampanas").val();
						var Otro = "<option value='-1' " + ("-1" == Anterior ? "selected='selected'" : "") +
							"><div class='white-text'>"+i18n.gettext("Todas las listas")+"</div></option>";

						$("#listaCampanas").html("");
						for (var i = 0; i < res.Listas.length; i++) {
							Otro += "<option value='" + res.Listas[i].list_id + "' " + (res.Listas[i].list_id == Anterior ?
								"selected='selected'" : "") + "><span style='color:black;'>" + res.Listas[i].list_name + "</span></option>";
						}
						$("#listaCampanas").html(Otro);
					} else {
						M.toast({
							html: res.Descripcion
						});
					}
				},
				error: function (data) {
					console.log(data);
					flagShida1 = false;
				}
			});
		}
	}

	var superTiempo;
	var flagInfo = true;
    function cargaGraficasCuadritos(){
        if (flagInfo) {
			flagInfo = false;
            var cualCampana = "";
            if(cualEstaActivo == 1){
                cualCampana = $("#campanaAgentes").val();
            }else{
                cualCampana = $("#campanaCampanas").val();
            }
            var parametros = {
                campana: cualCampana
            };
			$.ajax({
				url: "<?=MODULOS;?>homeAdmin/dameInfo",
				type: "POST",
				data: parametros,
				async: true,
				cache: false,
				dataType: "text",
				success: function (result) {
					flagInfo = true;
					var res = JSON.parse(result);
					if (res.Estado == 'ok') {
						refrescaGrafica0(res);
					} else {
						M.toast({
							html: res.Descripcion
						});
					}
				},
				error: function (data) {
					flagInfo = true;
				}
			});
		}
    }

	var superAcumulado;

	function cambiaRelleno(){
		if( $('#rellenaGraph').prop('checked') ) {
			consultaCampa(2);
		}else{
			consultaCampa(1);
		}
	}

	var graficaCampanias = null;

	function consultaCampa(valor){

		//alert(valor);

		var idCampa = $("#campanaCampanas").val();

		//alert("Consultando: "+idCampa);

		$("#lineCanvasEsp2").html("");

		$(".barritaW").show();
		let archived=document.getElementById("archived").checked?1:0;
		$.ajax({
			url: "CampanasHome/infoCampaHistAcum",
			type: "POST",
			data: {
					campana: idCampa,
					lista: 0,
					archived : archived,
				},
			async: true,
			cache: false,
			dataType: "text",
			success: function (resp) {

				var data = JSON.parse(resp);

				superAcumulado = data;

				var dataE = [];

				var seriesW = [];

				$.each(data.estatus, function( index, value ) {

					dataE = [];

					$.each(value.calls, function( index, value2 ) {


						time = (new Date(value2.fecha)).getTime();
						dato = parseInt(value2.cuenta);


						dataE.push([
							time,
							dato
						]);

					});

					if(valor == 1){


						seriesW.push({'name' : value.estatus, type: 'line', 'data': dataE});

					}else{

						seriesW.push({'name' : value.estatus, type: 'area', 'data': dataE});
					}



				});



				if(graficaCampanias != null){

					//alert("se destruyo");

					graficaCampanias.destroy();

					$('#lineCanvasEsp2').html('');

				}

				//Armado de la grafica

				// Create a timer
				var start = +new Date();

				//$("#lineCanvasEsp2").show();

				// Create the chart
				graficaCampanias = Highcharts.stockChart('lineCanvasEsp2', {
					chart: {
						events: {
							load: function () {
								if (!window.TestController) {
									this.setTitle(null, {
										text: ' '
									});
								}
							}
						},
						zoomType: 'x'
					},

					yAxis: {

						labels: {
							enabled: true
						}
					},

					rangeSelector: {

						enabled: false
					},

					legend: {
						layout: 'horizontal',
						align: 'center',
						verticalAlign: 'top',
						enabled: true,
						width: 1300,
						height: 500,
						x: 30,
						navigation: {
							enabled:true,
							activeColor: '#3E576F',
							animation: true,
							arrowSize: 12,
							inactiveColor: '#CCC',
							style: {
								fontWeight: 'bold',
								color: '#333',
								fontSize: '12px'
							}
						}
					},

					yAxis: {
						title: {
							text: traducirFrase('Llamadas')
						}
					},

					title: {
						text: traducirFrase("Lista historica acumulada de campaña")+' '+$('select[id="campanaCampanas"] option:selected').text()
					},

					series: seriesW

				});

				$(".barritaW").hide();


			},
			error: function (data) {
				console.error(data);
			}
		});

		//alert("Acabo de consultar")
	}

	var app = new Vue({
		el: '#main',
		data: {
			iam: 'agente',
			i18n : i18n
		},
		methods: {
			change: function (a) {
				this.iam = a;
			}
		},
		mounted: function () {
			window.bla;
			window.cardbla;
			function cambiarAOscuro() {

				for (let i = 0; i < bla.length; i++) {
					bla[i].classList.remove('white');
					bla[i].classList.add('grey');
					bla[i].classList.add('lighten-1');
					bla[i].style.filter = 'invert(100%)';
				}
				for (let i = 0; i < cardbla.length; i++) {
					cardbla[i].classList.remove('white');
					cardbla[i].classList.add('grey');
					cardbla[i].classList.add('lighten-1');
					cardbla[i].style.filter = 'invert(85%)';
				}
				document.getElementById('mainHome').style.filter = 'invert(85%)'
			}

			if (localStorage.getItem('background') == "black") {
				bla = document.getElementsByClassName('card-panel')
				bla = Array.prototype.slice.call(bla)
				cardbla = document.getElementsByClassName('card')
				cardbla = Array.prototype.slice.call(cardbla)
				cambiarAOscuro();
			}

            // Contenido content-script
            window.elems = document.querySelectorAll('.sidenav');
            window.instances = M.Sidenav.init(elems, {});
            window.d = new Date();
            window.hour = d.getHours() + ":" + d.getMinutes();
            window.myColors1 = [
                "#0048E5",
                "#0D56E6",
                "#1B64E7",
                "#2873E9",
                "#3681EA",
                "#438FEB",
                "#519EED",
                "#5EACEE",
                "#6CBAEF",
                "#79C9F1",
                "#87D7F2",
                "#95E6F4"
            ];
            window.myColors2 = [
                "rgba(17, 70, 176, 0.44)",
                "rgba(24, 77, 179, 0.49)",
                "rgba(31, 85, 183, 0.5)",
                "rgba(38, 92, 187, 0.5)",
                "rgba(45, 100, 191, 0.5)",
                "rgba(52, 108, 195, 0.5)",
                "rgba(60, 115, 199, 0.5)",
                "rgba(67, 123, 203, 0.5)",
                "rgba(74, 130, 207, 0.5)",
                "rgba(81, 138, 211, 0.5)",
                "rgba(88, 146, 215, 0.5)",
                "rgba(95, 153, 219, 0.5)",
                "rgba(103, 161, 223, 0.5)",
                "rgba(110, 168, 227, 0.5)",
                "rgba(117, 176, 231, 0.5)",
                "rgba(124, 184, 235, 0.5)",
                "rgba(131, 191, 239, 0.5)",
                "rgba(138, 199, 243, 0.5)",
                "rgba(138, 199, 243, 0.5)"
            ];
            window.myColors = [
                "rgba(9, 97, 229, 0.3)",
                "rgba(107, 238, 149, 0.3)",
                "rgba(244, 252, 0, 0.3)",
                "rgba(214, 176, 10, 0.3)",
                "rgba(13, 137, 98, 0.3)",
                "rgba(191, 42, 59, 0.3)",
                "rgba(237, 159, 42, 0.3)",

                "rgba(126, 73, 183, 0.3)",
                "rgba(52, 55, 153, 0.3)",
                "rgba(134, 145, 20, 0.3)",
                "rgba(16, 188, 3, 0.3)",
                "rgba(178, 209, 54, 0.3)",
                "rgba(224, 80, 210, 0.3)",
                "rgba(239, 100, 93, 0.3)",
                "rgba(75, 6, 132, 0.3)",
                "rgba(127, 175, 36, 0.3)",
                "rgba(56, 209, 99, 0.3)",
                "rgba(249, 83, 42, 0.3)",
                "rgba(247, 19, 201, 0.3)",
                "rgba(75, 242, 128, 0.3)",
                "rgba(162, 226, 49, 0.3)",
                "rgba(237, 208, 64, 0.3)",
                "rgba(89, 219, 189, 0.3)",
                "rgba(234, 83, 56, 0.3)",
                "rgba(6, 143, 150, 0.3)"
            ]
            window.h1 = [];
            window.d21 = [];

            function mete30h(arr, h) {
                for (let index = 0; index < 30; index++) {
                    arr.push(h);
                }
            }

            function mete30h2(arr, h) {
                for (let index = 0; index < 30; index++) {
                    arr.push(h);
                }
                return arr;
            }

            function mete30z(arr) {
                for (let index = 0; index < 30; index++) {
                    arr.push(0)
                }
                return arr
            }

            function mete30z2(arr) {
                for (let r = 0; r < 30; r++) {
                    arr.push(0)
                }

            }
            mete30z2(d21);
            window.arraynel = d21;
            window.arrayVacio1 = [];

            window.lineCanvas = document.getElementById("lineCanvas").getContext("2d");
            window.lineChart = new Chart(lineCanvas, {
                type: "line",
                data: {
                    labels: mete30h2(h1, hour),
                    datasets: [{
                            label: traducir2("Agentes esperando"),
                            backgroundColor: myColors[0],
                            borderColor: "rgb(0, 0, 0)",
                            data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        },
                        {
                            label: traducir2("Agentes pausados"),
                            backgroundColor: myColors[1],
                            borderColor: "rgb(0,0,0)",
                            data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        },
                        {
                            label: traducir2("Agentes en llamada cortada"),
                            backgroundColor: myColors[2],
                            borderColor: "rgb(0, 0, 0)",
                            data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        },
                        {
                            label: traducir2("Agentes calificando"),
                            backgroundColor: myColors[3],
                            borderColor: "rgb(3, 40, 68)",
                            data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        },
                        {
                            label: traducir2("Agentes en llamada"),
                            backgroundColor: myColors[4],
                            borderColor: "rgb(3, 40, 68)",
                            data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        }
                    ]
                },
                options: {
                    maintainAspectRatio: false,
                    scales: {
                        yAxes: [{
                            display: true,
                            ticks: {
                                min: 0, // minimum will be 0, unless there is a lower value.
                                // OR //
                                suggestedMax: 50
                            }
                        }]
                    }
                }
            });
            window.radarCanvas = document.getElementById("radarCanvas").getContext("2d");
            window.radarChart = new Chart(radarCanvas, {
                type: "radar",
                data: {
                    labels: [
                        traducir2("Agentes esperando"),
                        traducir2("Agentes pausados"),
                        traducir2("Agentes en llamada cortada"),
                        traducir2("Agentes calificando"),
                        traducir2("Agentes en llamada")
                    ],
                    datasets: [{
                        label: traducir2("Tendencia de Agentes"),
                        backgroundColor: myColors[0],
                        borderColor: "rgb(3, 40, 68)",
                        data: [0, 0, 0, 0, 0]
                    }]
                },
                options: {}
            });
            window.pieCanvas = document.getElementById("pieCanvas").getContext("2d");
            window.pieChart = new Chart(pieCanvas, {
                type: "pie",
                data: {
                    labels: [
                        traducir2("Agentes esperando"),
                        traducir2("Agentes pausados"),
                        traducir2("Agentes en llamada cortada"),
                        traducir2("Agentes calificando"),
                        traducir2("Agentes en llamada")
                    ],

                    datasets: [{
                        data: [0, 0, 0, 0, 0],
                        backgroundColor: myColors,
                        borderColor: "rgb(3, 40, 68)"
                    }]
                },
                options: {
                    tooltips: {
                        callbacks: {
                            label: function (tooltipItem, data) {
                                var dataset = data.datasets[tooltipItem.datasetIndex];
                                var meta = dataset._meta[Object.keys(dataset._meta)[0]];
                                var total = meta.total;
                                var currentValue = dataset.data[tooltipItem.index];
                                var percentage = parseFloat((currentValue / total * 100).toFixed(1));
                                if (Number.isNaN(percentage)) {
                                    return currentValue + ' (' + 0 + '%)';
                                } else {
                                    return currentValue + ' (' + percentage + '%)';
                                }

                            },
                            title: function (tooltipItem, data) {
                                return data.labels[tooltipItem[0].index];
                            }
                        }
                    },
                }
            });
            window.barCanvas = document.getElementById("barCanvas").getContext("2d");
            window.barChart = new Chart(barCanvas, {
                type: "horizontalBar",
                data: {
                    labels: [
                        traducir2("Agentes esperando"),
                        traducir2("Agentes pausados"),
                        traducir2("Agentes en llamada cortada"),
                        traducir2("Agentes calificando"),
                        traducir2("Agentes en llamada")
                    ],

                    datasets: [{
                        label: traducir2("Tendencia de Agentes"),
                        data: [0, 0, 0, 0, 0],
                        backgroundColor: myColors,
                        borderColor: "rgb(3, 40, 68)"
                    }]
                },
                options: {}
            });
            window.lineCanvas1 = document.getElementById("lineCanvas1").getContext("2d");
            window.radarCanvas1 = document.getElementById("radarCanvas1").getContext("2d");
            window.pieCanvas1 = document.getElementById("pieCanvas1").getContext("2d");
            window.barCanvas1 = document.getElementById("barCanvas1").getContext("2d");
            window.historico = [];
            window.histo2 = [];
            window.lineChart1 = null;
            window.radarChart1 = null;
            window.pieChart1 = null;
            window.barChart1 = null;
            window.historyCounter = 0;
            window.dat = [hour];
            window.aux1;
            window.aux2;
            window.aux3;

            window.creaTest = function(labels, data, hora) {
                if (1 == 1) {
                    if (lineChart1 != null) {
                        lineChart1.destroy();
                        radarChart1.destroy();
                        barChart1.destroy();
                        pieChart1.destroy();
                    }
                    for (var i = 0; i <= labels.length; i++) {
                        if (historico[i] == null) historico[i] = [];
                        mete30z(historico[i])
                        historico[i].push(data[i]);
                        dat[i] = {
                            label: labels[i],
                            backgroundColor: myColors[i],
                            borderColor: "rgb(0,0,0)",
                            data: historico[i]
                        };
                    }
                    histo2.push(hora);
                    mete30h(histo2, hora);
                    dat.pop();
                    lineChart1 = new Chart(lineCanvas1, {
                        type: "line",
                        data: {
                            labels: histo2,
                            datasets: dat
                        },
                        options: {
                            maintainAspectRatio: false,
                            scales: {
                                yAxes: [{
                                    display: true,
                                    ticks: {
                                        min: 0,
                                        suggestedMax: 30
                                    }
                                }]
                            }
                        }
                    });
                    radarChart1 = new Chart(radarCanvas1, {
                        type: "radar",
                        data: {
                            labels: labels,
                            datasets: [{
                                label: traducir2("Tendencia de estados por campaña"),
                                backgroundColor: myColors,
                                borderColor: "rgb(3, 40, 68)",
                                data: data
                            }]
                        },
                        options: {
                            maintainAspectRatio: false,
                            responsive: true
                        }
                    });
                    pieChart1 = new Chart(pieCanvas1, {
                        type: "pie",
                        data: {
                            labels: labels,
                            datasets: [{
                                data: data,
                                backgroundColor: myColors,
                                borderColor: "rgb(3, 40, 68)"
                            }]
                        },
                        options: {
                            maintainAspectRatio: false,
                            responsive: true,
                            tooltips: {
                                callbacks: {
                                    label: function (tooltipItem, data) {
                                        var dataset = data.datasets[tooltipItem.datasetIndex];
                                        var meta = dataset._meta[Object.keys(dataset._meta)[0]];
                                        var total = meta.total;
                                        var currentValue = dataset.data[tooltipItem.index];
                                        var percentage = parseFloat((currentValue / total * 100).toFixed(1));
                                        if (Number.isNaN(percentage)) {
                                            return currentValue + ' (' + 0 + '%)';
                                        } else {
                                            return currentValue + ' (' + percentage + '%)';
                                        }
                                    },
                                    title: function (tooltipItem, data) {
                                        return data.labels[tooltipItem[0].index];
                                    }
                                }
                            },


                        }
                    });
                    barChart1 = new Chart(barCanvas1, {
                        type: "horizontalBar",
                        data: {
                            labels: labels,
                            datasets: [{
                                label: traducir2("Tendencia de staus por campaña"),
                                data: data,
                                backgroundColor: myColors,
                                borderColor: "rgb(3, 40, 68)"
                            }]
                        },
                        options: {
                            maintainAspectRatio: false,
                            responsive: true
                        }
                    });
                } else {
                    if (historyCounter >= 30) {

                        historyCounter++;
                        lineChart1.data.labels.shift();


                    }
                    historyCounter++;
                    lineChart1.destroy();
                    radarChart1.destroy();
                    barChart1.destroy();
                    pieChart1.destroy();
                    for (var i = 0; i <= labels.length; i++) {
                        if (historico[i] == null) historico[i] = [];
                        mete30z(historico[i]);
                        historico[i].push(data[i]);
                        dat[i] = {
                            label: labels[i],
                            backgroundColor: myColors[i],
                            borderColor: "rgb(0,0,0)",
                            data: historico[i]
                        };
                    }

                    histo2.push(hora);
                    mete30h(histo2, hora);
                    dat.pop();
                    lineChart1 = new Chart(lineCanvas1, {
                        type: "line",
                        data: {
                            labels: histo2,
                            datasets: dat
                        },
                        options: {
                            maintainAspectRatio: false,
                            scales: {
                                yAxes: [{
                                    display: true,
                                    ticks: {
                                        min: 0,
                                        suggestedMax: 1000
                                    }
                                }]
                            }
                        }
                    });
                    radarChart1 = new Chart(radarCanvas1, {
                        type: "radar",
                        data: {
                            labels: labels,
                            datasets: [{
                                label: traducir2("Tendencia de estados por campaña"),
                                backgroundColor: myColors,
                                borderColor: "rgb(3, 40, 68)",
                                data: data
                            }]
                        },
                        options: {
                            maintainAspectRatio: false,
                            responsive: true
                        }
                    });

                    pieChart1 = new Chart(pieCanvas1, {
                        type: "pie",
                        data: {
                            labels: labels,
                            datasets: [{
                                data: data,
                                backgroundColor: myColors,
                                borderColor: "rgb(3, 40, 68)"
                            }]
                        },
                        options: {
                            maintainAspectRatio: false,
                            responsive: true,
                            tooltips: {
                                enabled: true
                            },
                            plugins: {
                                datalabels: {
                                    formatter: (value, ctx) => {

                                        let sum = 0;
                                        let dataArr = ctx.chart.data.datasets[0].data;
                                        dataArr.map(data => {
                                            sum += data;
                                        });
                                        let percentage = (value * 100 / sum).toFixed(2) + "%";
                                        return percentage;


                                    },
                                    color: '#fff',
                                }
                            }
                        }
                    });

                    barChart1 = new Chart(barCanvas1, {
                        type: "horizontalBar",
                        data: {
                            labels: labels,
                            datasets: [{
                                label: traducir2("Tendencia de staus por campaña"),
                                data: data,
                                backgroundColor: myColors,
                                borderColor: "rgb(3, 40, 68)"
                            }]
                        },
                        options: {
                            maintainAspectRatio: false,
                            responsive: true
                        }
                    });
                }
            }

            // Contenido content-script

			cargarCampanas();

			lineChart2 = Highcharts.stockChart('lineCanvasEsp', {
				rangeSelector: {
					enabled: false
				},
				time: {
					useUTC: false
				},
				legend: {
					layout: 'horizontal',
					align: 'center',
					verticalAlign: 'top',
					enabled: true
				},

				title: {
					text: traducirFrase('Agentes')
				},

				yAxis: {

					labels: {
						enabled: true
					}
				},

				exporting: {
					enabled: false
				},
				series: [{
					name: traducirFrase('Agentes esperando'),
					type: 'area',
					data: (function () {
							// generate an array of random data
							var data = [];
							return data;
						}())
					},
					{
					name: traducirFrase('Agentes pausados'),
					type: 'area',
					data: (function () {
							// generate an array of random data
							var data = [];
							return data;
						}())
					},
					{
					name: traducirFrase('Agentes en llamada cortada'),
					type: 'area',
					data: (function () {
							// generate an array of random data
							var data = [];
							return data;
						}())
					},
					{
					name: traducirFrase("Agentes calificando"),
					type: 'area',
					data: (function () {
							// generate an array of random data
							var data = [];
							return data;
						}())
					},
					{
					name: traducirFrase('Agentes en llamadas'),
					type: 'area',
					data: (function () {
							// generate an array of random data
							var data = [];
							return data;
						}())
					}
				]
			});


			$('.tabs').tabs();

			setInterval(() => {
				cargarCampanas();
			}, 60000);
			/*setInterval(function () {
				cargaGraficasCuadritos();
			}, 5000);*/
			setInterval(function () {
				refrescaBloqueAgentes();
				refrescaBloqueCampanas(primeraVez);
			}, 5000);
			llenaListaChat();
			trae_historico();
		}
	})

</script>
