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

(function()
{
    'use strict';

    var program_options = {
        tooltip: {
            borderWidth: 0,
            backgroundColor: 'rgba(51,51,51,1)',
            pointFormatter: function () {
                return false;
            },
            headerFormat: '<span style="font-size:12px;font-family:\'FS Me\', Arial, Helvetica, sans-serif;">{point.key}</span>',
            style: {
                color: '#fff'
            }
        },
        yAxis: {
            labels: {
                enabled: false
            }
        }
    };

    var fund_options = {
        tooltip: {
            borderWidth: 0,
            backgroundColor: 'rgba(51,51,51,1)',
            pointFormat: '<span style="color:#79b8e9;">\u25CF</span>  <span style="font-family:\'FS Me\', Arial, Helvetica, sans-serif;">{series.name}: {point.y}</span>',
            headerFormat: '<span style="font-size:12px;font-family:\'FS Me\', Arial, Helvetica, sans-serif;">{point.key}</span>',
            style: {
                color: '#fff'
            }
        }
    }

    var initialize_all_content = function() {
        investment_fund_table_content();
        investment_program_content();
    };

    var investment_fund_table_content = function() {
        $('.field.investment-gain input:radio[name="investment_gain"]').on('change', function() {
            if (this.checked) {
                $('.fund_list_table').addClass('hidden');
                $('.fund_list_table.' + this.value).removeClass('hidden');
            }
        });

        $('.fund_list_table').filter(function() {
            if (!$(this).data('fund_list_table_hasscript')) {
                return true;
            }
        }).data('fund_list_table_hasscript', true).each(function() {
            var c = $(this), //table container handle
                last_sort_col = null, //save last sort column
                last_sort_asc; //save last sort order

            // clear all checkboxes
            jQuery('input[type="checkbox"]', c).prop('checked', false);

            //for each row that...
            $('>tbody>tr', c).filter(function() {
                //contains data cells
                if ($('td', this).length) {
                    return true;
                }
            }).each(function() {
                var fc = $('td:first-child', this); //handle on first column
                //fill first column with structure...
                fc.append('<div class="extra_data"></div>');
                //and pieces of data from...
                $('.extra_data', fc).append('<div class="date">' + $('>td', this).eq(3).text() + '</div>'); //date column (4) and...
                $('.extra_data', fc).append('<div class="price">' + $('>td', this).eq(1).text() + ' ' + $('>td', this).eq(2).text() + '</div>'); //currency & price columns (2,3)
            });

            //grouping of rows
            var group = 0;
            $('>tbody>tr', c).each(function() {
                if ($('th', this).length) {
                    //if group header, add counter and mark as header
                    group++;
                    $(this).addClass('group_header_' + group);
                } else {
                    //if data row - mark with group number
                    $(this).addClass('group_' + group);
                }
            });

            //sort ascending
            $('.sort_button.sort_down', c).click(function() {
                var th = $(this).closest('th'); //handle on current <th>
                //mark correct column sorted
                $('>thead>tr>th.sorted', c).removeClass('sorted');
                th.addClass('sorted');
                //save which column and order was last sorted
                last_sort_col = th.index();
                last_sort_asc = true;

                //can mix groups if in "comparing" mode
                if (c.hasClass('comparing')) {
                    var gb = $('>tbody>tr.selected', c); //sorting only selected columns
                    gb.sort(function(a, b) {
                        return parseFloat($('td:eq(' + th.index() + ') .value', a).text()) - parseFloat($('td:eq(' + th.index() + ') .value', b).text());
                    }).appendTo($('>tbody', c));
                } else if (group == 0) {
                    var gb = $('.group_0', c);
                    gb.sort(function(a, b) {
                        return parseFloat($('td:eq(' + th.index() + ') .value', a).text()) - parseFloat($('td:eq(' + th.index() + ') .value', b).text());
                    }).appendTo($('>tbody', c));
                } else {
                    //otherwise, start a counter to not mix groups
                    for (var i = 1; i <= group; i++) {
                        var gh = $('.group_header_' + i, c), //handle on group header
                            gb = $('.group_' + i, c); //handle on group body - all rows that belong to current group

                        //sort rows where .value of the same column as th's index for a>b
                        gb.sort(function(a, b) {
                            return parseFloat($('td:eq(' + th.index() + ') .value', a).text()) - parseFloat($('td:eq(' + th.index() + ') .value', b).text());
                        }).insertAfter(gh);
                    }
                }
            });

            //sort descending
            $('.sort_button.sort_up', c).click(function() {
                var th = $(this).closest('th'); //handle on current <th>
                //remove sorted status
                th.removeClass('sorted');
                //save which column and order was last sorted
                last_sort_col = th.index();
                last_sort_asc = false;

                //can mix groups if in "comparing" mode
                if (c.hasClass('comparing')) {
                    var gb = $('>tbody>tr.selected', c); //sorting only selected columns
                    gb.sort(function(a, b) {
                        return parseFloat($('td:eq(' + th.index() + ') .value', b).text()) - parseFloat($('td:eq(' + th.index() + ') .value', a).text());
                    }).appendTo($('>tbody', c));
                } else if (group == 0) {
                    var gb = $('.group_0', c);
                    gb.sort(function(a, b) {
                        return parseFloat($('td:eq(' + th.index() + ') .value', b).text()) - parseFloat($('td:eq(' + th.index() + ') .value', a).text());
                    }).appendTo($('>tbody', c));
                } else {
                    //otherwise, start a counter to not mix groups
                    for (var i = 1; i <= group; i++) {
                        var gh = $('.group_header_' + i, c), //handle on group header
                            gb = $('.group_' + i, c); //handle on group body - all rows that belong to current group

                        //sort rows where .value of the same column as th's index for a<b
                        gb.sort(function(a, b) {
                            return parseFloat($('td:eq(' + th.index() + ') .value', b).text()) - parseFloat($('td:eq(' + th.index() + ') .value', a).text());
                        }).insertAfter(gh);
                    }
                }
            });

            //row selection code
            //compare code
            var rows_compare = function() {
                c.addClass('comparing');
                $('.fund_compare').addClass('comparing');

                //if the table was sorted, we need to sort it again, ignoring groups
                if (last_sort_col !== null) {
                    var gb = $('>tbody>tr.selected', c); //sorting only selected columns
                    if (last_sort_asc) {
                        gb.sort(function(a, b) {
                            return parseFloat($('td:eq(' + last_sort_col + ') .value', a).text()) - parseFloat($('td:eq(' + last_sort_col + ') .value', b).text());
                        }).appendTo($('>tbody', c));
                    } else {
                        gb.sort(function(a, b) {
                            return parseFloat($('td:eq(' + last_sort_col + ') .value', b).text()) - parseFloat($('td:eq(' + last_sort_col + ') .value', a).text());
                        }).appendTo($('>tbody', c));
                    }
                }
            };
            //uncompare code
            var rows_uncompare = function() {
                c.removeClass('comparing');
                $('.fund_compare').removeClass('comparing');

                //if the table was sorted, we need to restore groups and sort separately
                if (last_sort_col !== null) {
                    for (var i = 1; i <= group; i++) {
                        var gh = $('.group_header_' + i, c), //handle on group header
                            gb = $('.group_' + i, c); //handle on group body - all rows that belong to current group

                        gh.appendTo($('>tbody', c));
                        //sort rows where .value of the same column as last_sort_col index for last_sort_asc
                        if (last_sort_asc) {
                            gb.sort(function(a, b) {
                                return parseFloat($('td:eq(' + last_sort_col + ') .value', a).text()) - parseFloat($('td:eq(' + last_sort_col + ') .value', b).text());
                            });
                        } else {
                            gb.sort(function(a, b) {
                                return parseFloat($('td:eq(' + last_sort_col + ') .value', b).text()) - parseFloat($('td:eq(' + last_sort_col + ') .value', a).text());
                            });
                        }
                        gb.insertAfter(gh);
                    }
                }
            };

            //bind to buttons
            $('.fund_compare .button.compare').click(function(e) {
                e.preventDefault();
                rows_compare();
            });
            $('.fund_compare .button.uncompare').click(function(e) {
                e.preventDefault();
                rows_uncompare();
            });

            //check if 2 or more row selected
            var row_selection_check = function() {
                if ($('>tbody>tr.selected', c).length > 1) {
                    //if anything selected - show compare block
                    $('.fund_compare').removeClass('hidden');
                } else {
                    $('.fund_compare .button.uncompare').trigger('click');
                    $('.fund_compare').addClass('hidden');
                }
                //update number of selected rows in the block
                $('.fund_compare .text .value').html($('>tbody>tr.selected', c).length);
            };
            row_selection_check();

            //row selection
            $('>tbody>tr .control.checkbox>input', c).change(function() {
                var th = $(this), //handle on current checkbox
                    tr = th.closest('tr'), //handle on current row
                    siblings_th = c.siblings('.fund_list_table').find('input[data-fund=' + th.data('fund') + ']'),
                    siblings_tr = siblings_th.closest('tr');
                if (th.prop('checked')) {
                    tr.addClass('selected');
                    siblings_th.prop('checked', true);
                    siblings_tr.addClass('selected');
                } else {
                    tr.removeClass('selected');
                    siblings_th.prop('checked', false);
                    siblings_tr.removeClass('selected');
                }
                row_selection_check();
            });
        });
    };

    var investment_program_content = function() {
        $('.investment_program').filter(function() {
            if (!$(this).data('investment_program_hasscript')) {
                return true;
            }
        }).data('investment_program_hasscript', true).each(function() {
            var c = $(this); //container handle

            if (typeof(Highcharts) != 'undefined') {
                var structure_chart_id = 'structure_chart';
                var structure_chart = jQuery('#' + structure_chart_id);

                var result_chart_id = 'result_chart';
                var result_chart = jQuery('#' + result_chart_id);

                if (structure_chart.length) {
                    //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);

                    //structure chart
                    $.getJSON(structure_chart.data('sourceUrl'), function(data) {
                        Highcharts.chart(structure_chart_id, {
                            chart: {
                                plotBackgroundColor: null,
                                plotBorderWidth: null,
                                plotShadow: false,
                                type: 'pie',
                                margin: [0, 0, 0, 0],
                                spacing: [0, 0, 0, 0],
                                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: [80, '50%'],
                                    colors: ['#8f0908', '#d01429', '#ff4453', '#ff8183'],
                                    dataLabels: {
                                        enabled: false
                                    },
                                    showInLegend: true,
                                    size: 160,
                                    slicedOffset: 0
                                }
                            },
                            legend: {
                                layout: 'vertical',
                                align: 'left',
                                verticalAlign: 'top',
                                itemMarginTop: 15,
                                itemMarginBottom: 15,
                                useHTML: true,
                                itemStyle: {
                                    color: '#6a625a',
                                    fontSize: '16px',
                                    fontWeight: 'normal',
                                    lineHeight: '30px',
                                    cursor: 'default',
                                    textOverflow: 'auto',
                                },
                                itemHoverStyle: {
                                    color: '#6a625a'
                                },
                                labelFormatter: function() {
                                    return '<b style="color:#333;font-weight:bold;">' + this.y + '%</b> - ' + this.name;
                                },
                                symbolHeight: 30,
                                symbolPadding: 20,
                                padding: 8,
                                floating: true,
                                x: 210,
                                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: {
                                        maxWidth: 500
                                    },
                                    chartOptions: {
                                        plotOptions: {
                                            pie: {
                                                center: ['50%', 80]
                                            }
                                        },
                                        legend: {
                                            itemMarginTop: 10,
                                            itemMarginBottom: 10,
                                            itemStyle: {
                                                lineHeight: '25px',
                                            },
                                            x: 8,
                                            y: 180
                                        }
                                    }
                                }]
                            }
                        });
                    });
                }

                if (result_chart.length) {
                    var chart;
                    var compareSourceUrl;
                    var tools = $('.tools .compare');
                    var search_bar = $('.panel.search_bar');
                    var buttons = search_bar.find('.control.radio input:radio[name="invest-type"]');
                    var start_date_field = search_bar.find('.field input#start_date');
                    var end_date_field = search_bar.find('.field input#end_date');

                    var growth_block = jQuery('.chart_title');
                    var growth_result = growth_block.find('.result');

                    start_date_field.on('change', function(e, val) {
                        if (chart) {
                            var date = roundDate(Date.parse(jQuery(this).val()));
                            chart.rangeSelector.setInputValue('min', date);
                            result_chart.find('input.highcharts-range-selector[name="min"]').change();
                        }
                    });

                    end_date_field.on('change', function(e) {
                        if (chart) {
                            var date = roundDate(Date.parse(jQuery(this).val()));
                            chart.rangeSelector.setInputValue('max', date);
                            result_chart.find('input.highcharts-range-selector[name="max"]').change();
                        }
                    });

                    search_bar.on('change', 'input#start_date-user-input', function() {
                        if (chart) {
                            var date = roundDate(Date.parse(start_date_field.val()));
                            chart.rangeSelector.setInputValue('min', date);
                            result_chart.find('input.highcharts-range-selector[name="min"]').change();
                        }
                    });

                    search_bar.on('change', 'input#end_date-user-input', function() {
                        if (chart) {
                            var date = roundDate(Date.parse(end_date_field.val()));
                            chart.rangeSelector.setInputValue('max', date);
                            result_chart.find('input.highcharts-range-selector[name="max"]').change();
                        }
                    });

                    var roundDate = function(timestamp) {
                        var date = new Date(timestamp);

                        date.setHours(0);
                        date.setSeconds(0);
                        date.setMilliseconds(0);

                        return date;
                    };

                    $.getJSON(result_chart.data('sourceUrl'), function(data) {

                        var now = Date.now();

                        data = jQuery.grep(data, function(item) {
                            return item[0] <= now;
                        });

                        // create the chart
                        data = jQuery.map(data, function(item) {
                            return [[roundDate(item[0]).getTime(), item[1]]];
                        });

                        Highcharts.setOptions({
                            global: {
                                useUTC: false
                            }
                        });

                        var result_options = result_chart.data('results') === 'program' ? program_options : fund_options;
                        Highcharts.setOptions(result_options);

                        chart = Highcharts.stockChart(result_chart_id, {
                            credits: {
                                enabled: false
                            },
                            title: false,
                            rangeSelector: {
                                selected: 2,
                                buttons: [{
                                    type: 'year',
                                    count: 1,
                                    text: '1y'
                                }, {
                                    type: 'year',
                                    count: 3,
                                    text: '3y'
                                }, {
                                    type: 'year',
                                    count: 5,
                                    text: '5y'
                                }, {
                                    type: 'all',
                                    text: 'all'
                                }],
                                inputDateParser: function (value) {
                                    var date = new Date(value);
                                    var timestamp = date.valueOf();
                                    timestamp = timestamp + date.getTimezoneOffset() * 60 * 1000;
                                    return timestamp;
                                }
                            },
                            xAxis: {
                                type: 'datetime',
                                events: {
                                    setExtremes: function(event) {
                                        if (event.trigger != "rangeSelectorButton") {
                                            buttons.prop("checked", false);
                                        }

                                        var min = roundDate(event.min);
                                        var max = roundDate(event.max);

                                        start_date_field.siblings('input#start_date-user-input').datepicker('setDate', min);
                                        end_date_field.siblings('input#end_date-user-input').datepicker('setDate', max);

                                        // imask lib is binding events via addEventListener and those do not listen to jQuery.trigger
                                        start_date_field.siblings('input#start_date-user-input')[0].dispatchEvent(new Event('change'));
                                        end_date_field.siblings('input#end_date-user-input')[0].dispatchEvent(new Event('change'));
                                    },
                                    afterSetExtremes: function (event) {
                                        var find = function(timestamp) {
                                            for (var index in data) {
                                                var point = data[index];

                                                if (point[0] === timestamp.getTime()) {
                                                    return index;
                                                }
                                            }
                                        };

                                        if (event.min < data[0][0])
                                        {
                                            event.min = data[0][0];
                                        }

                                        if (event.max > data[data.length - 1][0])
                                        {
                                            event.max = data[data.length - 1][0];
                                        }

                                        var min = find(roundDate(event.min));
                                        var max = find(roundDate(event.max));

                                        if (min && max) {
                                            // Array.slice(a, b) does not include b, so make correction
                                            var selectedPoints = data.slice(min, max + 1);
                                            var open = parseFloat( selectedPoints[0][1] );
                                            var close = parseFloat( selectedPoints[selectedPoints.length - 1][1] );
                                            var increase = ( close / open - 1 ) * 100;

                                            growth_block.removeClass('hidden');
                                            growth_result.html(increase.toFixed(2) + '%');
                                            growth_result
                                                .removeClass('positive')
                                                .removeClass('negative')
                                                .addClass(increase > 0 ? 'positive' : 'negative');
                                        } else {
                                            growth_block.addClass('hidden');
                                        }
                                    }
                                }
                            },
                            series: [{
                                name: ' ',
                                type: 'area',
                                data: data,
                                gapSize: 0,
                                tooltip: {
                                    valueDecimals: 4
                                },
                                lineColor: Highcharts.getOptions().colors[0],
                                fillColor: {
                                    linearGradient: {
                                        x1: 0,
                                        y1: 0,
                                        x2: 0,
                                        y2: 1
                                    },
                                    stops: [
                                        [0, Highcharts.getOptions().colors[0]],
                                        [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
                                    ]
                                },
                                threshold: null
                            }],
                            chart: {
                                events: {
                                    load: function(e) {
                                        start_date_field.siblings('input#start_date-user-input').datepicker('setDate', roundDate(e.target.xAxis[0].min));
                                        end_date_field.siblings('input#end_date-user-input').datepicker('setDate', roundDate(e.target.xAxis[0].max));

                                        // imask lib is binding events via addEventListener and those do not listen to jQuery.trigger
                                        start_date_field.siblings('input#start_date-user-input')[0].dispatchEvent(new Event('change'));
                                        end_date_field.siblings('input#end_date-user-input')[0].dispatchEvent(new Event('change'));
                                    },
                                }
                            },
                        });

                        chart.redraw();
                    });

                    result_chart.on('compare', function() {
                        var compareSeries = chart.get('compare-series');
                        if (compareSeries) {
                            compareSeries.remove();
                        }

                        if (!compareSourceUrl) {
                            return;
                        }

                        $.getJSON(compareSourceUrl, function(data) {
                            data = jQuery.map(data, function(item) {
                                return [[roundDate(item[0]).getTime(), item[1]]];
                            });

                            chart.addSeries({
                                id: 'compare-series',
                                name: 'GOOG',
                                type: 'area',
                                data: data,
                                gapSize: 0,
                                tooltip: {
                                    valueDecimals: 2
                                },
                                lineColor: Highcharts.getOptions().colors[8],
                                fillColor: {
                                    linearGradient: null,
                                },
                                threshold: null
                            }, true);
                        });
                    })

                    buttons.on('change', function() {
                        var mapping = { "1y": 0, "3y": 1, "5y": 2, "all": 3 };

                        if (chart && this.checked) {
                            chart.rangeSelector.clickButton(mapping[this.value], {}, true);
                        }
                    });

                    tools.find('.action .js-compare').on('click', function(e) {
                        e.preventDefault();

                        compareSourceUrl = tools.find('#compare_to option:selected').attr('data-source-url');
                        result_chart.trigger('compare');
                    });

                    start_date_field.change();
                    end_date_field.change();
                }
            }

            $('.export_menu_cont', c).each(function() {
                var th = $(this), //handle on the whole menu container
                    trigger = $('.trigger', th); //handle on trigger
                trigger.click(function(e) {
                    e.preventDefault();
                    if (th.hasClass('open')) {
                        th.removeClass('open');
                    } else {
                        th.addClass('open');
                    }
                });
                $(document).click(function(e) {
                    var tar = $(e.target); //handle on clicked element on the page
                    //if clicked outside the container - close menu
                    if (!tar.is(th) && !tar.closest('.export_menu_cont').is(th)) {
                        th.removeClass('open');
                    }
                });
            });

            $('#profitability_table', c).each(function() {
                var th = $(this), //handle on the table
                    col_n = $('.tr.header_row>.td', th).length, //count the columns
                    data_row_n = $('.tr:not(.header_row)', th).length; //count the data rows
                //give desktop columns their class
                $('.tr:not(.header_row)', th).addClass('dt_only').last().addClass('last_data_row');
                //re-parse content for mobile; for each column...
                for (var i = 0; i < col_n; i++) {
                    //create a new row
                    var new_row = $('<div class="tr mob_only' + (i == 0 ? ' first_mob_row' : '') + '"></div>');
                    //fill new row with header...
                    $('<div class="header">' + $('.tr.header_row>.td:eq(' + i + ')', th).html() + '</div>').appendTo(new_row);
                    //...and data...
                    for (var j = 0; j < data_row_n; j++) {
                        //from each row
                        $($('.tr.dt_only:eq(' + j + ')>.td:eq(' + i + ')', th).html()).appendTo(new_row);
                    }
                    //and then append the newly created mobile data row
                    th.append(new_row);
                }
            });
        });
    };


    var page = jQuery(document);

    page.on('contentloaded', function(event)
    {
        var block = jQuery(event.target);

        if (!block.is(page))
        {
            return;
        }

        initialize_all_content();
    });

}());
