
// The game Version:
var moonLanderVersion = 0.2;

// Set default interface language:
var lang = "pt-br";

// If an inteface string change, this number will change:
var I18N_VERSION = 0.1;

/* Sequence:
** onload event on moon-lander.svg call init()
** init() call loadL10N()
** loadL10N() create an XMLHttpRequest object
** the onreadystatechange event on XMLHttpRequest call l10nLoaded()
** l10nLoaded() call init_b()
** init_b() enable the user to click to start the game
*/

var xmlhttp;
function loadL10N(){
  try {
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "l10n_"+ lang +".xml", true);
    xmlhttp.onreadystatechange = l10nLoaded;
    xmlhttp.send(null)
  }
  catch(e) {
    alert('loadL10N()\n\n'+
          'Something not cool happens while trying to load the l10n file to "'+
          lang +'".\n\n'+ e );
  }
}

var l10nXML;  // it will be loaded...
var l10nIsLoaded = false;
function l10nLoaded(){
  try {
    if ( xmlhttp.readyState == 4 ) {
      l10nXML = xmlhttp.responseXML.documentElement;
      l10nIsLoaded = true;
      L10N_VERSION = l10nXML.getElementsByTagName("l10n_version")[0].textContent;
      if ( L10N_VERSION != I18N_VERSION ) {
        alert( 'The localization file for "'+ lang  +
               '" has a not expected version value.'+
               '\nIt must be "'+ I18N_VERSION +'".' );
      }
      init_b();
    }
  }
  catch(e) {
    alert('l10nLoaded()\n\n'+
          'Something not cool happens while trying to load the l10n file to "'+
          lang +'".\n\n'+ e );
  }
}

function trim(str){
  return str.replace( /^[\s\t\n\r]*|[\s\t\n\r]*$/g, '' );
}

function i18n(id){
  var msgs = l10nXML.getElementsByTagName("msg");
  for ( var i=0; i<msgs.length; i++ ) {
    if ( trim(msgs[i].getElementsByTagName("id")[0].textContent) == trim(id) ) {
      var str = msgs[i].getElementsByTagName("str")[0].textContent;
    }
  }
  return str;
}

function listObjProps(obj){
  // This function helps developers to know the object properties
  var props = typeof(obj) +" : "+ obj +"\n";
  for ( var i in obj ) {
    props += "\n"+ i +" : ";
    try{
      props += obj[i];
    } catch(e) {
      props += e;
    }
  }
  var j = window.open("","_blank","width=500,height=550,scrollbars=1");
  j.document.write( "<pre>"+ props.replace(/</g, "&lt;") +"</pre>" );
  j.document.close();
}

function roundStr(num, decs){
  var mult = 1;
  for ( var i=0; i<decs; i++) {
    mult *= 10;
  }
  num = new String( Math.round( num * mult ) / mult );
  var dec = num.replace( /-?[0-9]*\.?([0-9]*)/, "$1" );
  if ( dec.length == 0  &&  decs > 0 ) { num += "."; }
  //alert( "num:"+ num +" dec:"+ dec +" mult"+ mult )
  if ( dec.length < decs ) {
    for ( var i=dec.length; i<decs; i++) {
      num += "0";
    }
  }
  return num
}

var svg;
var radiano = 180 / Math.PI;
var PI_divided_by_180 = Math.PI / 180;

function init(){
  loadL10N();
}

function init_b(){
  // This will realy init the game interface, but only after the l10nLoaded function.
  svg = window.document.getElementsByTagName("svg")[0];
  svg.w = svg.width.baseVal.value;
  svg.h = svg.height.baseVal.value;

  svg.info = {
    fps    : window.document.getElementById("info_fps"),
    fuel   : window.document.getElementById("info_fuel"),
    height : window.document.getElementById("info_height"),
    speed  : window.document.getElementById("info_speed")
  };
  
  // Set random position for the hangar:
  svg.hangar = window.document.getElementById("hangarGroup");
  svg.hangar.base = window.document.getElementById("hangar");
  svg.hangar.angle = Math.random() * 360;
  svg.hangar.transform.baseVal.getItem("matrix").setRotate( svg.hangar.angle, svg.w/2, svg.h/2 );
  
  svg.stars = {
    1 : window.document.getElementById("star1"),
    2 : window.document.getElementById("star2"),
    3 : window.document.getElementById("star3"),
    4 : window.document.getElementById("star4"),
    5 : window.document.getElementById("star5"),
    6 : window.document.getElementById("star6"),
    7 : window.document.getElementById("star7")
  };
  svg.stars.blink = function(star, opacity, inc){
    if ( star == 0 ) {
      star = Math.round( Math.random() * 6 ) + 1;
      opacity = 1;
      inc = -0.075;
    } else {
      if ( opacity < 0.3 ) {
        inc = 0.075;
      }
    }
    opacity += inc;
    if ( opacity > 1 ) { opacity = 1; }
    this[star].style.opacity = opacity;
    if ( opacity < 1 ) {
      setTimeout( "svg.stars.blink("+star+","+opacity+","+inc+");", 40 );
    }
  }
  
  // Make an easy way to get the moon properties:
  svg.moon = window.document.getElementById("moon");
  svg.moon.gradient = window.document.getElementById("moonGradient");
  svg.moon.gradient.matrix = svg.moon.gradient.gradientTransform.baseVal.getItem("matrix");
  svg.moon.matrix = svg.moon.transform.baseVal.getItem("matrix");
  
  svg.moon.rotate = function(){
    if ( this.gradient.matrix.angle == 360 ) {
      this.gradient.matrix.setRotate( 0 , svg.w/2, svg.h/2 );
    }
    this.gradient.matrix.setRotate( this.gradient.matrix.angle + 0.4 , svg.w/2, svg.h/2 );
    
    if ( this.matrix.angle == 0 ) {
      this.matrix.setRotate( 360 , svg.w/2, svg.h/2 );
    }
    this.matrix.setRotate( this.matrix.angle - 0.4 , svg.w/2, svg.h/2 );
  }
  
  // Make an easy way to get the nave properties:
  svg.nave = window.document.getElementById("nave");
  // Nave fire propellant:
  svg.nave.fireLeft   = window.document.getElementById("fireLeft");
  svg.nave.fireRight  = window.document.getElementById("fireRight");
  svg.nave.fireBottom = window.document.getElementById("fireBottom");
  // The base matrix to transform the nave SVG element:
  svg.nave.iniMatrix = svg.nave.transform.baseVal.getConsolidationMatrix();
  // The SVGTransform object from nave to set the transformation:
  svg.nave.matrix = svg.nave.transform.baseVal.getItem("matrix");
  // Manange Fuel:
  svg.nave.fuel = 600;
  // Helps to remember the actual angle:
  svg.nave.angle = 0;
  // Helps to remember the velocity vector:
  svg.nave.incX = 0;
  svg.nave.incY = 0;
  // Helps to remember the nave position:
  svg.nave.x = ( svg.w / 4 ) + ( Math.random() * ( svg.w / 4 ) );
  svg.nave.y = 30;
  svg.nave.fps = 0;
  svg.nave.fpsDateIni = 0;
  svg.nave.fpsFames = 1;

  svg.nave.move = function(){
    if ( this.fpsFames < 5 ) {
      this.fpsFames++
    } else {
      this.fpsFames = 1;
      this.fps = 5000 / new Date( (new Date()) - this.fpsDateIni ).getTime();
      this.fpsDateIni = new Date();
    }
    // Gravity:
    this.difX = (svg.w/2) - this.x;  // distancia horizontal do centro
    this.difY = (svg.h/2) - this.y;  // distancia vertical do centro
    this.dist = Math.sqrt( this.difX*this.difX + this.difY*this.difY );
    this.incX += this.difX / this.dist;  // add gravity X vector
    this.incY += this.difY / this.dist;  // add gravity Y vector
    this.x += this.incX * 0.3;
    this.y += this.incY * 0.3;
    this.angle = ( Math.atan2( this.difY, this.difX ) * radiano ) - 90;
    this.matrix.setMatrix(
        this.iniMatrix.translate( this.x, this.y ).rotate( this.angle )
      );
    if ( this.dist < 110 ) {
      this.dist = 110;
      clearInterval( svg.nave.moveInterval );
      svg.nave.boom();
    }
    svg.info.fps.textContent    = roundStr(this.fps, 2);
    svg.info.fuel.textContent   = roundStr(this.fuel, 2) +" l";
    svg.info.height.textContent = roundStr( this.dist-110, 2 ) +" u";
    var speed = Math.sqrt( this.incX*this.incX + this.incY*this.incY );
    svg.info.speed.textContent  = roundStr(speed, 2) +" u/s";
    if ( speed > 5 ) {
      svg.info.speed.style.setProperty( "fill", "#F80000", "important" );
    } else {
      svg.info.speed.style.removeProperty( "fill" );
    }
  }
  svg.nave.move();  // only to put on the start position and the initial values
  
  svg.nave.boom = function(){
    alert("Boom!");
    setTimeout('window.document.getElementById("boardRestart").style.visibility = "visible"',
               1000);
  }
  
  svg.onkeypress = function(e){
    switch( e.keyCode ) {
      case e.DOM_VK_LEFT :
        svg.nave.incY += -Math.sin( svg.nave.angle * PI_divided_by_180 );
        svg.nave.incX += -Math.cos( svg.nave.angle * PI_divided_by_180 );
        svg.nave.fireRight.style.visibility = "visible";
        setTimeout( "svg.nave.fireRight.style.visibility = 'hidden'", 50 );
        svg.nave.fuel -= 0.6;
        break;
      case e.DOM_VK_RIGHT :
        svg.nave.incY += Math.sin( svg.nave.angle * PI_divided_by_180 );
        svg.nave.incX += Math.cos( svg.nave.angle * PI_divided_by_180 );
        svg.nave.fireLeft.style.visibility = "visible";
        setTimeout( "svg.nave.fireLeft.style.visibility = 'hidden'", 50 );
        svg.nave.fuel -= 0.6;
        break;
      case e.DOM_VK_UP :
        svg.nave.incY += Math.sin( (svg.nave.angle - 90) * PI_divided_by_180 );
        svg.nave.incX += Math.cos( (svg.nave.angle - 90) * PI_divided_by_180 );
        svg.nave.fireBottom.style.visibility = "visible";
        setTimeout( "svg.nave.fireBottom.style.visibility = 'hidden'", 50 );
        svg.nave.fuel -= 2;
        break;
    }
    return false;
  }
  
  window.document.getElementById("textStartGame").textContent = i18n("Start Game");
  window.document.getElementById("textRestartGame").textContent = i18n("Restart Game");
  window.document.getElementById("textYouDied").textContent = i18n("You Died... :-(");
  window.document.getElementById("infoName_fuel").textContent = i18n("Fuel:");
  window.document.getElementById("infoName_height").textContent = i18n("Height:");
  window.document.getElementById("infoName_speed").textContent = i18n("Speed:");
  
  setInterval( "svg.stars.blink(0)", 7000 );
  setInterval( "svg.moon.rotate()", 300 );

}

function startGame(restart){
  if (restart) {
    svg.nave.incX = 0;
    svg.nave.incY = 0;
    svg.nave.x = ( svg.w / 4 ) + ( Math.random() * ( svg.w / 4 ) );
    svg.nave.y = 30;
    svg.nave.fuel = 600;
  }
  window.document.getElementById("boardStart").style.visibility = "hidden";
  window.document.getElementById("boardRestart").style.visibility = "hidden";
  svg.nave.moveInterval = setInterval( "svg.nave.move()", 50 );
}

function openConfig(){
  window.open("config.xml", "moon-lander-config",
              "width=300,height=300,screenX="+((screen.width/2)-150)+",screenY="+((screen.height/2)-200));
}

