// mog
/*jslint devel: true, browser: true */
var Demo = (function () {
    "use strict";

    var _audio, _sceneList;

    function keyHandler(event) {

        var SPACEBAR = 32,
            ESC = 27,
            M = 77;

        switch (event.keyCode) {

            case SPACEBAR:
                sync();
                break;

            case ESC:
                togglePause();
                break;

            case M:
                toggleMute();
                break;
        }
    }

    function toggleMute() {

        if(_audio.volume() <= 0)
            _audio.volume(.5);
        else
            _audio.volume(0);
    }

    function togglePause() {

        if (_audio.isPaused()) {
            _audio.play();
            window.requestAnimationFrame(loop, document);
        } else {
            _audio.pause();
        }
    }

    function sync() {

        var currentBeat = _audio.position() * _audio.bpm() / 60;
        console.log('[Beat] ', Math.round(currentBeat * 100) / 100, _audio.position());
    }

    function getAudio() {
        return _audio;
    }

    function getSceneList() {
        return _sceneList.getList();
    }

    function loop() {

        var position = _audio.position();

        if(position < _audio.duration()) {

            if (!_audio.isPaused()) {
                window.requestAnimationFrame(loop, document);
            }

            _sceneList.update(position);
        }
    }

    function onAudioReady() {

        //nuke callback
        _audio.onPlay(null);

        //TODO given in seconds atm, might change that to ms too
        _audio.position(0);

        _audio.volume(1);

        loop();
    }

    function initScenes() {

        _sceneList = SceneList();

        _sceneList.add(Intro, 0, 14000);

        _sceneList.add(Looping, 14000, 41000);

        _sceneList.add(IntoSpace, 41000, 63000);

        _sceneList.add(Space, 63000, 97400);

        _sceneList.add(Greetings, 97400, 145000);
    }

    function initAudio() {

        _audio = Audio();

        _audio.bpm(128);

        _audio.create('data/jpb-demo.ogg');

        _audio.onPlay(onAudioReady);
    }

    function start() {

        document.getElementById('root').onkeydown = keyHandler;

        initAudio();

        initScenes();

        _audio.play();
    }

    return {
        start:start,
        audio:getAudio,
        sceneList:getSceneList
    };
}());