/*
 *  $Id$
 *
 *  Contains javascript methods for the ATLAS live event display page
 *
 *  - Eric Jansen, University College London <eric.jansen -at- cern.ch>
 *
 */

// Initial image dimensions, for scaling
var imgWidth = 1152;
var imgHeight = 768;

// Delay between updates
var sleep = 10;

// Timeout identifiers
var refreshTimeout = 0, msgTimeout = 0, menuTimeout = 0;

// Number of images in the archive
var numArchive = 100;

// Toggle for forcing archive mode
var forceArchive = false;

// Date object for last displayed image modification time
var lastImage = null;

// XML/HTTP request object
var httpReq = null;

// Pointer to log message window (if any)
var logWindow = null;

// Base URL
var url = 'http://atlas-live.cern.ch/';
var file = 'live.png';
var archive = 'archive/';

// Function that is called by the timer to refresh the event image
function refresh() {
    // Stop running timer (if any) and restart timer
    clearTimeout(refreshTimeout);
    refreshTimeout = setTimeout('refresh()', sleep*1000);

    // If there is a pending request, cancel it
    if (httpReq) httpReq.abort();

    // Browser compatibility things
    if (window.XMLHttpRequest) {
        // Standard way to do this in all modern browsers
        httpReq = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        // Old Internet Explorers have to do everything differently, of course
        httpReq = new ActiveXObject('Microsoft.XMLHTTP');
    } else {
        // Useless browser, just update the image without any of the intelligent stuff
        document.getElementById('event').src = url + file + '?' + Math.random();
        return;
    }

    // Define the code that handles the response from the server
    httpReq.onreadystatechange = function stateChange() {
        var lastModified;
        var date;

        if (httpReq.readyState == 4 && httpReq.status == 200
                && (lastModified = httpReq.getResponseHeader('Last-Modified')) && (date = httpReq.getResponseHeader('Date'))) {

            var newImage = new Date(Date.parse(lastModified));
            var now = new Date(Date.parse(date));
            var difference = now-newImage;

            // If the image is less than 15 minutes old 
            if (!forceArchive && now-newImage < 300 * 1000) {

                // Check if it is newer than the one we are showing and possibly update
                if (!lastImage || newImage > lastImage) {
                    log('Last live image produced at ' + newImage + ', going to update');
                    document.getElementById('event').src = url + file + '?' + Math.random();
                    lastImage = newImage;
                } else {
                    log('Last live image produced at ' + newImage);
                }

                // Don't display the disclaimer
                hide('notlive');

            } else {
                // Show an archived image
                log('Last live image produced at ' + newImage + ', displaying archive image');
                document.getElementById('event').src = url + archive + Math.floor(numArchive * Math.random()) + '.png';

                // Make sure the "this is not live" disclaimer is visible
                show('notlive');
            }
        }
    }

    httpReq.open('HEAD', url + file, true);
    httpReq.send(null);
}

function log(text) {
    if (logWindow && logWindow.document) {
        time = new Date();
        logWindow.document.getElementById('log').innerHTML += '[' + now() + ']: ' + text + '<br />';
    }
}

function now() {
    var time = new Date();
    var hours = time.getHours() + '';
    var minutes = time.getMinutes() + '';
    var seconds= time.getSeconds() + '';

    if (hours.length == 1) hours = '0' + hours;
    if (minutes.length == 1) minutes = '0' + minutes;
    if (seconds.length == 1) seconds = '0' + seconds;

    return hours + ':' + minutes + ':' + seconds;
}

function message(text, timeout) {
    var msg = document.getElementById('msg');

    if (msgTimeout)
        clearTimeout(msgTimeout);

    msg.innerHTML = text;
    show('msg');

    msgTimeout = setTimeout('hideMessage()', timeout*1000);
}

function hide(id) {
    var element = document.getElementById(id);
    if (element)
        element.style.visibility = 'hidden';
}

function show(id) {
    var element = document.getElementById(id);
    if (element)
        element.style.visibility = 'visible';
}

function hideMessage() {
    hide('msg');
    msgTimeout = 0;
}

function scheduleHideMenu() {
    menuTimeout = setTimeout('hideMenu()', 1000);
}

function hideMenu() {
    hide('menu');
    clearTimeout(menuTimeout);
    menuTimeout = 0;
}

function showMenu() {
    show('menu');
    clearTimeout(menuTimeout);
    menuTimeout = 0;
}

function resize() {
    var scaleFactor;
    var width, height;

    if (window.innerWidth) {
        // All proper browsers
        width = window.innerWidth;
        height = window.innerHeight;
        log('window.innerWidth/Height: ' + width + 'x' + height + ', image: ' + imgWidth + 'x' + imgHeight);
    } else if (document.documentElement.clientWidth) {
        // Some IE versions
        width = document.documentElement.clientWidth;
        height = document.documentElement.clientHeight;
        log('document.documentElement.clientWidth/Height: ' + width + 'x' + height + ', image: ' + imgWidth + 'x' + imgHeight);
    } else if (document.body.clientWidth) {
        // Some other IE versions
        width = document.body.clientWidth;
        height = document.body.clientHeight;
        log('document.body.clientWidth/Height: ' + width + 'x' + height + ', image: ' + imgWidth + 'x' + imgHeight);
    } else {
        // Give up, no scaling
        log('Could not determine window size, no image scaling!');
        return;
    }

    width -= 20;
    height -= 20;

    height -= document.getElementById('menu').offsetHeight;

    if (width/imgWidth < height/imgHeight) {
        scaleFactor = width/imgWidth;
    } else {
        scaleFactor = height/imgHeight;
    }

    document.getElementById('event').style.width = Math.round(scaleFactor * imgWidth) + 'px';
    document.getElementById('event').style.height = Math.round(scaleFactor * imgHeight) + 'px';
}

function init() {
    window.onresize = resize;
    hide('menu');
    resize();
    refresh();

    document.onkeyup = function keyPress(event) {
        if (!event) event = window.event; // IE
        switch(event.keyCode) {
            case 32: 
                if (refreshTimeout) {
                    clearTimeout(refreshTimeout);
                    refreshTimeout = 0;
                    if (httpReq) {
                        httpReq.abort();
                        httpReq = null;
                    }
                    message("Paused automatic event updates...", 1);
                } else {
                    refresh();
                    message("Resuming automatic event updates...", 1);
                }
                break;
            case 61:
            case 107:
            case 187:
                sleep++;
                refresh();
                message("Delay between event updates now set to "+sleep+" second"+(sleep>1 ? "s" : ""), 1);
                break;
            case 45:
            case 109:
            case 189:
                if (sleep>1) sleep--;
                refresh();
                message("Delay between event updates now set to "+sleep+" second"+(sleep>1 ? "s" : ""), 1);
                break;
            case 27:
                hideMessage();
                hide('help');
                break;
            case 65:
                forceArchive = !forceArchive;
                lastImage = null;
                break;
            case 72:
                show('help');
                break;
            case 76:
                if (logWindow) {
                    logWindow.close();
                    logWindow = null;
                } else {
                    logWindow = window.open('', 'log', 'toolbar=0,location=0,menubar=0,directories=0,width=500,height=300');
                    logWindow.document.write('<html><head><title>Log window</title></head><body style="font-size: 8pt;"><h1>Log file</h1><div id="log"></div></body></html>');
                }
                break;
            default:
                log('Unknown key pressed: ' + event.keyCode);
                break;
        }
    }

}

function atcern(address) {
    document.write('<a href="mailto:'+address+'@cern.ch">'+address+'@cern.ch</a>');
}

