﻿//*********************Globals

//The maximum screen resolution( all image widths are relative to this resolution (cannot change this) )
var maxS = 1920;
//The maximum image height( changes depending on backgound image height )
var maxH = 5760;
//An object associative array holding all scaled elements original dimensions, by id
var images = {};
//An object associative array holding all scaled elements original position, by id
var positions = {};
//A visibility flag for each star, so we don't have to mess with getting styles from the browsers
var starVis = [];
//arrays for each stars position
var starX = [];
var starY = [];    
//An object holding the active gui controller in use
var control = null;
//The id of the active controller
var contId = null;
// Controllers positions when being controlled
var cX;
var cY;
//Engine condition
var drive = null;
//Throttle position sensor return
var tP = 0;
//Throttle position actual
var thrPos;
//Vector Direction
var sSX = "";
var sSY = "";
// Spaceships location in the Universe( starting location on the page )
var sZ = 0;
var sX = 500;               //Rough center
var sY = maxH;              //Set to maxH for bottom, zero for top
var altMul = 0;
// A message cue for lcd4, to slow down the displayed messages
var msgCue = new Array();                   //Cue of string messages
var timedMsg = false;                           //Message board state
// Detects first run of page to run startup animations
var firstRun = true;
// State of the background sound on or off
var bgsound = false;
//A genric handler for testing or debugging
var test = 0;
//Global functions
//Image preloader for Rollovers, Image Maps, animations etc.etc.
var throts = new Array("images/throttleIndMin.gif", "images/throttleIndMax.gif", "images/throttleInd1.gif", "images/throttleInd2.gif", "images/throttleInd3.gif", "images/throttleInd4.gif", "images/stick2.gif", "images/stick.gif");

var preloader = new Array();
for (var i = 0; i < throts.length; i++) {
    preloader[i] = new Image();
    preloader[i].src = throts[i];
}
//main onload initializer calls all functions when window loaded
function initialize() {
    moveSpaceship();                    //Start position of spaceship
    scale.alpha();                      //Get browser information
    scaleimages();                      //Resizes and positions all images
    window.onresize = scaleimages;      //Runs scaleimages on a resize
    stars("starfield");                 //Generates all the stars
    window.document.body.onscroll = setAltitude;
    window.setTimeout("useLCD3();", 2000);
    window.setTimeout("useLCD4();", 8950);
};
//Scales and positions the images according to screen resolution
function scaleimages() {

    scale.element("moon");
    scale.element("panel");
    scale.element("panel2");
     scale.element("throtInd");
    scale.element("startPanel");
    scale.element("throttle");
    scale.element("stick");
    scale.element("lcd1");
    scale.element("lcd2");
    scale.element("lcd3");
    scale.element("lcd4");
    scale.position("panel");
    scale.position("panel2");
     scale.position("throtInd");
    scale.position("startPanel");
    scale.position("throttle");
    scale.position("stick");
    scale.position("lcd1");
    scale.position("lcd2");
    scale.position("lcd3");
    scale.position("lcd4");
    scale.position("buttons");
}

//**********************Web Window Scaler Object
var scale = {

    //A browser checking function( will modify to detect alpha transparency ability)
    alpha: function() {
        var Safari = false;
        var Mozilla = false;
        var IE = false;
        var browser = window.navigator.vendor;
        if (browser) {
            Safari = browser.indexOf("Apple");
            if (Safari) {
                Safari = true;
                browser = "Safari";
            }
        }
        else if ((typeof (window.innerWidth) == 'number') && (!Safari)) {
            Mozilla = true;
            browser = "Mozilla";
        }
        else {
            IE = true;
            browser = "Explorer";
        }
        return browser;
    },
    // Function returns the available screen width
    width: function() {
        //The default screen dimensions
        var sW = 1000;
        if (scale.alpha() == "Mozilla") {
            sW = (window.innerWidth - 28);
        }
        else if (document.body && document.body.clientWidth) {
            sW = document.body.clientWidth;
        }
        else if (document.documentElement && document.documentElement.clientWidth) {
            sW = document.documentElement.clientWidth;
        }
        return sW;
    },
    // Function returns the available screen width
    height: function() {
        //The default screen dimensions
        var sH = 521;
        if (scale.alpha() == "Mozilla") {
            sH = (window.innerHeight - 14);
        }
        else if (document.body && document.body.clientHeight) {
            sH = document.body.clientHeight;
        }
        else if (document.documentElement && document.documentElement.clientHeight) {
            sH = document.documentElement.clientHeight;
        }
        return sH;
    },
    //Function scales an elements visual dimensions( saves old dimensions to array )
    element: function(id) {
        //Get images original width and height
        var elem = document.getElementById(id);
        if (elem.offsetWidth) elemW = elem.offsetWidth;
        if (elem.offsetHeight) elemH = elem.offsetHeight;
        //Set the original height and width to the images object, if not set
        if (!images[id + 'W']) {
            images[id + 'W'] = elemW.toString();
            images[id + 'H'] = elemH.toString();
        }
        //Scale it
        var oW = images[id + 'W'];
        var oH = images[id + 'H'];
        var newW = parseInt(oW / maxS * scale.width());
        var newH = parseInt(oH / 1000 * scale.height());
        //Set the images new width and height
        elem.style.width = newW.toString() + "px";
        elem.style.height = newH.toString() + "px";
        //Make it visible in case it is not
        elem.style.visibility = "visible";

    },
    //Function scales an elements position( saves original position to array )
    position: function(id) {
        //Get images original width and height
        var elem = document.getElementById(id);
        if (elem.offsetTop) elemTop = elem.offsetTop;
        if (elem.offsetLeft) elemLeft = elem.offsetLeft;
        //Set the original height and width to the images object, if not set
        if (!positions[id + 'T']) {
            positions[id + 'T'] = elemTop.toString();
            positions[id + 'L'] = elemLeft.toString();
        }
        //Scale it
        var oT = positions[id + 'T'];
        var oL = positions[id + 'L'];
        var newT = parseInt(oT / 1000 * scale.height());
        var newL = parseInt(oL / maxS * scale.width());
        //Set the images new width and height
        elem.style.top = newT.toString() + "px";
        elem.style.left = newL.toString() + "px";
    }
};
//Twinkly stars function
function stars(id) {

    //Get the element to put all the stars in
    var space = document.getElementById(id);
    //Get the available size of the starfield
    var sFW = space.offsetWidth - 2;
    var sFH = space.offsetHeight - 2;
    //Number of Stars( more than 300 starts to cause issues )
    var nS = 90;
    //twinkle rate
    var tR = 2500;
    //Create random initial positions for the stars within the starfield
    for (var i = 0; i < nS; ++i) {
        var xP = Math.floor(Math.random() * sFW);
        var yP = Math.floor(Math.random() * sFH);
        //Add the new positions to the arrays
        starX.push(xP);
        starY.push(yP);
    }
    //Holds a new star div object and its id
    var id;
    //Create the requested number of stars
    for (var i = 0; i < nS; ++i) {
        //Generate a unique id for the new star div element
        id = "star" + i;
        //Add each new star to the passed div element
        space.innerHTML += "<div id='"+id+"' style='border-top: 1px solid #ffffff; position: absolute; top: " + starY[i].toString() + "px; left: " + starX[i].toString() + "px; width: 1px; height; 1px; ' ></div>";
        //Set the stars visibility
         starVis[i] = true;     
        //Set a random flash rate for the star
        var rT = Math.floor(Math.random() * tR) + 500;
        if (i % 5 == 0) {
            window.setInterval("twinkle( '" + id + "' );", rT);
        }
    }
};
function twinkle(id) {
    //Move chance 0 -100
    var mC = 40;
    //Get the star by id
    var star = document.getElementById(id);
    //Get the star number
    starNum = parseInt(id.substring(4, 9));
    //Get the stars visibility
    var visible = starVis[starNum];
    //Change the stars visibility
    if (visible) {
        star.style.visibility = "hidden";
        starVis[starNum] = false;
    }
    else {
        star.style.visibility = "visible";
        starVis[starNum] = true;
    }
    //While its hidden, maybe move it somewhere else
    var move = Math.floor(Math.random() * mC);
    if (move < 1 && visible) {
    //Find the parent width and height
    //get a new random position within the cockpit window height 
    var xP = Math.floor(Math.random() * scale.width());
    var yP = Math.floor(Math.random() * (scale.height() - scale.height() / 30));
    //Assign the new position
    star.style.top = yP.toString() + "px";
    star.style.left = xP.toString() + "px";
    }
}

// Function to identify the spaceship controls when touched
function usingControl(evt) {
    var msDwn = ((evt) ? evt : ((window.event) ? window.event : null));
    var id = ((msDwn.target) ? msDwn.target.id : ((msDwn.srcElement) ? msDwn.srcElement.id : null));
    if (id.indexOf('stick') != -1) {
        control = document.getElementById(id);
        contId = "stick";
    }
    else if (id.indexOf('throttle') != -1) {
        control = document.getElementById(id);
        contId = "throttle";
    }
    if (control) {
        if (evt.clientX) {
            cX = evt.clientX;
            cY = evt.clientY;
        }
        else if (evt.pageX) {
            cX = evt.pageX;
            cY = evt.pageY;
        }
         return false;
    }
    else {
        control = null;
        contId = null;
        return false;
    }
}
//Function defines the range of motion and image changes for each control
function inControl(evt) {
    var msMove = (evt) ? evt : ((window.event) ? window.event : null);
    var lcd1 = document.getElementById("lcd1");
    var lcd2 = document.getElementById("lcd2");

    // The throttle control definition ( controls the speed of selected engine )
    if (control && contId == "throttle") {
        control.style.cursor = "pointer";
        lcd1.innerHTML = "Engine Power";
        var tInd = document.getElementById("throtInd");
        var oT = positions["throttle" + 'T'];
        var oL = positions["throttle" + 'L'];
        var newT = parseInt(oT / 1000 * scale.height());
        var newL = parseInt(oL / maxS * scale.width());
        var newH = parseInt(115 / 1000 * scale.height());
        var newW = parseInt(40 / maxS * scale.width())
        var rng = parseInt(newH / 5);
        var rngY;
        (msMove.clientY) ? rngY = msMove.clientY - (control.offsetTop + 16) : rngY = msMove.pageY - (control.offsetTop + 16);
        var newY = (control.offsetTop + parseInt(rngY));
        var newX = newL + Math.abs(parseInt((newT - newY) * newW / newH));
        var power = ((newT - control.offsetTop) * 1000);
        if (power == 58000) power = "Maximum  Power";
        if (power == 0) power = "Power is Off";
        lcd2.innerHTML = power;
        if (newY >= newT) {
            newY = newT;
            newX = newL;
        }
        if (newY <= (newT - newH)) {
            newY = (newT - newH);
            newX = newL + newW;
        }
        control.style.left = newX + "px";
        control.style.top = newY + "px";
        if (newY >= (newT - newH) && newY < (newT - newH + rng)) {
            tP = 16;
            tInd.src = "images/throttleIndMax.gif";
        }
        else if (newY >= (newT - newH + rng) && newY < (newT - newH + 2 * rng)) {
            tP = 8;
            tInd.src = "images/throttleInd4.gif";
        }
        else if (newY >= (newT - newH + 2 * rng) && newY < (newT - newH + 3 * rng)) {
            tP = 4;
            tInd.src = "images/throttleInd3.gif";
        }
        else if (newY >= (newT - newH + 3 * rng) && newY < (newT - newH + 4 * rng)) {
            tP = 2;
            tInd.src = "images/throttleInd2.gif";
        }
        else if (newY >= (newT - newH + 4 * rng) && newY < (newT - 5)) {
            tP = 1;
            tInd.src = "images/throttleInd1.gif";
        }
        else if (newY >= (newT - 5)) {
            tP = 0;
            tInd.src = "images/throttleIndMin.gif";
        }
        return true;
    }
    //The control stick definition ( controls background scrolling )
    else if (control && contId == "stick") {
    control.style.cursor = "pointer";
    lcd1.innerHTML = "Manual Control";
        var rngY;
        (msMove.clientY) ? rngY = parseInt(msMove.clientY - cY) : rngY = parseInt(msMove.pageY - cY);
        var rngX;
        (msMove.clientX) ? rngX = parseInt(msMove.clientX - cX) : rngX = parseInt(msMove.pageX - cX);
        var oT = positions["stick" + 'T'];
        var oL = positions["stick" + 'L'];
        var newT = parseInt(oT / 1000 * scale.height());
        var newL = parseInt(oL / maxS * scale.width());
        var newH = parseInt(40 / 1000 / 2 * scale.height());
        var newW = parseInt(40 / maxS / 2 * scale.width());
        if (newH < 10 || newW < 10) {
            newH = 10;
            newW = 10;
        }
        var newY = newT + parseInt(rngY);
        var newX = newL + parseInt(rngX);
        if (newY >= newT + newH) {
            newY = newT + newH;
        }
        else if (newY <= (newT - newH)) {
            newY = (newT - newH);
        }
        if (newX >= newL + newW) {
            newX = newL + newW;
        }
        else if (newX <= newL - newW) {
            newX = newL - newW;
        }
        lcd2.innerHTML = "Thrust: " + ((newT - newY) * tP * 1000) + " kgs";
        control.src = "images/stick2.gif";
        control.style.left = newX + "px";
        control.style.top = newY + "px";
        if (newX < (newL - 5)) {
            sSX = "left";
        }
        else if (newX > (newL + 5)) {
            sSX = "right";
        }
        else sSX = "";
        if (newY < (newT - 5)) {
            sSY = "down";
        }
        else if (newY > (newT + 5)) {
            sSY = "up";
        }
        else sSY = "";
        if (drive) window.clearInterval(drive);
        drive = window.setInterval("moveSpaceship();", 100);
        return false;
    }
    else {
        return false;
    }
}
//Releases control back to the spaceship autopilot
function autopilot() {
    var lcd1 = document.getElementById("lcd1");
    var lcd2 = document.getElementById("lcd2");
    if (drive) {
        window.clearInterval(drive);
        drive = null;
    }
    if (control) {
        control.style.cursor = "default";
        if (contId == "stick") {
            scale.position("stick");
            control.src = "images/stick.gif"
            sSY = "";
            sSX = "";
            lcd1.innerHTML = "Holding Position";
            lcd2.innerHTML = "Engines on Standby";
        }
        control = null;
        contId = null;
        return false;
    }
}
//Adjusts the altitude if the user srolls and displays the new altitude and heading
function setAltitude() {
    //Get the maximum ranges allowed
    var bottom = maxH - document.getElementById("cockpit").offsetHeight;
    var right = maxS - document.getElementById("cockpit").offsetWidth;
    //Which display to use
    var lcd4 = document.getElementById("lcd4");
    //The correct way to get scroll position
    var top = document.body.scrollTop;
    //May be false if it is a master page, why???
    if (top == 0) {
        // WTF is pageYOffset?? Stupid Mozilla
        if (window.pageYOffset) top = window.pageYOffset;
        //Last resort full DOM search for scroll position
        else top = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
    }
    //The correct way to get scroll position
    var left = document.body.scrollLeft;
    //May be false if it is a master page, why???
    if (left == 0) {
        // WTF is pageXOffset?? Stupid Mozilla
        if (window.pageYOffset) Left = window.pageXOffset;
        //Last resort full DOM search for scroll position
        else left = (document.body.parentElement) ? document.body.parentElement.scrollLeft : 0;
    }
    //This sets the sltitude if the user is scrolling without the control
    if (sY != top) sY = top;
    if (sX != left) sX = left;
    //Calculate the altitude
    var alt = parseInt(bottom - sY);
    //Check if ship is on the ground, if so display on ground
    if (sY >= bottom) {
        sY = bottom;
        alt = "On Ground";
    }
    //Check if at the maximum altitude/ top of screen
    else if (sY < 0) sY = 0;
    //Otherwise calculate a exponential altitude reading
    else {
        if (alt != "On Ground" && alt > 1000) alt += (alt - 1000) * 10;
        if (alt != "On Ground" && alt > 20000) alt += (alt - 20000) * 10;
    }
    //Checks for maxim left right ranges
    if (sX > right) sX = right;
    else if (sX < 0) sX = 0;
    //Calculate a heading
    var heading = parseInt(sX * 360 / right);
    //Display the altitude and heading
    lcd4.innerHTML = "Altitude: " + alt + "<br/>Heading: " + heading;
}
//Moves the background, which is visible through the viewport, making the spaceship "move"
function moveSpaceship() {
    var bottom = maxH - document.getElementById("cockpit").offsetHeight;
    var right = maxS - document.getElementById("cockpit").offsetWidth;
    var lcd3 = document.getElementById("lcd3");
    if (sSX && sSX == "left") {
        sX -= tP * tP;
    }
    else if (sSX && sSX == "right") {
        sX += tP * tP;
    }
    if (sSY && sSY == "down") {
        sY += tP * tP;
    }
    else if (sSY && sSY == "up") {
        sY -= tP * tP;
    }
    if (sY >= bottom) {
        sY = bottom;
    }
    else if (sY < 0) sY = 0;
    else {
        var alt = parseInt(bottom - sY);
        if (alt > 1000) alt += (alt - 1000) * 10;
        if (alt > 20000) alt += (alt - 20000) * 10;
    }
    if (sX > right) sX = right;
    else if (sX < 0) sX = 0;
    if (document.body.scrollLeft) {
        document.body.scrollLeft = sX;
        document.body.scrollTop = sY;
    }
    else {
        scrollTo(sX, sY);
    }
    if (!firstRun) setAltitude();
    firstRun = false;
}
function showMsgs(id) {
    // If a cued message and not one already displaying
    if (msgCue && msgCue.length > 0 && !timedMsg) {
        // Get the div to display the messages in
        var resBox = document.getElementById(id);
        // Get a message to display
        var msg = msgCue.shift();
        // Display the message to the div
        resBox.innerHTML = msg;
        // So we know there is an active message displaying
        timedMsg = true;
        // Check for another message when the time runs out
        window.setTimeout("nextMsg( '" + id + "' );", 420);
    }
}
//Function shows the next message because the last one is done
function nextMsg(id) {
    timedMsg = false;
    showMsgs(id);                       //Check cue for more messages
}
//Display a bunch of messages
function useLCD4() {
    msgCue.push("Systems Check");
    msgCue.push("Initializing");
    msgCue.push("Initializing.");
    msgCue.push("Initializing..");
    msgCue.push("Initializing...");
    msgCue.push("Computer Test --- OK");
    msgCue.push("Fuel Cell ------- OK");
    msgCue.push("Reserve Power --- OK");
    msgCue.push("Navigation ------ OK");
    msgCue.push("Life Support ---- OK");
    msgCue.push("Cooling System -- OK");
    msgCue.push("Hydraulics ------ OK");
    msgCue.push("Communications -- OK");
    msgCue.push("Engine systems -- OK");
    msgCue.push("Field Level ----- OK");
    msgCue.push("All Systems Go<br/>Propulsion System Go");
    showMsgs("lcd4");
}
function useLCD3() {
    msgCue.push("Starting Systems");
    msgCue.push("Backup Power - 28%");
    msgCue.push("Backup Power - 60%");
    msgCue.push("Backup Power - 86%");
    msgCue.push("Backup Power Charged");
    msgCue.push("Secondary Power - 34%");
    msgCue.push("Secondary Power - 64%");
    msgCue.push("Secondary Power - 90%");
    msgCue.push("Secondary Power Charged");
    msgCue.push("Primary Power - 44%");
    msgCue.push("Primary Power - 68%");
    msgCue.push("Primary Power - 92%");
    msgCue.push("Primary Power Charged");
    msgCue.push("Primary - 100%<br/>Secondary - 100%");
    showMsgs("lcd3");
}

//Function to turn the background sound on or off
function toggleSound() {
    var soundBox = document.getElementById("sound");
    var buttonsBox = document.getElementById("buttons");
    if (!bgsound) {
        soundBox.innerHTML = '<embed src="sounds/bgSound1.wav" autostart="true" loop="true" width="2px" height="0px" ></embed>';
        buttonsBox.style.color = "#0f0";
        buttonsBox.innerHTML = "Sound<br/>OFF";
        bgsound = true;
    }
    else {
        soundBox.innerHTML = "&nbsp";
        buttonsBox.style.color = "#090";
        buttonsBox.innerHTML = "Sound<br/>ON";
        bgsound = false;
    }
}

//Function chooses a player to play the sound
function getMimeType() {
    var mimeType = "application/x-mplayer2"; //default
    var agt = navigator.userAgent.toLowerCase();
    if (navigator.mimeTypes && agt.indexOf("windows") == -1) {
        //non-IE, no-Windows
        var plugin = navigator.mimeTypes["audio/mpeg"].enabledPlugin;
        if (plugin) mimeType = "audio/mpeg";  //Mac/Safari & Linux/FFox
    }
    return mimeType;
}
//Script all loaded so run it when the window is done loading
window.onload = initialize;