(function()
{

	/*
	 * Стрельбы
	 */
	
	// Чекбоксы и массовые операции
	
	var chosen = [],
	starred = [],
	inCompare = [];
	
	
	$('#massActionsClose').on('click', function() {
		$('#massActions').collapse('hide');
	});
	
	
	function moveScroller() {
	    var $anchor = $("#scroller-anchor");
	    var $scroller = $('#massActions');

	    var move = function() {
	        var st = $(window).scrollTop();
	        var ot = $anchor.offset().top;
	        if(st > ot) {
	            $scroller.css({
	                position: "fixed",
	                paddingTop: "15px",
	                top: "0px",
	                borderRight: "1px solid #ddd",
	                borderBottom: "1px solid #ddd"
	            });
	        } else {
	            if(st <= ot) {
	                $scroller.css({
	                    position: "relative",
	                    top: "",
	                    paddingTop: "0px",
	                    borderRight: "none",
	                    borderBottom: "none"
	                });
	            }
	        }
	    };
	    $(window).scroll(move);
	    move();
    }
    if ($("#scroller-anchor")[0]) {
		moveScroller();
    }


    function bindCheckboxes() {
        var $checkboxes = $(".checkbox");
        $checkboxes.unbind('change');
        $checkboxes.change(function () {
            if (this.checked) {
                if ($(this).data('star') === 1) {
                    starred.push($(this).data('job'));
                    $('.massActionButton[data-action="unstar"]').show()
                } else {
                    $('.massActionButton[data-action="star"]').show()
                }

                if ($(this).data('compare') === 1) {
                    inCompare.push($(this).data('job'));
                    $('.massActionButton[data-action="uncompare"]').show()
                } else {
                    $('.massActionButton[data-action="compare"]').show()
                }

                if (!$('#massActions').hasClass('in')) {
                    $('#massActions').collapse('show')
                }
                chosen.push($(this).data('job'));
                $('#massActionsJobCount').text(chosen.length)
            } else {
                var chosenIndex = chosen.indexOf($(this).data('job'));
                chosen.splice(chosenIndex, 1);

                if ($(this).data('star') === 1) {
                    var starIndex = starred.indexOf($(this).data('job'));
                    starred.splice(starIndex, 1)
                }

                if ($(this).data('compare') === 1) {
                    var compareIndex = inCompare.indexOf($(this).data('job'));
                    inCompare.splice(compareIndex, 1)
                }

                // скрываем кнопку "Убрать из избранного"
                if (starred.length === 0) {
                    $('.massActionButton[data-action="unstar"]').hide()
                }
                // скрываем кнопку "Убрать из избранного"
                if (starred.length === chosen.length) {
                    $('.massActionButton[data-action="star"]').hide()
                }
                // скрываем кнопку "Убрать из сравнения"
                if (inCompare.length === 0) {
                    $('.massActionButton[data-action="uncompare"]').hide()
                }
                // скрываем кнопку "Добавить в сравнение"
                if (inCompare.length === chosen.length) {
                    $('.massActionButton[data-action="compare"]').hide()
                }
                // Меняем количество выбранных стрельб и скрываем блок групповых операцй если 0
                $('#massActionsJobCount').text(chosen.length);
                if (chosen.length === 0) {
                    $('#massActions').collapse('hide')
                }
            }
        });
    }
	
	$('#massActionsTable').find('.massActionButton').bind('click', function() {
		var action = $(this).data('action');
		console.log(action);
		switch (action) {
			case 'compare':
				var toCompare = [];
				for (var i=0;i<chosen.length;i++) {
					if (inCompare.indexOf(chosen[i]) === -1 ) {
						toCompare.push(chosen[i])
					}
				}
				
				/*$('#compareModalJobList').text(toCompare.join(', '))
				
				$('#compareModal').modal('show')
				
				$('#compareModalSubmit').on('click', function() {*/
					$.post('/mass_compare.json', {
						"action" : 'add',
						"fire_ids[]" : toCompare
					}).success(function(data) {
						if (data.status === 1) {
							//$('#compareModal').modal('hide')
							window.location.reload(); // TODO: do it within this page
						}
					});
				//})
				break;
			case 'uncompare':
				
				/*$('#uncompareModalJobList').text(inCompare.join(', '))
				$('#uncompareModal').modal('show')
				
				$('#uncompareModalSubmit').on('click', function() {*/
					$.post('/mass_compare.json', {
						"action" : 'remove',
						"fire_ids[]" : inCompare
					}).success(function(data) {
						if (data.status === 1) {
							//$('#uncompareModal').modal('hide')
							window.location.reload(); // TODO: do it within this page
						}
					});
				//})
				break;
			case 'star':
				var toStar = [];
				for (var i=0;i<chosen.length;i++) {
					if (starred.indexOf(chosen[i]) === -1 ) {
						toStar.push(chosen[i])
					}
				}
				
				/*$('#starModalJobList').text(toStar.join(', '))
				
				$('#starModal').modal('show')
				
				$('#starModalSubmit').on('click', function() {*/
					$.post('/mass_fav.json', {
						"action" : 'add',
						"fire_ids[]" : toStar
					}).success(function(data) {
						if (data.status === 1) {
							//$('#starModal').modal('hide')
							window.location.reload(); // TODO: do it within this page
						}
					});
				//})
				break;
			case 'unstar':
				/*$('#unstarModalJobList').text(starred.join(', '))

				$('#unstarModal').modal('show')

				$('#unstarModalSubmit').on('click', function() {*/
					$.post('/mass_fav.json', {
						"action" : 'remove',
						"fire_ids[]" : starred
					}).success(function(data) {
						if (data.status === 1) {
							//$('#unstarModal').modal('hide')
							window.location.reload(); // TODO: do it within this page
						}
					});
				//})
				break;
			case 'move':
				$('#moveModalJobList').text(chosen.join(', '));
				$('#moveModal').modal('show');
				
				$('#task_input').on('propertychange input', function (e) {
					$('#moveModalTaskInput').removeClass('has-error');
				});
				
				$('#moveModalSubmit').on('click', function(event) {
					$.post('/mass_move.json', {
						"task" : $('#task_input').val(),
						"fire_ids[]" : chosen,
					}).success(function(data) {
						console.log(data);
						if (data.status === 1) {
							$('#moveModal').modal('hide');
							for (var i=0;i<chosen.length;i++) {
								$('#job_row__' + chosen[i]).remove()
							}
							chosen = []
						}
					});
				});
				break;
			case 'remove':
				$('#removeModalJobList').text(chosen.join(', '));
				$('#removeModal').modal('show');
				
				$('#removeModalSubmit').on('click', function() {
					$.post('/mass_delete.json', {
						"fire_ids[]" : chosen
					}).success(function(data) {
						if (data.status === 1) {
							$('#removeModal').modal('hide');
							$('#massActionsJobCount').text('0');
							$('#massActions').collapse('hide');
							for (var i=0;i<chosen.length;i++) {
								$('#job_row__' + chosen[i]).remove()
							}
							chosen = []
						}
					});
				});
				break;
		}
	});
	
	// ====== MORE JOBS ======


    $(window).scroll(function() {
       if($(window).scrollTop() + window.innerHeight > ($(document).height()-1) && !$('a#mobile_tab_tab').parent().hasClass('active')) {
           showMoreJobs();
       }
    });

    var fireTemplate = _.template($('#fireTemplate').text());

    function showMoreJobs() {
        var task = $('#globalTask').data('task'),
            before = $('.job_row').get(-1).dataset['job'];
        var url = '/'+ task + '/more_jobs.json?limit=30&before=' + before;
        $.get(url, function(jobs) {
        	if (!jobs.length) {
        		console.info('No more jobs');
        	}
            for (var n in jobs) {
                $('#fire_tab').append(fireTemplate({
                	fire: jobs[n],
                    task: task,
                	}));
            }
            bindMouseovers();
        	bindActions();
        	bindCheckboxes();
            // Рендерим превьюшки
            $('.job_preview').each(function() {
                if ( parseInt($(this).data('job')) < parseInt(before) ) {
                    previewJob($(this).data('job'), $(this).data('star'))
                }
            });
        }, "json");
    }

    bindMouseovers();
    bindActions();
    bindCheckboxes();

    // Рендерим превьюшки
	$('.job_preview').each(function() {
		previewJob($(this).data('job'), $(this).data('star'))
	});

    function bindMouseovers() {

        var $job_row = $('.job_row');

        $job_row.unbind();

        $job_row.bind('mouseenter', function(event){
            var job_id = $(this).attr('id').split('__')[1];
            $('#b_rightblock_frespace__' + job_id).show()
        });

        $job_row.bind('mouseleave', function(event){
            var job_id = $(this).attr('id').split('__')[1];
            $('#b_rightblock_frespace__' + job_id).hide()
        });
    }


	function bindActions() {
        var $actions = $('.job_row__action');
        $actions.off();
        $actions.on('click', function (event) {
            var button = $(this);
            var action = button.data('action');
            var job = button.data("job");

            switch (action) {
                case 'remove':
                    if (!confirm("Таки удалить эту стрельбу или нет?")) {
                        return false;
                    }
                    $.post('/mass_delete.json', {
                        "fire_ids[]": job
                    }).success(function (data) {
                        if (data.status === 1) {
                            $('#job_row__' + job).remove()
                        }
                    });
                    break;
                case 'compare':
                    action = button.data('actiondetail');
                    $.post('/mass_compare.json', {
                        "action": action,
                        "fire_ids[]": 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) {
                            if (data.status === 1) {
                                $(".b_compare_count").html(data.count);
                                if (data.count > 0) {
                                    $(".b_compare_count__delete").show();
                                } else {
                                    $(".b_compare_count__delete").hide();
                                }
                            }
                        }

                    });
                    break;
                case 'repeat':
                    var url = "/" + button.data("job") + "/repeat";
                    var win = window.open(url, '_blank');
                    win.focus();
                    break;
                case 'star':
                    // the star
                    var isFav = button.hasClass('star-yellow');
                    $.post('/' + button.data('task') + '/addtofav.json', {
                        action: isFav ? 'remove' : 'add',
                        job_id: job
                    }).success(function () {
                        if ($('#b_firebyid__img__pos1__' + job).html() === '') {
                            $('#b_firebyid__img__pos1__' + job).append('<i class="fa fa-star star-yellow"></i>')
                        }
                        else {
                            $('#b_firebyid__img__pos1__' + job).html('')
                        }
                        button.toggleClass('star-yellow');
                        button.toggleClass('text-muted');
                    });
                    break;
                default:
                    break;
            }
        });
    }

    function previewJob(job, star) {
    	$.getJSON("/preview?job="+job).done(function(data){
			var cfg={
					chart: {
			            renderTo: $("div#job_"+job+"_preview")[0],
			            height: 36,
			            width: 50,
			            borderRadius: 0,
			            margin: [1, 1, 1, 1],
			        },
			        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: {
			        		shadow: false,
			        		connectNulls: true,	
			        		animation: false,
			        		marker: {enabled: false},
			        		states: {hover: {enabled: false}},
			        	},
			        },
			        series: data,
				};
			if (star) {
				cfg.chart.height = 91;
				cfg.chart.width = 125
			}
	  		var chart=new Highcharts.Chart(cfg);    
			}
      )
    }
    
    
	/*
	 *  Mobile
	 */
	
	function renderMobile() {
		if ($("#mobile_tab") && $("#mobile_tab").html().trim() === '') {
			$("#mobile_tab").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_mobile_block', function() {
	    				  console.log('Mobiles loaded')
	    			  }
				)
			}
    }

    /*
     *  Info
     */

    function renderInfo() {
		if ($("#info_tab") && $("#info_tab").html().trim() === '') {
			$("#info_tab").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_task_info', function() {
	    				  console.log('Info loaded')
	    			  }
				)
			}
    }

	/*
	 *  Openstack
	 */
		
	function renderOpenstack(force) {
		if ($("#openstack_tab").html().trim() === '' || force) {
			$("#openstack_tab").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_openstack_block', 
					function(){
						engageManipulators();
						$("#openstack_create_button").click(
				    		 function() {
				    			$("#openstack_block_block_create").toggle();
				    			if ($('#openstack_block_block_create').is(':visible') && $("#openstack_block_block_create").html().trim() == '') {
				    				$("#openstack_block_block_create").html(
					    					 '<i class="krutilka fa fa-circle-o-notch fa-spin" aria-hidden="true"></i>'
					    					 ).load(location.protocol+'//'+location.host+location.pathname + '/render_create', function() {
					    						 engageCreateButton()
					    					 });
				    			}
				    		 }
					     );
						$("#openstack_allservers_button").click(
				    		 function() {
				    			 $("#openstack_block_block_select").toggle();
				    			 if ($('#openstack_block_block_select').is(':visible') && $('#openstack_block_block_select').html().trim() == '') {
					    			 $("#openstack_block_block_select").html(
					    					 '<i class="krutilka fa fa-circle-o-notch fa-spin" aria-hidden="true"></i>'
					    					 ).load(location.protocol+'//'+location.host+location.pathname + '/render_allservers', function(){
					    						 engageManipulators()
					    					 });
				    			 }
				    		 }
						)
					}
				)
			}
      	}
      
    function engageCreateButton() {
    	$("input#openstack_create_submit").click(
    		function() {
    			$(this).parent().append('<span style="padding-left: 0.4em;"><i class="c_krutilka fa fa-circle-o-notch fa-spin" aria-hidden="true"></i><span>');
    			$(this).prop('disabled', true);
    			$("input#vhost_name").css('background-color', '#FAFAFA');
    			$("select#vhost_flavor").css('background-color', '#FAFAFA');
    			$("select#vhost_image").css('background-color', '#FAFAFA');
    	    	$.ajax({
    	    		type: 'POST',
    				url : location.protocol+'//'+location.host+location.pathname + '/create_server',
    				data: {
 					   'vhost_image': $("select#vhost_image option:selected").val(), 
					   'vhost_name': $("input#vhost_name").val(), 
					   'vhost_flavor': $("select#vhost_flavor option:selected").val()
					   },
    				dataType : 'json'
    			}).success(function(data) {
    				if (data[0]['success']) {
    					renderOpenstack(true)
    				}
    				else {
    					$("img.c_krutilka").hide();
    	    			$("input#openstack_create_submit").prop('disabled', false);
    					$("span#error_text").html(data[0]['error_text']);
    					switch (data[0]['error']) {
    						case 'capacity':
    							$("#openstack_block_block_create").html(
    									'<div style="font-size:20pt; color: #7BA32D;"> \
    								    В облаке кончились ресурсы</div> \
    								    <div style="font-size:16pt; padding-top:7px;">ЛоЛ</div>'
    			    					 );
    							break;
    						case 'name':
    							$("input#vhost_name").css('background-color', '#FFD5C7');
    							break;
    						case 'flavor':
    							$("select#vhost_flavor").css('background-color', '#FFD5C7');
    							break;
    						case 'image':
    							$("select#vhost_image").css('background-color', '#FFD5C7');
    							break;
    					}
    				}
    			});
    		});
    }
      
    function engageManipulators() {
    	console.log('engaging manipulators');
    	$('button.server_manipulator').click(
				function(event) {
					var serverid = $(this).data()['serverid'];
					var action = $(this).data()['action'];
					if (action === 'rebuild') {
						if (confirm('Переналить машинку из исходного образа?')) {
							$(this).parent().append('<span style="padding-left: 0.4em;"><i class="krutilka fa fa-circle-o-notch fa-spin" aria-hidden="true"></i><span>');
							

			 				event.stopPropagation();
							event.preventDefault();
						}
						else {
							event.stopPropagation();
							event.preventDefault();
						}
					}
					else {
						$(this).parent().append('<span style="padding-left: 0.4em;"><i class="krutilka fa fa-circle-o-notch fa-spin" aria-hidden="true"></i><span>');
						$.ajax({
		 					url : location.protocol+'//'+location.host+location.pathname + '/manipulate_server?action='+action+'&id='+serverid,
		 					type : 'GET',
		 					dataType : 'json'
		 				}).success(function(data) {
		 					if (data['success']) {
		 						renderOpenstack(true)
		 					}
		 					else {
		 						alert(data['error']) 
		 					}
		 				});
		 				event.stopPropagation();
						event.preventDefault();
					}
					event.stopPropagation();
					event.preventDefault();
				}
    		);
		$('button.snapshot_manipulator').click(
				function(event) {
					var snapshotid = $(this).data()['snapshotid'];
					var action = $(this).data()['action'];
					if (action === 'delete') {
						if (confirm('Точно удалить?')) {
							$(this).parent().append('<span style="padding-left: 0.4em;"><i class="krutilka fa fa-circle-o-notch fa-spin" aria-hidden="true"></i><span>');
							$.ajax({
			 					url : location.protocol+'//'+location.host+location.pathname + '/manipulate_snapshot?action='+action+'&id='+snapshotid,
			 					type : 'GET',
			 					dataType : 'json'
			 				}).success(function() {
			 					renderOpenstack(true)
			 				});
			 				event.stopPropagation();
							event.preventDefault();
						} else {
							event.stopPropagation();
							event.preventDefault();
						}
					}
					else {
						$(this).parent().append('<span style="padding-left: 0.4em;"><i class="krutilka fa fa-circle-o-notch fa-spin" aria-hidden="true"></i><span>');
						$.ajax({
		 					url : location.protocol+'//'+location.host+location.pathname + '/manipulate_snapshot?action='+action+'&id='+snapshotid,
		 					type : 'GET',
		 					dataType : 'json'
		 				}).success(function() {
		 					renderOpenstack(true)
		 				});
		 				event.stopPropagation();
						event.preventDefault();
					}
					event.stopPropagation();
					event.preventDefault();
				}
			)
    }
		
	$('#mobile_tab_tab').on('shown.bs.tab', function(event) {
		console.log('mobile');
		renderMobile();
		event.preventDefault();
	});
	
	$('#openstack_tab_tab').on('shown.bs.tab', function(event) {
		console.log('openstack');
		renderOpenstack(false);
		event.preventDefault();
	});

	$('#info_tab_tab').on('shown.bs.tab', function(event) {
		console.log('info');
		renderInfo(false);
		event.preventDefault();
	});

	$( document ).ready(function() {
		if (location.hash === '#openstack') {
			$('#openstack_tab_tab').tab('show');
		} else if (location.hash === '#mobile') {
			$('#mobile_tab_tab').tab('show');
		}
	});
})();
