<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Kiosk</title>
        {% load static %}
        {% load custom_tags_and_filters %}
        {# jQuery #}
        <script type="text/javascript" src="{% static "jquery.min.js" %}"></script>
        {# Bootstrap #}
        <script type="text/javascript" src="{% static "bootstrap/js/bootstrap.min.js" %}"></script>
        <link rel="stylesheet" type="text/css" href="{% static "bootstrap/css/bootstrap.min.css" %}" />
        <link rel="stylesheet" type="text/css" href="{% static "bootstrap/css/bootstrap-theme.min.css" %}" />
        {# Numpad #}
        <script type="text/javascript" src="{% static "numpad/custom_numpad.jquery.js" %}"></script>
        <link rel="stylesheet" type="text/css" href="{% static "numpad/numpad.jquery.css" %}" />
        {# Virtual Keyboard	#}
        <script type="text/javascript" src="{% static "virtualkeyboard/jquery.keyboard.min.js" %}"></script>
        <link rel="stylesheet" type="text/css" href="{% static "virtualkeyboard/keyboard-basic.min.css" %}" />
        {# NEMO #}
        <link rel="shortcut icon" type="image/x-icon" href="{% static 'favicon.ico' %}" />
        <script type="text/javascript" src="{% static "nemo.js" %}"></script>
        <link rel="stylesheet" type="text/css" href="{% static "nemo.css" %}" />
        {# Kiosk #}
        <link rel="stylesheet" type="text/css" href="{% static "kiosk/kiosk.css" %}" />
        {# Badge Reader #}
        <script type="text/javascript" src="{% static "badge_reader.js" %}"></script>
        <!--suppress CssUnusedSymbol -->
        <style>
		.btn-extra-large
		{
			margin-top: 50px;
			margin-bottom: 50px;
			font-size: 36px;
		}
        {# Prevent links in tooltips #}
        .tooltip .tooltip-inner a
        {
            pointer-events: none;
        }
	
        </style>
    </head>
    <body>
        <div id="kiosk-container">
            <div class="container-fluid">
                <div id="default_content">
                    <h1>Scan your badge to control tools</h1>
                    <div id="occupancy"></div>
                    <div id="usage_title"></div>
                    <div class="tab-pane{% if tools_exist and tab == 'tools' %} active{% endif %} info-tooltip-container"
                         id="tools">
                        <div id="usage"></div>
                    </div>
                    <div id="alerts"></div>
                </div>
                <div id="error" style="display: none">
                    <h1>There was a problem communicating with the web server. Please visit the user office for assistance.</h1>
                </div>
                <div id="interlock_error" style="display: none">
                    <h1 class="text-center">
                        <span style="font-size: xx-large;
                                     margin-right:10px"
                              class="glyphicon glyphicon-exclamation-sign danger-highlight"></span>
                        Interlock error
                    </h1>
                    <h3 id="interlock_message" class="text-center"></h3>
                    <div class="col-xs-4" style="margin: 40px auto; float: initial">
                        <div id="inter_bypass" class="btn-block" style="display: none; margin-bottom: 10px">
                            <div class="alert alert-success" style="text-align:center; margin-bottom:0">
                                <span id="bypass_text" style="font-size:x-large"></span>
                            </div>
                        </div>
                        <div id="inter_try_again" class="btn-block" style="margin-bottom: 10px">
                            <div class="alert alert-info" style="text-align:center; margin-bottom:0">
                                <span style="font-size:x-large">Try again</span>
                            </div>
                        </div>
                        <div id="inter_back" class="btn-block" style="margin-bottom: 10px">
                            <div class="alert alert-warning" style="text-align:center; margin-bottom:0; font-size:x-large">Go back</div>
                        </div>
                        <div class="btn-block" onclick="revert()">
                            <div class="alert alert-warning" style="text-align:center; margin-bottom:0">
                                <span style="font-size:x-large">I've finished using this kiosk</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div id="status" style="display: none"></div>
                <div>
                    <h1 style="color:lightgrey" id="badge_number"></h1>
                </div>
            </div>
            <div class="countdown" style="position: fixed; bottom: 0; right: 0;font-size: x-large"></div>
        </div>
        {% include 'base/footer.html' with no_links=True %}
        <script type="text/javascript">
        {% with show_badge_number="application"|customization:"show_badge_number" %}
		let kiosk_badge_reader = new BadgeReader(send_badge_number, "{{ badge_reader.send_key }}", {% if badge_reader.record_key %}"{{ badge_reader.record_key }}"{% else %}undefined{% endif %}, {{ show_badge_number|yesno:"true,false" }});
        {% endwith %}
		let timeout_handle = null;
		let countdown_handle = null;
		let occupancy = new URLSearchParams(window.location.search).get('occupancy');
        let usage = new URLSearchParams(window.location.search).get('usage') !== null;
        let alerts = new URLSearchParams(window.location.search).get('alerts') !== null;
		let default_content_element = $("#default_content");
		let status_element = $("#status");
		let error_element = $("#error");
		let error_interlock_element = $("#interlock_error");
		let bypass_button = $("#inter_bypass");

        function show_alerts()
        {
            let alert_users = $(".alert.show-on-load");
            alert_users.each(function(index, element) {
                let speed = 4500;
                if ($(element).data('speed')) speed = $(element).data('speed')
                $(element).fadeTo(speed, 500).slideUp(500, function () {
                    $(element).slideUp(500);
                });
            });
        }
		function send_badge_number(badge_number)
		{
			clear_timeout();
			load_choices(badge_number);
		}

		if(occupancy)
		{
			fetch_occupancy();
			set_interval_when_visible(document, fetch_occupancy, 30000);
		}
        if (usage)
        {
            fetch_usage();
            set_interval_when_visible(document, fetch_usage, 30000);
        }
        if (alerts)
        {
            fetch_alerts();
            set_interval_when_visible(document, fetch_alerts, 30000);
        }

		function load_complete(response, status, xml_http_request)
		{
			if(status === "error")
			{
				default_content_element.hide();
				status_element.hide();
				error_interlock_element.hide();
				error_element.show();
				revert(15);
			}
            else
            {
                status_element.html(response).show();
            }
			$("#badge_number").html("");
			show_alerts();
		}
		function revert(delay, callback)
		{
            callback = callback || revert_to_default_content;
			clear_timeout();
			let countdown = delay - 1;
			delay = delay * 1000;
			timeout_handle = setTimeout(callback, delay);
			countdown_handle = setInterval(function()
            {
				$('.countdown').html(countdown);
				countdown --;
			}, 1000);
		}
		function revert_to_default_content()
		{
			fetch_occupancy();
            fetch_usage();
            fetch_alerts();
			clear_timeout();
			close_numpads();
			close_keyboards();
			status_element.hide();
			error_interlock_element.hide();
			error_element.hide();
			$("#badge_number").html("");
			default_content_element.show();
		}
		function clear_timeout()
		{
			if(timeout_handle != null)
				clearTimeout(timeout_handle);
			timeout_handle = null;
			if (countdown_handle != null)
				clearInterval(countdown_handle);
			countdown_handle = null;
			$(".countdown").html("");
		}
		function select_project(element, project_id)
		{
			$(".project-choice").removeClass('active');
			$(element).addClass('active');
			$("#project_id").val(project_id);
            $("#pre_usage_questions").show();
			update_start_button();
		}
		function load_choices(badge_number)
		{
			let data = {
				'location': '{{ location }}',
				'badge_number': badge_number,
                'category': '{{ request.GET.category|default_if_none:"" }}',
			};
			default_content_element.hide();
			error_interlock_element.hide();
			error_element.hide();
			status_element.html("<h1>Loading choices...</h1>").show();
			ajax_get('{% url 'kiosk_choices' %}?' + $.param(data), undefined, load_complete);
		}
		function tool_information(url)
		{
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
			status_element.html("<h1>Loading tool information...</h1>").show();
            ajax_get(url, undefined, load_complete);
		}
		function tool_report_problem(url)
        {
            default_content_element.hide();
            error_element.hide();
            error_interlock_element.hide();
            let data = $('#tool_control').serialize();
            status_element.html("<h1>Loading report a problem...</h1>").show();
            ajax_post(url, data, load_complete);
        }
        function report_problem()
        {
            default_content_element.hide();
            error_element.hide();
            error_interlock_element.hide();
            let data = $('#tool_report_problem').serialize();
            status_element.html("<h1>Reporting problem...</h1>").show();
            ajax_post('{% url 'report_problem_from_kiosk' %}', data, load_complete);
        }
        function tool_post_comment(url)
        {
            default_content_element.hide();
            error_element.hide();
            error_interlock_element.hide();
            let data = $('#tool_control').serialize();
            status_element.html("<h1>Loading post a comment...</h1>").show();
            ajax_post(url, data, load_complete);
        }
        function post_comment()
        {
            default_content_element.hide();
            error_element.hide();
            error_interlock_element.hide();
            let data = $('#tool_post_comment').serialize();
            status_element.html("<h1>Posting comment...</h1>").show();
            ajax_post('{% url 'post_comment_from_kiosk' %}', data, load_complete);
        }
		function view_category(url)
		{
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
			status_element.html("<h1>Loading category...</h1>").show();
            ajax_get(url, undefined, load_complete);
		}
		function tool_reservation(url)
		{
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
			let data = $('#tool_control').serialize();
			status_element.html("<h1>Loading tool reservation...</h1>").show();
            ajax_post(url, data, load_complete);
		}
		function cancel_reservation(url, reservation_id)
		{
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
            let data = $('#cancel_reservation_' + reservation_id).serialize();
			status_element.html("<h1>Cancelling reservation...</h1>").show();
            ajax_post(url, data, load_complete);
		}
		function reserve_tool()
		{
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
			let data = $('#tool_reservation').serialize();
			status_element.html("<h1>Reserving tool...</h1>").show();
            ajax_post('{% url 'reserve_tool_from_kiosk' %}', data, load_complete);
		}
		function try_post_catch_interlock_error(url, data)
        {
            ajax_post(url, data, function(response, status, xml_http_request) {interlock_success_callback(response, status, xml_http_request)}, function(response, status, xml_http_request) { return interlock_failure_callback(response, status, xml_http_request, url, data) })
        }

		function enter_wait_list(tool_id, customer_id)
        {
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
			let url = "{% url 'enter_wait_list_from_kiosk' %}";
			status_element.html("<h1>Entering wait list...</h1>").show();
			let data = {
                tool_id: tool_id,
				customer_id: customer_id
			};
            ajax_post(url, data, load_complete);
		}

		function exit_wait_list(tool_id, customer_id)
        {
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
			let url = "{% url 'exit_wait_list_from_kiosk' %}";
			status_element.html("<h1>Exiting wait list...</h1>").show();
            let data = {
                tool_id: tool_id,
				customer_id: customer_id
			};
            ajax_post(url, data, load_complete);
		}

		function enable_tool(tool_id)
		{
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
			let data = $('#tool_control').serialize();
			if (tool_id)
			{
				data += '&tool_id=' + tool_id;
			}
			status_element.html("<h1>Enabling tool...</h1>").show();
			try_post_catch_interlock_error('{% url 'enable_tool_from_kiosk' %}', data);
		}
		function disable_tool(shorten, force)
		{
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
            let data = ""
            if (force === undefined || !force)
            {
            	data += $("#tool_control").serialize();
            }
            else
            {
                data += "&tool_id=" + $("#tool_control input[name='tool_id']").val();
                data += "&customer_id=" + $("#tool_control input[name='customer_id']").val();
			}
            if (shorten !== undefined && shorten) data += '&shorten=True';
			status_element.html("<h1>Disabling tool...</h1>").show();
			try_post_catch_interlock_error('{% url 'disable_tool_from_kiosk' %}', data);
		}
		function interlock_success_callback(response, status, xml_http_request)
        {
            error_interlock_element.hide();
            status_element.html(response).show();
        }
		function interlock_failure_callback(response, status, xml_http_request, url, data)
        {
            revert(45);
            {# Specific case here where we have an error but it could be bypassed #}
            if (status === 'error' && response.status === 501)
            {
                status_element.hide();
                let response_data = response.responseJSON;
                $("#interlock_message").html(response_data['message'])
                bypass_button.hide();
                error_interlock_element.show();
                {# we can bypass, show the button #}
                if (response_data["bypass_allowed"] === true)
                {
                    bypass_button.off("click")
                    $('#bypass_text').html(response_data['action'] + " anyway");
                    bypass_button.show();
                    bypass_button.one('click', function ()
                    {
                        data += "&bypass=True";
                        try_post_catch_interlock_error(url, data);
                    });
                }
                {# hook up try again button #}
                let inter_try_again_button = $("#inter_try_again");
                inter_try_again_button.off("click");
                inter_try_again_button.one('click', function ()
                {
                    error_interlock_element.hide();
                    status_element.html("<h1>Trying again...</h1>").show();
                    setTimeout(function()
                    {
                        try_post_catch_interlock_error(url, data);
                    }, 200);
                });
                {# hook up back button #}
                let inter_back_button = $("#inter_back");
                inter_back_button.off("click");
                inter_back_button.one('click', function ()
                {
                    let urlParams = new URLSearchParams(data);
                    tool_information("{% url 'kiosk_tool_information' '11111111111' '999999999999' 'back_to_start' %}".replace('11111111111', urlParams.get("tool_id")).replace('999999999999', urlParams.get("customer_id")).replace('back_to_start', urlParams.get("back")));
                });
            }
            else
            {
                load_complete(response, status, xml_http_request);
            }
        }
		function csrf_token()
		{
			return '{{ csrf_token }}';
		}
		function fetch_occupancy()
		{
            if (occupancy) {
                ajax_get('{% url 'kiosk_occupancy' %}', {'occupancy': occupancy}, function (response) {
                    $("#occupancy").html(response);
                });
            }
        }
        function logout_user(tool_id, badge_number)
		{
			status_element.html("<h1>Logging you out...</h1>").show();
            ajax_get('{% url 'kiosk_logout_user' '999' %}'.replace('999', tool_id), {"badge_number": badge_number}, load_complete);
		}
        function fetch_usage()
		{
            if(usage)
            {
                $("#usage_title").html("<h2>Tools in use</h2>")
                ajax_get('{% url 'kiosk_usage' %}', {'interest': 'tools'},
                    function (response) {
                        $("#usage").html(response);
                        $(".in_use").css("display", "table-row");
                        $(".idle").hide();
                        $(".glyphicon-remove-circle").hide();
                    }
                );
            }
        }
        function fetch_alerts()
        {
            {% if "NEMO.apps.area_access"|app_installed %}
                if(alerts)
                {
                    $("#alerts").load("{% url 'area_access_alerts' %}");
                }
            {% endif %}
        }
		function close_numpads()
		{
			$.each($('[data-numpad]'), function (index, item)
            {
				$(item).data('numpad').close(false);
			});
		}
        function close_keyboards()
		{
            $.each($('.ui-keyboard-input'), function (index, item)
			{
                $(item).data('keyboard').close(false);
            })
        }
        {# Auto hide tooltips on kiosk page after 30 seconds #}
	    $(document).on('shown.bs.tooltip',  function () {
          let tooltip = $('.tooltip');
          setTimeout(function () {
            tooltip.hide();
          }, 30000);
        });
        </script>
    </body>
</html>
