/*
 * Tutz: a javascript library for playing tiny sounds
 * by Lailson Bandeira
 * based on Jules Gravinese/Thomas Fuchs (scriptaculous) [1] and Reinier Zwitserloot [2] works
 * [1] http://mir.aculo.us/2007/3/12/script-aculo-us-1-7-1-beta
 * [2] http://www.zwitserloot.com/2007/01/31/sound-in-webbrowsers-without-flash
 */
Tutz = {
	loops: [],
	
	preload: function(url) {
		this._play(url, false);
	},
	
	play: function(url) {
		this._play(url, true);
	},
	
	loop: function(url, options) {
		if(!options) options = {};
		if(!options.interval) options.interval = 1;
		if(!options.times) options.times = 'forever';
		
		options.counter = 0;
		this._playLoop(url, options);
	},
	
	stop: function(track) {
		if(this.loops[track])
			clearTimeout(this.loops[track]);
	},
	
	_play: function(url, autostart) {
		var element = (window.attachEvent && !window.opera) ?
		              this._createElementIE(url, autostart) :
					  this._createElement(url, autostart);
		document.body.appendChild(element);
	},
	
	_createElement: function(url, autostart) {
		var html = '<embed src="#{url}" loop="false" autostart="#{autostart}" hidden="true" type="audio/mpeg" style="height:0"/>';
		html = html.replace('#{url}', url).replace('#{autostart}', autostart);
		var range = document.createRange();
		range.selectNodeContents(document.body);
		return range.createContextualFragment(html);
	},
	
	_createElementIE: function(url, autostart) {
		var element = document.createElement('bgsound');
		element.setAttribute('src', url);
		element.setAttribute('loop', 0);
		if(!autostart) element.setAttribute('volume', -10000);
		return element;
	},
	
	_playLoop: function(url, options) {
		this.play(url);
		options.counter++;
		
		if(options.times != 'forever'
			&& options.counter >= options.times)
			return;
		
		var THIS = this;
		var timer = setTimeout(function() {
			THIS._playLoop(url, options);
		}, options.interval*1000);
		
		if(options.track)
			this.loops[options.track] = timer;
	}
};

if(navigator.userAgent.indexOf('Gecko') > -1 && navigator.plugins) {
	var QuickTime = false;
	for(var i = 0; i < navigator.plugins.length; i++) {
		if(navigator.plugins[i].name.indexOf("QuickTime") > -1) {
			QuickTime = true; break;
		}
	}
	if(!QuickTime) {
		Tutz._play = function() {};
		Tutz.loop = function() {};
		Tutz.stop = function() {};
	}
}