// audioplayer.js
define([],function () {

	var context;

	var Audio = {

		readyToPlay: false,

		initialize: function() {
			try {
				// Fix up for prefixing
				window.AudioContext = window.AudioContext||window.webkitAudioContext;
				Audio.context = context = new AudioContext();
				console.log("WebAudio loaded.")
			} catch(e) {
				alert('Web Audio API is not supported in this browser');
			}
		},

		loadMusic: function(url, bpm, callback) {
			var request = new XMLHttpRequest();
			request.open('GET', url, true);
			request.responseType = 'arraybuffer';

			function onError() {
				alert('Could not load the file.')
			} 

			// Decode asynchronously
			request.onload = function() {
				Audio.context.decodeAudioData(request.response, function(buffer) {
					Audio.musicBuffer = buffer;
					Audio.readyToPlay = true;
					callback();
				}, onError);

				Audio.bpm = parseInt(bpm);
				Audio.bps = Audio.bpm/60;
				Audio.beat_multiplier = Audio.bps / 4;
			}
			request.send();
		},

		play: function() {

			if(Audio.readyToPlay) {
				Audio.source = Audio.context.createBufferSource(); // creates a sound source
				Audio.source.buffer = Audio.musicBuffer;                    // tell the source which sound to play
				Audio.source.connect(Audio.context.destination);       // connect the source to the context's destination (the speakers)
				Audio.source.start(0);
			}
			
		},

		pause: function() {

		},

		stop: function() {

		},

		getTime: function() {
			return Audio.source.context.currentTime * Audio.bps;
		}

	};

	return Audio;
});