(function() {
	
	'use strict';
	var statusIcons = {
    		"completed": "fa fa-check text-success quit_status-icon",
    		"interrupted": "fa fa-hand-paper-o text-danger quit_status-icon",
    		"other": "fa fa-question text-muted quit_status-icon",
    		"autostop": "fa fa-exclamation-circle text-danger quit_status-icon",
        },
	offlineJobTemplate = _.template($('#offlineJobTemplate').text()),
	onlineJobTemplate = _.template($('#onlineJobTemplate').text()),
	jobCommentsTemplate = _.template($('#jobCommentsTemplate').text());
	
	if ($("#mainpage-for_user").data('user')) {
		$(".mainpage-jobs__switch").hide();
	}
	
    function stream_update() {
    	var for_user = $("#mainpage-for_user").data('user') || $(".mainpage-jobs__switch.visible").data('user');
    	console.log(for_user);
    	var url="/api/job/online.json?limit=100";
    	if (for_user) {
    		url+="&user="+for_user;
    	}
        $.getJSON(url, function(onlines) {
            var active = [];
            for (var n in onlines) {
                update_online(onlines[n]);
                active.push(onlines[n]['job_number']);
            }
            var all_active = $(".mainpage-jobs__panel-online").children(".active");
            all_active.each(function() {
            	var job=Math.round($(this).attr("job"));
                if (jQuery.inArray(job, active) < 0) {
                    console.info("Remove " + job);
                    move_to_offline(job);
                } else {
                	var obj=$("#duration_info_"+job);
                	obj.html(update_time_left($(this)));
                }
            });
        });

        window.setTimeout(stream_update, 10000);
    }

    function init_offlines() {
    	var for_user = $("#mainpage-for_user").data('user') || $(".mainpage-jobs__switch.visible").data('user');
    	console.log(for_user);
    	var url="/api/job/offline.json?limit=10";
    	if (for_user) {
    		url+="&user="+for_user;
    	}
    	
        $.get(url, function(jobs) {
        	console.info('Populating offline stream');
            $('.mainpage-jobs__panel-offline').html("");
            for (var n in jobs) {
                var owner = (jobs[n].person == $('#request_user_login').text());
                $('.mainpage-jobs__panel-offline').append(offlineJobTemplate({
                	job: jobs[n], 
                	statusIcons: statusIcons, 
                	owner: owner, 
                	}));
                /*console.log(job.comments)
                if (job.comments_count) {
                	$('#jobComments__'+job.job_number).html("")
                }
                for (var i; i < job.comments.length; i++) {
                	console.log(job.comments[i])
                	var comment = job.comments[i]
                	$('#jobComments__'+job.job_number).append(jobCommentsTemplate({owner: 0, comment: comment}))
                }*/
                bindEditables(jobs[n].job_number);
                preview(jobs[n]);
            }
            bindActions();
        }, "json");
    }

    function move_to_offline(job) {
    	console.info("Moving to offline "+job);
        $('#stream_job_' + job).fadeOut(1000, function() {
	        $('#stream_job_' + job).remove();	
        	$.getJSON("/api/job/offline.json?job="+job, function(jobs) {
        		var owner = (jobs[0].person == $('#request_user_login').text());
	            $('.mainpage-jobs__panel-offline').prepend(offlineJobTemplate({
	            	job: jobs[0], 
                	statusIcons: statusIcons, 
                	owner: owner, 
                	}));
	            $('#stream_offl_job_' + job).hide().fadeIn(500);
	            preview(jobs[0]);
	            bindEditables(jobs[0].job_number);
	            bindActions();
        	});
        });
    }

    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 'Left: '+length_duration(left);
    	} else {
			return 'Elapsed: '+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 owner = (online['person'] == $('#request_user_login').text());
    	var res = onlineJobTemplate({job: online, statusIcons: statusIcons, owner: owner});
        preview(online);
        var raw = res.replace(/(<([^>]+)>)/ig, "");
        if (!$('#stream_job_' + online['job_number']).length) {
            $('.mainpage-jobs__panel-online').prepend('<div class="active" style="display:none" id="stream_job_' + online['job_number'] + '"></div>');
            $('#stream_job_' + online['job_number']).html(res);
            $('#stream_job_' + online['job_number']).hide().fadeIn(500);
            $('#stream_job_' + online['job_number']).attr('estimated_duration', online['estimated_duration']);
            $('#stream_job_' + online['job_number']).attr('started', online['started']);
            bindEditables(online['job_number']);
            bindActions();
            bindTestStop();
        } else {
        	// update if changed
	        if ($('#stream_job_' + online['job_number']).attr("raw") !== raw) {
	        	$('#stream_job_' + online['job_number']).html(res);
	            bindEditables(online['job_number']);
	        }
        }

        if ($('#stream_job_' + online['job_number']).attr("raw") !== raw) {
            $('#stream_job_' + online['job_number']).html(res);
            $('#stream_job_' + online['job_number']).attr("job", online['job_number']);
            $('#stream_job_' + online['job_number']).attr("raw", raw);
            bindTestStop();
            bindActions();
            bindEditables(online['job_number']);
        }
    }

	function bindTestStop() {
		var stop_button = $(".stop_button");
		stop_button.unbind("click");
        stop_button.click(function(){
   			var job = this.id.split("__")[1];
        	if ( confirm('Остановить стрельбу '+job+"?")){
	        	$(this).attr("src", "/media/img/ajax.gif");
	        	$(this).unbind("click");
	   			$.get("/api/jobclose_frontend?job_n="+job);
   			}
        });
	}

	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['job_number']).done(function(data){
				var cfg={
						chart: {
				            renderTo: $("div#job_"+job['job_number']+"_preview")[0],
				            height: 91,
				            width: 125,
				            borderRadius: 0,
				            margin: [1, 1, 1, 1],
				            animation: false,
				        },
				        credits: {
				        	enabled: false,
				        },
				        title: {
				   			text: "",
				        },
				        subtitle: {
				        	text: "",
				        },
				        navigator: {
				            enabled: false,
				        },
				        rangeSelector: {
				        	enabled: false,
				        },
				        scrollbar: {
				        	enabled: false,
				        },
				        tooltip: {
							enabled: false,						        	
				        },
				        exporting: {
				            enabled: false,
				        },
				        xAxis: {
				        	labels: {enabled: false},
				        	tickLength: 0,
				        	lineWidth: 0,
				        },
				        yAxis: [{
					        	labels: {enabled: false},
					        	tickAmount: 0,
					        	tickLength: 0,
					        	lineWidth: 0,
					        	min: 0,
					        	title: {
					        		text: ''
					        	},
					        	stackind: 'normal',
					        	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: {
				        		enableMouseTracking: false,
				        		cropThreshold: 125,
				        		shadow: false,
				        		connectNulls: true,	
				        		animation: false,
				        		marker: {enabled: false},
				        		states: {hover: {enabled: false}},
				        	},
				        },
				        series: data,
					};
		  		var chart=new Highcharts.StockChart(cfg);    
				}
          )
	}
	
	function ui_set__show_user_jobs(value) {
		if (!value) {
			value = ""
		}
		$.get('/ui_set/?param=show_user_jobs&value='+value)
	}
	

	init_offlines();
    $('.mainpage-jobs__panel-online').html("");
    stream_update();


    function showMore() {
    	var url="/api/job/offline.json?limit=10&before="+$('div.mainpage-jobs__panel-offline div.offline:last-child').data('job');
    	var for_user = $("#mainpage-for_user").data('user') || $(".mainpage-jobs__switch.visible").data('user');
    	if (for_user) {
    		url+="&user="+for_user;
    	}
        $.get(url, function(jobs) {
        	if (!jobs.length) {
        		console.info('No more jobs');
        	}
        	else {
        		console.info('Populating offline stream');
        	}
            for (var n in jobs) {
                var owner = (jobs[n].person == $('#request_user_login').text());
                $('.mainpage-jobs__panel-offline').append(offlineJobTemplate({
                	job: jobs[n], 
                	statusIcons: statusIcons, 
                	owner: owner, 
                	}));
                bindEditables(jobs[n].job_number);
                preview(jobs[n]);
            }
            bindActions();
        }, "json");
    }


    $(window).scroll(function() {
       if($(window).scrollTop() + $(window).height() > ($(document).height()-1)) {
           showMore();
       }
    });
    
    
    $(".mainpage-jobs__switch").click(function(){
    	$(".mainpage-jobs__switch:hidden").addClass('visible');
    	$(".mainpage-jobs__switch:hidden").show();
    	$(this).hide();
    	$(this).removeClass('visible');
        $('.mainpage-jobs__panel-online').html("");
        init_offlines();
        stream_update();
        ui_set__show_user_jobs(!$(this).data('user'));
    });
    
    
	$('.b-editable').bind('mouseenter', function() {
		$('span#'+this.id+'_pencil').show();
	});
	$('.b-editable').bind('mouseleave', function() {
		$('span#'+this.id+'_pencil').hide();
	});
	
	function bindActions() {
		$('.stream__action').unbind();
		$('.stream__action').on('click', function (event) {
			var button = $(this);
			var action = button.data('action');
			var job = button.data('job');
			

			switch (action) {
				case 'remove':
					if (!confirm("Seriously? Delete test # "+job+"?")) {
						return false;
					}
					$.post('/deletejob.json', {
						"job_id" : job
					}).success(function(data) {
						if (data.status == "1") {
							$.when($('#stream_offl_job_'+job).animate({ opacity: 0 }, 1000).promise()
							).done(function(){
								$('#stream_offl_job_'+job).remove()
							});
						}
					});
					break;
				case 'compare':
					var action = button.data('actiondetail');
					var url;
					if (action == 'add') {
						url = '/compare/add_jobs'
					}
					else {
						url = '/compare/remove_jobs'
					}
					$.post(url, {
						"jobs" : job,
					}).success(function(data) {
						if (action == 'add') {
							button.data('actiondetail', 'remove')
						}
						else {
							button.data('actiondetail', 'add')
						}
						button.toggleClass('text-muted');
						button.toggleClass('text-success');
						if (data && data.success == "1") {
                            $(".b_compare_count").html(data.count);
                            if (data.count > 0) {
                                $(".b_compare_count__delete").show();
                            } else {
                                $(".b_compare_count__delete").hide();
                            }
						}

					});
					break;
				case 'edit':
					window.location.href = job + "/edit";
					break;
				case 'star':
					$.ajax('/addtofav.json', {
						type : 'POST',
						data: {
							job_id : job,
						},
						success: function() {
							button.toggleClass('stream__action_active');
							button.toggleClass('text-muted');
						},
					});
					break;
				default:
					break;
			}
		});
	}
	
	
	function bindEditables(job_number) {
		/*
		 * При клике на редактирование имени стрельбы
		 */
		
		$('.b-overload-offline-meta__title.b-editable').on('mouseenter', function(event) {
			var job_n = $(this).data('job');
			$('span#name_pencil__'+job_n).show()
		});
		
		$('.b-overload-offline-meta__title.b-editable').on('mouseleave', function(event) {
			var job_n = $(this).data('job');
			$('span#name_pencil__'+job_n).hide()
		});
		
		$('.b-overload-offline-meta__title.b-editable').on('click', function(event) {
			var job_n = $(this).data('job');
			$(this).hide();
			$('#b_editname_block__'+job_n).show();
			$("#b_editname_block__firename__"+job_n).val($('.b-editable[data-action="edit-name"].b-editable[data-job="'+job_n+'"]').text());
			$("#b_editname_block__firename__"+job_n).focus();

			$("#b_editname_block__okey__"+job_n).show();
			$("#b_editname_block__cancel__"+job_n).show();
			$("#b_editname_block__ajax__"+job_n).hide();
		});
		/*
		 * Завершение редактирования имени
		 */
		$('#b_editname_block__cancel__'+job_number).on('click', function(event) {
			var job_n = $(this).data('job');
			$('#b_editname_block__'+job_n).hide();
			$('.b-editable[data-action="edit-name"].b-editable[data-job="'+job_n+'"]').show();
		});
		/*
		 * Результат редактирования стрельбы
		 */
		$('#b_editname_block__okey__'+job_number).on('click', function(event) {
			var job_n = $(this).data('job');
			var text = $("#b_editname_block__firename__"+job_n).val();
			var block = this;

			$("#b_editname_block__okey__"+job_n).hide();
			$("#b_editname_block__cancel__"+job_n).hide();
			$("#b_editname_block__ajax__"+job_n).show();

			$.ajax("/api/jobedit_frontend?job_n="+job_n, {
				type : 'POST',
				dataType : 'json',
				data : {
					'name' : text
				},
				success : function(data) {
					if (data) {
						if (data.success == 1) {
							$('.b-editable[data-action="edit-name"].b-editable[data-job="'+job_n+'"]').text(text);
							$('#b_editname_block__'+job_n).hide();
							$('.b-editable[data-action="edit-name"].b-editable[data-job="'+job_n+'"]').show();
						} else {
							reterror(data.error);
						}
					} else {
						reterror('error');
					}

				},
				error : function() {
					reterror('error');
				}
			});
			var reterror = function(typeoferror) {
				$("#b_editname_block__okey__"+job_n).show();
				$("#b_editname_block__cancel__"+job_n).show();
				$("#b_editname_block__ajax__"+job_n).hide();
			};
		});

		/*
		 * Редактирование описания
		 */
		
		$('.b-overload-offline-meta__description.b-editable').on('mouseenter', function(event) {
			var job_n = $(this).data('job');
			$('span#dsc_pencil__'+job_n).show()
		});
		
		$('.b-overload-offline-meta__description.b-editable').on('mouseleave', function(event) {
			var job_n = $(this).data('job');
			$('span#dsc_pencil__'+job_n).hide()
		});
		
		$('.b-overload-offline-meta__description.b-editable').on('click', function(event) {
			var job_n = $(this).data('job');
			$(this).hide();
			$('#b_editcomment_block__'+job_n).show();
			$("#b_editcomment_block__firecomment__"+job_n).val($('.b-editable[data-action="edit-dsc"].b-editable[data-job="'+job_n+'"]').text());
			$("#b_editcomment_block__firecomment__"+job_n).focus();

			$("#b_editcomment_block__okey__"+job_n).show();
			$("#b_editcomment_block__cancel__"+job_n).show();
			$("#b_editcomment_block__ajax__"+job_n).hide();
		});

		$('#b_editcomment_block__cancel__'+job_number).on('click', function(event) {
			var job_n = $(this).data('job');
			$('#b_editcomment_block__'+job_n).hide();
			$('.b-editable[data-action="edit-dsc"].b-editable[data-job="'+job_n+'"]').show();
		});

		$('#b_editcomment_block__okey__'+job_number).on('click', function(event) {
			var job_n = $(this).data('job');
			var text = $("#b_editcomment_block__firecomment__"+job_n).val();
			var block = this;

			$("#b_editcomment_block__okey__").hide();
			$("#b_editcomment_block__cancel__").hide();
			$("#b_editcomment_block__ajax__").show();
			$.ajax("/api/jobedit_frontend?job_n="+job_n, {
				type : 'POST',
				dataType : 'json',
				data : {
					'description' : text
				},
				success : function(data) {
					if (data) {
						if (data.success == 1) {
							$('.b-editable[data-action="edit-dsc"].b-editable[data-job="'+job_n+'"]').text(text);
							$('#b_editcomment_block__'+job_n).hide();
							$('.b-editable[data-action="edit-dsc"].b-editable[data-job="'+job_n+'"]').show();
						} else {
							reterror(data.error);
						}
					} else {
						console.log('error')
					}
				},
				error : function() {
					console.log('error')
				}
			});
			var reterror = function(typeoferror) {
				$("#b_editcomment_block__okey__").show();
				$("#b_editcomment_block__cancel__").show();
				$("#b_editcomment_block__ajax__").hide();
			};
		});
	}
	
	bindActions();

})();
