/* 
 * 
 * This file (session.timeout.java) is part of DebGen Biobank Software developed by ASTRID Research.
 * All rights reserved. Reproduction, modification, use or disclosure
 * to third parties without express authority is forbidden.
 * 
 * Copyright ASTRID Research Inc., Hungary, 2009-2010.
 * 
 * ASTRID Research
 * Headquaters: Csapo utca 42. Debrecen H-4029 HUNGARY
 * Phone: +36-52-533-173        Fax: +36-52-533-174
 * Web: http://www.astrid.hu    E-mail: info@astrid.hu
 * 
 * Project name: DebGen Biobank Software project.
 * URLS:
 *             Istvan Zoltan Nagy (istvan.nagy@astrid.hu)
 */

function startTimer(seconds) {
    elapsed = 0;
    document.getElementById("remaining").innerHTML = printTime(sessionTime - elapsed);
    document.getElementById("popupRemaining").innerHTML = printTime(sessionTime - elapsed);
    if (seconds && seconds > 0) {
        $(document).everyTime("1s",function(i) {
            checkTime(i);
        },seconds);
    }
}

function checkTime(i) {
    elapsed++;
    if (elapsed == popupTime) {
        doPopup();
    }
    document.getElementById("remaining").innerHTML = printTime(sessionTime-elapsed);
    document.getElementById("popupRemaining").innerHTML = printTime(sessionTime-elapsed);
    if (elapsed >= sessionTime) {
        $("#dialog-confirm").dialog('close');
        $("#dialog-toolate").dialog({
            resizable: true,
            height: 150,
            width: 350,
            modal: true,
            buttons: {
                OK: function() {
                    $(this).dialog('close');
                    location.href = "logout.html";
                }
            }
        });
    }
}

function printTime(seconds) {
    secs = seconds % 60;
    mins = (seconds - secs) / 60;
    return ((mins >= 10) ? mins : "0" + mins) + ":" + ((secs >= 10) ? secs : "0" + secs);
}

function renewSessionAjax() {
    $('#noop').ajaxSubmit({
        dataType:  'json',
        // success identifies the function to invoke when the server response
        // has been received
        success:   resetTimer
    });
}

function resetTimer(data) {
    if (data && data.result && data.result == "true") {
        elapsed = 0;
        jQuery.each(jQuery.timer.global, function(index, item) {
            jQuery.timer.remove(item);
        });
        startTimer(sessionTime);
    }
}

function doPopup() {
    $("#dialog-confirm").dialog({
        resizable: true,
        height: 150,
        width: 350,
        modal: true,
        buttons: {
            OK: function() {
                renewSessionAjax();
                $(this).dialog('close');
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        }
    });
    $("#dialog-confirm").dialog('open');
}
