/**
 * Created by noob on 16.01.17.
 */

( function() {

    'use strict';

    $("#submitAddMobileCompare").click(function() {
        var jobs = $('#addMobileJobsToCompare').val();
        if (jobs){
            var url = '/mobilecompare/add_jobs';
            $.post(url, {
                "jobs" : jobs
            }).success(function(data) {
                if (data) {
                    if (data.success === 1) {
                        $(".b_mobilecompare_count").html(jobs.split(',').length);
                        if (jobs.split(',').length > 0) {
                            $(".b_mobilecompare_count__delete").show();
                        } else {
                            $(".b_mobilecompare_count__delete").hide();
                        }
                        window.location = '/mobilecompare/';
                    }
                }
            }, 'json');
        }
    });

    var group = $('.groupBy.active').data('criterion'); // группировка по цвету

    $('.groupBy').on('click', function (event) {
        if (!$(this).hasClass('active')) {
            $('.groupBy').removeClass('active');
            $(this).addClass('active');
            group = $(this).data('criterion');
            console.log($(this).data('criterion'));
            if ($('#mobilecompare__tab__timeline_quantiles').hasClass('active')) {
                var $mobileTimelineQuantilesContainer = $("#mobileTimelineQuantilesContainer");
                if ($mobileTimelineQuantilesContainer.html() === "" || $mobileTimelineQuantilesContainer.data('group') !== group) {
                    renderTimelineQuantilesPlot($('#quantilesSelectors a.active'), group);
                    $mobileTimelineQuantilesContainer.data('group', group)
                }
            } else if ($('#mobilecompare__tab__bar_avg').hasClass('active')) {
                var $mobileBarAvgContainer = $("#mobileBarAvgContainer");
                if ($mobileBarAvgContainer.html() === "" || $mobileBarAvgContainer.data('group') !== group) {
                    renderBarAvgPlot('', group);
                    $mobileBarAvgContainer.data('group', group)
                }
            }
        }
    });

    var parsedHash = getUrlVars();
    var jobs = parsedHash["jobs"] ? parsedHash["jobs"] : '';
    var jobs_url = '';
    if (jobs) {
        jobs_url = '/mobilecompare/reset_jobs';
        $.ajax({
            url : jobs_url,
            type : 'POST',
            data: {"jobs": jobs},
            dataType : 'json'
        }).success(function (data) {
            if (data['success'] === 1) {
                $(".b_mobilecompare_count").html(jobs.split(',').length);
                if (jobs.split(',').length > 0) {
                    $(".b_mobilecompare_count__delete").show();
                } else {
                    $(".b_mobilecompare_count__delete").hide();
                }
            }
        });
    }
    else {
        jobs = $("#user_mobile_job_numbers").data('numbers');
        if (!jobs) {
            jobs_url = '/mobilecompare/get_compare_jobs.json';
            $.ajax({
                url : jobs_url,
                type : 'GET',
                dataType : 'json'
            }).success(function(data) {
                if (data["jobs"]) {
                    jobs = data["jobs"]
                } else {
                    window.location = '/mobilecompare/no_compare_jobs'
                }
            }).fail(function(){
                console.log('fail');
                window.location = '/mobilecompare/no_compare_jobs'
            });
        }
    }

    setHash({'jobs': jobs});

    function getUrlVars (str) {
        var vars = {};
	    if (str === undefined) {
	        str = window.location.href.replace('#','&')
	    }
	    str = str.replace(/</g, "&lt;").replace(/>/g, "&gt;");
	    str.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
            vars[key] = value;
	    });
	    return vars;
	}

	var $quantilesSelectors = $('#quantilesSelectors a');
    $quantilesSelectors.off();
	$quantilesSelectors.on('click', function(event){
    	$("#selector_krutilka").show();
        renderTimelineQuantilesPlot($(this), group);
        event.stopPropagation();
        event.preventDefault();
    });
    renderTimelineQuantilesPlot($('#quantilesSelectors a.active'), group);

    $('#mobilecompare__tab__timeline_quantiles').on('shown.bs.tab', function(event) {
        var $mobileTimelineQuantilesContainer = $("#mobileTimelineQuantilesContainer");
    	if ($mobileTimelineQuantilesContainer.html() === "" || $mobileTimelineQuantilesContainer.data('group') !== group) {
    		renderTimelineQuantilesPlot($('#quantilesSelectors a.active'), group);
    		$mobileTimelineQuantilesContainer.data('group', group)
    	}
		event.preventDefault();
	});
	
	$('#mobilecompare__tab__bar_avg').on('shown.bs.tab', function(event) {
	    var $mobileBarAvgContainer = $("#mobileBarAvgContainer");
		if ($mobileBarAvgContainer.html() === "" || $mobileBarAvgContainer.data('group') !== group) {
            renderBarAvgPlot('', group);
            $mobileBarAvgContainer.data('group', group)
		}
		event.preventDefault();
	});
	
	renderMetaTable();

    function renderTimelineQuantilesPlot(selector, groupby){
        $.getJSON('/mobilecompare/mobile_plot?type=timeline_quantiles&selector='+selector.data('selector')+'&job_numbers='+jobs+'&groupby='+groupby, {}, function(data) {
            var cfg={
                chart: {
                    width: $('#mobileTimelineQuantilesContainer').width(),
                },
                xAxis: {
                    labels: {
                        enabled: false,
                        },
                    tickLength: 0,
                },
                series: data.data,
            };

            $.extend(true, cfg, commonConfig);
            console.log(cfg);
            Highcharts.StockChart('mobileTimelineQuantilesContainer', cfg);
        	$('#quantilesSelectors a.active').removeClass('active');
        	selector.addClass('active');
        	$("#selector_krutilka").hide();
        });
    }

    function renderBarAvgPlot(selector, groupby){
	    $.getJSON('/mobilecompare/mobile_plot?type=bar_avg&job_numbers='+jobs+'&groupby='+groupby, {}, function(data) {
	        var cfg={
	            chart: {
	                width: $('#mobileBarAvgContainer').width(),
	                enabledTracking: false,
	                type: 'column',
	            },
	            xAxis: {
	                labels: {
	                    enabled: false,
	                    },
	                categories: [0],
	                tickLength: 0,
	                crosshair: {
	                    snap: false,
	                    width: 0,
	                }
	            },
	            series: data.data,
	            tooltip : {
	                enabled: false,
	            },
	        };
	
	        $.extend(true, cfg, commonConfig);
	        Highcharts.StockChart('mobileBarAvgContainer', cfg)
	        
	    });
    }

    function renderMetaTable() {
    	$.getJSON('/mobilecompare/mobile_metatable?job_numbers='+jobs, {}, function(data) {
	        for (var i=0; i<data.length; i++) {
	            $('#header').append('<th style="color: '+data[i].color+'"><a href="/mobile/'+data[i].header+'">'+data[i].header+'</a></th>');
	            $('#name').append('<td style="color: '+data[i].color+'">'+data[i].name+'</td>');
	            $('#dsc').append('<td style="color: '+data[i].color+'">'+data[i].dsc+'</td>');
	            $('#task').append('<td style="color: '+data[i].color+'"><a href="/'+data[i].task+'#mobile">'+data[i].task+'</a></td>');
	            $('#app').append('<td style="color: '+data[i].color+'">'+data[i].app+'</td>');
	            $('#ver').append('<td style="color: '+data[i].color+'">'+data[i].ver+'</td>');
	            $('#device_model').append('<td style="color: '+data[i].color+'">'+data[i].device_model+'</td>');
	
	            $('#jobsControls').append('<tr>'+
	                '<td style="border-top: none; color: '+data[i].color+'"> \
                        <a href="/mobile/'+data[i].header+'">'+data[i].header+'</a>\
	                    <span class="removeJobFromCompare fa fa-times-circle-o text-muted" \
                              data-job="'+data[i].header+'" \
                              aria-hidden="true" \
                              style="font-size: 12pt; cursor:pointer;"> \
                        </span> \
                    </td> \
	                <td style="border-top: none; color: '+data[i].color+'">'+data[i].name+'</td> \
	                </tr>');

                $(".removeJobFromCompare").on('click', function(){
                    var job_n = $(this).data('job');
                    var url = '/mobilecompare/remove_jobs';
                    $.post(url, {
                            "jobs" : job_n
                        }).success(function(data) {
                            if (data && data["success"] === 1) {
                                $('#mobilecompare_menu_link').find('a')[0].click();
                            }
                        }, 'json');
                });

	        }
	        // TODO: diff mask for table
	    });
    }

    // Ресайзим график
    $( window ).resize(function() {
    	for (var i=0; i<Highcharts.charts.length; i++){
    		var chart = Highcharts.charts[i];
    		if (chart) {
    			chart.setSize($(chart.container).width(), 400, false)
    		}
    	}
    });
//
    function setHash(parsedHash) {
        if (parsedHash){
            var hashKeys = Object.keys(parsedHash);
            var newHash = '';
            for (var k=0; k < hashKeys.length; k++) {
                newHash += '&' + hashKeys[k] + '=' + parsedHash[hashKeys[k]]
            }
            window.location.hash = newHash.slice(1)
        }
    }

    var commonConfig = {
        chart: {
                reflow: false,
                height: 400,
                animation: false,
                style: {
                    fontFamily: 'Yandex Sans Text Web'
                },
            },
            plotOptions: {
                column : {
                    borderWidth: 0,
                    states: {hover: {enabled: false}},
                    dataLabels: {
                        enabled: true,
                        verticalAlign: 'middle',
                        inside: true,
                        color: '#FFFFFF',
                        align: 'right',
                        y: 10, // 10 pixels down from the top
                        style: {
                            textOutline: null,
                            fontSize: '16px',
                            fontFamily: '"Yandex Sans Text Web", "Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;',
                        },
                        formatter: function() {
                            return this.y
                        }
                    },
                },
                series : {
                    animation : false,
                    shadow: false,
                    states: {
                    	hover: {
                    		enabled: false,
                    	}
                    }
                },
            },
            title: {
                text: "",
                style: {
                    fontFamily: '"Yandex Sans Text Web", "Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;',
                },
            },
            tooltip : {
                animation : false,
                hideDelay: 10,
                headerFormat: "",
                borderRadius : 2,
                borderWidth : 1,
            },
            navigator: {
                enabled: false,
            },
            rangeSelector: {
                enabled: false,
            },
            exporting: {
                enabled: false,
            },
            credits: {
                enabled: false,
            },
            scrollbar: {
                enabled: false,
            },
            yAxis: {
                opposite: false,
                title: {
                    text: null,
                },
            },
            legend : {
                enabled: true,
                align : 'center',
                verticalAlign : 'bottom',
                itemStyle : {
                    color : '#333',
                },
                borderWidth : 0
            },
    };
    
    $(document).ready(function() {
    	// TODO: чтение активного таба из хэша урла. 
    	$(".nav-link.active").tab('show');
    });
    
})();


