//= require vendor/highstock.js
//= require vendor/adapt-chart-to-legend.js
//= require shared/field_trigger.js

(function()
{
    'use strict';

    var updateFundTotal = function()
    {
        var total = 0;

        var totalElement    = jQuery('.dialog.fund-edit .funds > .total .value');
        var pertacageInputs = jQuery('.dialog.fund-edit .field.percentage input');

        pertacageInputs.each(function(index)
        {
            var value = parseInt(jQuery(this).val()) || 0;

            total += value;
        });

        totalElement.text(total + ' %');
    };

    var page = jQuery(document);

    // count remaining characters in message field
    page.on('contentloaded', function(event)
    {
        var block = jQuery(event.target);

        var messageInput           = block.find('.dialog.changes .field.message textarea');
        var messageInputLengthText = block.find('.dialog.changes .field.message .length');

        messageInput.on('input', function()
        {
            messageInputLengthText.text( getRemainingCharacterCount(messageInput) );
        });
    });

    // attach fund remove button handler
    page.on('contentloaded', function(event)
    {
        var block = jQuery(event.target);

        var funds = block.find('.dialog.fund-edit .funds');

        funds.on('click', '.fund .remove', function()
        {
            jQuery(this).closest('.fund').remove();
            updateFundTotal();
        });
    });

    // attach fund add button handler
    page.on('contentloaded', function(event)
    {
        var block = jQuery(event.target);

        var tools = block.find('.dialog.fund-edit .funds > .tools');
        var addButton = tools.find('.button.add');
        var fundTemplateHtml = block.find('.dialog.fund-edit .funds > template').html().trim();

        addButton.on('click', function()
        {
            var fund = jQuery(fundTemplateHtml).insertBefore(tools);
            var idSuffix = '-' + Math.random().toString(16).slice(2);

            fund.find('input, select').each(function()
            {
                var control = jQuery(this);
                var labels = jQuery(this).closest('.field').find('label');
                var uniqueId = control.attr('id') + idSuffix;

                control.attr('id', uniqueId);
                labels.attr('for', uniqueId);
            });

            fund.find('.field:first').find('input, select').focus().select();
            fund.find('input[type="number"]').each(function()
            {
                jQuery(this).trigger('number:attach');
            });
        });
    });

    // update fund total when changing percentage input values
    page.on('contentloaded', function(event)
    {
        var block = jQuery(event.target);

        var funds = block.find('.dialog.fund-edit .funds');

        funds.on('input change', '.field.percentage input', function()
        {
            updateFundTotal();
        });

    });

    // show success dialog when fund changes submitted
    page.on('contentloaded', function(event)
    {
        var block = jQuery(event.target);
        var submit = block.find('.dialog.fund-edit .button[type="submit"]');

        submit.on('click', function(event)
        {
            page.trigger('dialog:open', { source: '.dialog.fund-success' });

            return false;
        });
    });

    // build chart in fund dialog
    page.on('contentloaded', function(event)
    {
        var block = jQuery(event.target);

        var dialog = block.find('.dialog.funds');

        var chart = dialog.find('.chart');
        var chartId = chart.attr('id');

        if (typeof Highcharts == 'undefined' || !chart.length)
        {
            return;
        }

        // legend circle positioning
        (function(H) {
            H.wrap(H.Legend.prototype, 'positionItem', function(proceed, item) {
                proceed.call(this, item);
                if (item.legendSymbol) {
                    item.legendSymbol.translate(0, 7);
                }
                if (item.legendLine) {
                    item.legendLine.translate(0, 7);
                }
            });
        }) (Highcharts);

        jQuery.getJSON(chart.data('sourceUrl'), function(data) {
            var highchart = Highcharts.chart(chartId, {
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    type: 'pie',
                    margin: [0, 0, 0, 0],
                    spacing: [0, 0, 0, 0],
                    animation: false,
                    height: 205,
                    style: {
                        fontFamily: '"FS Me", Arial, Helvetica, sans-serif'
                    }
                },
                title: false,
                credits: {
                    enabled: false
                },
                tooltip: {
                    enabled: false,
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: false,
                        animation: false,
                        borderWidth: 0,
                        center: ['50%', 81],
                        colors: ['#8f0908', '#d01429', '#ff4453', '#ff8183'],
                        dataLabels: {
                            enabled: false
                        },
                        showInLegend: true,
                        size: 160,
                        slicedOffset: 0
                    }
                },
                legend: {
                    layout: 'vertical',
                    align: 'left',
                    verticalAlign: 'top',
                    itemMarginTop: 10,
                    itemMarginBottom: 10,
                    itemStyle: {
                        color: '#6a625a',
                        fontSize: '16px',
                        fontWeight: 'normal',
                        cursor: 'default',
                        textOverflow: 'auto',
                        lineHeight: '25px',
                    },
                    itemHoverStyle: {
                        color: '#6a625a'
                    },
                    labelFormatter: function() {
                        return '<b style="color:#333;font-weight:bold;">' + this.y + '%</b> - ' + this.name;
                    },
                    symbolHeight: 30,
                    symbolPadding: 27,
                    padding: 0,
                    floating: true,
                    x: 8,
                    y: 193,
                    navigation: {
                        enabled: false
                    },
                    adjustChartSize: true
                },
                series: [{
                    name: 'Structure',
                    colorByPoint: true,
                    innerSize: '60%',
                    states: {
                        hover: {
                            enabled: false
                        }
                    },
                    data: data,
                    point: {
                        events: {
                            legendItemClick: function() {
                                return false;
                            }
                        }
                    }
                }],
                responsive: {
                    rules: [{
                        condition: {
                            minWidth: 560,
                        },
                        chartOptions: {
                            plotOptions: {
                                pie: {
                                    center: [81, 81],
                                }
                            },
                            legend: {
                                itemMarginTop: 15,
                                itemMarginBottom: 15,
                                itemStyle: {
                                    lineHeight: '30px',
                                },
                                x: 210,
                                y: null,
                                width: 330
                            }
                        }
                    }]
                }
            });


            var dialogTrigger = jQuery('a[href="#' + dialog.attr('id') + '"]');

            dialogTrigger.on('mfpOpen', function(event)
            {
                highchart.reflow();
            });
        });
    });

}());
