// this file contains script for time tracking

// variable for idle time counting
var G_IDLE_TIME = 0;
var G_MAX_IDLE_TIME = 3;
var G_INTERVAL_TIME = 1;
var G_WARN_TIME = 2;

$(document).ready(function () {
    idle_time_track_script(this);
});

var idle_time_track_script = function(pthis)
{
    var idleInterval = setInterval(timerIncrement, G_INTERVAL_TIME*60000); // var * 1 minute
    // add popup box to the body so that we can show it
    // document.body.innerHTML += popup_code;

    //Zero the idle timer on mouse movement.
    $(pthis).mousemove(function (e) {
        G_IDLE_TIME = 0;
        /*
        $.post("API.php", { idle_time: "REFRESH" }, function (data) {            
        },"json");
        */
    });
    $(pthis).keypress(function (e) {
        G_IDLE_TIME = 0;
        $.post("API.php", { idle_time: "REFRESH" }, function (data) {            
        },"json");
    });
}

function timerIncrement() {
    G_IDLE_TIME = G_IDLE_TIME + 1;
    
    if (G_IDLE_TIME > (G_MAX_IDLE_TIME - G_WARN_TIME)) { 
        $.post("API.php", { idle_time: "GET" }, function (data) {
            //console.log("idle time from API is ",data.idle_time)
            if(data.action === "logout_user")
            {
                $.post("API.php", { register: "LOGOUT" }, function (data) {
                    // alert("Passes maximum idle time");
                    $("#id-modal-idle-time-warn-popup").modal("hide");
                    $("#id-modal-idle-time-logout-popup").modal("show");
                    // window.location.replace("index.php");
                });
            }

            if(data.action == "warn_idle_user")
            {
                $("#id-modal-idle-time-warn-popup").modal("show");
            }
        },"json");        
    }
}

$("#id-btn-idle-time-popup-login").click(function(){
    window.location.replace("register.php");
});

$("#id-modal-idle-time-logout-popup").on("hidden.bs.modal", function () {
    window.location.replace("register.php");
});

$("#id-btn-idle-time-continue-work").click(function(){
    G_IDLE_TIME = 0;
    $.post("API.php", { idle_time: "REFRESH" }, function (data) { 
        $("#id-modal-idle-time-warn-popup").modal("hide");           
    },"json");
});

;