(function() {
	/*
	 * список "Мои проекты"
	 */

    $("#projects_list_opener").click(function() {
    	var popup_url = "/mainpage/projects/";
        $("#projects_list_opener").hide();
        $("#projects_list").show();
        $.get(popup_url, function(data) {
			$("#projects_popup").html(data);
        });
    });

    $("#projects_list_hider").click(function() {
        $("#projects_list").hide();
        $("#projects_list_opener").show();
    });
    
    
	/*
	 * кнопка для показа формы создания KPI
	 */

	$("#add_kpi_button")
			.click(
					function(event) {
						$(this).hide();
						$("#finish_comp_edit_button").hide();
						$(".cancel_edit_component").hide();
						$("#add_kpi_form").show();
						event.preventDefault();
						event.stopPropagation();
					});

	/*
	 * кнопка для скрытия формы создания KPI
	 */

	$(".cancel_add_kpi")
			.click(
					function(event) {
						$("#add_kpi_form").hide();
						$("#finish_comp_edit_button").show();
						$(".cancel_edit_component").show();
						$("#add_kpi_button").show();
						event.preventDefault();
						event.stopPropagation();
					});
	
	/*
	 * кнопка удаления KPI
	 */
	
	$(".delete_kpi")
	.click(
			function(event) {
				
					var project = this.id.split("__")[1];
					var component = this.id.split("__")[2];
					var kpi = this.id.split("__")[3];
					var dsc = $('td#kpi_dsc__' + kpi).text();
				if (confirm('Удалить KPI: \n' + dsc +'?')) {
					var url = "/regress/" + project + "/" + component + "/delete_kpi?kpi=" + kpi;
					$.get(url, function(data) {
						document.location.reload(true);
						});
				} else {
				    // Do nothing!
				}
			});
	
	/*
	 * кнопка редактирования KPI
	 */
	
	$(".edit_kpi_button")
			.click(
					function(event) {
						var kpi = this.id.split("__")[1];
						var kpitype = this.id.split("__")[2];
						$('div#edit_kpi_form__' + kpi).html('<div style="padding-top: 2.2em;"><i class="krutilka fa fa-circle-o-notch fa-spin" aria-hidden="true"></i></div>').load(
				    			  location.protocol+'//'+location.host+location.pathname + '/render_kpi_editor?kpi=' + kpi, function() {
				    					/*
				    					 * кнопка для скрытия формы редактирования KPI
				    					 */

				    					$(".cancel_edit_kpi")
				    							.click(
				    									function(event) {
				    										var kpi = this.id.split("__")[1];
				    										$("#edit_kpi_form__" + kpi).hide();
				    										event.preventDefault();
				    										event.stopPropagation();
				    									});
				    					var $editKpiButton = $("#edit_kpi_button__"+kpi+"__"+kpitype);
				    					$editKpiButton.unbind();
				    					$editKpiButton
				    							.click(
				    									function(event) {
				    										$('div#edit_kpi_form__' + kpi).toggle() 
				    									})
				    			  });
						//$("#edit_kpi_form__" + kpi).show()
						//$("#graphs_"+ kpitype + "_" + kpi).show();
						event.preventDefault();
						event.stopPropagation();
					});
	
	/*
	 * кнопка отмены редактирования компонента 
	 */
	$(".cancel_edit_component")
	.click(
			function(event) {
				var project = this.id.split("__")[1];
				var component = this.id.split("__")[2];
				var url = "/regress/" + project + "/" + component;
				window.location.replace(url);
			});
	
	/*
	 * переключение между табами
	 */
	$(".tab_panel_tab")
	.click(
			function(event) {
				var service = $(this).data('service'),
				project = $(this).data('project');
				
				$('#component_list').html('<i class="krutilka fa fa-circle-o-notch fa-spin" aria-hidden="true"></i>');
				
				$("a.nav-link.active").removeClass('active');
				$(this).find('a').addClass('active');
				
				var page = new ComponentListView();
				page.loadComponentList(project, service);

                var url = '/regress/' + project + '?service=' + service;
				window.history.replaceState('', document.getElementsByTagName('title')[0].innerHTML, url);
                window.location.reload();

			});
	
	$(document).ready(function() {
		
		var activeTab = $(".tab_panel_tab_link.active");
		var service = activeTab.data('service')?activeTab.data('service'):'',
		project = activeTab.data('project');
		
		var page = new ComponentListView();
		page.loadComponentList(project, service);
	});
	
	function ComponentListView() {
		
	}
	
	ComponentListView.prototype.loadComponentList = function(project, service) {
		var self = this;
		var url = "/api/regress/"+project+"/componentlist.json?service="+service+"&order=-service";
		var list = $("div#component_list");

		$.getJSON(url)
				.done(self.fillComponentList).fail(function() {
					list.text("Failed to get component list for project");
				}).always(function() {
					list.find(".krutilka").hide();
				});
	};

	ComponentListView.prototype.fillComponentList = function(component_list_data) {
		
		var activeTab = $(".tab_panel_tab_link.active");
		var service = activeTab.data('service');
        var component_n = activeTab.data('component');
		project = activeTab.data('project');
		
	    $('body').append('<div id="blackout"></div>');
	    $('#blackout').bind('click', function(){
	    	popup_rebuild();
	    	$('.popup-box').hide();
	    	$(this).hide()
	    });
	    
	    
	    function popup_rebuild() {
	    	$('.popup-bottom').html(
					'<button id="popup-redirect" type="button" class="btn btn-secondary btn-sm job_button">К стрельбе</button>\
					<br>\
				    <button id="popup-delete" type="button" class="btn btn-secondary btn-sm job_button">Удалить</button>\
				    <br>\
				    <button id="popup-comment" type="button" class="btn btn-secondary btn-sm job_button">Комментировать</button>'																	    		
	    		)
	    }
	     
		var list = $("div#component_list");
		
		for ( var n = 0; n < component_list_data.length; n++) {
			var compId = component_list_data[n].n;
			var componentTemplate = _.template($('#componentTemplate').text());
			var container = $("<div class='panel panel-default component-container' data-component_id='"+compId+"'></div>");
			if (component_list_data[n].project !== project) {
				container.append(componentTemplate({component: component_list_data[n], compId: compId, anotherProject: project, projectValue: project}))
			}
			else {
				container.append(componentTemplate({component: component_list_data[n], compId: compId, anotherProject: "", projectValue: project}))
			}

            if (component_n === '') {
                list.append(container);
            }
            
            else if (compId === component_n) {
                list.append(container);
            }
        }

		$('.componentEditIcon').on('click', function(event){
            var project = $(this).data('project');
            var component = $(this).data('component');
            var url = "/regress/" + project + "/" + component + "/edit";
            $.get(url, function() {
                window.location.replace(url);
            });
        });

        $('.componentDeleteIcon').on('click', function(event){
            var project = $(this).data('project');
            var component = $(this).data('component');
            if (confirm('Удалить компонент "' + component + '"?')) {
                var url = "/regress/" + project + "/delete_component?component=" + component;
                $.get(url, function() {
                    window.location.replace("/regress/" + project);
                    });
            } else {
                // Do nothing!
            }
        });
	
		list.find(".component-container").map(
				function(ix, obj) {
					var compId = $(obj).data("component_id");
					loadKpiPlots(compId)
				});

		function loadKpiPlots(compId) {
			var job_limit = $('#kpi_radio_container__'+compId).find("button.active").data('limit');
			var kpi_url = "/api/regress/" + compId + "/kpilist.json";
			var kpi_list = $("div#kpi_list_" + compId);
			$.getJSON(kpi_url)
                .done(function(data) {
                    for ( var n = 0; n < data.length; n++) {
                        var kpi_container = $("<div class='col-md-6 kpi-container' id='kpi-container_"+data[n].n+"' data-kpi_id='"+data[n].n+"'><div></div><div id='sla_"+data[n].n+"'></div></div>");
                        kpi_list.append(kpi_container);
                    }
                    kpi_list.find(".kpi-container").map(
                        function(ix, obj) {
                            //var plotWidth = ($(window).width() - 80 - $('td#projects').width()) / data.length
                            var kpiID = $(obj).data("kpi_id");
                            var kpi_data_url = "/regress/kpi/" + kpiID
                                    + "/data.json?job_limit=" + job_limit;
                            $.getJSON(kpi_data_url).done(function(data){
                                var max_y;
                                if (data.yaxis_label === " %") {
                                     max_y = 100
                                }
                                else {
                                    max_y = null
                                }
                                var cfg={
                                        chart: {
                                            renderTo: $(obj).find("div")[0],
                                            height: 350,
                                            zoomType: 'x',
                                            resetZoomButton: {
                                                theme: {
                                                    fill: 'white',
                                                    stroke: 'silver',
                                                    r: 0,
                                                    states: {
                                                        hover: {
                                                            fill: '#41739D',
                                                            style: {
                                                                color: 'white'
                                                            }
                                                        }
                                                    }
                                                },
                                                relativeTo: 'chart'
                                            },
                                            style: {
                                                fontFamily: 'Yandex Sans Text Web'
                                            },
                                            marginTop: 80
                                        },
                                        yAxis: {
                                            startOnTick: false,
                                            title: {
                                                text: ''
                                            },
                                            allowDecimals: false,
                                            max: max_y,
                                            labels: {
                                                align: 'left',
                                                x: 8,
                                                y: -4,
                                                formatter: function() {
                                                    return this.axis.defaultLabelFormatter.call(this) + ' ' + (data.yaxis_label || '');
                                                }
                                            }
                                        },
                                        title: {
                                            text: data.title
                                        },
                                        subtitle: {
                                            text: data.subtitle
                                        },
                                        plotOptions: {
                                            series: {
                                                turboThreshold : 5000,
                                                marker: {
                                                    enabled: true,
                                                    radius: 2
                                                },
                                                animation : false,
                                                states: {hover: {enabled: false}},
                                                cursor: 'pointer',
                                                point: { events: { click: function(event) {
                                                    var tooltip = $(obj).find("g.highcharts-tooltip").children()[0];
                                                    //tooltip.width.baseVal.value
                                                    $('.popup-box').css({'width' : '190px', 'left' : event.pageX - tooltip.getAttribute('anchorX')+'px', 'top' : event.pageY - tooltip.getAttribute('anchorY')+'px'});
                                                    $('#blackout').css({'width' : $(document).width()+'px', 'height' : $(document).height()+'px'});
                                                    $(".job_button").css({'width' : '160px', "align": "center"});
                                                    if (data.xaxis_type === 'datetime'){
                                                        $('.popup-box').data("job-id", data.xaxis_job_ids[this.category].split(" |")[0]);
                                                        var formattedTime = moment.utc(this.category).format("DD-MM-YYYY HH:mm:ss"); // will display time in dd.mm.yyyy hh:mm:ss format
                                                        $('#popup-title').html(formattedTime)

                                                    }
                                                    else {
                                                        $('.popup-box').data("job-id", data.xaxis_job_ids[this.category].split(" |")[0]);
                                                        $('#popup-title').html(data.xaxis_job_ids[this.category].split(" |")[0])
                                                    }

                                                    var job_version = data.xaxis_job_ids[this.category].split(" |")[1];
                                                    $("#popup-version").html(job_version);

                                                    $('.popup-box').show();
                                                    $('#blackout').show();

                                                    //button redirect
                                                    $("#popup-redirect").bind("click", function(event){
                                                        event.stopPropagation();
                                                        event.preventDefault();
                                                        var url = '/'+$('.popup-box').data("job-id");
                                                        var win = window.open(url, '_blank');
                                                        $('.popup-box').hide();
                                                        $('#blackout').hide();
                                                        $("#popup-redirect").unbind();
                                                            win.focus();
                                                    });

                                                    //button delete
                                                    $("#popup-delete").bind("click", function(event){
                                                        event.stopPropagation();
                                                        event.preventDefault();
                                                        if (!confirm("Удалить стрельбу "+$('.popup-box').data("job-id")+"\?")) {
                                                            return false;
                                                        }

                                                        $.post('/mass_delete.json', {
                                                            "fire_ids[]" : $('.popup-box').data("job-id")
                                                        }).success(function(data) {
                                                            if (data.status === 1) {
                                                                location.reload()
                                                            } else {
                                                                alert("Failed to delete job");
                                                            }
                                                        });
                                                    });

                                                    //button comment
                                                    $("#popup-comment").bind("click", function(event){
                                                        event.stopPropagation();
                                                        event.preventDefault();

                                                        $('.popup-bottom').html(
                                                        '<form id="commentForm" method="POST" action="/api/job/'+$(".popup-box").data("job-id")+'/regresscomment.json"> \
                                                        <input type="text" maxlength="256" name="comment" class="form-control" style="width: 150px; margin: 0.2em;"/>\
                                                        <input type="button" id="submit_button" class="btn btn-secondary" style="width: 154px; margin: 0.2em;" value="Okay"/>\
                                                        </form>'
                                                        );

                                                        $('#submit_button').click(function(event){
                                                            $.ajax({
                                                              url: $('#commentForm').attr('action'),
                                                              type: 'post',
                                                              data : $('#commentForm').serialize(),
                                                              async: false,
                                                              success: function(data){
                                                                    console.log(data);
                                                                    $('.popup-bottom').html(
                                                                        '<span id="success_v">&#10003;</span>'
                                                                    );
                                                                    if (data) {
                                                                        $.when(
                                                                            $("#success_v").animate({ opacity: 1 }, 700).promise()
                                                                        ).done(function(){
                                                                            location.reload();
                                                                            /*$('.popup-box').hide();
                                                                            popup_rebuild()
                                                                            $('#blackout').hide();*/
                                                                        });
                                                                    }
                                                                  }
                                                            });
                                                            event.preventDefault();
                                                        });
                                                    });

                                                }}}
                                            },
                                            area : {
                                                lineWidth : 0,
                                                fillOpacity : 1
                                            },
                                            line : {
                                                lineWidth : 2,
                                                zIndex : 1,
                                                shadow : false
                                            }
                                        },
                                        tooltip : {
                                            animation : false,
                                            hideDelay: 10,
                                            style: {
                                                fontSize: '14px'
                                            },
                                            useHTML: true,
                                            formatter: function() {
                                                // splitting long job version string into rows by 40 symbols.
                                                var job_version = data.xaxis_job_ids[this.x].split(" |")[1];
                                                if (job_version.length > 40) {
                                                    var split_version = '<small style="line-height: 10px;">';
                                                    var count = job_version.length / 40;
                                                    for (var i=0; i < count; i++) {
                                                        split_version += '</small><small style="line-height: 10px;">' + job_version.slice(40*i, 40*(i+1));
                                                        split_version += '</small><br />'
                                                    }
                                                    var job_version = split_version
                                                }
                                                else {
                                                    job_version = '<small style="line-height: 10px;">' + job_version + '</small>'
                                                }
                                                // formatting tooltip
                                                var res = '';
                                                if (data.xaxis_type === 'datetime') {
                                                    var formattedTime = moment.utc(this.x).format("DD-MM-YYYY HH:mm:ss");
                                                    res += '<small>' + formattedTime +'</small><br>'
                                                }
                                                else {
                                                    var job_date = data.xaxis_job_ids[this.x].split(" |")[2];
                                                    res += '<small style="font-weight: bold;">' + this.x +'</small>';
                                                    res += '<small>&nbsp(' + job_date +')</small><br>'
                                                }
                                                res += job_version + '<br>';
                                                res += '<table class="tooltip-table">';
                                                this.points.forEach(function(point, i) {
                                                    if(point.series.type !== 'flags'){
                                                        var ser = '';
                                                        ser += '<tr><td><span style="color: ' + point.series.color + ';">' +
                                                        point.series.name +
                                                        ': </span></td><td>' +
                                                        '<span style="font-weight: bold; color: ' + point.series.color + ';">' +
                                                        point.y.toString().split('.')[0].replace(/\B(?=(\d{3})+(?!\d))/g, "'"); // regexp: thousands delimiter
                                                        if (point.y.toString().indexOf(".") > 0) { // pretty fraction part
                                                            var fraction = point.y.toString().split('.')[1];
                                                            while (fraction && fraction.length < 3) {
                                                                fraction = fraction + '0'
                                                            }
                                                            ser += '<span style="font-size: 80%; font-weight: bold; color: ' + point.series.color + ';">.' +
                                                            fraction + '</span>';
                                                        }
                                                        ser += data.yaxis_label + '</span></td></tr>';
                                                        res += ser	;
                                                    }
                                                });
                                                res += '</table>';
                                                // comments
                                                /*
                                                $.each(this.points, function(i, point) {
                                                    if(this.series.name == 'comments') {
                                                        var comment = data.xaxis_job_ids[this.x].split(" |")[2]
                                                        if (comment) {
                                                            var comment_arr = comment.split(" -- ")
                                                            var comment_footer = comment_arr[comment_arr.length - 1];
                                                            var comment_text = ''
                                                            for (var i=0; i<comment_arr.length - 1; i++) {
                                                                comment_text += comment_arr[i];
                                                            }
                                                            if (comment_text.length > 32) { //if comment is too long split it
                                                                var split_comment = '<br>';
                                                                var count = comment_text.length / 32;
                                                                for (var i=0; i < count; i++) {
                                                                    split_comment += '<span style="color: ' + this.series.color + '; line-height: 16px;">' +
                                                                        comment_text.slice(32*i, 32*(i+1)) + '</span><br>'
                                                                }
                                                                comment_text = split_comment
                                                                comment = comment_text + '-- ' + '<span style="color: ' + this.series.color + '; line-height: 16px;">' +
                                                                    comment_footer + '</span>'
                                                            }
                                                            else {
                                                                comment = '<br><span style="color: ' + this.series.color + '; line-height: 16px;">' +
                                                                    comment_text + '</span>' + '<br />-- ' + '<span style="color: ' + this.series.color + '; line-height: 16px;">' +
                                                                    comment_footer + '</span>'
                                                            }
                                                            res += comment;
                                                        }
                                                    }
                                                })*/
                                                return res;
                                            },
                                            shared : true,
                                            borderColor: '#d8d8d8',
                                            borderRadius : 5,
                                            borderWidth : 1,
                                            shadow: false,
                                            crosshairs : {
                                                width : 1,
                                                color : 'gray',
                                                dashStyle : 'shortdot',
                                                zIndex: 3
                                            }
                                        },
                                        navigator: {
                                            enabled: false
                                        },
                                        rangeSelector: {
                                            enabled: false
                                        },
                                        scrollbar: {
                                            enabled: false
                                        },
                                        exporting: {
                                            enabled: false
                                        },
                                        credits: {
                                            enabled: false
                                        },
                                        legend : {
                                            itemMarginBottom: 5,
                                            align : 'center',
                                            verticalAlign : 'bottom',
                                            itemStyle : {
                                                color : '#333',
                                                fontWeight: 400
                                            },
                                            reversed: true,
                                            borderWidth : 0
                                        }
                                    };
                                /// SLA
                                if (data.sla_pass === false){
                                    $.extend(cfg.chart, {backgroundColor: '#FFD5C7'});
                                }
                                else {
                                    $.extend(cfg.chart, {backgroundColor: '#ffffff'})
                                }

                                // EVENTS SERIES
                                if (data.events_series) {
                                    $.extend(cfg, {yAxis:[{
                                        startOnTick: false,
                                        title: {
                                            text: ''
                                        },
                                        allowDecimals: false,
                                        max: max_y,
                                        labels: {
                                            align: 'left',
                                            x: 8,
                                            y: -4,
                                            formatter: function() {
                                                return this.axis.defaultLabelFormatter.call(this) + ' ' + (data.yaxis_label || '');
                                            }
                                        }
                                        },{
                                            title: {
                                                text: ''
                                            },
                                            gridLineColor: '#ffffff',
                                            gridLineWidth: 0,
                                            labels: {
                                                enabled: false
                                            },
                                            height: 0,
                                            top: 0,
                                            max: 0
                                        }]
                                    });
                                    $.extend(cfg.chart, {height: 350})
                                }

                                var seriesData = data.series.concat([
                                                                    {
                                                                        type: 'flags',
                                                                        showInLegend: false,
                                                                        name: '',
                                                                        data: data.events_series.data,
                                                                        onSeries: data.series[0].id,
                                                                        shape: 'squarepin',
                                                                        zIndex: 20,
                                                                        enableMouseTracking: false,
                                                                        events: {
                                                                            mouseOver: function(event) {

                                                                            }
                                                                        },
                                                                        point: {
                                                                            events: {
                                                                                mouseOver: function(event) {
                                                                                    console.log(this)
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                ]);
                                /*
                                 * DATETIME XAXIS
                                 */
                                if (data.xaxis_type === 'datetime'){

                                    // extend config;
                                    $.extend(cfg, {
                                        xAxis: {
                                            type: 'datetime',
                                            tickInterval: data.tickInterval,
                                            tickWidth: 0,
                                            lineWidth: 0,
                                            labels: {
                                                enabled: false
                                                }
                                            },
                                        series: seriesData
                                        })

                                }
                                /*
                                 * NON DATETIME XAXIS
                                 */
                                else {
                                    $.extend(cfg, {
                                        xAxis: {
                                            lineWidth: 0,
                                            categories: data.xaxis,
                                            tickInterval: data.tickInterval,
                                            tickWidth: 0,
                                            showFirstLabel: true,
                                            showLastLabel: true,
                                            labels: {
                                                enabled: false
                                                }
                                        },
                                        series: seriesData
                                    });
                                }
                                var chart=new Highcharts.Chart(cfg);
                            }
                        )
                    });
					var kpi_radio_container = $('#kpi_radio_container__'+compId);
					kpi_radio_container.find('button').unbind();
					kpi_radio_container.find('button').click(
							function(event) {
								$(this).unbind();
								$("button").removeClass("active");
								$(this).addClass("active");
								$.when(kpi_list.html('<i class="krutilka fa fa-circle-o-notch fa-spin" aria-hidden="true"></i>')).then(loadKpiPlots(compId));
								event.preventDefault();
								event.stopPropagation();
					});
					var anchor = $(location.hash);
                    console.log(anchor);
                    if (anchor[0]) {
                        $(document.body).scrollTop(anchor.offset().top);
                    }
				}
            ).fail(function() {
                kpi_list.text("Failed to get kpi list for component");
            }).always(function() {
                kpi_list.find(".krutilka").hide();
            });
        }
    };

})();


