$(document).ready(function(){

    function renderChartElement(elem, withLoading, withLabels) {
        var $elem = $(elem);
        var chartID = $elem.attr('id');
        var chartData = eval($elem.attr('data-chart-data'));
        var chartType = $elem.attr('data-chart-type');
        var chartColors = [];
        $elem.closest('article').find('.cta a').each(function(){
            var color = $(this).css('background-color');
            chartColors.push(color);
        });
        for (var i=0, l=chartData.length; i < l; i++) {
            chartData[i][1] = parseFloat(chartData[i][1]);
        }
        var options = {
		    theme: 'gray',
            colors: chartColors,
		    chart: {
			    renderTo: chartID,
                animation: withLoading
		    },
		    tooltip: {
			    formatter: function() {
				    return '<b>' + this.point.name + '</b>: ' + this.y + ' %';
			    }
		    },
		    plotOptions: {
			    pie: {
                    animation: withLoading,
				    dataLabels: {
                        enabled: (withLabels || false),
					    formatter: function() {
						    return this.y + ' %<br><b>' + this.point.name + '</b>';
					    }
				    }
			    }
		    },
		    series: [{
			    type: chartType,
			    name: '',
			    data: chartData
		    }]
	    };
        if (!withLoading) {
            options.loading = {hideDuration: 0, showDuration: 0};
        }
	    chart = new Highcharts.Chart(options);
        $elem.data('chart', chart);
    }

    function renderActivePoll(activePoll) {
        var activeChart = activePoll.find('.poll-chart').eq(0);
        var featuredPoll = activePoll.clone();
        featuredPoll.find('.poll-chart').remove();
        featuredPoll.find('.medgray').removeClass('medgray').addClass('red');
        $('#feature .content').html(featuredPoll.html());
        var featuredChart = $('#featured-poll-chart');
        featuredChart.attr('data-chart-data', activeChart.attr('data-chart-data'));
        featuredChart.attr('data-chart-type', activeChart.attr('data-chart-type'));
        renderChartElement(featuredChart, true, true);
        $('#polls .poll.row-end').removeClass('row-end');
        $('#polls .poll:not(.poll-active)').filter(function(index) {return index % 4 === 3;}).addClass('row-end');
        $('#latest-poll #feature .details .info').tooltip({relative: true, offset: [-15, -10]}).click(function(e) {
            e.preventDefault();
        });
        $('#latest-poll #feature .share').tooltip({ relative: true, offset: [-15, 0]}).click(function(e) {
            e.preventDefault();
        });
        Cufon.refresh();
    }

    $('div[data-chart-data][data-chart-type]').each(function(i, elem) {
        renderChartElement(elem, false);
    });

    if (!$('#polls .poll-active').length) {
        $('#polls .poll').eq(0).addClass('poll-active');
    }

    var activePoll = $('#polls .poll-active article').eq(0);
    if (activePoll.length) {
        renderActivePoll(activePoll);
    }

    var isRed = false;
    $('#polls .poll .poll-chart').hover(
        function(e) {
            // Hover-in
            var poll = $(this).parents().filter('.poll');
            var grey = poll.find('.medgray');
            if (grey.length) {
                isRed = false;
                poll.find('.medgray').removeClass('medgray').addClass('red');
            }
            if (!isRed) {
                var activeChart = $(this);
                var chart = activeChart.data('chart');
                chart.destroy();
                renderChartElement(activeChart, false);
            }
            isRed = true;
        },
        function(e) {
            // Hover-out
            var poll = $(this).parents().filter('.poll');
            var red = poll.find('.red');
            if (red.length) {
                isRed = true;
                poll.find('.red').removeClass('red').addClass('medgray');
            }
            if (isRed) {
                var activeChart = $(this);
                var chart = activeChart.data('chart');
                chart.destroy();
                renderChartElement(activeChart, false);
            }
            isRed = false;
        }
    );

    $('#polls .poll').click(function(e) {
        $('#polls .poll-active').removeClass('poll-active');
        $(this).addClass('poll-active');
        var activePoll = $(this).find('article').eq(0);
        location.hash = $(this).attr('data-poll-id');
        renderActivePoll(activePoll);
        window.scrollTo(0, 0) ;
    });

    if (location.hash) {
        var poll = $('#polls .poll[data-poll-id="' + location.hash.replace('#', '') + '"]');
        if (poll.length) {
            poll.click();
        }
    }   

    $('#polls .details .info').tooltip({relative: true, offset: [-15, -5]});
    $('#latest-poll #polls .share').tooltip({ relative: true, offset: [-15, -5]});
    $('.tooltip a.twitter, .tooltip a.facebook').click(function(e) {
        e.preventDefault();
        window.open($(this).attr('href'),
            'popUpWindow',
            'height=600,width=900,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes'
        );
    });
});

