/* Elementric  ::  A modular, UX-focused web application framework by Phillip Luther
 * --------------------------------------------------------------------------------------------
 * Elementric is distributed under the terms of the GNU General Public License.
 * Copyright 2011 by Phillip Luther
 * 
 * Documentation, extensions, and download information available at elementric.org
 */


dojo.declare('EL_audioWidgets', null, {

	autoRender : function() {
		
			/*
			 * @param	: {string} the path to an audio file
			 *
			 * @return	: {object} a src node for use in an HTML5 audio player
			 *
			 * @description	:
			 *	Creates and returns a "src" node to append in an HTML5 audio player
			 */
		function buildAudioSrc( audioFile)
		{
				//what'd they pass us? (at this point we'll only support mp3 and ogg)
			var srcType = ( audioFile.substr( audioFile.length - 3, 3) === 'ogg')	? 'audio/ogg'
												: 'audio/mpeg';

				//create and send back our src node
			return dojo.create('source', {
							src	: audioFile,
							type	: srcType
			}); 
		}

			/*
			 * @return	: {object} an HTML5 audio node
			 *
			 * @description	:
			 *	Creates and returns an empty HTML5 audio node; slightly unnecessary, but I'll flesh
			 *	this out later and wanted to have it abstracted.
			 */
		function buildAudioNode()
		{
				//create the blank node
			var audioNode =  dojo.create('audio', {
								controls	: 'controls',
								preload		: 'auto',
								class		: 'audio-player'
			});

				//fill it with our fallback text
			audioNode.innerHTML = 'Your browser can\'t handle HTML5. Use the download links below to listen to this track.';

				//and kick it back
			return audioNode;
		}
				 
			/*
			 * @param	: {object} an audio container node
			 *
			 * @return	: {object} a fully-formed HTML5 audio player
			 *
			 * @description	:
			 *	Dynamically builds a simple audio player (expand this later) based on any audio files
			 *	found inside the given container.
			 */
		function renderAudioPlayer( audioContainer)
		{
					//build our empty audio node
			var 	audioNode = buildAudioNode(),

					//grab any audio files inside this container				
				audioFiles = dojo.query('.audio-file', audioContainer);

				//build and append each file to our audio node for dynamic file serving
			for ( var i = audioFiles.length; i--; )
			{
				dojo.place( buildAudioSrc( audioFiles[i].href), audioNode);
			}

				//kick back the completed player
			return audioNode;
		}
			
				//first, snatch up all of our audio containers
		var	audioContainers = dojo.query('.audio-container'),
			
				//placeholder for below
			audioPlayer;

			//then cycle through them and render our players
		for ( var i = audioContainers.length; i--; )
		{
			dojo.place( renderAudioPlayer( audioContainers[i]), audioContainers[i], 4);
		}
	}
});

	//load our constructor class
var audioWidgets = new EL_audioWidgets();

