// 8bit.js https://github.com/meenie/8bit.js
// arrangement via http://herbalcell.com/static/sheets/legend-of-zelda/overworld-labels.pdf
var music = new BandJS();
music.load = function(json) {
    if (! json) {
        throw new Error('JSON is required for this method to work.');
    }
    // Need to have at least instruments and notes
    if (typeof json['instruments'] === 'undefined') {
        throw new Error('You must define at least one instrument');
    }
    if (typeof json['notes'] === 'undefined') {
        throw new Error('You must define notes for each instrument');
    }
    // Shall we set a time signature?
    if (typeof json['timeSignature'] !== 'undefined') {
        this.setTimeSignature(json['timeSignature'][0], json['timeSignature'][1]);
    }
    // Maybe some tempo?
    if (typeof json['tempo'] !== 'undefined') {
        this.setTempo(json['tempo']);
    }
    // Lets create some instruments
    var instrumentList = {};
    for (var instrument in json['instruments']) {
        if (! json['instruments'].hasOwnProperty(instrument)) {
            continue;
        }
        instrumentList[instrument] = this.createInstrument(
            json['instruments'][instrument].name,
            json['instruments'][instrument].pack
        );
    }
    // Now lets add in each of the notes
    var measureDuration;
    console.log(this.dottedEighth);
    for (var instrument in json['notes']) {
        if (! json['notes'].hasOwnProperty(instrument)) {
            continue;
        }
        json['notes'][instrument].forEach(function(note) {
            note.forEach(function(measure) {
                if (measure.length === 1) {
                    instrumentList[instrument].rest(measure[0]);
                }
                else {
                    instrumentList[instrument].note(measure[0], measure[1], measure[2]);
                }
            });
        });
        instrumentList[instrument].finish();
    }
    this.end();
};
music.load(musicjson);
music.end();
music.onFinished(function() {
    playing = false;
    enablePlay();
});
function enablePlay() {
    playButton.disabled = false;
    pauseButton.disabled = true;
    stopButton.disabled = true;
}
function playZelda() {
    playButton.disabled = true;
    pauseButton.disabled = false;
    stopButton.disabled = false;
    music.play();
    playing = true;
}
function pauseZelda() {
    if (playing) {
        music.pause();
        playing = false;
    }
    else {
        music.play();
        playing = true;
    }
}
function stopZelda() {
    music.stop();
    playing = false;
    enablePlay();
}
var playButton = document.getElementById("playButton"),
    pauseButton = document.getElementById("pauseButton"),
    stopButton = document.getElementById("stopButton"),
    playing = false;
playButton.onclick = playZelda;
pauseButton.onclick = pauseZelda;
stopButton.onclick = stopZelda;