var g_scc_wdt_warning = unescape('Your MediaServer Web session has been idle for over 27 minutes.')
var g_scc_wdt_timer_format = unescape('Time remaining before automatic log out: {timer}');
var g_scc_wdt_stay_button = unescape('Stay Logged In');
var g_scc_wdt_leave_button = unescape('Log Out Now');
//////////////////////////////////////////////////////////////////////
// requires jquery to be included in the wrapper.
g_scc_wdt_present = true
g_scc_wdt_redirected = false
var scc_wdt_timer_id = null
var scc_wdt_last_post = null
g_scc_wdt_reset_from_idle = false;
g_scc_wdt_logout_from_idle = false;

function scc_wdt_status(msg, color) {
    var el = document.getElementById('scc_wdt_debug_status')
    if (el == null) return
    el.style.background = color
    el.innerHTML = msg
}

//////////////////////////////////////////////////////////////////////
// this function should be emitted by the server as inline script
function scc_onwdt(sid, interval, warnIdle, logOut) {
    if (logOut) {
        if (g_scc_wdt_redirected == false) {
            window.location = '/scripts/sccmgcgi.dll?LogOut'
        } else {
            // the session has expired for an anonymous user - just close out the warning since the user may restart the session anonymously.
            scc_wdt_show_warning(0)
        }
    } else {
        var d = new Date()
        scc_wdt_show_warning(warnIdle)
        scc_wdt_invoke_timer(sid)
        scc_wdt_status('scc_onwdt', 'blue')
    }
}
//////////////////////////////////////////////////////////////////////
function scc_wdt_invoke_timer(thenms) {
    var d = new Date()
    var nowms = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
    var diffms = nowms - thenms

    if (g_scc_wdt_redirected) { // this indicates an anonymous session relog 
        // For web edit forms, cancel out to invoking page.
        g_scc_wdt_redirected = false;
        // reload the form causing a check out
        top.frames.document.location.href = top.frames.document.location.href;
    }
    clearTimeout(scc_wdt_timer_id)
    scc_wdt_timer_id = setTimeout('scc_wdt_invoke_timer(' + thenms + ')', 500);
    if (diffms > 1000) {
        d = scc_wdt_last_post
        var last = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
        scc_wdt_status((nowms - last) / 1000, 'goldenrod')
    }

}
//////////////////////////////////////////////////////////////////////
function scc_onwdt_warning_timer(totalSeconds) {

    var el = document.getElementById('sccwdtwarningtimer')
    if (el == null) return

    if (totalSeconds >= 0) {
        var minutes = (Math.floor(totalSeconds / 60)) + ''
        var seconds = (totalSeconds % 60) + ''
        if (minutes.length == 1) minutes = '0' + minutes
        if (seconds.length == 1) seconds = '0' + seconds
        var timer = minutes + ':' + seconds
        if (g_scc_wdt_timer_format.indexOf('{timer}', 0) > -1) {
            timer = g_scc_wdt_timer_format.replace('{timer}', timer)
        }
        el.innerHTML = timer
        setTimeout('scc_onwdt_warning_timer(' + (totalSeconds - 1) + ')', 1000)
    }
    else if (totalSeconds <= -1) {
        scc_wdt_show_warning(0)
    }
}
//////////////////////////////////////////////////////////////////////
function scc_wdt_show_warning(warnIdle) {
    var box = document.getElementById('sccwdtwarningbox');
    if (warnIdle == 0) {
        if (box != null) {
            box.style.visibility = 'hidden'
        }
    } else {
        if (box == null) {
            box = document.createElement('div')
            box.setAttribute('id', 'sccwdtwarningbox')
            box.style.visibility = 'visible'
            box.style.position = 'absolute'
            box.style.zIndex = '1';
            box.style.left = '16px'
            box.style.top = '16px'

            var table = document.createElement('table');
            table.style.background = 'yellow'
            table.style.border = '1px double red'
            table.style.padding = '16px 16px 16px 16px'

            var tbody = document.createElement('tbody')
            var tr = document.createElement('tr')
            var td = document.createElement('td')
            td.innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;';
            tr.appendChild(td)
            tbody.appendChild(tr)

            tr = document.createElement('tr')
            td = document.createElement('td')
            td.setAttribute('align', 'center')
            td.innerHTML = g_scc_wdt_warning;
            tr.appendChild(td)
            tbody.appendChild(tr)

            tr = document.createElement('tr')
            td = document.createElement('td')
            td.innerHTML = '&nbsp;';
            tr.appendChild(td)
            tbody.appendChild(tr)

            tr = document.createElement('tr')
            td = document.createElement('td')
            td.setAttribute('align', 'center')
            td.setAttribute('id', 'sccwdtwarningtimer')
            td.innerHTML = "stubbed";
            tr.appendChild(td)
            tbody.appendChild(tr)

            tr = document.createElement('tr')
            td = document.createElement('td')
            td.innerHTML = '&nbsp;';
            tr.appendChild(td)
            tbody.appendChild(tr)

            tr = document.createElement('tr')
            td = document.createElement('td')
            td.setAttribute('align', 'center')
            var button = document.createElement('button')
            button.onclick = function () { g_scc_wdt_reset_from_idle = true; scc_wdt(true); }
            button.innerHTML = g_scc_wdt_stay_button;
            button.style.marginRight = '32px';
            td.appendChild(button);
            tr.appendChild(td)
            button = document.createElement('button')
            button.onclick = function () { g_scc_wdt_logout_from_idle = true; scc_wdt(); }
            button.innerHTML = g_scc_wdt_leave_button;
            td.appendChild(button);
            tr.appendChild(td)
            tbody.appendChild(tr)

            tr = document.createElement('tr')
            td = document.createElement('td')
            td.innerHTML = '&nbsp;';
            tr.appendChild(td)
            tbody.appendChild(tr)

            table.appendChild(tbody)
            box.appendChild(table)
            document.body.appendChild(box)
        }
        box.style.visibility = 'visible'
        scc_onwdt_warning_timer(warnIdle)
    }
}
//////////////////////////////////////////////////////////////////////

function scc_wdt(immediate) {
    scc_wdt_last_post = new Date()
    clearTimeout(scc_wdt_timer_id)
    scc_wdt_timer_id = null
    if (g_scc_wdt_logout_from_idle) {
        if (g_scc_wdt_redirected == false) {
            window.location = '/scripts/sccmgcgi.dll?LogOut'
            return
        } else {
            // else an anonymous session - just die quietly.        
            scc_wdt_show_warning(0)
            scc_wdt_status('anonymous session expired', 'red')
        }
        return
    }
    var el;
    var d = new Date()
    var sid = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
    var relurl = '/scripts/sccmgcgi.dll?Command=JavaScript&name=jswdt&sid=' + sid;
    // this is in response to the user requesting the session not expire (via the warning box)
  
    if (g_scc_wdt_redirected == true) {
        // check for edit form        
        relurl += '&redir=1'
    }

    relurl += '&json=1'; // expect a json response

    /* The get verb of the /leases/lease resource returns all lease information.
    Invoking this verb does not extend the lease.
    */
    scc_wdt_status('scc_wdt', 'green')

    if (g_scc_wdt_reset_from_idle) {
        g_scc_wdt_reset_from_idle = false;
        scc_wdt_show_warning(0)
        relurl += '&reset=1'
        $.ajax({
            type: 'GET',
            url: relurl,
            dataType: 'json',
            timeout: 10000,
            error: function (jqXHR, textStatus, errorThrown) {      
                scc_wdt_status(textStatus + ':' + errorThrown, 'red')
            },
            success: function (data, textStatus, jqXHR) {
                scc_wdt_status(textStatus, 'blue')
                scc_onwdt(data.sid, data.interval, data.warnIdle, data.logOut)   
            }
        });
    } else {
        $.ajax({
            type: 'GET',
            url: relurl,
            dataType: 'json',
            timeout: 10000,
            error: function (jqXHR, textStatus, errorThrown) {
                setTimeout(function () { scc_wdt(); }, 2000);
                scc_wdt_status(textStatus + ':' + errorThrown, 'red')
            },
            success: function (data, textStatus, jqXHR) {
                setTimeout(function () { scc_wdt(); }, 9500);
                scc_wdt_status(textStatus, 'blue')
                scc_onwdt(data.sid, data.interval, data.warnIdle, data.logOut)
            }
        });
    }
}


setTimeout(function () { scc_wdt(); }, 2500);


