/*

SoundManager 2 Demo: Play MP3 links "in-place"
----------------------------------------------

http://schillmania.com/projects/soundmanager2/

A simple demo making MP3s playable "inline"
and easily styled/customizable via CSS.

Requires SoundManager 2 Javascript API.

*/

function InlinePlayer() {
	var player = this;
	var sm = soundManager; // soundManager instance
	this.links = [];
	this.sounds = [];
	this.soundsByURL = [];
	this.lastSound = null;
	this.soundCount = 0;
	
	this.css = {
		// CSS class names appended to link during various states
		sDefault: 'sm2_link', // default state
		sLoading: 'sm2_loading',
		sPlaying: 'sm2_playing',
		sPaused: 'sm2_paused'
	}
	
	this.addEventHandler = function(o,evtName,evtHandler) {
		typeof(attachEvent)=='undefined'?o.addEventListener(evtName,evtHandler,false):o.attachEvent('on'+evtName,evtHandler);
	}
	
	this.removeEventHandler = function(o,evtName,evtHandler) {
		typeof(attachEvent)=='undefined'?o.removeEventListener(evtName,evtHandler,false):o.detachEvent('on'+evtName,evtHandler);
	}
	
	this.classContains = function(o,cStr) {
		return (typeof(o.className)!='undefined'?o.className.indexOf(cStr)+1:false);
	}
	
	this.addClass = function(o,cStr) {
		if (!o || !cStr) return false; // safety net
		if (player.classContains(o,cStr)) return false;
		o.className = (o.className?o.className+' ':'')+cStr;
	}
	
	this.removeClass = function(o,cStr) {
		if (!o || !cStr) return false; // safety net
		if (!player.classContains(o,cStr)) return false;
		o.className = o.className.replace(new RegExp('( '+cStr+')|('+cStr+')','g'),'');
	}
	
	this.getSoundByURL = function(sURL) {
		return (typeof player.soundsByURL[sURL] != 'undefined'?player.soundsByURL[sURL]:null);
	}
	
	this.events = {
		
		// handlers for sound events as they're started/stopped/played
		
		play: function() {
			player.removeClass(this._data.oLink,this._data.className);
			this._data.className = player.css.sPlaying;
			player.addClass(this._data.oLink,this._data.className);
			sm._writeDebug('==================== 1');
		},
		
		stop: function() {
			player.removeClass(this._data.oLink,this._data.className);
			this._data.className = '';
			sm._writeDebug('==================== 2');
		},
		
		pause: function() {
			player.removeClass(this._data.oLink,this._data.className);
			this._data.className = player.css.sPaused;
			player.addClass(this._data.oLink,this._data.className);
			sm._writeDebug('==================== 3');
		},
		
		finish: function() {
			player.removeClass(this._data.oLink,this._data.className);
			this._data.className = '';
			sm._writeDebug('==================== 4');
		}
		
	}
	
	this.getTheDamnLink = (navigator.userAgent.match(/MSIE/i)) ? function() { return window.event.srcElement; } : function(e) { return e.target; }
	
    this.handleClick = function(e)
	{ 
		var o = player.getTheDamnLink(e); 
		var sURL = o.getAttribute('href');
		
		// Only Links with .mp3
		if (!o.href || !o.href.match(/.mp3$/i)) return true;
		
		sm._writeDebug('handleClick()');
		
		var soundURL = (o.href);
		var thisSound = player.getSoundByURL(soundURL);
		sm._writeDebug('click: thisSound:'+thisSound);
		
		if (thisSound) {
			// already exists
			sm._writeDebug('sound exists');
			if (thisSound == player.lastSound) {
				// and was playing (or paused)
				sm._writeDebug('toggling pause');
				thisSound.togglePause();
				
				if (thisSound.paused) {
					player.removeClass(thisSound._data.oLink,thisSound._data.className);
					thisSound._data.className = player.css.sPaused;
					player.addClass(thisSound._data.oLink,thisSound._data.className);
				}
				else {
					player.removeClass(thisSound._data.oLink,thisSound._data.className);
					thisSound._data.className = player.css.sPlaying;
					player.addClass(thisSound._data.oLink,thisSound._data.className);
				}
			}
			else {
				// different sound
				thisSound.togglePause();// start playing current
				
				sm._writeDebug('sound different than last sound: '+player.lastSound.sID);
				
				if (player.lastSound)
					player.stopSound(player.lastSound);
			}
		}
		else {
			// create sound
			thisSound = sm.createSound({
					id:		'mp3Sound'+(player.soundCount++),
					url:		soundURL,
					onplay:		player.events.play,
					onstop:		player.events.stop,
					onpause:	player.events.pause,
					onfinish:	player.events.finish
			});
			
			// tack on some custom data
			thisSound._data = {
				// DOM node for reference within SM2 object event handlers
				oLink: o,
				className: player.css.sPlaying
			};
			
			player.soundsByURL[soundURL] = thisSound;
			player.sounds.push(thisSound);
			
			if (player.lastSound)
				player.stopSound(player.lastSound);
			
			thisSound.play();
			// stop last sound
		}
		
		player.lastSound = thisSound; // reference for next call
		
		if (typeof e != 'undefined' && typeof e.preventDefault != 'undefined') {
			e.preventDefault();
		}
		else {
			event.returnValue = false;
		}
		return false;
	}
	
	this.stopSound = function(oSound) {
		sm._writeDebug('stopping sound: '+oSound.sID);
		soundManager.stop(oSound.sID);
		soundManager.unload(oSound.sID);
	}
	
	this.init = function() {
		sm._writeDebug('inlinePlayer.init()');
		var oLinks = document.getElementsByTagName('a');
		// grab all links, look for .mp3
		var foundItems = 0;
		for (var i=0; i<oLinks.length; i++) {
			if (oLinks[i].href.match(/.mp3$/i)) {
				player.addClass(oLinks[i],player.css.sDefault); // add default CSS decoration
				foundItems++;
			}
		}
		if (foundItems>0) {
			player.addEventHandler(document,'click',player.handleClick);
		}
		sm._writeDebug('inlinePlayer.init(): Found '+foundItems+' relevant items.');
	}
	
	this.init();
	
}

// =======================================================================

// MAIN
// ====

var inlinePlayer=null;

soundManager.onload=function() {
	inlinePlayer=new InlinePlayer();
}

// =======================================================================
// =======================================================================


