
/* ______________________________________________________________________

	Sounc Class
	This class creates a Sound object based on SoundManager 2.

	Requires: Mootools 1.2

	License: MIT License

	Author:
	eneko.alonso@gmail.com
	http://enekoalonso.com
   ______________________________________________________________________
*/


var SoundController = {
	
}

var Sound = new Class({
	ClassName: 'Sound',
	Implements: [Options, Events],

	options: {
		interval: 0,
		delay: 0
	},

	initialize: function(options) {
		this.setOptions(options);
		this.chkAudio = $('chk-audio');

		var self = this;

		this.sound = soundManager.createSound({
			id: self.options.name,
			multiShot: true,
			url: self.options.mp3,
			volume: self.options.volume? self.options.volume:100,
			onfinish: function() { 
				if (self.options.loop) {
					// self.play({position: self.options.loopStart});
					self.play();
				}
			},
			whileplaying: function() {
				// console.log(self.sound.position);
				if (!self.chkAudio.get('checked')) this.stop();
				
				// if (self.options.loop && self.sound.position > self.options.loopEnd) {
					// self.sound.setPosition(self.options.loopStart);
					// self.play({position: self.options.loopStart});
				// }
			}
		});

		// If delay is set, sound will autoplay after that number of miliseconds
		if (this.options.delay) {
			setTimeout(function(){
				self.play();
			}, this.options.delay);
		}
	},

	play: function(options) {
		// If interval is set, sound will autoplay every interval
		if (this.options.interval) {
			if (this.options.interval instanceof Array) {
				var interval = Random.get(this.options.interval[0], this.options.interval[1]);
			} else {
				var interval = this.options.interval;
			}
			console.log(this.options.name + ': setting interval: ' + interval)
			var self = this;
			this.intervalTimer = setTimeout(function() {
				self.play();
			}, interval);
		}

		if (!this.chkAudio.get('checked')) return this;
		this.sound.play(options);

		return this;
	}
});

