
var timeout_warning_ms = 10000
var caps_lock_message_timeout = 5000

function init_page(timeout) {
    setTimeout(count_down, Math.max(0, (timeout * 1000) - timeout_warning_ms))

    if (document.forms[0].user.value == '') {
        document.forms[0].user.focus()
    } else {
        document.forms[0].pwd.focus()
    }

    if (window.name != window.top.name) {
        // prevents logout in frames
        window.top.location = window.location
    }

    var password_input = document.getElementById('password_input')
    if (password_input) {
        password_input.onkeypress = okp
    }
}

var count_down_now = timeout_warning_ms
function count_down() {
    var message_node = document.getElementById('countdown')

    if (count_down_now <= 0) {
        count_down_now = 0
    }

    // innerHTML now works in most browsers.
    if (count_down_now == 0) {
        // Expire
        var inputs = document.getElementsByTagName("input")
        for (var i = 0; i < inputs.length; i++) {
            inputs[i].disabled = true
        }
        message_node.innerHTML = 'You took too long to log in. <a href="' + get_current_location() +'">Try again.<\/a>'
    } else {
        message_node.innerHTML = 'This page expires in ' + Math.floor(count_down_now/1000) + ' seconds.'
        count_down_now -= 1000
        setTimeout(count_down, 1000)
    }
}


// Returns the current location.
// Remove anchor fragments from the end of URL's as they
// causes problems when the user clicks on the try again link
function get_current_location() {
    var location = document.location.toString()
    var hash_location = location.indexOf('#')
    if(hash_location >= 0) {
        location = location.substring(0 , hash_location)
    }
    return location
}

function okp(event) {
    var event = event ? event : window.event
    try {
        event.which = event.which ? event.which : event.keyCode
    } catch (e) {
    }

    if (
        // Shift not pressed and upper case
        (!event.shiftKey && (event.which > 64 && event.which < 91))
        ||
        // Shift pressed and lower case
        (event.shiftKey && (event.which > 96 && event.which < 123))
    ) {
        show_by_id('caps_lock_on')
        setTimeout(function () {hide_by_id('caps_lock_on')}, caps_lock_message_timeout)
    } else {
        hide_by_id('caps_lock_on')
    }
}


function show_by_id(id) {
    document.getElementById(id).style.display = 'block'
}


function hide_by_id(id) {
    document.getElementById(id).style.display = 'none'
}
