Number.prototype.formatNumber = function(c, d, t){
	var n = this, 
	c = isNaN(c = Math.abs(c)) ? 2 : c, 
	d = d == undefined ? "." : d, 
	t = t == undefined ? "," : t, 
	s = n < 0 ? "-" : "", 
	i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), 
	j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };

// window.myLineChart = null;
// var charts=[]; // global

$('.datepicker').datepicker({
	format: 'dd/mm/yyyy',
	endDate: '0d',
	autoclose: true,
	language: 'pt-BR'
});

$('.datepicker').mask('00/00/0000');

function carregar_dados(){
	// console.log(window.myLineChart);
	
	$(document).ready(function() {
		var dados = jQuery('#formGrafico').serialize();
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_grafico",
			data: dados,
			success: function(data){
				$('.preloader').css({display:"none"});
				if(data == '-1') {window.location.href = "./"; return;}
				if(data.substring(0,2) == "-2") {toastr.clear(); toastr.error(data.substring(2)); return;}
				desenharGrafico(JSON.parse(data));
			},
			beforeSend: function(){
				$('.preloader').css({display:"block"});
			},
			complete: function(){
				$('.preloader').css({display:"none"});
			},
			error: function(){
				$('.preloader').css({display:"none"});
				toastr.clear(); toastr.error("Houve um erro ao atualizar"); return;
			}
		});
	});
}

var moedaUsuario = null;

function desenharGrafico(dados){
	if (typeof dados[0] === "undefined") {
	    var consultoria = "0";
		moedaUsuario = 0;
	}
	else{
		var consultoria = dados[0][0] == "1";
		moedaUsuario = parseInt(dados[0][1]);
		
		var somenteCampanha = dados[0][2] == "1";		
	}

	var impressions_active = true;
	var clicks_active = true;
	var invalid_active = false;
	var ctr_active = false;
	var avgCPC_active = false;
	var cost_active = false;
	// var avgPosition_active = false;
	// var imprAbsTop_active = false;
	// var imprTop_active = false;

	if(window.myLineChart != null){
		cur_legend = window.myLineChart.legend.legendItems;
		impressions_active = !cur_legend[0]['hidden'];
		clicks_active = !cur_legend[1]['hidden'];
		invalid_active = !cur_legend[2]['hidden'];
		ctr_active = !cur_legend[3]['hidden'];
		// avgPosition_active = !cur_legend[4]['hidden'];
		// imprAbsTop_active = !cur_legend[4]['hidden'];
		// imprTop_active = !cur_legend[5]['hidden'];
		if(consultoria & cur_legend.length == 6){
			avgCPC_active = !cur_legend[4]['hidden'];
			cost_active = !cur_legend[5]['hidden'];
		}
		window.myLineChart.destroy();
	}
	moment.locale('pt-BR');
	
	var timeFormat = 'DD/MM/YYYY';

	var labels = [];
	var impressions = [];
	var clicks = [];
	var invalid = [];
	var ctr = [];
	// var avgPosition = [];
	// var imprAbsTop = [];
	// var imprTop = [];
	if(consultoria){
		var avgCPC = [];
		var cost = [];
	}

	for (var i=1; i < dados.length; i++){
		var dado = dados[i];

		labels.push(new Date(dado.period));

		clicks.push(parseInt(dado.clicks));
		invalid.push(parseInt(dado.invalid));
		impressions.push(parseInt(dado.impressions));
		ctr.push(parseFloat(dado.ctr));
		// avgPosition.push(parseFloat(dado.avgPosition));
		// imprAbsTop.push(parseInt(dado.imprAbsTop));
		// imprTop.push(parseInt(dado.imprTop));

		if(consultoria){
			avgCPC.push(parseFloat(dado.avgCPC));
			cost.push(parseFloat(dado.cost));
		}
	}

	var datasets = [];

	datasets.push({
		label: "Qtd. Anúncios",
		yAxisID: 'A',
		fill: false,
		data: impressions,
		backgroundColor: 'rgba(60, 141, 188, 1)',
		borderColor: 'rgba(60, 141, 188, 1)',
		tension: 0,
		hidden: !impressions_active
	});

	datasets.push({
		label: "Acessos ao Site",
		yAxisID: 'B',
		fill: false,
		data: clicks,
		backgroundColor: 'rgba(0, 192, 239, 1)',
		borderColor: 'rgba(0, 192, 239, 1)',
		tension: 0,
		hidden: !clicks_active
	});

	datasets.push({
		label: "Cliques Inválidos",
		yAxisID: 'C',
		fill: false,
		data: invalid,
		backgroundColor: 'rgba(102, 0, 0, 1)',
		borderColor: 'rgba(102, 0, 0, 1)',
		tension: 0,
		hidden: !invalid_active
	});

	datasets.push({
		label: "% Acessos / Anúncios",
		yAxisID: 'D',
		fill: false,
		data: ctr,
		backgroundColor: 'rgba(221, 75, 57, 1)',
		borderColor: 'rgba(221, 75, 57, 1)',
		hidden: !ctr_active,
		tension: 0
	});

	// if (somenteCampanha) {
	// 	datasets.push({
	// 		label: "% 1ª Posição",
  //    yAxisID: 'G',
	// 		fill: false,
	// 		data: imprAbsTop,
	// 		backgroundColor: 'rgba(76, 175, 80, 1)',
	// 		borderColor: 'rgba(76, 175, 80, 1)',
	// 		hidden: !imprAbsTop_active,
	// 		tension: 0
	// 	});
	
	// 	datasets.push({
	// 		label: "% Apareceu no Topo",
  //    yAxisID: 'H',
	// 		fill: false,
	// 		data: imprTop,
	// 		backgroundColor: 'rgba(96, 92, 168, 1)',
	// 		borderColor: 'rgba(96, 92, 168, 1)',
	// 		hidden: !imprTop_active,
	// 		tension: 0
	// 	});
		
	// }

	if(consultoria){
		datasets.push({
			label: "Custo Por Clique",
      yAxisID: 'E',
			fill: false,
			data: avgCPC,
			backgroundColor: 'rgba(0, 32, 63,1)',
			borderColor: 'rgba(0, 32, 63, 1)',
			hidden: !avgCPC_active,
			tension: 0
		});

		datasets.push({
			label: "Custo Total",
      yAxisID: 'F',
			fill: false,
			data: cost,
			backgroundColor: 'rgb(255, 180, 102,1)',
			borderColor: 'rgb(255, 180, 102, 1)',
			hidden: !cost_active,
			tension: 0
		});
	}

	var config = {
		type: 'LineWithLine',
		data: {
			labels: labels,
			datasets: datasets
		},
		options: {
			responsive: true,
			scaleShowVerticalLines: false,
			maintainAspectRatio: false,
			title: {
				text: "Gráfico Geral"
			},
			tooltips: {
				mode: 'index',
				intersect: false,
				titleFontFamily: "'Source Sans Pro',sans-serif",
				bodyFontFamily: "'Source Sans Pro',sans-serif",
				xPadding: 8,
				yPadding: 8,
				bodySpacing: 4,
				callbacks: {
					label: function(tooltipItem, data) {
						var datasetIndex = tooltipItem.datasetIndex;
						var dataset = data.datasets[datasetIndex];
						var content = dataset.data[tooltipItem.index];
						switch(datasetIndex){
							case 0:
							case 1:
							case 2:
								return dataset.label + ": " + content.formatNumber(0, ",", ".");
							case 3:
								return dataset.label + ": " + content.toString().replace(".",",") + "%";
              // case 4:
							// 	return dataset.label + ": " + content.toString() + "%";
							// case 5:
							// 	return dataset.label + ": " + content.toString() + "%";
							case 4:
							case 5:
								switch(moedaUsuario){
									case 1:
										return dataset.label + ": $ " + content.formatNumber(2, ".", ",");
									case 2:
										return dataset.label + ": € " + content.formatNumber(2, ".", ",");
									default:
										return dataset.label + ": R$ " + content.formatNumber(2, ",", ".");
								}
								
							default:
								return dataset.label + ": " + content.toString();
						}
	                }
				}
			},
			scales: {
				xAxes: [{
					type: "time",
					time: {
						parser: timeFormat,
						tooltipFormat: 'll',
						unit: "day"
					},
					scaleLabel: {
						display: true,
					},
					ticks: {
						autoSkip: false,
						maxRotation: 0,
						minRotation: 0,
						fontFamily: "'Source Sans Pro',sans-serif"
					},
					gridLines: {
						drawOnChartArea: false
					}
				}],
				yAxes: [{},
					{
						// display: true,
						id: 'A',
						type: 'linear',
						position: 'left',
						scaleLabel: {
							display: true,
							labelString: 'Qtd. Anúncios',
							fontColor: 'rgba(60, 141, 188, 1)',
							fontSize:13
						}
					}, 
					{
						display: true,
						id: 'B',
						type: 'linear',
						position: 'right',
						scaleLabel: {
							display: true,
							labelString: 'Acesso ao Site',
							fontColor: 'rgba(0, 192, 239, 1)',
							fontSize:13
						},
					}, 
					{
						display: false,
						id: 'C',
						type: 'linear',
						position: 'left',
						scaleLabel: {
							display: true,
							labelString: 'Cliques inválidos',
							fontColor: 'rgba(102, 0, 0, 1)',
							fontSize:13
						},
					}, 
					{
						display: false,
						id: 'D',
						type: 'linear',
						position: 'right',
						scaleLabel: {
							display: true,
							labelString: '% Acessos/Anúncios',
							fontColor: 'rgba(221, 75, 57, 1)',
							fontSize:13
						},
					}, 
					{
						display: false,
						id: 'E',
						type: 'linear',
						position: 'left',
						scaleLabel: {
							display: true,
							labelString: 'Custo por Clique',
							fontColor: 'rgba(0, 32, 63, 1)',
							fontSize:13
						},
					}, 
					{
						display: false,
						id: 'F',
						type: 'linear',
						position: 'right',
						scaleLabel: {
							display: true,
							labelString: 'Custo Total',
							fontColor: 'rgb(255, 180, 102, 1)',
							fontSize:13
						},
					}
				]
			},
			legend: {
				display: true,
			    labels: {
			        boxWidth: 16,
			        fontFamily: "'Source Sans Pro',sans-serif",
			        fontSize: 13,
			        padding: 10
			    }
			}
		}
	};

	if (window.myLineChart !== undefined && window.myLineChart !== null) {
		window.myLineChart.destroy();
		
		var ctx = document.getElementById("canvas");
		window.myLineChart = new Chart(ctx, config);
		window.myLineChart.config.options.scales.yAxes[0].display = false;

		window.myLineChart.legend.legendItems.map((item, index) => {

			if (index > 1) {
				// console.log(index, 'entrou');
				// console.log(window.myLineChart.config.options.scales.yAxes[index], 'entrou');
				// console.log(window.myLineChart.data.datasets[index], 'entrou');

				item.hidden = true;
				window.myLineChart.data.datasets[index].hidden = true;
				// window.myLineChart.config.options.scales.yAxes[index].display = false;
			}else{
				// console.log(index, 'entrou1');
				// console.log(window.myLineChart.config.options.scales.yAxes[index], 'entrou1');
				// console.log(window.myLineChart.data.datasets[index], 'entrou1');

				if (index === 1) {
					window.myLineChart.config.options.scales.yAxes[index+2].display = false;
				}
				// console.log(index);
				item.hidden = false;
				window.myLineChart.data.datasets[index].hidden = false;
				
			}
		})
		window.myLineChart.update();
	}else{
		var ctx = document.getElementById("canvas");
		window.myLineChart = new Chart(ctx, config);
		window.myLineChart.config.options.scales.yAxes[0].display = false;
		window.myLineChart.update();
	}

}

// function variosYAxes(){
	var original = Chart.defaults.global.legend.onClick;
	Chart.defaults.global.legend.onClick = function(e, legendItem) {
		if (!window.myLineChart.config.options.scales.yAxes[legendItem.datasetIndex+1].display) {
			window.myLineChart.config.options.scales.yAxes[legendItem.datasetIndex+1].display = true;
		}else{
			window.myLineChart.config.options.scales.yAxes[legendItem.datasetIndex+1].display = false;
		}
		original.call(this, e, legendItem);
	};
// }

function atualizar(){
	var valor = $('#data').val();
	if(valor == "CUSTOM_DATE")
		$('.datadiv').removeClass("hide");
	else{
		$('.datadiv').addClass("hide");
		carregar_dados();
		salvarFiltro(valor,'','');
		
	}
}

$('#data, #switch, #periodo').change(function(){ atualizar(); });
$('#datapersonalizada').click(function(){
	salvarFiltro($('#data').val(),$('#datainicial').val(),$('#datafinal').val());
	carregar_dados();
});

// Hook into main event handler
Chart.defaults.LineWithLine = Chart.defaults.line;
Chart.controllers.LineWithLine = Chart.controllers.line.extend({
   draw: function(ease) {
      Chart.controllers.line.prototype.draw.call(this, ease);

      if (this.chart.tooltip._active && this.chart.tooltip._active.length) {
         var activePoint = this.chart.tooltip._active[0],
             ctx = this.chart.ctx,
						 x = activePoint.tooltipPosition().x;
             topY = this.chart.scales['y-axis-0'].top,
             bottomY = this.chart.scales['y-axis-0'].bottom;

         // draw line
         ctx.save();
         ctx.beginPath();
         ctx.moveTo(x, topY);
         ctx.lineTo(x, bottomY);
         ctx.lineWidth = 2;
         ctx.setLineDash([5, 5]);
         ctx.strokeStyle = '#d2d6de';
         ctx.stroke();
         ctx.restore();
      }
   }
});

// desenharGrafico([]);

pegarFiltro(function(filtro,data1,data2){
	$('#data').val(filtro);
	$('#datainicial').val(data1);
	$('#datafinal').val(data2);
	if(filtro == "CUSTOM_DATE"){
		$('.datadiv').removeClass("hide");
	}
	
	carregar_dados();
});