define(["util"], function(Util) {
    var MusicManager = {
        cues: [],
        elem: null,
        time: 0,


        init: function(onLoad) {
            var elem = document.createElement("audio");
            elem.preload = "auto";
            var load = onLoad;
            elem.addEventListener('canplaythrough', function() {
                console.log("HEYYY");
                load();
            });
            document.body.appendChild(elem);
            this.elem = elem;
        },

        /**
         * url: The URL of the music track.
         * tempo: The tempo of the track
         * syncOffset: The offset of the track (how many seconds into the track the 1st beat is)
         */
        load: function(url, onLoaded) {
            this.elem.src = url;
        },

        play: function() {
            this.elem.play();
        },

        cue: function(opts) {
            this.cues.push({
                time:  Util.beatsToTime(this.tempo, opts),
                callback: opts.callback
            });
        },

        update: function() {
            var time = this.elem.currentTime;
            for(var i in this.cues) {
                var cue = this.cues[i];
                if(cue.time <= time) {
                    cue.callback();
                    this.cues.splice(i, 1);
                }
            }

            return time;
        },
        
        tempo: 130,
        syncOffset: 0
    };

    return MusicManager;
});