var soundManager=null;function SoundManager(b,a){this.flashVersion=8;this.debugMode=true;this.useConsole=true;this.consoleOnly=false;this.waitForWindowLoad=false;this.nullURL="null.mp3";this.allowPolling=true;this.useMovieStar=false;this.bgColor="#ffffff";this.useHighPerformance=false;this.flashLoadTimeout=750;this.wmode=null;this.allowFullScreen=true;this.defaultOptions={autoLoad:false,stream:true,autoPlay:false,onid3:null,onload:null,whileloading:null,onplay:null,onpause:null,onresume:null,whileplaying:null,onstop:null,onfinish:null,onbeforefinish:null,onbeforefinishtime:5000,onbeforefinishcomplete:null,onjustbeforefinish:null,onjustbeforefinishtime:200,multiShot:true,position:null,pan:0,volume:100};this.flash9Options={isMovieStar:null,usePeakData:false,useWaveformData:false,useEQData:false,onbufferchange:null,ondataerror:null};this.movieStarOptions={onmetadata:null,useVideo:false,bufferTime:null};var f=null;var e=this;this.version=null;this.versionNumber="V2.95a.20090501";this.movieURL=null;this.url=null;this.altURL=null;this.swfLoaded=false;this.enabled=false;this.o=null;this.id=(a||"sm2movie");this.oMC=null;this.sounds={};this.soundIDs=[];this.muted=false;this.isFullScreen=false;this.isIE=(navigator.userAgent.match(/MSIE/i));this.isSafari=(navigator.userAgent.match(/safari/i));this.isGecko=(navigator.userAgent.match(/gecko/i));this.debugID="soundmanager-debug";this.specialWmodeCase=false;this._debugOpen=true;this._didAppend=false;this._appendSuccess=false;this._didInit=false;this._disabled=false;this._windowLoaded=false;this._hasConsole=(typeof console!="undefined"&&typeof console.log!="undefined");this._debugLevels=["log","info","warn","error"];this._defaultFlashVersion=8;this._oRemoved=null;this._oRemovedHTML=null;var g=function(h){return document.getElementById(h)};this.filePatterns={flash8:/\.mp3(\?.*)?$/i,flash9:/\.mp3(\?.*)?$/i};this.netStreamTypes=["aac","flv","mov","mp4","m4v","f4v","m4a","mp4v","3gp","3g2"];this.netStreamPattern=new RegExp("\\.("+this.netStreamTypes.join("|")+")(\\?.*)?$","i");this.filePattern=null;this.features={buffering:false,peakData:false,waveformData:false,eqData:false,movieStar:false};this.sandbox={type:null,types:{remote:"remote (domain-based) rules",localWithFile:"local with file access (no internet access)",localWithNetwork:"local with network (internet access only, no local access)",localTrusted:"local, trusted (local + internet access)"},description:null,noRemote:null,noLocal:null};this._setVersionInfo=function(){if(e.flashVersion!=8&&e.flashVersion!=9){alert('soundManager.flashVersion must be 8 or 9. "'+e.flashVersion+'" is invalid. Reverting to '+e._defaultFlashVersion+".");e.flashVersion=e._defaultFlashVersion}e.version=e.versionNumber+(e.flashVersion==9?" (AS3/Flash 9)":" (AS2/Flash 8)");if(e.flashVersion>8){e.defaultOptions=e._mergeObjects(e.defaultOptions,e.flash9Options);e.features.buffering=true}if(e.flashVersion>8&&e.useMovieStar){e.defaultOptions=e._mergeObjects(e.defaultOptions,e.movieStarOptions);e.filePatterns.flash9=new RegExp("\\.(mp3|"+e.netStreamTypes.join("|")+")(\\?.*)?$","i");e.features.movieStar=true}else{e.useMovieStar=false;e.features.movieStar=false}e.filePattern=e.filePatterns[(e.flashVersion!=8?"flash9":"flash8")];e.movieURL=(e.flashVersion==8?"soundmanager2.swf":"soundmanager2_flash9.swf");e.features.peakData=e.features.waveformData=e.features.eqData=(e.flashVersion>8)};this._overHTTP=(document.location?document.location.protocol.match(/http/i):null);this._waitingforEI=false;this._initPending=false;this._tryInitOnFocus=(this.isSafari&&typeof document.hasFocus=="undefined");this._isFocused=(typeof document.hasFocus!="undefined"?document.hasFocus():null);this._okToDisable=!this._tryInitOnFocus;this.useAltURL=!this._overHTTP;var d="http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html";this.strings={notReady:"Not loaded yet",appXHTML:"appendChild/innerHTML set failed."};this.supported=function(){return(e._didInit&&!e._disabled)};this.getMovie=function(h){return e.isIE?window[h]:(e.isSafari?g(h)||document[h]:g(h))};this.loadFromXML=function(h){try{e.o._loadFromXML(h)}catch(i){e._failSafely();return true}};this.createSound=function(i){if(arguments.length==2){i={id:arguments[0],url:arguments[1]}}var j=e._mergeObjects(i);var h=j;if(e._idCheck(h.id,true)){return e.sounds[h.id]}if(e.flashVersion>8&&e.useMovieStar){if(h.isMovieStar===null){h.isMovieStar=(h.url.match(e.netStreamPattern)?true:false)}if(h.isMovieStar){}if(h.isMovieStar&&(h.usePeakData||h.useWaveformData||h.useEQData)){h.usePeakData=false;h.useWaveformData=false;h.useEQData=false}}e.sounds[h.id]=new f(h);e.soundIDs[e.soundIDs.length]=h.id;if(e.flashVersion==8){e.o._createSound(h.id,h.onjustbeforefinishtime)}else{e.o._createSound(h.id,h.url,h.onjustbeforefinishtime,h.usePeakData,h.useWaveformData,h.useEQData,h.isMovieStar,(h.isMovieStar?h.useVideo:false),(h.isMovieStar?h.bufferTime:false))}if(h.autoLoad||h.autoPlay){if(e.sounds[h.id]){e.sounds[h.id].load(h)}}if(h.autoPlay){e.sounds[h.id].play()}return e.sounds[h.id]};this.createVideo=function(h){if(arguments.length==2){h={id:arguments[0],url:arguments[1]}}if(e.flashVersion>=9){h.isMovieStar=true;h.useVideo=true}else{return false}if(!e.useMovieStar){}return e.createSound(h)};this.destroySound=function(j,h){if(!e._idCheck(j)){return false}for(var k=0;k<e.soundIDs.length;k++){if(e.soundIDs[k]==j){e.soundIDs.splice(k,1);continue}}e.sounds[j].unload();if(!h){e.sounds[j].destruct()}delete e.sounds[j]};this.destroyVideo=this.destroySound;this.load=function(h,i){if(!e._idCheck(h)){return false}e.sounds[h].load(i)};this.unload=function(h){if(!e._idCheck(h)){return false}e.sounds[h].unload()};this.play=function(h,i){if(!e._idCheck(h)){if(typeof i!="Object"){i={url:i}}if(i&&i.url){i.id=h;e.createSound(i)}else{return false}}e.sounds[h].play(i)};this.start=this.play;this.setPosition=function(h,i){if(!e._idCheck(h)){return false}e.sounds[h].setPosition(i)};this.stop=function(h){if(!e._idCheck(h)){return false}e.sounds[h].stop()};this.stopAll=function(){for(var h in e.sounds){if(e.sounds[h] instanceof f){e.sounds[h].stop()}}};this.pause=function(h){if(!e._idCheck(h)){return false}e.sounds[h].pause()};this.pauseAll=function(){for(var h=e.soundIDs.length;h--;){e.sounds[e.soundIDs[h]].pause()}};this.resume=function(h){if(!e._idCheck(h)){return false}e.sounds[h].resume()};this.resumeAll=function(){for(var h=e.soundIDs.length;h--;){e.sounds[e.soundIDs[h]].resume()}};this.togglePause=function(h){if(!e._idCheck(h)){return false}e.sounds[h].togglePause()};this.setPan=function(h,i){if(!e._idCheck(h)){return false}e.sounds[h].setPan(i)};this.setVolume=function(i,h){if(!e._idCheck(i)){return false}e.sounds[i].setVolume(h)};this.mute=function(h){if(typeof h!="string"){h=null}if(!h){for(var j=e.soundIDs.length;j--;){e.sounds[e.soundIDs[j]].mute()}e.muted=true}else{if(!e._idCheck(h)){return false}e.sounds[h].mute()}};this.muteAll=function(){e.mute()};this.unmute=function(h){if(typeof h!="string"){h=null}if(!h){for(var j=e.soundIDs.length;j--;){e.sounds[e.soundIDs[j]].unmute()}e.muted=false}else{if(!e._idCheck(h)){return false}e.sounds[h].unmute()}};this.unmuteAll=function(){e.unmute()};this.getMemoryUse=function(){if(e.flashVersion==8){return 0}if(e.o){return parseInt(e.o._getMemoryUse(),10)}};this.setPolling=function(h){if(!e.o||!e.allowPolling){return false}e.o._setPolling(h)};this.disable=function(j){if(typeof j=="undefined"){j=false}if(e._disabled){return false}e._disabled=true;for(var h=e.soundIDs.length;h--;){e._disableObject(e.sounds[e.soundIDs[h]])}e.initComplete(j)};this.canPlayURL=function(h){return(h?(h.match(e.filePattern)?true:false):null)};this.getSoundById=function(i,j){if(!i){throw new Error("SoundManager.getSoundById(): sID is null/undefined")}var h=e.sounds[i];if(!h&&!j){}return h};this.onload=function(){soundManager._wD("Warning: soundManager.onload() is undefined.",2)};this.onerror=function(){};this._idCheck=this.getSoundById;this._complain=function(h,i){};var c=function(){return false};c._protected=true;this._disableObject=function(i){for(var h in i){if(typeof i[h]=="function"&&typeof i[h]._protected=="undefined"){i[h]=c}}h=null};this._failSafely=function(h){if(typeof h=="undefined"){h=false}if(!e._disabled||h){e.disable(h)}};this._normalizeMovieURL=function(h){var i=null;if(h){if(h.match(/\.swf(\?.*)?$/i)){i=h.substr(h.toLowerCase().lastIndexOf(".swf?")+4);if(i){return h}}else{if(h.lastIndexOf("/")!=h.length-1){h=h+"/"}}}return(h&&h.lastIndexOf("/")!=-1?h.substr(0,h.lastIndexOf("/")+1):"./")+e.movieURL};this._getDocument=function(){return(document.body?document.body:(document.documentElement?document.documentElement:document.getElementsByTagName("div")[0]))};this._getDocument._protected=true;this._createMovie=function(y,n){if(e._didAppend&&e._appendSuccess){return false}if(window.location.href.indexOf("debug=1")+1){e.debugMode=true}e._didAppend=true;e._setVersionInfo();var w=(n?n:e.url);var r=(e.altURL?e.altURL:w);e.url=e._normalizeMovieURL(e._overHTTP?w:r);n=e.url;var t=null;if(e.useHighPerformance&&e.useMovieStar&&e.defaultOptions.useVideo===true){t="soundManager note: disabling highPerformance, not applicable with movieStar mode + useVideo";e.useHighPerformance=false}e.wmode=(!e.wmode&&e.useHighPerformance&&!e.useMovieStar?"transparent":e.wmode);if(e.wmode!==null&&e.flashLoadTimeout!==0&&!e.useHighPerformance&&!e.isIE&&navigator.platform.match(/win32/i)){e.specialWmodeCase=true;e.wmode=null}if(e.flashVersion==8){e.allowFullScreen=false}var A={name:y,id:y,src:n,width:"100%",height:"100%",quality:"high",allowScriptAccess:"always",bgcolor:e.bgColor,pluginspage:"http://www.macromedia.com/go/getflashplayer",type:"application/x-shockwave-flash",wmode:e.wmode,allowfullscreen:(e.allowFullScreen?"true":"false")};if(!e.wmode){delete A.wmode}var h={id:y,data:n,type:"application/x-shockwave-flash",width:"100%",height:"100%",wmode:e.wmode};var o=null;var B=null;if(e.isIE){o=document.createElement("div");var u='<object id="'+y+'" data="'+n+'" type="application/x-shockwave-flash" width="100%" height="100%"><param name="movie" value="'+n+'" /><param name="AllowScriptAccess" value="always" /><param name="quality" value="high" />'+(e.wmode?'<param name="wmode" value="'+e.wmode+'" /> ':"")+'<param name="bgcolor" value="'+e.bgColor+'" /><param name="allowFullScreen" value="'+(e.allowFullScreen?"true":"false")+'" /><!-- --></object>'}else{o=document.createElement("embed");for(B in A){if(A.hasOwnProperty(B)){o.setAttribute(B,A[B])}}}var j=document.createElement("div");j.id=e.debugID+"-toggle";var k={position:"fixed",bottom:"0px",right:"0px",width:"1.2em",height:"1.2em",lineHeight:"1.2em",margin:"2px",textAlign:"center",border:"1px solid #999",cursor:"pointer",background:"#fff",color:"#333",zIndex:10001};j.appendChild(document.createTextNode("-"));j.onclick=e._toggleDebug;j.title="Toggle SM2 debug console";if(navigator.userAgent.match(/msie 6/i)){j.style.position="absolute";j.style.cursor="hand"}for(B in k){if(k.hasOwnProperty(B)){j.style[B]=k[B]}}var v=e._getDocument();if(v){e.oMC=g("sm2-container")?g("sm2-container"):document.createElement("div");if(!e.oMC.id){e.oMC.id="sm2-container";e.oMC.className="movieContainer";var p=null;var q=null;if(e.useHighPerformance){p={position:"fixed",width:"8px",height:"8px",bottom:"0px",left:"0px"}}else{p={position:"absolute",width:"1px",height:"1px",top:"-999px",left:"-999px"}}var l=null;for(l in p){if(p.hasOwnProperty(l)){e.oMC.style[l]=p[l]}}try{if(!e.isIE){e.oMC.appendChild(o)}v.appendChild(e.oMC);if(e.isIE){q=e.oMC.appendChild(document.createElement("div"));q.className="sm2-object-box";q.innerHTML=u}e._appendSuccess=true}catch(z){throw new Error(e.strings.appXHTML)}}else{e.oMC.appendChild(o);if(e.isIE){q=e.oMC.appendChild(document.createElement("div"));q.className="sm2-object-box";q.innerHTML=u}e._appendSuccess=true}if(!g(e.debugID)&&((!e._hasConsole||!e.useConsole)||(e.useConsole&&e._hasConsole&&!e.consoleOnly))){var m=document.createElement("div");m.id=e.debugID;m.style.display=(e.debugMode?"block":"none");if(e.debugMode&&!g(j.id)){try{v.appendChild(j)}catch(i){throw new Error(e.strings.appXHTML)}v.appendChild(m)}}v=null}if(t){}};this._writeDebug=function(i,p,k){if(!e.debugMode){return false}if(typeof k!="undefined"&&k){i=i+" | "+new Date().getTime()}if(e._hasConsole&&e.useConsole){var h=e._debugLevels[p];if(typeof console[h]!="undefined"){console[h](i)}else{console.log(i)}if(e.useConsoleOnly){return true}}var n="soundmanager-debug";try{var m=g(n);if(!m){return false}var l=document.createElement("div");if(++e._wdCount%2===0){l.className="sm2-alt"}if(typeof p=="undefined"){p=0}else{p=parseInt(p,10)}l.appendChild(document.createTextNode(i));if(p){if(p>=2){l.style.fontWeight="bold"}if(p==3){l.style.color="#ff3333"}}m.insertBefore(l,m.firstChild)}catch(j){}m=null};this._writeDebug._protected=true;this._wdCount=0;this._wdCount._protected=true;this._wD=this._writeDebug;this._wDAlert=function(h){alert(h)};if(window.location.href.indexOf("debug=alert")+1&&e.debugMode){e._wD=e._wDAlert}this._toggleDebug=function(){var i=g(e.debugID);var h=g(e.debugID+"-toggle");if(!i){return false}if(e._debugOpen){h.innerHTML="+";i.style.display="none"}else{h.innerHTML="-";i.style.display="block"}e._debugOpen=!e._debugOpen};this._toggleDebug._protected=true;this._debug=function(){for(var k=0,h=e.soundIDs.length;k<h;k++){e.sounds[e.soundIDs[k]]._debug()}};this._debugTS=function(k,h,i){if(typeof sm2Debugger!="undefined"){try{sm2Debugger.handleEvent(k,h,i)}catch(j){}}};this._debugTS._protected=true;this._mergeObjects=function(j,h){var m={};for(var k in j){if(j.hasOwnProperty(k)){m[k]=j[k]}}var l=(typeof h=="undefined"?e.defaultOptions:h);for(var n in l){if(l.hasOwnProperty(n)&&typeof m[n]=="undefined"){m[n]=l[n]}}return m};this.createMovie=function(h){if(h){e.url=h}e._initMovie()};this.go=this.createMovie;this._initMovie=function(){if(e.o){return false}e.o=e.getMovie(e.id);if(!e.o){if(!e.oRemoved){e._createMovie(e.id,e.url)}else{if(!e.isIE){e.oMC.appendChild(e.oRemoved)}else{e.oMC.innerHTML=e.oRemovedHTML}e.oRemoved=null;e._didAppend=true}e.o=e.getMovie(e.id)}if(e.o){if(e.flashLoadTimeout>0){}}};this.waitForExternalInterface=function(){if(e._waitingForEI){return false}e._waitingForEI=true;if(e._tryInitOnFocus&&!e._isFocused){return false}if(e.flashLoadTimeout>0){if(!e._didInit){}setTimeout(function(){if(!e._didInit){if(!e._overHTTP){}e._debugTS("flashtojs",false,": Timed out"+(e._overHTTP)?" (Check flash security)":" (No plugin/missing SWF?)")}if(!e._didInit&&e._okToDisable){e._failSafely(true)}},e.flashLoadTimeout)}else{if(!e.didInit){}}};this.handleFocus=function(){if(e._isFocused||!e._tryInitOnFocus){return true}e._okToDisable=true;e._isFocused=true;if(e._tryInitOnFocus){window.removeEventListener("mousemove",e.handleFocus,false)}e._waitingForEI=false;setTimeout(e.waitForExternalInterface,500);if(window.removeEventListener){window.removeEventListener("focus",e.handleFocus,false)}else{if(window.detachEvent){window.detachEvent("onfocus",e.handleFocus)}}};this.initComplete=function(h){if(e._didInit){return false}e._didInit=true;if(e._disabled||h){e._debugTS("onload",false);e.onerror.apply(window);return false}else{e._debugTS("onload",true)}if(e.waitForWindowLoad&&!e._windowLoaded){if(window.addEventListener){window.addEventListener("load",e.initUserOnload,false)}else{if(window.attachEvent){window.attachEvent("onload",e.initUserOnload)}}return false}else{if(e.waitForWindowLoad&&e._windowLoaded){}e.initUserOnload()}};this.initUserOnload=function(){e.onload.apply(window)};this.init=function(){e._initMovie();if(e._didInit){return false}if(window.removeEventListener){window.removeEventListener("load",e.beginDelayedInit,false)}else{if(window.detachEvent){window.detachEvent("onload",e.beginDelayedInit)}}try{e.o._externalInterfaceTest(false);if(!e.allowPolling){}e.setPolling(true);if(!e.debugMode){e.o._disableDebug()}e.enabled=true;e._debugTS("jstoflash",true)}catch(h){e._debugTS("jstoflash",false);e._failSafely(true);e.initComplete();return false}e.initComplete()};this.beginDelayedInit=function(){e._windowLoaded=true;setTimeout(e.waitForExternalInterface,500);setTimeout(e.beginInit,20)};this.beginInit=function(){if(e._initPending){return false}e.createMovie();e._initMovie();e._initPending=true;return true};this.domContentLoaded=function(){if(document.removeEventListener){document.removeEventListener("DOMContentLoaded",e.domContentLoaded,false)}e.go()};this._externalInterfaceOK=function(){if(e.swfLoaded){return false}e._debugTS("swf",true);e._debugTS("flashtojs",true);e.swfLoaded=true;e._tryInitOnFocus=false;if(e.isIE){setTimeout(e.init,100)}else{e.init()}};this._setSandboxType=function(h){var i=e.sandbox;i.type=h;i.description=i.types[(typeof i.types[h]!="undefined"?h:"unknown")];if(i.type=="localWithFile"){i.noRemote=true;i.noLocal=false}else{if(i.type=="localWithNetwork"){i.noRemote=false;i.noLocal=true}else{if(i.type=="localTrusted"){i.noRemote=false;i.noLocal=false}}}};this.reboot=function(){if(e.soundIDs.length){}for(var h=e.soundIDs.length;h--;){e.sounds[e.soundIDs[h]].destruct()}try{if(e.isIE){e.oRemovedHTML=e.o.innerHTML}e.oRemoved=e.o.parentNode.removeChild(e.o)}catch(j){}e.enabled=false;e._didInit=false;e._waitingForEI=false;e._initPending=false;e._didInit=false;e._didAppend=false;e._appendSuccess=false;e._didInit=false;e._disabled=false;e._waitingforEI=true;e.swfLoaded=false;e.soundIDs={};e.sounds=[];e.o=null;window.setTimeout(function(){soundManager.beginDelayedInit()},20)};this.destruct=function(){e.disable(true)};f=function(h){var i=this;this.sID=h.id;this.url=h.url;this.options=e._mergeObjects(h);this.instanceOptions=this.options;this._iO=this.instanceOptions;this.pan=this.options.pan;this.volume=this.options.volume;this._lastURL=null;this._debug=function(){if(e.debugMode){var l=null;var n=[];var k=null;var m=null;var j=64;for(l in i.options){if(i.options[l]!==null){if(i.options[l] instanceof Function){k=i.options[l].toString();k=k.replace(/\s\s+/g," ");m=k.indexOf("{");n[n.length]=" "+l+": {"+k.substr(m+1,(Math.min(Math.max(k.indexOf("\n")-1,j),j))).replace(/\n/g,"")+"... }"}else{n[n.length]=" "+l+": "+i.options[l]}}}}};this._debug();this.id3={};this.resetProperties=function(j){i.bytesLoaded=null;i.bytesTotal=null;i.position=null;i.duration=null;i.durationEstimate=null;i.loaded=false;i.playState=0;i.paused=false;i.readyState=0;i.muted=false;i.didBeforeFinish=false;i.didJustBeforeFinish=false;i.isBuffering=false;i.instanceOptions={};i.instanceCount=0;i.peakData={left:0,right:0};i.waveformData={left:[],right:[]};i.eqData=[]};i.resetProperties();this.load=function(j){if(typeof j!="undefined"){i._iO=e._mergeObjects(j);i.instanceOptions=i._iO}else{j=i.options;i._iO=j;i.instanceOptions=i._iO;if(i._lastURL&&i._lastURL!=i.url){i._iO.url=i.url;i.url=null}}if(typeof i._iO.url=="undefined"){i._iO.url=i.url}if(i._iO.url==i.url&&i.readyState!==0&&i.readyState!=2){return false}i.url=i._iO.url;i._lastURL=i._iO.url;i.loaded=false;i.readyState=1;i.playState=0;try{if(e.flashVersion==8){e.o._load(i.sID,i._iO.url,i._iO.stream,i._iO.autoPlay,(i._iO.whileloading?1:0))}else{e.o._load(i.sID,i._iO.url,i._iO.stream?true:false,i._iO.autoPlay?true:false);if(i._iO.isMovieStar&&i._iO.autoLoad&&!i._iO.autoPlay){i.pause()}}}catch(k){e._debugTS("onload",false);e.onerror();e.disable()}};this.unload=function(){if(i.readyState!==0){if(i.readyState!=2){i.setPosition(0,true)}e.o._unload(i.sID,e.nullURL);i.resetProperties()}};this.destruct=function(){e.o._destroySound(i.sID);e.destroySound(i.sID,true)};this.play=function(k){if(!k){k={}}i._iO=e._mergeObjects(k,i._iO);i._iO=e._mergeObjects(i._iO,i.options);i.instanceOptions=i._iO;if(i.playState==1){var j=i._iO.multiShot;if(!j){return false}else{}}if(!i.loaded){if(i.readyState===0){i._iO.stream=true;i._iO.autoPlay=true;i.load(i._iO)}else{if(i.readyState==2){return false}else{}}}else{}if(i.paused){i.resume()}else{i.playState=1;if(!i.instanceCount||e.flashVersion>8){i.instanceCount++}i.position=(typeof i._iO.position!="undefined"&&!isNaN(i._iO.position)?i._iO.position:0);if(i._iO.onplay){i._iO.onplay.apply(i)}i.setVolume(i._iO.volume,true);i.setPan(i._iO.pan,true);e.o._start(i.sID,i._iO.loop||1,(e.flashVersion==9?i.position:i.position/1000))}};this.start=this.play;this.stop=function(j){if(i.playState==1){i.playState=0;i.paused=false;if(i._iO.onstop){i._iO.onstop.apply(i)}e.o._stop(i.sID,j);i.instanceCount=0;i._iO={}}};this.setPosition=function(k,j){if(typeof k=="undefined"){k=0}var l=Math.min(i.duration,Math.max(k,0));i._iO.position=l;if(!j){}e.o._setPosition(i.sID,(e.flashVersion==9?i._iO.position:i._iO.position/1000),(i.paused||!i.playState))};this.pause=function(){if(i.paused||i.playState===0){return false}i.paused=true;e.o._pause(i.sID);if(i._iO.onpause){i._iO.onpause.apply(i)}};this.resume=function(){if(!i.paused||i.playState===0){return false}i.paused=false;e.o._pause(i.sID);if(i._iO.onresume){i._iO.onresume.apply(i)}};this.togglePause=function(){if(i.playState===0){i.play({position:(e.flashVersion==9?i.position:i.position/1000)});return false}if(i.paused){i.resume()}else{i.pause()}};this.setPan=function(k,j){if(typeof k=="undefined"){k=0}if(typeof j=="undefined"){j=false}e.o._setPan(i.sID,k);i._iO.pan=k;if(!j){i.pan=k}};this.setVolume=function(j,k){if(typeof j=="undefined"){j=100}if(typeof k=="undefined"){k=false}e.o._setVolume(i.sID,(e.muted&&!i.muted)||i.muted?0:j);i._iO.volume=j;if(!k){i.volume=j}};this.mute=function(){i.muted=true;e.o._setVolume(i.sID,0)};this.unmute=function(){i.muted=false;var j=typeof i._iO.volume!="undefined";e.o._setVolume(i.sID,j?i._iO.volume:i.options.volume)};this._whileloading=function(j,k,l){if(!i._iO.isMovieStar){i.bytesLoaded=j;i.bytesTotal=k;i.duration=Math.floor(l);i.durationEstimate=parseInt((i.bytesTotal/i.bytesLoaded)*i.duration,10);if(i.readyState!=3&&i._iO.whileloading){i._iO.whileloading.apply(i)}}else{i.bytesLoaded=j;i.bytesTotal=k;i.duration=Math.floor(l);i.durationEstimate=i.duration;if(i.readyState!=3&&i._iO.whileloading){i._iO.whileloading.apply(i)}}};this._onid3=function(n,k){var o=[];for(var m=0,l=n.length;m<l;m++){o[n[m]]=k[m]}i.id3=e._mergeObjects(i.id3,o);if(i._iO.onid3){i._iO.onid3.apply(i)}};this._whileplaying=function(k,l,n,j,m){if(isNaN(k)||k===null){return false}if(i.playState===0&&k>0){k=0}i.position=k;if(i._iO.usePeakData&&typeof l!="undefined"&&l){i.peakData={left:l.leftPeak,right:l.rightPeak}}if(i._iO.useWaveformData&&typeof n!="undefined"&&n){i.waveformData={left:n.split(","),right:j.split(",")}}if(i._iO.useEQData&&typeof m!="undefined"&&m){i.eqData=m}if(i.playState==1){if(i.isBuffering){i._onbufferchange(0)}if(i._iO.whileplaying){i._iO.whileplaying.apply(i)}if(i.loaded&&i._iO.onbeforefinish&&i._iO.onbeforefinishtime&&!i.didBeforeFinish&&i.duration-i.position<=i._iO.onbeforefinishtime){i._onbeforefinish()}}};this._onload=function(j){j=(j==1?true:false);if(!j){if(e.sandbox.noRemote===true){}if(e.sandbox.noLocal===true){}}i.loaded=j;i.readyState=j?3:2;if(i._iO.onload){i._iO.onload.apply(i)}};this._onbeforefinish=function(){if(!i.didBeforeFinish){i.didBeforeFinish=true;if(i._iO.onbeforefinish){i._iO.onbeforefinish.apply(i)}}};this._onjustbeforefinish=function(j){if(!i.didJustBeforeFinish){i.didJustBeforeFinish=true;if(i._iO.onjustbeforefinish){i._iO.onjustbeforefinish.apply(i)}}};this._onfinish=function(){if(i._iO.onbeforefinishcomplete){i._iO.onbeforefinishcomplete.apply(i)}i.didBeforeFinish=false;i.didJustBeforeFinish=false;if(i.instanceCount){i.instanceCount--;if(!i.instanceCount){i.playState=0;i.paused=false;i.instanceCount=0;i.instanceOptions={};if(i._iO.onfinish){i._iO.onfinish.apply(i)}}}else{if(i.useVideo){}}};this._onmetadata=function(j){if(!j.width&&!j.height){j.width=320;j.height=240}i.metadata=j;i.width=j.width;i.height=j.height;if(i._iO.onmetadata){i._iO.onmetadata.apply(i)}};this._onbufferchange=function(j){if(i.playState===0){return false}if(j==i.isBuffering){return false}i.isBuffering=(j==1?true:false);if(i._iO.onbufferchange){i._iO.onbufferchange.apply(i)}};this._ondataerror=function(j){if(i.playState>0){if(i._iO.ondataerror){i._iO.ondataerror.apply(i)}}else{}}};this._onfullscreenchange=function(h){e.isFullScreen=(h==1?true:false);if(!e.isFullScreen){try{window.focus()}catch(i){}}};if(window.addEventListener){window.addEventListener("focus",e.handleFocus,false);window.addEventListener("load",e.beginDelayedInit,false);window.addEventListener("unload",e.destruct,false);if(e._tryInitOnFocus){window.addEventListener("mousemove",e.handleFocus,false)}}else{if(window.attachEvent){window.attachEvent("onfocus",e.handleFocus);window.attachEvent("onload",e.beginDelayedInit);window.attachEvent("unload",e.destruct)}else{e._debugTS("onload",false);soundManager.onerror();soundManager.disable()}}if(document.addEventListener){document.addEventListener("DOMContentLoaded",e.domContentLoaded,false)}}if(typeof SM2_DEFER=="undefined"||!SM2_DEFER){soundManager=new SoundManager()};

// http://www.berniecode.com/writing/animator.html

// Applies a sequence of numbers between 0 and 1 to a number of subjects
// construct - see setOptions for parameters
function Animator(options) {
	this.setOptions(options);
	var _this = this;
	this.timerDelegate = function(){_this.onTimerEvent()};
	this.subjects = [];
	this.subjectScopes = [];
	this.target = 0;
	this.state = 0;
	this.lastTime = null;
};
Animator.prototype = {
	// apply defaults
	setOptions: function(options) {
		this.options = Animator.applyDefaults({
			interval: 20,  // time between animation frames
			duration: 400, // length of animation
			onComplete: function(){},
			onStep: function(){},
			transition: Animator.tx.easeInOut
		}, options);
	},
	// animate from the current state to provided value
	seekTo: function(to) {
		this.seekFromTo(this.state, to);
	},
	// animate from the current state to provided value
	seekFromTo: function(from, to) {
		this.target = Math.max(0, Math.min(1, to));
		this.state = Math.max(0, Math.min(1, from));
		this.lastTime = new Date().getTime();
		if (!this.intervalId) {
			this.intervalId = window.setInterval(this.timerDelegate, this.options.interval);
		}
	},
	// animate from the current state to provided value
	jumpTo: function(to) {
		this.target = this.state = Math.max(0, Math.min(1, to));
		this.propagate();
	},
	// seek to the opposite of the current target
	toggle: function() {
		this.seekTo(1 - this.target);
	},
	// add a function or an object with a method setState(state) that will be called with a number
	// between 0 and 1 on each frame of the animation
	addSubject: function(subject,scope) {
		this.subjects[this.subjects.length] = subject;
		this.subjectScopes[this.subjectScopes.length] = scope;
		return this;
	},
	// remove all subjects
	clearSubjects: function() {
		this.subjects = [];
		this.subjectScopes = [];
	},
	// forward the current state to the animation subjects
	propagate: function() {
		var value = this.options.transition(this.state);
		for (var i=0; i<this.subjects.length; i++) {
			if (this.subjects[i].setState) {
				this.subjects[i].setState(value);
			} else {
				this.subjects[i].apply(this.subjectScopes[i],[value]);
			}
		}
	},
	// called once per frame to update the current state
	onTimerEvent: function() {
		var now = new Date().getTime();
		var timePassed = now - this.lastTime;
		this.lastTime = now;
		var movement = (timePassed / this.options.duration) * (this.state < this.target ? 1 : -1);
		if (Math.abs(movement) >= Math.abs(this.state - this.target)) {
			this.state = this.target;
		} else {
			this.state += movement;
		}
		
		try {
			this.propagate();
		} finally {
			this.options.onStep.call(this);
			if (this.target == this.state) {
				window.clearInterval(this.intervalId);
				this.intervalId = null;
				this.options.onComplete.call(this);
			}
		}
	},
	// shortcuts
	play: function() {this.seekFromTo(0, 1)},
	reverse: function() {this.seekFromTo(1, 0)},
	// return a string describing this Animator, for debugging
	inspect: function() {
		var str = "#<Animator:\n";
		for (var i=0; i<this.subjects.length; i++) {
			str += this.subjects[i].inspect();
		}
		str += ">";
		return str;
	}
}
// merge the properties of two objects
Animator.applyDefaults = function(defaults, prefs) {
	prefs = prefs || {};
	var prop, result = {};
	for (prop in defaults) result[prop] = prefs[prop] !== undefined ? prefs[prop] : defaults[prop];
	return result;
}
// make an array from any object
Animator.makeArray = function(o) {
	if (o == null) return [];
	if (!o.length) return [o];
	var result = [];
	for (var i=0; i<o.length; i++) result[i] = o[i];
	return result;
}
// convert a dash-delimited-property to a camelCaseProperty (c/o Prototype, thanks Sam!)
Animator.camelize = function(string) {
	var oStringList = string.split('-');
	if (oStringList.length == 1) return oStringList[0];
	
	var camelizedString = string.indexOf('-') == 0
		? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
		: oStringList[0];
	
	for (var i = 1, len = oStringList.length; i < len; i++) {
		var s = oStringList[i];
		camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
	}
	return camelizedString;
}
// syntactic sugar for creating CSSStyleSubjects
Animator.apply = function(el, style, options) {
	if (style instanceof Array) {
		return new Animator(options).addSubject(new CSSStyleSubject(el, style[0], style[1]));
	}
	return new Animator(options).addSubject(new CSSStyleSubject(el, style));
}
// make a transition function that gradually accelerates. pass a=1 for smooth
// gravitational acceleration, higher values for an exaggerated effect
Animator.makeEaseIn = function(a) {
	return function(state) {
		return Math.pow(state, a*2); 
	}
}
// as makeEaseIn but for deceleration
Animator.makeEaseOut = function(a) {
	return function(state) {
		return 1 - Math.pow(1 - state, a*2); 
	}
}
// make a transition function that, like an object with momentum being attracted to a point,
// goes past the target then returns
Animator.makeElastic = function(bounces) {
	return function(state) {
		state = Animator.tx.easeInOut(state);
		return ((1-Math.cos(state * Math.PI * bounces)) * (1 - state)) + state; 
	}
}
// make an Attack Decay Sustain Release envelope that starts and finishes on the same level
// 
Animator.makeADSR = function(attackEnd, decayEnd, sustainEnd, sustainLevel) {
	if (sustainLevel == null) sustainLevel = 0.5;
	return function(state) {
		if (state < attackEnd) {
			return state / attackEnd;
		}
		if (state < decayEnd) {
			return 1 - ((state - attackEnd) / (decayEnd - attackEnd) * (1 - sustainLevel));
		}
		if (state < sustainEnd) {
			return sustainLevel;
		}
		return sustainLevel * (1 - ((state - sustainEnd) / (1 - sustainEnd)));
	}
}
// make a transition function that, like a ball falling to floor, reaches the target and/
// bounces back again
Animator.makeBounce = function(bounces) {
	var fn = Animator.makeElastic(bounces);
	return function(state) {
		state = fn(state); 
		return state <= 1 ? state : 2-state;
	}
}
 
// pre-made transition functions to use with the 'transition' option
Animator.tx = {
	easeInOut: function(pos){
		return ((-Math.cos(pos*Math.PI)/2) + 0.5);
	},
	linear: function(x) {
		return x;
	},
	easeIn: Animator.makeEaseIn(1.5),
	easeOut: Animator.makeEaseOut(1.5),
	strongEaseIn: Animator.makeEaseIn(2.5),
	strongEaseOut: Animator.makeEaseOut(2.5),
	elastic: Animator.makeElastic(1),
	veryElastic: Animator.makeElastic(3),
	bouncy: Animator.makeBounce(1),
	veryBouncy: Animator.makeBounce(3)
}

// animates a pixel-based style property between two integer values
function NumericalStyleSubject(els, property, from, to, units) {
	this.els = Animator.makeArray(els);
	if (property == 'opacity' && window.ActiveXObject) {
		this.property = 'filter';
	} else {
		this.property = Animator.camelize(property);
	}
	this.from = parseFloat(from);
	this.to = parseFloat(to);
	this.units = units != null ? units : 'px';
}
NumericalStyleSubject.prototype = {
	setState: function(state) {
		var style = this.getStyle(state);
		var visibility = (this.property == 'opacity' && state == 0) ? 'hidden' : '';
		var j=0;
		for (var i=0; i<this.els.length; i++) {
			try {
				this.els[i].style[this.property] = style;
			} catch (e) {
				// ignore fontWeight - intermediate numerical values cause exeptions in firefox
				if (this.property != 'fontWeight') throw e;
			}
			if (j++ > 20) return;
		}
	},
	getStyle: function(state) {
		state = this.from + ((this.to - this.from) * state);
		if (this.property == 'filter') return "alpha(opacity=" + Math.round(state*100) + ")";
		if (this.property == 'opacity') return state;
		return Math.round(state) + this.units;
	},
	inspect: function() {
		return "\t" + this.property + "(" + this.from + this.units + " to " + this.to + this.units + ")\n";
	}
}

// animates a colour based style property between two hex values
function ColorStyleSubject(els, property, from, to) {
	this.els = Animator.makeArray(els);
	this.property = Animator.camelize(property);
	this.to = this.expandColor(to);
	this.from = this.expandColor(from);
	this.origFrom = from;
	this.origTo = to;
}

ColorStyleSubject.prototype = {
	// parse "#FFFF00" to [256, 256, 0]
	expandColor: function(color) {
		var hexColor, red, green, blue;
		hexColor = ColorStyleSubject.parseColor(color);
		if (hexColor) {
			red = parseInt(hexColor.slice(1, 3), 16);
			green = parseInt(hexColor.slice(3, 5), 16);
			blue = parseInt(hexColor.slice(5, 7), 16);
			return [red,green,blue]
		}
		if (window.DEBUG) {
			alert("Invalid colour: '" + color + "'");
		}
	},
	getValueForState: function(color, state) {
		return Math.round(this.from[color] + ((this.to[color] - this.from[color]) * state));
	},
	setState: function(state) {
		var color = '#'
				+ ColorStyleSubject.toColorPart(this.getValueForState(0, state))
				+ ColorStyleSubject.toColorPart(this.getValueForState(1, state))
				+ ColorStyleSubject.toColorPart(this.getValueForState(2, state));
		for (var i=0; i<this.els.length; i++) {
			this.els[i].style[this.property] = color;
		}
	},
	inspect: function() {
		return "\t" + this.property + "(" + this.origFrom + " to " + this.origTo + ")\n";
	}
}

// return a properly formatted 6-digit hex colour spec, or false
ColorStyleSubject.parseColor = function(string) {
	var color = '#', match;
	if(match = ColorStyleSubject.parseColor.rgbRe.exec(string)) {
		var part;
		for (var i=1; i<=3; i++) {
			part = Math.max(0, Math.min(255, parseInt(match[i])));
			color += ColorStyleSubject.toColorPart(part);
		}
		return color;
	}
	if (match = ColorStyleSubject.parseColor.hexRe.exec(string)) {
		if(match[1].length == 3) {
			for (var i=0; i<3; i++) {
				color += match[1].charAt(i) + match[1].charAt(i);
			}
			return color;
		}
		return '#' + match[1];
	}
	return false;
}
// convert a number to a 2 digit hex string
ColorStyleSubject.toColorPart = function(number) {
	if (number > 255) number = 255;
	var digits = number.toString(16);
	if (number < 16) return '0' + digits;
	return digits;
}
ColorStyleSubject.parseColor.rgbRe = /^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i;
ColorStyleSubject.parseColor.hexRe = /^\#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;

// Animates discrete styles, i.e. ones that do not scale but have discrete values
// that can't be interpolated
function DiscreteStyleSubject(els, property, from, to, threshold) {
	this.els = Animator.makeArray(els);
	this.property = Animator.camelize(property);
	this.from = from;
	this.to = to;
	this.threshold = threshold || 0.5;
}

DiscreteStyleSubject.prototype = {
	setState: function(state) {
		var j=0;
		for (var i=0; i<this.els.length; i++) {
			this.els[i].style[this.property] = state <= this.threshold ? this.from : this.to; 
		}
	},
	inspect: function() {
		return "\t" + this.property + "(" + this.from + " to " + this.to + " @ " + this.threshold + ")\n";
	}
}

// animates between two styles defined using CSS.
// if style1 and style2 are present, animate between them, if only style1
// is present, animate between the element's current style and style1
function CSSStyleSubject(els, style1, style2) {
	els = Animator.makeArray(els);
	this.subjects = [];
	if (els.length == 0) return;
	var prop, toStyle, fromStyle;
	if (style2) {
		fromStyle = this.parseStyle(style1, els[0]);
		toStyle = this.parseStyle(style2, els[0]);
	} else {
		toStyle = this.parseStyle(style1, els[0]);
		fromStyle = {};
		for (prop in toStyle) {
			fromStyle[prop] = CSSStyleSubject.getStyle(els[0], prop);
		}
	}
	// remove unchanging properties
	var prop;
	for (prop in fromStyle) {
		if (fromStyle[prop] == toStyle[prop]) {
			delete fromStyle[prop];
			delete toStyle[prop];
		}
	}
	// discover the type (numerical or colour) of each style
	var prop, units, match, type, from, to;
	for (prop in fromStyle) {
		var fromProp = String(fromStyle[prop]);
		var toProp = String(toStyle[prop]);
		if (toStyle[prop] == null) {
			if (window.DEBUG) alert("No to style provided for '" + prop + '"');
			continue;
		}
		
		if (from = ColorStyleSubject.parseColor(fromProp)) {
			to = ColorStyleSubject.parseColor(toProp);
			type = ColorStyleSubject;
		} else if (fromProp.match(CSSStyleSubject.numericalRe)
				&& toProp.match(CSSStyleSubject.numericalRe)) {
			from = parseFloat(fromProp);
			to = parseFloat(toProp);
			type = NumericalStyleSubject;
			match = CSSStyleSubject.numericalRe.exec(fromProp);
			var reResult = CSSStyleSubject.numericalRe.exec(toProp);
			if (match[1] != null) {
				units = match[1];
			} else if (reResult[1] != null) {
				units = reResult[1];
			} else {
				units = reResult;
			}
		} else if (fromProp.match(CSSStyleSubject.discreteRe)
				&& toProp.match(CSSStyleSubject.discreteRe)) {
			from = fromProp;
			to = toProp;
			type = DiscreteStyleSubject;
			units = 0;   // hack - how to get an animator option down to here
		} else {
			if (window.DEBUG) {
				alert("Unrecognised format for value of "
					+ prop + ": '" + fromStyle[prop] + "'");
			}
			continue;
		}
		this.subjects[this.subjects.length] = new type(els, prop, from, to, units);
	}
}

CSSStyleSubject.prototype = {
	// parses "width: 400px; color: #FFBB2E" to {width: "400px", color: "#FFBB2E"}
	parseStyle: function(style, el) {
		var rtn = {};
		// if style is a rule set
		if (style.indexOf(":") != -1) {
			var styles = style.split(";");
			for (var i=0; i<styles.length; i++) {
				var parts = CSSStyleSubject.ruleRe.exec(styles[i]);
				if (parts) {
					rtn[parts[1]] = parts[2];
				}
			}
		}
		// else assume style is a class name
		else {
			var prop, value, oldClass;
			oldClass = el.className;
			el.className = style;
			for (var i=0; i<CSSStyleSubject.cssProperties.length; i++) {
				prop = CSSStyleSubject.cssProperties[i];
				value = CSSStyleSubject.getStyle(el, prop);
				if (value != null) {
					rtn[prop] = value;
				}
			}
			el.className = oldClass;
		}
		return rtn;
		
	},
	setState: function(state) {
		for (var i=0; i<this.subjects.length; i++) {
			this.subjects[i].setState(state);
		}
	},
	inspect: function() {
		var str = "";
		for (var i=0; i<this.subjects.length; i++) {
			str += this.subjects[i].inspect();
		}
		return str;
	}
}
// get the current value of a css property, 
CSSStyleSubject.getStyle = function(el, property){
	var style;
	if(document.defaultView && document.defaultView.getComputedStyle){
		style = document.defaultView.getComputedStyle(el, "").getPropertyValue(property);
		if (style) {
			return style;
		}
	}
	property = Animator.camelize(property);
	if(el.currentStyle){
		style = el.currentStyle[property];
	}
	return style || el.style[property]
}


CSSStyleSubject.ruleRe = /^\s*([a-zA-Z\-]+)\s*:\s*(\S(.+\S)?)\s*$/;
CSSStyleSubject.numericalRe = /^-?\d+(?:\.\d+)?(%|[a-zA-Z]{2})?$/;
CSSStyleSubject.discreteRe = /^\w+$/;

// required because the style object of elements isn't enumerable in Safari
/*
CSSStyleSubject.cssProperties = ['background-color','border','border-color','border-spacing',
'border-style','border-top','border-right','border-bottom','border-left','border-top-color',
'border-right-color','border-bottom-color','border-left-color','border-top-width','border-right-width',
'border-bottom-width','border-left-width','border-width','bottom','color','font-size','font-size-adjust',
'font-stretch','font-style','height','left','letter-spacing','line-height','margin','margin-top',
'margin-right','margin-bottom','margin-left','marker-offset','max-height','max-width','min-height',
'min-width','orphans','outline','outline-color','outline-style','outline-width','overflow','padding',
'padding-top','padding-right','padding-bottom','padding-left','quotes','right','size','text-indent',
'top','width','word-spacing','z-index','opacity','outline-offset'];*/


CSSStyleSubject.cssProperties = ['azimuth','background','background-attachment','background-color','background-image','background-position','background-repeat','border-collapse','border-color','border-spacing','border-style','border-top','border-top-color','border-right-color','border-bottom-color','border-left-color','border-top-style','border-right-style','border-bottom-style','border-left-style','border-top-width','border-right-width','border-bottom-width','border-left-width','border-width','bottom','clear','clip','color','content','cursor','direction','display','elevation','empty-cells','css-float','font','font-family','font-size','font-size-adjust','font-stretch','font-style','font-variant','font-weight','height','left','letter-spacing','line-height','list-style','list-style-image','list-style-position','list-style-type','margin','margin-top','margin-right','margin-bottom','margin-left','max-height','max-width','min-height','min-width','orphans','outline','outline-color','outline-style','outline-width','overflow','padding','padding-top','padding-right','padding-bottom','padding-left','pause','position','right','size','table-layout','text-align','text-decoration','text-indent','text-shadow','text-transform','top','vertical-align','visibility','white-space','width','word-spacing','z-index','opacity','outline-offset','overflow-x','overflow-y'];


// chains several Animator objects together
function AnimatorChain(animators, options) {
	this.animators = animators;
	this.setOptions(options);
	for (var i=0; i<this.animators.length; i++) {
		this.listenTo(this.animators[i]);
	}
	this.forwards = false;
	this.current = 0;
}

AnimatorChain.prototype = {
	// apply defaults
	setOptions: function(options) {
		this.options = Animator.applyDefaults({
			// by default, each call to AnimatorChain.play() calls jumpTo(0) of each animator
			// before playing, which can cause flickering if you have multiple animators all
			// targeting the same element. Set this to false to avoid this.
			resetOnPlay: true
		}, options);
	},
	// play each animator in turn
	play: function() {
		this.forwards = true;
		this.current = -1;
		if (this.options.resetOnPlay) {
			for (var i=0; i<this.animators.length; i++) {
				this.animators[i].jumpTo(0);
			}
		}
		this.advance();
	},
	// play all animators backwards
	reverse: function() {
		this.forwards = false;
		this.current = this.animators.length;
		if (this.options.resetOnPlay) {
			for (var i=0; i<this.animators.length; i++) {
				this.animators[i].jumpTo(1);
			}
		}
		this.advance();
	},
	// if we have just play()'d, then call reverse(), and vice versa
	toggle: function() {
		if (this.forwards) {
			this.seekTo(0);
		} else {
			this.seekTo(1);
		}
	},
	// internal: install an event listener on an animator's onComplete option
	// to trigger the next animator
	listenTo: function(animator) {
		var oldOnComplete = animator.options.onComplete;
		var _this = this;
		animator.options.onComplete = function() {
			if (oldOnComplete) oldOnComplete.call(animator);
			_this.advance();
		}
	},
	// play the next animator
	advance: function() {
		if (this.forwards) {
			if (this.animators[this.current + 1] == null) return;
			this.current++;
			this.animators[this.current].play();
		} else {
			if (this.animators[this.current - 1] == null) return;
			this.current--;
			this.animators[this.current].reverse();
		}
	},
	// this function is provided for drop-in compatibility with Animator objects,
	// but only accepts 0 and 1 as target values
	seekTo: function(target) {
		if (target <= 0) {
			this.forwards = false;
			this.animators[this.current].seekTo(0);
		} else {
			this.forwards = true;
			this.animators[this.current].seekTo(1);
		}
	}
}

// an Accordion is a class that creates and controls a number of Animators. An array of elements is passed in,
// and for each element an Animator and a activator button is created. When an Animator's activator button is
// clicked, the Animator and all before it seek to 0, and all Animators after it seek to 1. This can be used to
// create the classic Accordion effect, hence the name.
// see setOptions for arguments
function Accordion(options) {
	this.setOptions(options);
	var selected = this.options.initialSection, current;
	if (this.options.rememberance) {
		current = document.location.hash.substring(1);
	}
	this.rememberanceTexts = [];
	this.ans = [];
	var _this = this;
	for (var i=0; i<this.options.sections.length; i++) {
		var el = this.options.sections[i];
		var an = new Animator(this.options.animatorOptions);
		var from = this.options.from + (this.options.shift * i);
		var to = this.options.to + (this.options.shift * i);
		an.addSubject(new NumericalStyleSubject(el, this.options.property, from, to, this.options.units));
		an.jumpTo(0);
		var activator = this.options.getActivator(el);
		activator.index = i;
		activator.onclick = function(){_this.show(this.index)};
		this.ans[this.ans.length] = an;
		this.rememberanceTexts[i] = activator.innerHTML.replace(/\s/g, "");
		if (this.rememberanceTexts[i] === current) {
			selected = i;
		}
	}
	this.show(selected);
}

Accordion.prototype = {
	// apply defaults
	setOptions: function(options) {
		this.options = Object.extend({
			// REQUIRED: an array of elements to use as the accordion sections
			sections: null,
			// a function that locates an activator button element given a section element.
			// by default it takes a button id from the section's "activator" attibute
			getActivator: function(el) {return document.getElementById(el.getAttribute("activator"))},
			// shifts each animator's range, for example with options {from:0,to:100,shift:20}
			// the animators' ranges will be 0-100, 20-120, 40-140 etc.
			shift: 0,
			// the first page to show
			initialSection: 0,
			// if set to true, document.location.hash will be used to preserve the open section across page reloads 
			rememberance: true,
			// constructor arguments to the Animator objects
			animatorOptions: {}
		}, options || {});
	},
	show: function(section) {
		for (var i=0; i<this.ans.length; i++) {
			this.ans[i].seekTo(i > section ? 1 : 0);
		}
		if (this.options.rememberance) {
			document.location.hash = this.rememberanceTexts[section];
		}
	}
}

function ThreeSixtyPlayer() {
  var self = this;
  var pl = this;
  var sm = soundManager; // soundManager instance
  var isIE = (navigator.userAgent.match(/msie/i));
  var isOpera = (navigator.userAgent.match(/opera/i));
  var isSafari = (navigator.userAgent.match(/safari/i));
  var isChrome = (navigator.userAgent.match(/chrome/i));
  this.excludeClass = '360-exclude'; // CSS class for ignoring MP3 links

  this.links = [];
  this.sounds = [];
  this.soundsByURL = [];
  this.indexByURL = [];
  this.lastSound = null;
  this.soundCount = 0;
  this.oUITemplate = null;
  this.oUIImageMap = null;

  this.config = {
    playNext: true,   // stop after one sound, or play through list until end
    autoPlay: false,   // start playing the first sound right away
    loadRingColor: '#ccc', // how much has loaded
    playRingColor: '#aaa', // how much has played
    backgroundRingColor: '#eee', // color shown underneath load + play ("not yet loaded" color)
    circleDiameter: null, // set dynamically according to values from CSS
    circleRadius: null,
    imageRoot: '/bin/sm2/demo/360-player/', // image path to prepend for transparent .GIF - eg. /images/
    animDuration: 500,
    animTransition: Animator.tx.bouncy, // http://www.berniecode.com/writing/animator.html
    showHMSTime: true, // hours:minutes:seconds vs. seconds-only
    scaleFont: false,  // also set the font size (if possible) while animating the circle

    useWaveformData: false, // optional: spectrum or EQ graph in canvas
    waveformDataColor: '#0099ff',
    waveformDataDownsample: 3, // use only one in X (of a set of 256 values) - 1 means all 256
    waveformDataOutside: false,
    waveformDataConstrain: false, // if true, +ve values only - keep within inside circle
    waveformDataLineRatio: 0.64,

    useEQData: true,
    eqDataColor: '#339933',
    eqDataDownsample: 4, // use only one in X (of 256 values)
    eqDataOutside: true,
    eqDataLineRatio: 0.54,

    usePeakData: true,
    peakDataColor: '#ff33ff',
    peakDataOutside: true,
    peakDataLineRatio: 0.5,

    useAmplifier: false, // "pulse" like a speaker

    fontSizeMax: null // set according to CSS

  }

  this.css = {
    // CSS class names appended to link during various states
    sDefault: 'sm2_link', // default state
    sBuffering: 'sm2_buffering',
    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.hasClass = function(o,cStr) {
	return (typeof(o.className)!='undefined'?o.className.match(new RegExp('(\\s|^)'+cStr+'(\\s|$)')):false);
  }

  this.addClass = function(o,cStr) {
    if (!o || !cStr || self.hasClass(o,cStr)) return false;
    o.className = (o.className?o.className+' ':'')+cStr;
  }

  this.removeClass = function(o,cStr) {
    if (!o || !cStr || !self.hasClass(o,cStr)) return false;
    o.className = o.className.replace(new RegExp('( '+cStr+')|('+cStr+')','g'),'');
  }

  this.getElementsByClassName = function(className,tagNames,oParent) {
    var doc = (oParent||document);
    var matches = [];
    var i,j;
    var nodes = [];
    if (typeof tagNames != 'undefined' && typeof tagNames != 'string') {
      for (i=tagNames.length; i--;) {
        if (!nodes || !nodes[tagNames[i]]) {
          nodes[tagNames[i]] = doc.getElementsByTagName(tagNames[i]);
        }
      }
    } else if (tagNames) {
      nodes = doc.getElementsByTagName(tagNames);
    } else {
      nodes = doc.all||doc.getElementsByTagName('*');
    }
    if (typeof(tagNames)!='string') {
      for (i=tagNames.length; i--;) {
        for (j=nodes[tagNames[i]].length; j--;) {
          if (self.hasClass(nodes[tagNames[i]][j],className)) {
            matches.push(nodes[tagNames[i]][j]);
          }
        }
      }
    } else {
      for (i=0; i<nodes.length; i++) {
        if (self.hasClass(nodes[i],className)) {
          matches.push(nodes[i]);
        }
      }
    }
    return matches;
  }

  this.getParentByNodeName = function(oChild,sParentNodeName) {
    if (!oChild || !sParentNodeName) return false;
    sParentNodeName = sParentNodeName.toLowerCase();
    while (oChild.parentNode && sParentNodeName != oChild.parentNode.nodeName.toLowerCase()) {
      oChild = oChild.parentNode;
    }
    return (oChild.parentNode && sParentNodeName == oChild.parentNode.nodeName.toLowerCase()?oChild.parentNode:null);
  }

  this.getParentByClassName = function(oChild,sParentClassName) {
    if (!oChild || !sParentClassName) return false;
    while (oChild.parentNode && !self.hasClass(oChild.parentNode,sParentClassName)) {
      oChild = oChild.parentNode;
    }
    return (oChild.parentNode && self.hasClass(oChild.parentNode,sParentClassName)?oChild.parentNode:null);
  }

  this.getSoundByURL = function(sURL) {
    return (typeof self.soundsByURL[sURL] != 'undefined'?self.soundsByURL[sURL]:null);
  }

  this.isChildOfNode = function(o,sNodeName) {
    if (!o || !o.parentNode) {
      return false;
    }
    sNodeName = sNodeName.toLowerCase();
    do {
      o = o.parentNode;
    } while (o && o.parentNode && o.nodeName.toLowerCase() != sNodeName);
    return (o && o.nodeName.toLowerCase() == sNodeName?o:null);
  }

  this.isChildOfClass = function(oChild,oClass) {
    if (!oChild || !oClass) return false;
    while (oChild.parentNode && !self.hasClass(oChild,oClass)) {
      oChild = self.findParent(oChild);
    }
    return (self.hasClass(oChild,oClass));
  }

  this.findParent = function(o) {
    if (!o || !o.parentNode) return false;
    o = o.parentNode;
    if (o.nodeType == 2) {
      while (o && o.parentNode && o.parentNode.nodeType == 2) {
        o = o.parentNode;
      }
    }
    return o;
  }

  this.getStyle = function(o,sProp) {
	// http://www.quirksmode.org/dom/getstyles.html
	try {
	  if (o.currentStyle) {
	    return o.currentStyle[sProp];
      } else if (window.getComputedStyle) {
	    return document.defaultView.getComputedStyle(o,null).getPropertyValue(sProp);
	  }
	} catch(e) {
	  // oh well	
	}
	return null;
  }

  this.findXY = function(obj) {
    var curleft = 0;
    var curtop = 0;
    do {
	  curleft += obj.offsetLeft;
	  curtop += obj.offsetTop;
	} while (obj = obj.offsetParent);
    return [curleft,curtop];
  }

  this.getMouseXY = function(e) {
    // http://www.quirksmode.org/js/events_properties.html
    e = e?e:event;
    if (e.pageX || e.pageY) {
	  return [e.pageX,e.pageY];
    } else if (e.clientX || e.clientY) {
	  return [e.clientX+self.getScrollLeft(),e.clientY+self.getScrollTop()];
    }
  }

  this.getScrollLeft = function() {
    return (document.body.scrollLeft+document.documentElement.scrollLeft);
  }

  this.getScrollTop = function() {
    return (document.body.scrollTop+document.documentElement.scrollTop);
  }

  this.events = {

    // handlers for sound events as they're started/stopped/played

    play: function() {
      pl.removeClass(this._360data.oUIBox,this._360data.className);
      this._360data.className = pl.css.sPlaying;
      pl.addClass(this._360data.oUIBox,this._360data.className);
	  self.fanOut(this);
    },

    stop: function() {
      pl.removeClass(this._360data.oUIBox,this._360data.className);
      this._360data.className = '';
	  self.fanIn(this);
    },

    pause: function() {
      pl.removeClass(this._360data.oUIBox,this._360data.className);
      this._360data.className = pl.css.sPaused;
      pl.addClass(this._360data.oUIBox,this._360data.className);
    },

    resume: function() {
      pl.removeClass(this._360data.oUIBox,this._360data.className);
      this._360data.className = pl.css.sPlaying;
      pl.addClass(this._360data.oUIBox,this._360data.className);      
    },

    finish: function() {
      pl.removeClass(this._360data.oUIBox,this._360data.className);
      this._360data.className = '';
      // self.clearCanvas(this._360data.oCanvas);
      this._360data.didFinish = true; // so fan draws full circle
	  self.fanIn(this);
      if (pl.config.playNext) {
        var nextLink = (pl.indexByURL[this._360data.oLink.href]+1);
        if (nextLink<pl.links.length) {
          pl.handleClick({'target':pl.links[nextLink]});
        }
      }
    },

	whileloading: function() {
      if (this.paused) {
        self.updatePlaying.apply(this);
      }
	},
	
	whileplaying: function() {
      self.updatePlaying.apply(this);
	},

     bufferchange: function() {
       if (this.isBuffering) {
         pl.addClass(this._360data.oUIBox,pl.css.sBuffering);
       } else {
         pl.removeClass(this._360data.oUIBox,pl.css.sBuffering);
       }
     }

  }

  this.stopEvent = function(e) {
   if (typeof e != 'undefined' && typeof e.preventDefault != 'undefined') {
      e.preventDefault();
    } else if (typeof event != 'undefined' && typeof event.returnValue != 'undefined') {
      event.returnValue = false;
    }
    return false;
  }

  this.getTheDamnLink = (isIE)?function(e) {
    // I really didn't want to have to do this.
    return (e && e.target?e.target:window.event.srcElement);
  }:function(e) {
    return e.target;
  }

  this.handleClick = function(e) {
    // a sound link was clicked
    var o = self.getTheDamnLink(e);
    if (o.nodeName.toLowerCase() != 'a') {
      o = self.isChildOfNode(o,'a');
      if (!o) return true;
    }
    if (!self.isChildOfClass(o,'ui360')) {
	  // not a link we're interested in
	  return true;
    }
    var sURL = o.getAttribute('href');
    if (!o.href || !sm.canPlayURL(o.href) || self.hasClass(o,self.excludeClass)) {
      if (isIE && o.onclick) {
        return false; // IE will run this handler before .onclick(), everyone else is cool?
      }
      return true; // pass-thru for non-MP3/non-links
    }
    sm._writeDebug('handleClick()');
    var soundURL = (o.href);
    var thisSound = self.getSoundByURL(soundURL);
    if (thisSound) {
      // already exists
      if (thisSound == self.lastSound) {
        // and was playing (or paused)
        thisSound.togglePause();
      } else {
        // different sound
        thisSound.togglePause(); // start playing current
        sm._writeDebug('sound different than last sound: '+self.lastSound.sID);
        if (self.lastSound) {
		  self.stopSound(self.lastSound);
		}
      }
    } else {
	  // append some dom shiz
	
      // create sound
      thisSound = sm.createSound({
       id:'ui360Sound'+(self.soundCount++),
       url:soundURL,
       onplay:self.events.play,
       onstop:self.events.stop,
       onpause:self.events.pause,
       onresume:self.events.resume,
       onfinish:self.events.finish,
       onbufferchange:self.events.bufferchange,
	   whileloading:self.events.whileloading,
	   whileplaying:self.events.whileplaying
      });
      var oContainer = o.parentNode;
      // tack on some custom data

      thisSound._360data = {
        oLink: o, // DOM node for reference within SM2 object event handlers
        className: self.css.sPlaying,
        oUIBox: self.getElementsByClassName('sm2-360ui','div',oContainer)[0],
        oCanvas: self.getElementsByClassName('sm2-canvas','canvas',oContainer)[0],
        oButton: self.getElementsByClassName('sm2-360btn','img',oContainer)[0],
        oTiming: self.getElementsByClassName('sm2-timing','div',oContainer)[0],
        oCover: self.getElementsByClassName('sm2-cover','div',oContainer)[0],
        lastTime: null,
        didFinish: null,
        pauseCount:0,
        radius:0,
        amplifier: (self.config.usePeakData?0.9:1), // TODO: x1 if not being used, else use dynamic "how much to amplify by" value
		radiusMax: self.config.circleDiameter*0.175, // circle radius
		width:0,
		widthMax: self.config.circleDiameter*0.4, // width of the outer ring
		lastValues: {
		  bytesLoaded: 0,
		  bytesTotal: 0,
		  position: 0,
		  durationEstimate: 0
		}, // used to track "last good known" values before sound finish/reset for anim
		animating: false,
		oAnim: new Animator({
		  duration: self.config.animDuration,
		  transition:self.config.animTransition,
		  onComplete: function() {
			// var thisSound = this;
			// thisSound._360data.didFinish = false; // reset full circle
  		  }
		}),
		oAnimProgress: function(nProgress) {
		  var thisSound = this;
		  thisSound._360data.radius = parseInt(thisSound._360data.radiusMax*thisSound._360data.amplifier*nProgress);
		  thisSound._360data.width = parseInt(thisSound._360data.widthMax*thisSound._360data.amplifier*nProgress);
          if (self.config.scaleFont && self.config.fontSizeMax != null) {
		    thisSound._360data.oTiming.style.fontSize = parseInt(Math.max(1,self.config.fontSizeMax*nProgress))+'px';
		    thisSound._360data.oTiming.style.opacity = nProgress;
		  }
		  if (thisSound.paused || thisSound.playState == 0 || thisSound._360data.lastValues.bytesLoaded == 0 || thisSound._360data.lastValues.position == 0) {
            self.updatePlaying.apply(thisSound);
          }
		}
      };

	  // set the cover width/height to match the canvas
	  thisSound._360data.oCover.style.width = self.config.circleDiameter+'px';
	  thisSound._360data.oCover.style.height = self.config.circleDiameter+'px';

	  // minimize ze font
	  if (self.config.scaleFont && self.config.fontSizeMax != null) {
	    thisSound._360data.oTiming.style.fontSize = '1px';
	  }

	  // set up ze animation
	  thisSound._360data.oAnim.addSubject(thisSound._360data.oAnimProgress,thisSound);

	  // animate the radius out nice
	  self.refreshCoords(thisSound);

	  self.updatePlaying.apply(thisSound);

      self.soundsByURL[soundURL] = thisSound;
      self.sounds.push(thisSound);
      if (self.lastSound) {
	    self.stopSound(self.lastSound);
	  }
      thisSound.play();
    }

    self.lastSound = thisSound; // reference for next call

    if (typeof e != 'undefined' && typeof e.preventDefault != 'undefined') {
      e.preventDefault();
    } else if (typeof event != 'undefined') {
      event.returnValue = false;
    }
    return false;
  }

  this.fanOut = function(oSound) {
	 var thisSound = oSound;
	 if (thisSound._360data.animating == 1) {
	   return false;	
	 }
	 thisSound._360data.animating = 0;
	 soundManager._writeDebug('fanOut: '+thisSound.sID+': '+thisSound._360data.oLink.href);
	 thisSound._360data.oAnim.seekTo(1); // play to end
	 window.setTimeout(function() {
	   // oncomplete hack
	   thisSound._360data.animating = 0;
	 },self.config.animDuration+20);
  }

  this.fanIn = function(oSound) {
	 var thisSound = oSound;
	 if (thisSound._360data.animating == -1) {
	   return false;	
	 }
	 thisSound._360data.animating = -1;
	 soundManager._writeDebug('fanIn: '+thisSound.sID+': '+thisSound._360data.oLink.href);
	// massive hack
	 thisSound._360data.oAnim.seekTo(0); // play to end
	window.setTimeout(function() {
	 // reset full 360 fill after animation has completed (oncomplete hack)
	  thisSound._360data.didFinish = false;
	  thisSound._360data.animating = 0;
	  self.resetLastValues(thisSound);
	},self.config.animDuration+20);

  }

  this.resetLastValues = function(oSound) {
    var oData = oSound._360data;
    oData.lastValues.position = 0;
    // oData.lastValues.bytesLoaded = 0; // will likely be cached, if file is small
    // oData.lastValues.bytesTotal = 0;
    // oData.lastValues.durationEstimate = 0;
  }

  this.refreshCoords = function(thisSound) {
    thisSound._360data.canvasXY = self.findXY(thisSound._360data.oCanvas);
    // thisSound._360data.canvasMid = [Math.floor(thisSound._360data.oCanvas.offsetWidth/2), Math.floor(thisSound._360data.oCanvas.offsetHeight/2)]; // doesn't work in IE, w/h are wrong
    thisSound._360data.canvasMid = [self.config.circleRadius,self.config.circleRadius];
    thisSound._360data.canvasMidXY = [thisSound._360data.canvasXY[0]+thisSound._360data.canvasMid[0], thisSound._360data.canvasXY[1]+thisSound._360data.canvasMid[1]];
  }

  this.stopSound = function(oSound) {
	soundManager._writeDebug('stopSound: '+oSound.sID);
    soundManager.stop(oSound.sID);
    soundManager.unload(oSound.sID);
  }

  this.buttonClick = function(e) {
    var o = e?(e.target?e.target:e.srcElement):event.srcElement;
    self.handleClick({target:self.getParentByClassName(o,'sm2-360ui').nextSibling}); // link next to the nodes we inserted
    return false;
  }

  this.buttonMouseDown = function(e) {
	// user might decide to drag from here
	// watch for mouse move
	document.onmousemove = function(e) {
	  // should be boundary-checked, really (eg. move 3px first?)
	  self.mouseDown(e);
	}
	self.stopEvent(e);
	return false;
  }

  this.mouseDown = function(e) { 
    if (!self.lastSound) {
	  self.stopEvent(e);
      return false;	
    }
    var thisSound = self.lastSound;
    // just in case, update coordinates (maybe the element moved since last time.)
    self.refreshCoords(thisSound);
    var oData = self.lastSound._360data;
    self.addClass(oData.oUIBox,'sm2_dragging');
    oData.pauseCount = (self.lastSound.paused?1:0);
    // self.lastSound.pause();
    self.mmh(e?e:event);
    document.onmousemove = self.mmh;
    document.onmouseup = self.mouseUp;
    self.stopEvent(e);
    return false;
  }

  this.mouseUp = function(e) {
    var oData = self.lastSound._360data;
    self.removeClass(oData.oUIBox,'sm2_dragging');
    if (oData.pauseCount == 0) {
      self.lastSound.resume();
    }
    document.onmousemove = null;
    document.onmouseup = null;
  }

  var fullCircle = 360;

  this.mmh = function(e) {
	if (typeof e == 'undefined') {
	  var e = event;
	}
    var oSound = self.lastSound;
    var coords = self.getMouseXY(e);
    var x = coords[0];
 	var y = coords[1];
    var deltaX = x-oSound._360data.canvasMidXY[0];
    var deltaY = y-oSound._360data.canvasMidXY[1];
    var angle = Math.floor(fullCircle-(self.rad2deg(Math.atan2(deltaX,deltaY))+180));
    oSound.setPosition(oSound.durationEstimate*(angle/fullCircle));
    self.stopEvent(e);
    return false;
  }

  // assignMouseDown();

  this.drawSolidArc = function(oCanvas, color, radius, width, radians, startAngle, noClear) {

    // thank you, http://www.snipersystems.co.nz/community/polarclock/tutorial.html

    var x = radius;
    var y = radius;

    var canvas = oCanvas;

    if (canvas.getContext){
      // use getContext to use the canvas for drawing
      var ctx = canvas.getContext('2d');
    }

    // var startAngle = 0;
    var oCanvas = ctx;

    if (!noClear) {
      self.clearCanvas(canvas);
    }
    // ctx.restore();

    if (color) {
	  ctx.fillStyle = color;
    } else {
	  // ctx.fillStyle = 'black';
    }

    oCanvas.beginPath();

    if (isNaN(radians)) {
	  radians = 0;
	}

    var innerRadius = radius-width;
	var doesntLikeZero = (isOpera || isSafari); // safari 4 doesn't actually seem to mind.

    if (!doesntLikeZero || (doesntLikeZero && radius > 0)) {
      oCanvas.arc(0, 0, radius, startAngle, radians, false);
      var endPoint = self.getArcEndpointCoords(innerRadius, radians);
      oCanvas.lineTo(endPoint.x, endPoint.y);
      oCanvas.arc(0, 0, innerRadius, radians, startAngle, true);
      oCanvas.closePath();
      oCanvas.fill();
    }

  }

  this.getArcEndpointCoords = function(radius, radians) {
    return {
      x: radius * Math.cos(radians), 
      y: radius * Math.sin(radians)
    };
  }


this.deg2rad = function(nDeg) {
  return (nDeg * Math.PI/180);
}

this.rad2deg = function(nRad) {
  return (nRad * 180/Math.PI);
}

this.getTime = function(nMSec,bAsString) {
  // convert milliseconds to mm:ss, return as object literal or string
  var nSec = Math.floor(nMSec/1000);
  var min = Math.floor(nSec/60);
  var sec = nSec-(min*60);
  // if (min == 0 && sec == 0) return null; // return 0:00 as null
  return (bAsString?(min+':'+(sec<10?'0'+sec:sec)):{'min':min,'sec':sec});
}

this.clearCanvas = function(oCanvas) {
    var canvas = oCanvas;
    var ctx = null;
    if (canvas.getContext){
      // use getContext to use the canvas for drawing
      ctx = canvas.getContext('2d');
    }
    var width = canvas.offsetWidth;
    var height = canvas.offsetHeight;
    ctx.clearRect(-(width/2), -(height/2), width, height);
}


var fullCircle = (isOpera||isChrome?359.9:360); // I dunno what Opera doesn't like about this.

this.updatePlaying = function() {
  if (this.bytesLoaded) {
    this._360data.lastValues.bytesLoaded = this.bytesLoaded;
    this._360data.lastValues.bytesTotal = this.bytesTotal;
  }
  if (this.position) {
    this._360data.lastValues.position = this.position;	
  }
  if (this.durationEstimate) {
    this._360data.lastValues.durationEstimate = this.durationEstimate;
  }	
  self.drawSolidArc(this._360data.oCanvas,self.config.backgroundRingColor,this._360data.width,this._360data.radius,self.deg2rad(fullCircle),0);
  self.drawSolidArc(this._360data.oCanvas,self.config.loadRingColor,this._360data.width,this._360data.radius,self.deg2rad(fullCircle*(this._360data.lastValues.bytesLoaded/this._360data.lastValues.bytesTotal)),0,true);
  if (this._360data.lastValues.position != 0) {
    // don't draw if 0 (full black circle in Opera)
    self.drawSolidArc(this._360data.oCanvas,self.config.playRingColor,this._360data.width,this._360data.radius,self.deg2rad((this._360data.didFinish==1?fullCircle:fullCircle*(this._360data.lastValues.position/this._360data.lastValues.durationEstimate))),0,true);
  }

  var timeNow = (self.config.showHMSTime?self.getTime(this.position,true):parseInt(this.position/1000));

  if (timeNow != this._360data.lastTime) {
    this._360data.lastTime = timeNow;
    this._360data.oTiming.innerHTML = timeNow;
  }

  // draw spectrum, if applicable
  if (!isIE) { // IE can render maybe 3 or 4 FPS when including the wave/EQ.
    self.updateWaveform(this);
    // self.updateWaveformOld(this);
  }

}

  this.updateWaveform = function(oSound) {

    if ((!self.config.useWaveformData && !self.config.useEQData) || (!sm.features.waveformData && !sm.features.eqData)) {
      // feature not enabled..
      return false;
    }

    if (!oSound.waveformData.left.length && !oSound.eqData.length && !oSound.peakData.left) {
      // no data (or errored out/paused/unavailable?)
      return false;
    }

	 /* use for testing the data */
	 /*
	  for (i=0; i<256; i++) {
	    oSound.eqData[i] = 1-(i/256);
	  }
	 */

    var oCanvas = oSound._360data.oCanvas.getContext('2d');
    var offX = 0;
    var offY = parseInt(self.config.circleDiameter/2);
    var scale = offY/2; // Y axis (+/- this distance from 0)
    var lineWidth = Math.floor(self.config.circleDiameter-(self.config.circleDiameter*0.175)/(self.config.circleDiameter/255)); // width for each line
    lineWidth = 1;
    var lineHeight = 1;
    var thisY = 0;
    var offset = offY;

    if (self.config.useWaveformData) {
      // raw waveform
	  var downSample = self.config.waveformDataDownsample; // only sample X in 256 (greater number = less sample points)
	  downSample = Math.max(1,downSample); // make sure it's at least 1
	  var dataLength = 256;
	  var sampleCount = (dataLength/downSample);
	  var startAngle = 0;
	  var endAngle = 0;
	  var waveData = null;
	  var innerRadius = (self.config.waveformDataOutside?1:(self.config.waveformDataConstrain?0.5:0.565));
	  var scale = (self.config.waveformDataOutside?0.7:0.75);
	  var perItemAngle = self.deg2rad((360/sampleCount)*self.config.waveformDataLineRatio); // 0.85 = clean pixel lines at 150? // self.deg2rad(360*(Math.max(1,downSample-1))/sampleCount);
	  for (var i=0; i<dataLength; i+=downSample) {
	    startAngle = self.deg2rad(360*(i/(sampleCount)*1/downSample)); // +0.67 - counter for spacing
	    endAngle = startAngle+perItemAngle;
	    waveData = oSound.waveformData.left[i];
	    if (waveData<0 && self.config.waveformDataConstrain) {
		  waveData = Math.abs(waveData);
	    }
		self.drawSolidArc(oSound._360data.oCanvas,self.config.waveformDataColor,oSound._360data.width*innerRadius,oSound._360data.radius*scale*waveData,endAngle,startAngle,true);
	  }
	}
	
	if (self.config.useEQData) {
	  // EQ spectrum
	  var downSample = self.config.eqDataDownsample; // only sample N in 256
      var yDiff = 0;
	  downSample = Math.max(1,downSample); // make sure it's at least 1
	  var eqSamples = 192; // drop the last 25% of the spectrum (>16500 Hz), most stuff won't actually use it.
	  var sampleCount = (eqSamples/downSample);
	  var innerRadius = (self.config.eqDataOutside?1:0.565);
	  var direction = (self.config.eqDataOutside?-1:1);
	  var scale = (self.config.eqDataOutside?0.5:0.75);
	  var startAngle = 0;
	  var endAngle = 0;
	  var perItemAngle = self.deg2rad((360/sampleCount)*self.config.eqDataLineRatio); // self.deg2rad(360/(sampleCount+1));
	  var playedAngle = self.deg2rad((oSound._360data.didFinish==1?360:360*(oSound._360data.lastValues.position/oSound._360data.lastValues.durationEstimate)));
	  var j=0;
	  var iAvg = 0;
      for (var i=0; i<eqSamples; i+=downSample) {
	    startAngle = self.deg2rad(360*(i/eqSamples));
	    endAngle = startAngle+perItemAngle;
 		self.drawSolidArc(oSound._360data.oCanvas,(endAngle>playedAngle?self.config.eqDataColor:self.config.playRingColor),oSound._360data.width*innerRadius,oSound._360data.radius*scale*(oSound.eqData[i]*direction),endAngle,startAngle,true);
      }
    }

/*
    if (self.config.usePeakData) {
	  // draw waveform peaks, with history, based on position
	  var peakAvg = (oSound.peakData.left||oSound.peakData.right); // ehh, let's just keep it simple for now.
      if (!self.peakDataHistory['p'+oSound.position]) {
	    // new data
		self.callbackCount++;
 	    self.peakDataHistory['p'+oSound.position] = {
	      'peak': peakAvg, // cache it
	      'position': oSound.position,
	      'angle': 0
	    }
      }
      // var estimatedPoints = parseInt((self.callbackCount/oSound._360data.lastValues.position)*oSound._360data.lastValues.durationEstimate); // how many points we expect to draw
	  // console.log('estimatedPoints: '+estimatedPoints);
	  // may need to wait until fully-loaded before getting the number and starting to draw.
	  
	  var i = null;
	  var innerRadius = (self.config.peakDataOutside?1:0.565);
	  var direction = (self.config.peakDataOutside?-1:1);
	  var scale = (self.config.peakDataOutside?0.5:0.75);
	  var startAngle = 0;
	  var endAngle = 0;
	  var lastAngle = 0;
	  // GUESS at how many callbacks, use to calculate angle. I dunno.
	  var perItemAngle = self.deg2rad(1); // self.deg2rad((360/(oSound._360data.lastValues.durationEstimate/8))*self.config.peakDataLineRatio); // self.deg2rad(360/(sampleCount+1));
	  var playedAngle = self.deg2rad((oSound._360data.didFinish==1?360:360*(oSound._360data.lastValues.position/oSound._360data.lastValues.durationEstimate)));
	  for (i in self.peakDataHistory) {
		// draw things.
		if (self.peakDataHistory[i].position <= oSound.position) {
	        startAngle = self.deg2rad(360*(self.peakDataHistory[i].position/oSound.durationEstimate));
	        endAngle = startAngle+perItemAngle;
	        self.peakDataHistory[i].angle = endAngle; // ?
	        self.drawSolidArc(oSound._360data.oCanvas,self.config.peakDataColor,oSound._360data.width*innerRadius,oSound._360data.radius*scale*(self.peakDataHistory[i].peak*direction),endAngle,startAngle,true);
	    }
      }
    }
*/

    // experimental
    if (self.config.usePeakData) {
      if (!oSound._360data.animating) {
        var nPeak = (oSound.peakData.left||oSound.peakData.right); // (0.8+((oSound.peakData.left||oSound.peakData.right)*0.2));
		// GIANT HACK: use EQ spectrum data for bass frequencies
		var eqSamples = 3;
		for (var i=0; i<eqSamples; i++) {
		  nPeak = (nPeak||oSound.eqData[i]);
		}
        oSound._360data.amplifier = (self.config.useAmplifier?(0.9+(nPeak*0.1)):1);
        oSound._360data.radiusMax = self.config.circleDiameter*0.175*oSound._360data.amplifier;
        oSound._360data.widthMax = self.config.circleDiameter*0.4*oSound._360data.amplifier;
        oSound._360data.radius = parseInt(oSound._360data.radiusMax*oSound._360data.amplifier);
        oSound._360data.width = parseInt(oSound._360data.widthMax*oSound._360data.amplifier);
      }
    }

  }

  this.updateWaveformOld = function(oSound) {

    if ((!self.config.useWaveformData && !self.config.useEQData && !self.config.usePeakData) || (!sm.features.waveformData && !sm.features.eqData && !sm.features.peakData)) {
      // feature not enabled..
      return false;
    }

    if (!oSound.waveformData.left.length && !oSound.eqData.length && !oSound.peakData.left.length) {
      // no data (or errored out/paused/unavailable?)
      return false;
    }

    var oCanvas = oSound._360data.oCanvas.getContext('2d');
    var offX = 0;
    var offY = parseInt(self.config.circleDiameter*2/3);
    var scale = offY*1/3; // Y axis (+/- this distance from 0)
    var downSample = 1;
    downSample = Math.max(1,downSample);
    var j = oSound.waveformData.left.length;
    var lineWidth = Math.max(1,((j*1/downSample)/self.config.circleDiameter));
    var lineHeight = scale*2.5;
    var thisY = 0;
    var offset = offY;
	var rotateDeg = -90;
    oCanvas.rotate(self.deg2rad(rotateDeg*-1)); // compensate for arc starting at EAST // http://stackoverflow.com/questions/319267/tutorial-for-html-canvass-arc-function
    oCanvas.translate(-self.config.circleRadius,-self.config.circleRadius);

    if (self.config.useWaveformData) {
	  for (var i=0; i<j; i+=downSample) {
	    thisY = offY+(oSound.waveformData.left[i]*scale);
	    oCanvas.fillRect((i/j*(self.config.circleDiameter-lineWidth)+1),thisY,lineWidth,lineHeight);
	  }
	} else {
	  // EQ spectrum
      var offset = 9;
      var yDiff = 0;
      for (var i=0; i<128; i+=4) {
	    yDiff = oSound.eqData[i]*scale;
	    oCanvas.fillRect(i/128*(self.config.circleDiameter-4),self.config.circleDiameter-yDiff,lineWidth*3,yDiff);
      }
    }

    // finished drawing..
    oCanvas.translate(self.config.circleRadius,self.config.circleRadius);
    oCanvas.rotate(self.deg2rad(rotateDeg)); // compensate for arc starting at EAST

  }

  this.callbackCount = 0;
  this.peakDataHistory = [];

  this.getUIHTML = function() {
	return [
	 '<canvas class="sm2-canvas" width="'+self.config.circleDiameter+'" height="'+self.config.circleDiameter+'"></canvas>',
	 ' <img src="'+self.config.imageRoot+'empty.gif" class="sm2-360btn sm2-360btn-default" style="border:none" />', // note use of imageMap, edit or remove if you use a different-size image.
	 ' <div class="sm2-timing'+(navigator.userAgent.match(/safari/i)?' alignTweak':'')+'"></div>', // + Ever-so-slight Safari horizontal alignment tweak
	 ' <div class="sm2-cover"></div>'
	];
  }

  this.init = function() {
    sm._writeDebug('threeSixtyPlayer.init()');
    var oItems = self.getElementsByClassName('ui360','div');
    var oLinks = [];

    for (var i=0,j=oItems.length; i<j; i++) {
	  oLinks.push(oItems[i].getElementsByTagName('a')[0]);
    }
    // grab all links, look for .mp3
    var foundItems = 0;
    var oCanvas = null;
    var oCanvasCTX = null;
    var oCover = null;

	self.oUITemplate = document.createElement('div');
	self.oUITemplate.className = 'sm2-360ui';
	
	// fake a 360 UI so we can get some numbers from CSS, etc.

	var oFakeUI = document.createElement('div');
	oFakeUI.className = 'ui360';

	var oFakeUIBox = oFakeUI.appendChild(self.oUITemplate.cloneNode(true));
	oFakeUI.style.position = 'absolute';
	oFakeUI.style.left = '-9999px';
	var uiHTML = self.getUIHTML();

    oFakeUIBox.innerHTML = uiHTML[1]+uiHTML[2]+uiHTML[3];
    delete uiHTML;

	var oTemp = document.body.appendChild(oFakeUI);

	self.config.circleDiameter = parseInt(oFakeUIBox.offsetWidth);
	self.config.circleRadius = parseInt(self.config.circleDiameter/2);
	var oTiming = self.getElementsByClassName('sm2-timing','div',oTemp)[0];
	self.config.fontSizeMax = parseInt(self.getStyle(oTiming,'font-size'));
	if (isNaN(self.config.fontSizeMax)) {
	  // getStyle() etc. didn't work.
	  self.config.fontSizeMax = null;
	}
	soundManager._writeDebug('diameter, font size: '+self.config.circleDiameter+','+self.config.fontSizeMax);

	oFakeUI.parentNode.removeChild(oFakeUI);
	delete oFakeUI;
	delete oFakeUIBox;
	delete oTemp;

	// canvas needs inline width and height, doesn't quite work otherwise
	self.oUITemplate.innerHTML = self.getUIHTML().join('');

    for (i=0,j=oLinks.length; i<j; i++) {
      if (sm.canPlayURL(oLinks[i].href) && !self.hasClass(oLinks[i],self.excludeClass)) {
        self.addClass(oLinks[i],self.css.sDefault); // add default CSS decoration
        self.links[foundItems] = (oLinks[i]);
        self.indexByURL[oLinks[i].href] = foundItems; // hack for indexing
        foundItems++;
		// add canvas shiz
		var oUI = oLinks[i].parentNode.insertBefore(self.oUITemplate.cloneNode(true),oLinks[i]);

        if (isIE && typeof G_vmlCanvasManager != 'undefined') { // IE only
          var o = oLinks[i].parentNode;
          var o2 = document.createElement('canvas');
          o2.className = 'sm2-canvas';
          var oID = 'sm2_canvas_'+parseInt(Math.random()*1048576);
          o2.id = oID;
		  o2.width = self.config.circleDiameter;
		  o2.height = self.config.circleDiameter;
          oUI.appendChild(o2);
          G_vmlCanvasManager.initElement(o2); // Apply ExCanvas compatibility magic
          oCanvas = document.getElementById(oID);
        } else { 
          // add a handler for the button
          oCanvas = oLinks[i].parentNode.getElementsByTagName('canvas')[0];
        }
        oCover = self.getElementsByClassName('sm2-cover','div',oLinks[i].parentNode)[0];
        var oBtn = oLinks[i].parentNode.getElementsByTagName('img')[0];
		var oBtn = oLinks[i].parentNode.getElementsByTagName('img')[0]
        self.addEventHandler(oBtn,'click',self.buttonClick);
		self.addEventHandler(oCover,'mousedown',self.mouseDown);
	    oCanvasCTX = oCanvas.getContext('2d');
        oCanvasCTX.translate(self.config.circleRadius,self.config.circleRadius);
        oCanvasCTX.rotate(self.deg2rad(-90)); // compensate for arc starting at EAST // http://stackoverflow.com/questions/319267/tutorial-for-html-canvass-arc-function
      }
    }
    if (foundItems>0) {
      self.addEventHandler(document,'click',self.handleClick);
	  if (self.config.autoPlay) {
	    self.handleClick({target:self.links[0],preventDefault:function(){}});
	  }
    }
    sm._writeDebug('threeSixtyPlayer.init(): Found '+foundItems+' relevant items.');
  }

}

var threeSixtyPlayer = null;

soundManager.debugMode = (window.location.href.match(/debug=1/i)); // disable or enable debug output
soundManager.consoleOnly = true;
soundManager.url = '/bin/sm2/swf/';
soundManager.debugMode = false;
soundManager.flashVersion = 9;
soundManager.useHighPerformance = true;

threeSixtyPlayer = new ThreeSixtyPlayer();

if (threeSixtyPlayer.config.useWaveformData) {
  soundManager.flash9Options.useWaveformData = true;
}
if (threeSixtyPlayer.config.useEQData) {
  soundManager.flash9Options.useEQData = true;
}
if (threeSixtyPlayer.config.usePeakData) {
  soundManager.flash9Options.usePeakData = true;
}

soundManager.onload = function() {
  // soundManager.createSound() etc. may now be called
  threeSixtyPlayer.init();
}

