{% extends "layout.html" %}

{% block title %}manage instances{% endblock %}

{% load bootstrap3 %}
{% block content %}
<div class="container-fluid">
    <div class="row">

  	<div class="col-md-1"></div>

  	<div class="col-md-10" id="instances_list">
  	{% include "instances/list.html" %}

	<div class="col-md-1"></div>

	</div>
</div>

{% endblock %}


{% block bottomjs %}
<script type="text/javascript"> <!--
	jQuery( document ).ready(function( $ ) {
		// TODO: Try this?
	   	//$('#instancesform tbody tr').formset();
	   	window.picostackRefreshWorkerFn = function () {
	   		// Loop through each popover on the page
			$("[data-toggle=popover]").each(function() {
			    // Hide this popover if it's visible and if the user clicked outside of it
			    // if ($(this).next('div.popover:visible').length && $(".popover").has(e.target).length === 0) {
			    $(this).popover("hide");
			    // }
		  	});		
  			// Do ajax request.
			$.ajax({
				url: "/list_instances",
				success: function( data ) {
		    		// if ( console && console.log ) {
			        // 	    console.log( "data:", data);
		    		// }
		    		$('#instances_list').hide().html(data).fadeIn();
	  			},
	  			complete: function() {
	  				// TODO: update html with data only if string hash is different.
	  				// For connection instructions.
	  				$("[data-toggle='popover']").popover({
 					   container: 'body'
					});
	  				// Add click handler to the refresh button.
		  			$('#refreshInstancesButton').on('click', function (e) {
			  			clearTimeout(window.picostackRefreshWorkerTimer);
			  			picostackRefreshWorkerFn();  			
					});
		     		// Schedule the next request when the current one's complete.
	    	  		window.picostackRefreshWorkerTimer = setTimeout(window.picostackRefreshWorkerFn, 5000);
		    	}
		    });
	    };
	    picostackRefreshWorkerFn();
	    $('#instances_list').hover(
	    	function () {
	    		// Block refresh if user has his mouse on top of the form.
	    		clearTimeout(window.picostackRefreshWorkerTimer);
	   		},
	    	function () {
	    		// Continue refreshing when user leaves the form.
				window.picostackRefreshWorkerTimer = setTimeout(window.picostackRefreshWorkerFn, 5000);
	   		}
	    );
	 
	});	
--></script>

{% endblock %}
