
//nimiavaruus
TDEMO = {
  audioStatus : false,
  inited : false
};

//aloitetaan demo, kun kaikki alustustoimenpiteet
//on varmasti suoritettu
var allLoaded = function(){
  if(TDEMO.audioStatus && TDEMO.inited){
    TDEMO.mainloop();
  }
};

var audioReady = function(){
  TDEMO.audioStatus = true;
  TDEMO.audio = document.getElementById("audio");
  allLoaded();
};

//alustusfunktio, joka luo juttuja nimiavaruuteen.
var init = function(){  

  TDEMO.width = screen.width;
  TDEMO.height = screen.height;
  
  //alustetaan renderer
  TDEMO.renderer = new THREE.WebGLRenderer();
  TDEMO.renderer.setSize(TDEMO.width, TDEMO.height);
  TDEMO.renderer.setClearColor(0x000012);
  
  TDEMO.renderer.domElement.style.width = TDEMO.width;
  TDEMO.renderer.domElement.style.height = TDEMO.height;
  document.getElementById("demo").appendChild(TDEMO.renderer.domElement);
  
  //ajastus ja parttien vaihto
  TDEMO.currentPart = 0;
  TDEMO.nextPart = 1;
  
  TDEMO.frameCount = 0;
  TDEMO.timeElapsed = 0;
  
  TDEMO.bpm = 125;
  //seconds per beat (beattien välinen aika sekunteina)
  //n. 0,48s
  TDEMO.spb = (1/(125/60));
  
  TDEMO.audio_duration = 164.56;
  
  //Tähän luodaan partit
  TDEMO.parts = [
    //duration, start time, end time
    //in seconds!
    new Text(27.84, 0, 27.84),
    new Tunneli(40.32, 27.84, 68.16),
    new Snowflake(32.16, 68.16, 100.32),
    new Peili(26.88, 100.32, 127.2),
    new Tree(17.76, 127.2, 145.44),
    new End(20.12, 145.44, TDEMO.audio_duration)
  ];
  
  //alustetaan partit
  for(var i = 0; i < TDEMO.parts.length; ++i){
    //tässä kutsutaan partin alustusfunktiota, joka
    //luo partin scenen
    TDEMO.parts[i].initScene();
  }
  
  TDEMO.started = false;
  TDEMO.mainloop = function(){

    if(!TDEMO.started){
      TDEMO.started = true;
      TDEMO.audio.play();
    }
    
    TDEMO.timeElapsed = TDEMO.audio.currentTime;
    ++TDEMO.frameCount;
    
    //partin vaihto
    if(TDEMO.timeElapsed >= TDEMO.parts[TDEMO.currentPart].endTime && TDEMO.nextPart < TDEMO.parts.length){
      TDEMO.parts[TDEMO.nextPart].prepare(TDEMO.timeElapsed);
      
      TDEMO.currentPart = TDEMO.nextPart;
      ++TDEMO.nextPart;
    }
    
    TDEMO.parts[TDEMO.currentPart].animate(TDEMO.timeElapsed);
    TDEMO.parts[TDEMO.currentPart].render(TDEMO.timeElapsed);
    
    if(TDEMO.timeElapsed < TDEMO.audio_duration){
      requestAnimationFrame(TDEMO.mainloop);
    }
    else{
      cancelAnimationFrame(TDEMO.mainloop);
      TDEMO.renderer.domElement.style.display = "none";
      document.getElementById("credits").style.display = "block";
    }
    
    
  }
  
  //alustus on tehty, kutsutaan tarkastusfunktiota
  TDEMO.inited = true;
  allLoaded();
}