(function() {
	'use strict';
	var statusIcons = {
    		"completed": "quit_status-icon fa fa-check text-success",
    		"interrupted": "quit_status-icon fa fa-hand-paper-o text-danger",
    		"other": "quit_status-icon fa fa-question text-muted",
    		"autostop": "quit_status-icon fa fa-exclamation-circle text-danger",

    		'0': 'quit_status-icon fa fa-check text-success',

    		'1': 'quit_status-icon fa fa-hand-paper-o text-danger',
            '2': 'quit_status-icon fa fa-hand-paper-o text-danger',
            '3': 'quit_status-icon fa fa-hand-paper-o text-danger ',
            '4': 'quit_status-icon fa fa-hand-paper-o text-danger',
            '5': 'quit_status-icon fa fa-hand-paper-o text-danger',
            '6': 'quit_status-icon fa fa-hand-paper-o text-danger',
            '7': 'quit_status-icon fa fa-hand-paper-o text-danger',
            '8': 'quit_status-icon fa fa-hand-paper-o text-danger',
            '9': 'quit_status-icon fa fa-hand-paper-o text-danger',
            '11': 'quit_status-icon fa fa-hand-paper-o text-danger',
            '12': 'quit_status-icon fa fa-hand-paper-o text-danger',
            '13': 'quit_status-icon fa fa-hand-paper-o text-danger',
            '14': 'quit_status-icon fa fa-hand-paper-o text-danger',
            '15': 'quit_status-icon fa fa-hand-paper-o text-danger',

            '21': 'quit_status-icon fa fa-exclamation-circle text-danger',
            '22': 'quit_status-icon fa fa-exclamation-circle text-danger',
            '23': 'quit_status-icon fa fa-exclamation-circle text-danger',
            '24': 'quit_status-icon fa fa-exclamation-circle text-danger',
            '25': 'quit_status-icon fa fa-exclamation-circle text-danger',
            '26': 'quit_status-icon fa fa-exclamation-circle text-danger',
            '27': 'quit_status-icon fa fa-exclamation-circle text-danger',
            '28': 'quit_status-icon fa fa-exclamation-circle text-danger',
            '29': 'quit_status-icon fa fa-exclamation-circle text-danger',
            '30': 'quit_status-icon fa fa-exclamation-circle text-danger',
            '31': 'quit_status-icon fa fa-exclamation-circle text-danger',
            '32': 'quit_status-icon fa fa-exclamation-circle text-danger',

            '100': 'quit_status-icon fa fa-meh-o quit_status-icon'
        },

	offlineJobTemplate = _.template($('#offlineJobTemplate').text()),
	onlineJobTemplate = _.template($('#onlineJobTemplate').text()),
	queuedJobTemplate = _.template($('#queuedJobTemplate').text()),
	mobileJobTemplate = _.template($('#mobileJobTemplate').text());

    $(document).ready(function () {
        var $toggles = $('.toggleCustomStyle');
        $toggles.each(function(){
            $(this).css('width', '100%');
        });
        var $offs = $('.toggle-off');
        $offs.each(function(){
            $(this).css('background-color', '#ffffff');
        });
        var $handles = $('.toggle-handle');
        $handles.each(function(){
            $(this).css('border-color', '#ddd');
        });
    });

    function stream_update() {
        var mobile = $('#toggle-mobile').prop('checked');
        var user = $('#toggle-user').prop('checked');
        if (!mobile) {
            var stream_url = "/api/job/online.json?limit=50";
            if (user) {
                stream_url += "&user=" + $('#global-login').data('login');
            }
            $.get(stream_url, function (idsData) {

                var ids = [];
                for (var i = 0; i < idsData.length; i++) {
                    ids.push(idsData[i]['n'])
                }
                var present = [];
                var present_online = $(".mainpage-jobs__panel-online").children(".active");
                var present_queued = $(".mainpage-jobs__panel-queued").children(".active");

                present_online.each(function () {
                    var job_n = Math.round($(this).attr("job"));
                    if ($.inArray(job_n, ids) < 0) {
                        console.info("Remove " + job_n);
                        move_to_offline(job_n);
                    } else {
                        present.push(job_n)
                    }
                });
                present_queued.each(function () {
                    var job_n = Math.round($(this).attr("job"));
                    if ($.inArray(job_n, ids) < 0) {
                        console.info("Remove " + job_n);
                        $('#stream_job_' + job_n).remove();	// queued job will probably go online or become obsolete
                    } else {
                        present.push(job_n)
                    }
                });

                var new_active = [];

                for (var n in ids) {
                    if ($.inArray(ids[n], present) < 0) {
                        console.info("New " + ids[n]);
                        new_active.push(ids[n]);
                    }
                }
                if (new_active.length > 0) {
                    console.log(new_active);
                    var template_data_url = "/mainpage/stream_jobs.json?ids=" + new_active.join();
                    $.ajax({
                        url: template_data_url,
                        type: 'GET',
                        dataType: 'json',
                        async: false,
                        success: function (data) {
                            for (var i in data) {
                                if (data.hasOwnProperty(i)) {
                                    var status = data[i]['status'];
                                    if (status === 'queued') {
                                        update_queued(data[i])
                                    }
                                    else {
                                        update_online(data[i])
                                    }
                                }
                            }
                        }
                    })
                }
                window.setTimeout(stream_update, 10000);
            })
        }
    }

    function init_offlines() {
        var mobile = $('#toggle-mobile').prop('checked');
        var user = $('#toggle-user').prop('checked');
        var url = "";
        if (mobile) {
    	    url = "/mobile/mobilejobsstream";
    	    $(".mainpage-jobs__panel-online").hide();
        }
        else {
            url = "/api/v2/jobs/?td__isnull=&limit=10&order_by=-n";
            $(".mainpage-jobs__panel-online").show();
        }
        if (user) {
            url += "&person="+$('#global-login').data('login');
        }

        $.getJSON(url)
          .done(function(jobs) {
            var offlineJobsPanel = $('.mainpage-jobs__panel-offline');
            offlineJobsPanel.html("");
            jobs = jobs.results;
            console.info('Populating offline stream');
            for (var n in jobs) {
                if (jobs.hasOwnProperty(n)) {
                    var job = jobs[n];
                    if (mobile) {
                        offlineJobsPanel.append(mobileJobTemplate({job: job}));
                    }
                    else {
                        offlineJobsPanel.append(offlineJobTemplate({job: job, statusIcons: statusIcons}));
                        preview(jobs[n]);
                    }
                }
             }
          })
          .fail(function() {
              console.error('Failed to get offline jobs');
          });
    }

    function move_to_offline(job_n) {
    	console.info("Moving to offline "+job_n);
        $('#stream_job_' + job_n).fadeOut(1000, function() {
	        $('#stream_job_' + job_n).remove();
        	$.get("/api/v2/jobs/"+job_n, function(job) {
	            $('.mainpage-jobs__panel-offline').prepend(offlineJobTemplate({job: job, statusIcons: statusIcons}));
	            $('#stream_offl_job_' + job_n).hide().fadeIn(500);
	            preview(job);
        	}, "json");
        });
    }

    function update_time_left(obj) {
    	var start=new Date(obj.attr("started")*1000);
    	var now=new Date();
    	var duration=Math.round((now.getTime()-start.getTime())/1000);
    	var est=obj.attr("estimated_duration");
    	var left=Math.round(est-duration);

    	if (left>0) {
			return 'Осталось: '+length_duration(left);
    	} else {
			return 'Прошло: '+length_duration(duration);
    	}
    }

    function short_host(host) {
    	host=host.replace(/.tanks.yandex.net$/i, "");
    	host=host.replace(/.yandex.net$/i, "");
    	host=host.replace(/.yandex.ru$/i, "");
    	return host;
    }

    function update_online(online) {
    	var res = onlineJobTemplate({job: online, statusIcons: statusIcons});
        var raw = res.replace(/(<([^>]+)>)/ig, "");

        var streamJob = $('#stream_job_' + online['n']);

        if (!streamJob.length) {
            $('.mainpage-jobs__panel-online')
                .prepend('<div class="active" style="display:none" id="stream_job_' + online['n'] + '"></div>');
            streamJob = $('#stream_job_' + online['n']);
            streamJob.html(res);
            streamJob.hide().fadeIn(300);
            //$('#stream_job_' + online['n']).attr('estimated_duration', online['estimated_duration']);
            streamJob.attr('started', online['fd']);
            bind_test_stop();
        } else {
        	// update if changed
	        if (streamJob.attr("raw") !== raw) {
	        	streamJob.html(res);
	        }
        }

        if (streamJob.attr("raw") !== raw) {
            streamJob.html(res);
            streamJob.attr("job", online['n']);
            streamJob.attr("raw", raw);
            bind_test_stop();
        }
    }

    function update_queued(queued) {
    	var res = queuedJobTemplate({job: queued});
        var raw = res.replace(/(<([^>]+)>)/ig, "");

        var streamJob = $('#stream_job_' + queued['n']);

        if (!streamJob.length) {
            $('.mainpage-jobs__panel-queued').prepend('<div class="active" style="display:none" id="stream_job_' + queued['n'] + '"></div>');
            streamJob = $('#stream_job_' + queued['n']);
            streamJob.html(res);
            streamJob.hide().fadeIn(300);
            bind_test_stop();
        } else {
        	// update if changed
	        if (streamJob.attr("raw") !== raw) {
	        	streamJob.html(res);
	        }
        }

        if (streamJob.attr("raw") !== raw) {
            streamJob.html(res);
            streamJob.attr("job", queued['n']);
            streamJob.attr("raw", raw);
            bind_test_stop();
        }
    }

	function bind_test_stop() {
        var stopButton = $(".stop_button");
		stopButton.unbind("click");
        stopButton.click(function(){
   			var job = this.id.split("__")[1];
        	if ( confirm('Остановить стрельбу '+job+"?")){
	        	$(this).attr("class", "fa fa-circle-o-notch fa-spin");
	        	$(this).unbind("click");
	   			$.get("/api/job/"+job+"/close.json");
   			}
        });
	}

	function length_duration(totalSec) {
		var hours = parseInt( totalSec / 3600 ) % 24;
		var minutes = parseInt( totalSec / 60 ) % 60;
		var seconds = totalSec % 60;

		return (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);
	 }

	function short_date(date1) {
		var res='';
		var m_names = ["Января", "Февраля", "Марта",
			"Апреля", "Мая", "Июня", "Июля", "Августа", "Сентября",
			"Октября", "Ноября", "Декабря"];

		res+=date1.getDate()+' '+m_names[date1.getMonth()].toLowerCase();
		var now=new Date();
		if (now.getFullYear()!=date1.getFullYear()) {
			res+=' '+date1.getFullYear();
		}
		res+=' в '+date1.getHours()+':'+(date1.getMinutes()<10?'0':'')+date1.getMinutes();
		return res;
	}

	function preview(job) {
        $.getJSON("/preview?job=" + job['n']).done(function(data){
				var cfg={
						chart: {
				            renderTo: $("div#job_"+job['n']+"_preview")[0],
				            height: 91,
				            width: 125,
				            borderRadius: 0,
				            margin: [1, 1, 1, 1],
				            animation: false,
				            style: {
				                fontFamily: 'Yandex Sans Text Web'
				            },
				        },
				        title: {
				   			text: "",
				        },
				        subtitle: {
				        	text: "",
				        },
				        navigator: {
				            enabled: false,
				        },
				        rangeSelector: {
				        	enabled: false,
				        },
				        scrollbar: {
				        	enabled: false,
				        },
				        exporting: {
				            enabled: false,
				        },
				        credits: {
				        	enabled: false,
				        },
				        tooltip: {
							enabled: false,
				        },
				        xAxis: {
				        	labels: {enabled: false},
				        	tickLength: 0,
				        	lineWidth: 0,
				        },
				        yAxis: [{
					        	labels: {enabled: false},
					        	tickAmount: 0,
					        	tickLength: 0,
					        	lineWidth: 0,
					        	min: 0,
					        	title: {
					        		text: ''
					        	},
					        	showFirstLabel: false,
					        	showLastLabel: false,
					        	endOnTick: false,
					        	startOnTick: false,
					        	gridLineWidth: 0,
				        	},
				        	{
					        	labels: {enabled: false},
					        	tickAmount: 0,
					        	tickLength: 0,
					        	lineWidth: 0,
					        	min: 0,
					        	title: {
					        		text: ''
					        	},
					        	showFirstLabel: false,
					        	showLastLabel: false,
					        	endOnTick: false,
					        	startOnTick: false,
					        	gridLineWidth: 0,
				        	}],
				        legend: {
				        	enabled: false
				        },
				        plotOptions: {
				        	series: {
				        		cropThreshold: 125,
				        		shadow: false,
				        		connectNulls: true,
				        		animation: false,
				        		marker: {enabled: false},
				        		states: {hover: {enabled: false}},
				        	},
				        },
				        series: data,
					};
		  		new Highcharts.Chart(cfg);
				}
        )
	}

	function ui_set__show_user_jobs(value) {
		if (!value) {
			value = ""
		}
		$.get('/ui_set/?param=show_user_jobs&value='+value)
	}

	function ui_set__show_mobile_jobs(value) {
		if (!value) {
			value = ""
		}
		$.get('/ui_set/?param=show_mobile_jobs&value='+value)
	}

	init_offlines();
    $('.stream_active').html("");
    stream_update();

    $('#toggle-mobile').change(function() {
        init_offlines();
        ui_set__show_mobile_jobs($(this).prop('checked'));
    });

    $('#toggle-user').change(function() {
        init_offlines();
        ui_set__show_user_jobs($(this).prop('checked'));
        stream_update();
    });

})();
