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.myLine = null;

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

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

function carregar_dados(){
	$(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 impressions_active = true;
	var clicks_active = true;
	var invalid_active = false;
	var convertedClicks_active = false;
	var convRate_active = false;
	var ctr_active = false;
	var avgPosition_active = false;
	var avgCPC_active = false;
	var cost_active = false;

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

	var labels = [];
	var impressions = [];
	var clicks = [];
	var invalid = [];
	var convertedClicks = [];
	var convRate = [];
	var ctr = [];
	var avgPosition = [];
	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));
		convertedClicks.push(parseInt(dado.convertedClicks));
		convRate.push(parseFloat(dado.convRate));
		ctr.push(parseFloat(dado.ctr));
		avgPosition.push(parseFloat(dado.avgPosition));

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


	var datasets = [];

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

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

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

	datasets.push({
		label: "Contatos Recebidos",
		fill: false,
		data: convertedClicks,
		backgroundColor: 'rgba(0, 166, 90, 0.5)',
		borderColor: 'rgba(0, 166, 90, 1)',
		hidden: !convertedClicks_active,
		tension: 0
	});

	datasets.push({
		label: "% Contatos / Acessos",
		fill: false,
		data: convRate,
		backgroundColor: 'rgba(243, 156, 18, 0.5)',
		borderColor: 'rgba(243, 156, 18, 1)',
		hidden: !convRate_active,
		tension: 0
	});

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

	datasets.push({
		label: "Posição Média",
		fill: false,
		data: avgPosition,
		backgroundColor: 'rgba(96, 92, 168, 0.5)',
		borderColor: 'rgba(96, 92, 168, 1)',
		hidden: !avgPosition_active,
		tension: 0
	});

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

		datasets.push({
			label: "Custo Total",
			fill: false,
			data: cost,
			backgroundColor: 'rgba(17, 17, 17, 0.5)',
			borderColor: 'rgba(17, 17, 17, 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:
							case 3:
								return dataset.label + ": " + content.formatNumber(0, ",", ".");
							case 4:
							case 5:
								return dataset.label + ": " + content.toString().replace(".",",") + "%";
							case 7:
							case 8:
								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: [{
					scaleLabel: {
						display: false
					},
					ticks: {
						fontFamily: "'Source Sans Pro',sans-serif"
					}
				}]
			},
			legend: {
				display: true,
			    labels: {
			        boxWidth: 16,
			        fontFamily: "'Source Sans Pro',sans-serif",
			        fontSize: 13,
			        padding: 10
			    }
			}
		}
	};
	$(document).ready(function() {
		var ctx = document.getElementById("canvas").getContext("2d");
		window.myLine = new Chart(ctx, config);
	});
}

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