//-----------------------------------------------------
// Nimiavaruus
//-----------------------------------------------------
TDEMO = {
    audioStatus : false,
    videoStatuses : [false, false],
    inited : false,
    user : false,
    sync : false,
    started : false,

    //ajastus ja parttien vaihto
    timeElapsed : 0,
    timeHelper : 0, // In case of no audio

    brightnessVal : 0.0,
    
    partIndex : 0,
    
    width : 0,
    height : 0,
    minx : 0,
    maxx : 0,
    miny : 0,
    maxy : 0,

    //some camera parameters
    fov: 55,
    near : 0.2,
    far : 800,
    aspect : 1,
  
    mainloop : function(){

        if(!TDEMO.started){
            TDEMO.started = true;
            TDEMO.mainPart.prepare(0);

            if(CONF.demomode) {
                TDEMO.audio.play();
            }
            else{
                TDEMO.audio.pause();
                TDEMO.audio.currentTime = CONF.row/CONF.rr;
            }
        }
        
        TDEMO.timeElapsed = TDEMO.audio.currentTime;
        if(!TDEMO.audio.paused) {
            //otherwise we may jump into a point in the audio where there's
            //no timeframe, resulting in Rocket setting row 2 and we report
            //row 1 back - thus Rocket spasming out
            CONF.row = TDEMO.timeElapsed * CONF.rr;

            // this informs Rocket where we are
            CONF.syncDevice.update(CONF.row);
        }
        
        var bright = (SYNC.brightness.getValue(CONF.row) || 0);
        TDEMO.colorcorrect.uniforms[ "brightness" ].value = bright;
        
        var negate = (SYNC.negate.getValue(CONF.row) || 0);
        TDEMO.colorcorrect.uniforms[ "negate" ].value = negate;
        
        var index = SYNC.part.getValue(CONF.row);
        if(index !== TDEMO.partIndex && index < TDEMO.parts.length && index >= 0){
            TDEMO.partIndex = index;
            TDEMO.mainPart.finish();
            TDEMO.mainPart = TDEMO.parts[TDEMO.partIndex];
            TDEMO.mainPart.prepare(TDEMO.timeElapsed);
        }
        
        var delta = TDEMO.clock.getDelta();
        TDEMO.mainPart.animate(TDEMO.timeElapsed, delta);
        
        TDEMO.renderer.clear();
        TDEMO.composer.render(delta);
        
        if(CONF.demomode || !TDEMO.audio.paused){            
            if(TDEMO.audio.ended && CONF.demomode){
                cancelAnimationFrame(TDEMO.mainloop);
            }
            else{
                requestAnimationFrame(TDEMO.mainloop);
            }
        }
        else{
            cancelAnimationFrame(TDEMO.mainloop);
        }
    }
  
};

//-----------------------------------------------------
// FUNKTIOT JOTKA ALOITTAA KAIKEN
//-----------------------------------------------------
//aloitetaan demo, kun kaikki alustustoimenpiteet
//on varmasti suoritettu
var allLoaded = function(){
    console.log("Audio: ", TDEMO.audioStatus, " Videos: ", TDEMO.videoStatuses[0], TDEMO.videoStatuses[1], " Init: ", TDEMO.inited, " Sync: ", TDEMO.sync, " User: ", TDEMO.user);
    if(TDEMO.audioStatus && TDEMO.videoStatuses[0] && TDEMO.videoStatuses[1] && TDEMO.inited && TDEMO.user && TDEMO.sync){
        document.getElementById("loader").style.display = "none";

        setTimeout(function(){
            TDEMO.mainloop();
        }, 1000);
    }
};

var audioReady = function(){
    if(!TDEMO.audioStatus){
        TDEMO.audioStatus = true;  
        allLoaded();
    }
};

var video1Ready = function(){
    if(!TDEMO.videoStatuses[0]){
        TDEMO.videoStatuses[0] = true;  
        allLoaded();
    }
};

var video2Ready = function(){
    if(!TDEMO.videoStatuses[1]){
        TDEMO.videoStatuses[1] = true;  
        allLoaded();
    }
};

var onResize = function(){
  var demoEl = document.getElementById("demo");
  demoEl.style.position = "absolute";
  demoEl.style.top = ((window.innerHeight-TDEMO.height)/2).toString() + "px";
  demoEl.style.left = ((window.innerWidth-TDEMO.width)/2).toString() + "px";
};

var start = function(){
  
  window.addEventListener("resize", onResize);
  
  document.getElementById("start").style.display = "none";
  document.getElementById("demo").style.display = "block";
  document.getElementById("demo").style.cursor="none";
  document.getElementById("loader").style.display = "block";
  init();
  initRocket();

  setTimeout(function(){
    TDEMO.user = true;
    allLoaded();
  }, 5000);
};

//-----------------------------------------------------

//-----------------------------------------------------
// Parttien luominen ja alustaminen.
//-----------------------------------------------------
var loadTextures = function(){
    var t = {};
    //THREE.ImageUtils.crossOrigin = true;
    
    TDEMO.TextureLoader = new THREE.TextureLoader();
    TDEMO.CubeLoader = new THREE.CubeTextureLoader();
    
    //Globe partin tekstuuri
    t.globe = TDEMO.TextureLoader.load(verkkosaari);
    t.globe.wrapS = THREE.MirroredRepeatWrapping;
    t.globe.wrapT = THREE.RepeatWrapping;
    t.globe.repeat.set(2,2);
    
    //Things partin midsphere tekstuuri
    t.midSphere = TDEMO.TextureLoader.load(verkkosaari);
    t.midSphere.wrapS = THREE.MirroredRepeatWrapping;
    t.midSphere.wrapT = THREE.RepeatWrapping;
    t.midSphere.repeat.set(4,4);
    
    //Things partin box tekstuuri
    t.box = TDEMO.TextureLoader.load(verkkosaari);
    t.box.wrapS = THREE.MirroredRepeatWrapping;
    t.box.wrapT = THREE.RepeatWrapping;
    t.box.repeat.set(4,4);
    
    //Things partin meri tekstuuri
    t.meri = TDEMO.TextureLoader.load(meri);
    t.meri.wrapS = THREE.MirroredRepeatWrapping;
    t.meri.wrapT = THREE.RepeatWrapping;
    t.meri.repeat.set(4,4);
    
    //Kissojen tekstuuri
    t.cat = TDEMO.TextureLoader.load(verkkosaari);
    t.cat.wrapS = THREE.MirroredRepeatWrapping;
    t.cat.wrapT = THREE.MirroredRepeatWrapping;
    t.cat.repeat.set(4,4);
    
    //Puu tekstuuri puu kuution käyttöön
    t.puukuutio = TDEMO.TextureLoader.load(puu);
    t.puukuutio.wrapS = THREE.MirroredRepeatWrapping;
    t.puukuutio.wrapT = THREE.MirroredRepeatWrapping;
    t.puukuutio.repeat.set(1,1);
    
    //Puu obj torni-tekstuuri
    t.torni = TDEMO.TextureLoader.load(torni);//THREE.ImageUtils.loadTexture(torni);
    t.torni.wrapS = THREE.MirroredRepeatWrapping;
    t.torni.wrapT = THREE.MirroredRepeatWrapping;
    t.torni.repeat.set(4,4);
    
    //Tunnelihahmo
    t.hahmo = TDEMO.TextureLoader.load(hahmo);
    t.hahmo.wrapS = THREE.RepeatWrapping;
    t.hahmo.wrapT = THREE.RepeatWrapping;
    t.hahmo.flipY = false;
    t.hahmo.repeat.set(40,1);
    
    //Tunneli sateenkaari
    t.rainbow = TDEMO.TextureLoader.load(raidat);
    t.rainbow.wrapS = THREE.RepeatWrapping;
    t.rainbow.wrapT = THREE.RepeatWrapping;
    t.rainbow.repeat.set(1,2);
    
    //Ihminen hahmo
    t.ihminen = TDEMO.TextureLoader.load(hahmo);
    t.ihminen.flipY = false;
    
    //Taivas
    t.taivas = TDEMO.TextureLoader.load(taivas_bw);
    t.taivas.wrapS = THREE.RepeatWrapping;
    t.taivas.wrapT = THREE.RepeatWrapping;
    t.taivas.repeat.set(4,1);
    
    //Environment tekstuuri...
    t.env_taivas = TDEMO.CubeLoader.load([
        taivas_bw, taivas_bw,
        taivas_bw, taivas_bw,
        taivas_bw, taivas_bw ]);
    t.env_taivas.mapping = THREE.CubeReflectionMapping;
    
    
    //Videotekstuurit
    t.tikkurila = new THREE.VideoTexture(document.getElementById( 'tikkurila' ));
    t.tikkurila.minFilter = THREE.LinearFilter;
    t.tikkurila.magFilter = THREE.LinearFilter;
    t.tikkurila.format = THREE.RGBFormat;

    t.bolzano = new THREE.VideoTexture(document.getElementById( 'bolzano' ));
    t.bolzano.minFilter = THREE.LinearFilter;
    t.bolzano.magFilter = THREE.LinearFilter;
    t.bolzano.format = THREE.RGBFormat;
    
    return t;
};

var initParts = function(){
    
    //Creating commons such as textures
    
    TDEMO.textures = loadTextures();
    TDEMO.heightGeometry = HeightField();
    
    
    TDEMO.parts = [
        new LightCloud(),//0
        new CubeScape(),//1
        new Tunnel(),//2
        new Globe(),//3
        new Things(),//4
        new Lentokentta(),//5
        new Spheres(),//6
        new Treecubes(),//7
        new Chaos(), //8
        new Human(), //9
        new ExplodingHeart() //10
    ];
    TDEMO.partIndex = 0;
    TDEMO.mainPart = TDEMO.parts[0];
};

//-----------------------------------------------------
// Alustaa renderöintiin liittyvät jutut
//-----------------------------------------------------
var init = function(){

    TDEMO.clock = new THREE.Clock();
    TDEMO.aspect = TDEMO.width/TDEMO.height;

    //some commonly used values
    TDEMO.minx = -TDEMO.width/2;
    TDEMO.maxx = TDEMO.width/2;
    TDEMO.miny = -TDEMO.height/2;
    TDEMO.maxy = TDEMO.height/2;

    //alustetaan renderer
    TDEMO.renderer = new THREE.WebGLRenderer();
    TDEMO.renderer.setPixelRatio(window.devicePixelRatio);
    TDEMO.renderer.setSize(TDEMO.width, TDEMO.height);
    TDEMO.renderer.setClearColor(0x000000);
    TDEMO.renderer.autoClear = false;
    //TDEMO.renderer.preserveDrawingBuffer = false;

    TDEMO.renderer.domElement.style.width = TDEMO.width;
    TDEMO.renderer.domElement.style.height = TDEMO.height;
    document.getElementById("demo").appendChild(TDEMO.renderer.domElement);
  
    //POSTPROCESSING PIPELINE
    //COMPOSER
    TDEMO.composer = new THREE.EffectComposer(TDEMO.renderer);
    //EFFECTS
    
    TDEMO.colorcorrect = new THREE.ShaderPass(THREE.ParaguayColorCorrect);
    TDEMO.colorcorrect.uniforms[ "brightness" ].value = -3.0;

    //THE LAST THING TO COMBINE ALL
    TDEMO.copyPass = new THREE.ShaderPass(THREE.CopyShader);
    TDEMO.copyPass.renderToScreen = true;

    TDEMO.composer.addPass(TDEMO.colorcorrect);
    TDEMO.composer.addPass(TDEMO.copyPass);
  
  initParts();
  
  //alustus on tehty, kutsutaan tarkastusfunktiota
  TDEMO.inited = true;
  allLoaded();
};

//-----------------------------------------------------
// Rockettiin liittyvät functiot ja alustus
//-----------------------------------------------------
function onSyncReady(){

    //SYNC objekti loytyy config.js:tiedostosta
    //JOS KAYTAT TESTISYNKKITRAKKIA VALITA PARAMETRI TRUE BINDILLE!!!
    SYNC.bindTracks(/*true*/);

    TDEMO.sync = true;
    allLoaded();
};

function onSyncUpdate(row){
    if (!isNaN(row)) {
        CONF.row = row;
    }
    TDEMO.mainloop();
};

function onPlay(){
    TDEMO.audio.currentTime = CONF.row / CONF.rr;
    TDEMO.audio.play();
    TDEMO.mainloop();
};

function onPause(){
    CONF.row = TDEMO.audio.currentTime * CONF.rr;
    window.cancelAnimationFrame(TDEMO.mainloop);
    TDEMO.audio.pause();
};

var initRocket = function(){
    if(CONF.demomode) {
        CONF.syncDevice.setConfig({'rocketXML':'revision16.rocket'});
        CONF.syncDevice.init("demo");
    } else {
        //CONF.syncDevice.setConfig({'socketURL':'ws://192.168.0.100:1338'});
        CONF.syncDevice.init();
    }

    CONF.syncDevice.on('ready', onSyncReady);
    CONF.syncDevice.on('update', onSyncUpdate);
    CONF.syncDevice.on('play', onPlay);
    CONF.syncDevice.on('pause', onPause);
};


var onLoad = function(){
    TDEMO.audio = document.createElement('audio');
    TDEMO.audio.id = "audio";
    TDEMO.audio.setAttribute('src', 'bin/rev16v1f.ogg');
    TDEMO.audio.load();
    TDEMO.audio.addEventListener("canplaythrough", audioReady);
    document.body.appendChild(TDEMO.audio);
    
    var v1 = document.createElement('video');
    v1.id = "tikkurila";
    v1.style.display = "none";
    v1.loop = true;
    v1.muted = true;
    v1.setAttribute('src', 'bin/videot/tikkurila.m4v');
    v1.load();
    v1.addEventListener("canplaythrough", video1Ready);
    document.body.appendChild(v1);
    
    var v2 = document.createElement('video');
    v2.id = "bolzano";
    v2.style.display = "none";
    v2.loop = true;
    v2.muted = true;
    v2.setAttribute('src', 'bin/videot/bolzano.m4v');
    v2.load();
    v2.addEventListener("canplaythrough", video2Ready);
    document.body.appendChild(v2);
    
    var startbtn = document.createElement("button");
    var t = document.createTextNode("START");
    startbtn.appendChild(t);
    startbtn.addEventListener("click", selectResolution);
    document.getElementById("start").appendChild(startbtn);
};