var requestMapUpdates = 0;
var requestUpdates = 0;
var currentProfile = 0;
var init = 0;

var aspectHeight = 560;

var width = $(".vis").width(),
    aspect = aspectHeight / 1200,
    height = width * aspect;

var mapSVG = d3.select(".vis").append("svg")
    .attr("preserveAspectRatio", "xMinYMin meet")
    .attr("viewBox", "0 0 1200 " + aspectHeight)
    .attr("width", width)
    .attr("height", height);

//Projeção
var projection = d3.geo.mercator()
    .scale(720)
    .translate([1100, 100]);

var path = d3.geo.path()
    .projection(projection);

//Barra da apuração

mapSVG.append("g")
    .append("rect")
    .attr("x",10)
    .attr("y",2)
    .attr("width",2)
    .attr("height",aspectHeight-10)
    .style("fill","#2c3e50");

mapSVG.append("g")
    .append("text")
    .attr("x",20)
    .attr("y",15)
    .style("fill","#ecf0f1")
    .text("Apurado");

mapSVG.append("g")
    .append("rect")
    .attr("class","readCount")
    .attr("x",10)
    .attr("y",2)
    .attr("width",2)
    .attr("height",5)
    .style("fill","#ecf0f1");
mapSVG.append("g")
    .append("text")
    .attr("class","readText")
    .attr("x",20)
    .attr("y",35)
    .style("fill","#ecf0f1")
    .text("0%");

//Escala da apuração
var countScale = d3.scale.linear()
    .range([0, aspectHeight-10])
    .domain([0,100]);

// Inicialização do Gráfico do País
var chartWidth = 500,chartHeight = 600,chartMargin = 40;
var chartSVG = d3.select(".chart").append("svg")
    .attr("id","chart")
    .attr("width",chartWidth)
    .attr("height",chartHeight);

var y = d3.scale.linear()
    .range([0,chartHeight])
    .domain([0,100]);

var x = null,xAxis = null;


//Definição das escalas de cores
var colorScale = [];
colorScale[0] = d3.scale.linear().domain([0, 50]).range(["#99d8c9", "#005824"]);
colorScale[1] = d3.scale.linear().domain([0, 50]).range(["#9ecae1", "#084594"]);
colorScale[2] = d3.scale.linear().domain([0, 50]).range(["#fc9272", "#99000d"]);
colorScale[3] = d3.scale.linear().domain([0, 50]).range(["#bdbdbd", "#252525"]);
var colors = ["#016c59","#084594","#99000d","#252525"];

//Desenho do Mapa
d3.json("json/states_bra.topo.json", function(error, bra) {
    mapSVG.append("g")
        .attr("id", "states")
        .selectAll("path")
        .data(topojson.feature(bra, bra.objects.states_bra).features)
        .enter()
        .append("path")
        .attr("id", function(d) { return d.id; })
        .attr("class", "state")
        .attr("data-state", function(d) { return d.properties.name; })
        .attr("d", path)
        .on("mouseenter", function(d) { startTooltip(d.id); loadTooltipData(d.id); })
        .on("mouseout", function() { closeTooltip(); })
        .on("mousemove", function() { moveTooltip(d3.mouse(d3.select('body').node())); });
});
//Carrega as informações
function loadMapData (profile) {
    currentProfile = profile;
    requestMapUpdates++;
    $.ajax({
        url: "http://d3.fabiosikansi.com/election.php?request=" + requestMapUpdates + "&callback=?",
        jsonp: "callback",
        dataType: "jsonp",
        data: {
            format: "json"
        },
        success: function( response ) {
            if (requestMapUpdates == response.requestNumber) updateMapData(response,profile);
        }
    });
}
//Atualiza os dados com o mapa
function updateMapData (data,profile) {
    //Atualiza o tempo da página
    $("#time").html(data.time);
    //Atualiza as cores
    data.states.forEach(function (state) {
        d3.select("#BRA-" + state.key).style('fill', function () {
            if (profile == 1)
                return colorScale[0](100*state.c1/state.total);
            if (profile == 2)
                return colorScale[1](100*state.c2/state.total);
            if (profile == 3)
                return colorScale[2](100*state.c3/state.total);
            if (profile == 0) {
                var max = 0,color;
                if (state.c1 > state.c2) {
                    max = state.c1;
                    color = 0;
                } else {
                    max = state.c2;
                    color = 1;
                }
                if (state.c3 > max) {
                    max = state.c3;
                    color = 2;
                }
                return colorScale[color](100*max/state.total);
            }
        });
    });
    //Inicializa o gráfico de barras
    if (init == 0) {
        init = 1;

        x = d3.scale.ordinal()
            .rangeRoundBands([0, chartWidth], 0.1, 0.1)
            .domain(data.country.votes.map(function(d) { return d.name; }));

        xAxis = d3.svg.axis()
            .scale(x)
            .outerTickSize(0)
            .orient("bottom");

        chartSVG.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + (chartHeight-chartMargin) + ")")
            .call(xAxis);

        chartSVG.selectAll(".bar")
            .data(data.country.votes)
            .enter().append("rect")
            .attr("class", "bar")
            .attr("x", function(d) { return x(d.name); })
            .attr("width", x.rangeBand())
            .attr("height", 0)
            .attr("y", chartHeight - chartMargin)
            .style("text-anchor","middle")
            .style("fill",function (d,k) { return colors[k]; });

        chartSVG.selectAll(".barValue")
            .data(data.country.votes)
            .enter().append("text")
            .attr("class","barValue")
            .text("0.00%")
            .attr("x", function(d) { return x(d.name) + x.rangeBand()/2; })
            .attr("y", function() { return chartHeight - chartMargin - 10; })
            .style("text-anchor","middle");
    }
    //Atualiza o valor númerico no gráfico
    chartSVG.selectAll(".bar").data(data.country.votes)
        .transition()
        .duration(1000)
        .attr('data-votes', function (d) { return (100*d.votes/data.country.read).toFixed(2); })
        .attr("height", function(d) { return y(100*d.votes/data.country.read); })
        .attr("y", function(d) { return chartHeight - chartMargin - y(100*d.votes/data.country.read); });

    chartSVG.selectAll(".barValue").data(data.country.votes)
        .transition()
        .duration(1000)
        .text(function (d) { return (100*d.votes/data.country.read).toFixed(2) + "%"; })
        .attr("y", function(d) { return chartHeight - chartMargin - y(100*d.votes/data.country.read) - 10; });

    //Atualiza a linha de votos apurados
    mapSVG.select(".readCount")
        .transition()
        .duration(1000)
        .attr("height",countScale(100*data.country.read/data.country.total));

    mapSVG.select(".readText")
        .text((100*data.country.read/data.country.total).toFixed(2) + "%")
        .transition()
        .duration(1000)
        .attr("y",function () {
            var y = countScale(100*data.country.read/data.country.total);
            return (y > 35) ? y : 35;
        } );
}

function startTooltip (state) {
    if (state == "BRA-612" || state == "BRA-613" || state == "BRA-614") {
        $("#statePopover").removeClass('bottom');
        $("#statePopover").addClass('top');
    } else {
        if ($("#statePopover").hasClass('top')) {
            $("#statePopover").removeClass('top');
            $("#statePopover").addClass('bottom');
        }
    }
    $("#statePopover").attr('data-current-state',state);
    $("#statePopover").css('display','block');

}

function moveTooltip (coordinates) {
    if ($("#statePopover").hasClass('bottom')) {
        $("#statePopover").css('left',(coordinates[0] - 148) + "px");
        $("#statePopover").css('top',(coordinates[1] - 50) + "px");
    } else {
        $("#statePopover").css('left',(coordinates[0] - 148) + "px");
        $("#statePopover").css('top',(coordinates[1] - 250) + "px");
    }
}

function closeTooltip () {
    $("#statePopover").css('display','none');
}

function loadTooltipData (state) {
    $("#statePopover .popover-title").html("Carregando...");
    $("#statePopover .popover-content").html("");
    requestUpdates++;
    $.ajax({
        url: "http://d3.fabiosikansi.com/election.php?request=" + requestUpdates + "&h=16&m=45&state=" + state + "&callback=?",
        jsonp: "callback",
        dataType: "jsonp",
        data: {
            format: "json"
        },
        success: function( response ) {
            if (requestUpdates == response.requestNumber) fillTooltip(response);
        }
    });
}

function fillTooltip (data) {
    $("#statePopover .popover-title").html(data.name);
    var svg = d3.select("#statePopover .popover-content").append('svg')
        .attr("width", 250)
        .attr("height", 140);
    var candidatos = svg.selectAll('g')
        .data(data.votes)
        .enter()
        .append('g');

    candidatos.append('text')
        .attr('x',0)
        .attr('y',function (d,k) { return (k*35) + 10; })
        .style('font-size','10px')
        .text(function (d) {  return d.name; });
    candidatos.append('rect')
        .attr('height',15)
        .attr('width',function (d) {  return (200*d.votes/100); })
        .attr('x',0)
        .attr('y',function (d,k) { return (k*35) + 15; })
        .style('fill',function (d,k) { return colors[k]; });
    candidatos.append('text')
        .attr('x',250)
        .attr('y',function (d,k) { return (k*35) + 25; })
        .style('font-size','10px')
        .style('font-weight','bold')
        .style('text-anchor','end')
        .style('fill','black')
        .text(function (d) {  return d.votes.toFixed(2) + "%"; });
}

$(document).on("ready", function () {
    loadMapData(currentProfile);
    setInterval (function () {
        loadMapData(currentProfile);
    },30*1000);
});

$(window).resize(function() {
    var width = $(".vis").width();
    var height = $(".vis").height();
    mapSVG.attr("width", width);
    mapSVG.attr("height", height);

});