
// Javascript code used for all versions of startup page

// Requires prototype.js library

// Simple class to write a cookie with a given name, info, and expiration
//
Cookie = Class.create({
    // Initializes cookie object with its name. Nothing is changed in the browser.
    // path: if undefined, it will use "/" as path, i.e., match any location
    //  on the same domain. To match just the page's directory (and subdirs)
    //  pass null as path.
    initialize: function(name, path)
    {
        this.name = name;
        this.path = path;
    },

    // Sets this cookie to the given value and with the given expiration
    // lifeteime.
    set: function(value, secondsToExpire)
    {
        var expDate = new Date();
        expDate.setTime(expDate.getTime() + secondsToExpire*1000);
        var path = '';
        if (this.path !== null)
        {
            if (this.path == undefined)
                path = '; path=/';
            else
                path = '; path=' + this.path;
        }

        document.cookie = this.name + "=" + escape(value)
                         + "; expires=" + expDate.toGMTString() + path;
    }
});



// Hook for Internet Explorer
if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && navigator.userAgent.indexOf("Windows") != -1 && navigator.userAgent.indexOf("Windows 3.1") == -1)
{
    document.write('<SCRIPT LANGUAGE=VBScript\> \n');
    document.write('on error resume next \n');
    document.write('Sub main_FSCommand(ByVal command, ByVal args)\n');
    document.write('  call main_DoFSCommand(command, args)\n');
    document.write('end sub\n');
    document.write('</SCRIPT\> \n');
}

function main_DoFSCommand(command, args)
{
    switch (command)
    {
        case "toggleLog":
            toggleLog();
            break;
        case "doLog":
            doLog(args);
            break;
        case "showReportWindow":
            showReportWindow(args);
            break;
        case "getAdobe":
            getAdobe();
            break;
        case "showPdf":
            showPdf(args);
            break;
        case "showUrl":
            showUrl(args);
            break;
        case "showGame":
            showGame(args);
            break;
        case "hideGame":
            hideGame();
            break;
        case "showBanner":
            showBanner();
            break;
        case "hideBanner":
            hideBanner();
            break;
        case "saveSession":
            saveSession(args);
            break;
    }
}

function saveSession(arg)
{
    var c = new Cookie("lts-session");
    c.set(arg, 30);
}


var logwin;
var logtext="<pre>";

function toggleLog()
{
    if (!logwin || logwin.closed)
    {
        logwin = window.open('', 'log',
        'titlebar=no,toolbar=no,width=400,height=500,resizable=yes,scrollbars=yes,' +
        'screenX=0,screenY=0,left=0,top=0,menubar=no,status=no,alwaysRaised=yes');
        logwin.document.write(logtext);
        logwin.document.close();
    }
    else
    {
        logwin.close();
    }
}

function doLog(text)
{
    logtext += text + "\n";
    if (logwin && !logwin.closed)
    {
        logwin.document.write(logtext);
        logwin.document.close();
    }
}

var adobeWin;

function getAdobe()
{
    adobeWin = window.open("http://www.adobe.com/products/acrobat/readstep2.html", "AdobeWin");
}

function showUrl(url)
{
    window.open(url, "_blank");
}


var schoolWindow;
var reportWindow;
var skillsWindow;
var screenWidth = screen.availWidth;
var screenHeight = screen.availHeight;

function showReportWindow(args)
{
    var theWidth = 700;
    if (theWidth > screenWidth)
        theWidth = screnWidth;
	var theHeight = screenHeight-120;
	var leftPos = 40;// 40 is to move it off the edge a bit
	var topPos = 40;
    var xrand = Math.floor(Math.random()*1000000);
    reportURL = "/servlet/rserver?" + args + "&xrand=" + xrand;
	var waitURL = "waitmessage.html";
    reportWindow = window.open(waitURL,"ReportWindow","toolbar=no,width="+theWidth+",height="+theHeight+",menubar=no,left="+leftPos+",screenX="+leftPos+",top="+topPos+",screenY="+topPos+",resizeable=yes,scrollbars=yes");
    setTimeout('reportWindow.focus();',250); // prevent focus error on older browsers
}

function waitDone()
{ // the waitmessage document is fully loaded
	reportWindow.location.href = reportURL;
}

function showPdf(file)
{
    var theWidth = 700;
    if (theWidth > screenWidth)
        theWidth = screnWidth;
	var theHeight = screenHeight-120;
    var leftPos = 140;//  to move it off the edge a bit
	var topPos = 40;
    skillsWindow = window.open(file,"SkillsWindow","toolbar=no,width="+theWidth+",height="+theHeight+",menubar=no,left="+leftPos+",screenX="+leftPos+",top="+topPos+",screenY="+topPos+",resizeable=yes,scrollbars=yes");
    setTimeout('skillsWindow.focus();',250); // prevent focus error on older browsers
}

var APP_WIDTH = 800;
var APP_HEIGHT = 600;

function generateFlash(div, url, w, h, bgColor)
{
    if (!bgColor)
        bgColor = "#000000";
    div.update(
        "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'" +
        "    codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0'" +
        "    width='" + w + "' height='" + h + "' id='app2' align=''>" +
        "    <param name='movie' value='" + url + "'>" +
        "    <param name='quality' value='high'>" +
        "    <param name='bgcolor' value='#000000' />" +
        "    <embed src='" + url + "' quality='high'" +
        "        width='" + w + "' height='" + h + "' bgcolor='" + bgColor + "'" +
        "        name='mv970397021' align='' type='application/x-shockwave-flash'" +
        "        swLiveConnect='true' pluginspage='http://www.macromedia.com/go/getflashplayer'>" +
        "    </embed>" +
        "</object>"
        );
}

function IsIE()
{
    return navigator.appName == "Microsoft Internet Explorer";
}


function now()
{
    var d = new Date();
    var t = d.getTime();
    delete d;
    return t;
}

//------------------------------------------------------------------------------
/** Downloads a file from the gien URL to make sure it's in local cache,
 * notifying the given element about download progress.
 */
function downloadUrl(url, elem)
{
    var req = new XMLHttpRequest();
    var tLast = 0;
    var tStart = now();
    var pe = new PeriodicalExecuter(function(pei) {
        var dt = now() - tStart;
        var msg = Math.floor(dt/1000) + '.' + Math.floor((dt%1000)/100)
        $('info_value').update(msg);
    },
    0.1);

    req.onreadystatechange = function()
    {
        if (req.readyState == 4)
        {
            pe.stop();
            $('info').setStyle({'visibility':'hidden'});
            centerInWindow();
        }
    };
    // Start asynchronous download
    req.open('GET',url,true);

    //XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
    req.overrideMimeType('text/plain; charset=x-user-defined');

    req.send(null);
}

function showGame(url)
{
    // Force game to show and app to hide
    // We also need to position the game at the same location the main app lies.
    // This location is given by the object element (IE) or by the embed element
    // (all others). Determine by comparing height with height attribute.
    if (!IsIE())
    {
        $('main').setStyle({'visibility':'hidden'});
        var topLeft = $('main').cumulativeOffset();
        $('info').setStyle({'left':topLeft.left+'px', 'top':topLeft.top+'px', 'visibility':'visible'});
        $('game').setStyle({'left':'-1000px', 'top':'-1000px'});
        downloadUrl(url, $('info'));
    }
    generateFlash($('game'), url, APP_WIDTH, APP_HEIGHT);
}

function hideGame()
{
    // Force game to hide and unload, and app to show
    $('main').setStyle({'visibility':'visible'});
    $('game').update('');
    $('info').setStyle({'visibility':'hidden'});
}

function hideBanner()
{
    $('browsealoud').setStyle({display:'none'});
}

function showBanner()
{
    $('browsealoud').setStyle({display:'block'});
}

function centerInWindow()
{
    var wDim;
    if (document.body.clientWidth)
        wdim = {width:document.body.clientWidth, height:document.body.clientHeight};
    else
        wdim = {width:window.innerWidth, height:window.innerHeight};
    var w = APP_WIDTH;
    var h = APP_HEIGHT;
    var left = Math.max((wdim.width - w)/2, 0);
    var top = Math.max((wdim.height - h)/2, 0);
    $('main').setStyle({'left':left+'px', 'top':top+'px'});
    if ($('info').getStyle('visibility') != 'visible')
        $('game').setStyle({'left':left+'px', 'top':top+'px'});
}

document.observe('dom:loaded', function() {
    centerInWindow();
    Element.observe(window, 'resize', function(ev) {
        centerInWindow();
    });
    $('info').observe('lts:progress', function(ev) {
        var progress = ev.memo;
        if (progress >= 100)
        {
            $('info').setStyle({'visibility':'hidden'});
            centerInWindow();
        }
        else
            $('info_percent').update(progress)
    });

});