/*
*   SoundCloud Custom Player jQuery Plugin
*   Author: Matas Petrikas, matas@soundcloud.com
*   Copyright (c) 2009  SoundCloud Ltd.
*   Licensed under the MIT license:
*   http://www.opensource.org/licenses/mit-license.php
*
*   Usage:
*   <a href="http://soundcloud.com/matas/hobnotropic" class="sc-player">My new dub track</a>
*   The link will be automatically replaced by the HTML based player
*/(function(e){var t=function(e){var t=function(e){return{h:Math.floor(e/36e5),m:Math.floor(e/6e4%60),s:Math.floor(e/1e3%60)}}(e),n=[];t.h>0&&n.push(t.h);n.push(t.m<10&&t.h>0?"0"+t.m:t.m);n.push(t.s<10?"0"+t.s:t.s);return n.join(":")},n=function(e){e.sort(function(){return 1-Math.floor(Math.random()*3)});return e},r=!0,i=!1,s=e(document),o=function(e){try{r&&window.console&&window.console.log&&window.console.log.apply(window.console,arguments)}catch(t){}},u=i?"sandbox-soundcloud.com":"soundcloud.com",a=document.location.protocol==="https:",f=function(e,t){var n=(a||/^https/i.test(e)?"https":"http")+"://api."+u+"/resolve?url=",r="format=json&consumer_key="+t+"&callback=?";a&&(e=e.replace(/^http:/,"https:"));return/api\./.test(e)?e+"?"+r:n+e+"&"+r},l=function(){var t=function(){var e=!1;try{var t=new Audio;e=t.canPlayType&&/maybe|probably/.test(t.canPlayType("audio/mpeg"))}catch(n){}return e}(),n={onReady:function(){s.trigger("paScPlayer:onAudioReady")},onPlay:function(){s.trigger("paScPlayer:onMediaPlay")},onPause:function(){s.trigger("paScPlayer:onMediaPause")},onEnd:function(){s.trigger("paScPlayer:onMediaEnd")},onBuffer:function(e){s.trigger({type:"paScPlayer:onMediaBuffering",percent:e})}},r=function(){var t=new Audio,r=function(e){var t=e.target,r=(t.buffered.length&&t.buffered.end(0))/t.duration*100;n.onBuffer(r);t.currentTime===t.duration&&n.onEnd()},i=function(e){var t=e.target,r=(t.buffered.length&&t.buffered.end(0))/t.duration*100;n.onBuffer(r)};e('<div class="pa-sc-player-engine-container"></div>').appendTo(document.body).append(t);t.addEventListener("play",n.onPlay,!1);t.addEventListener("pause",n.onPause,!1);t.addEventListener("timeupdate",r,!1);t.addEventListener("progress",i,!1);return{load:function(e,n){t.pause();t.src=e.stream_url+(/\?/.test(e.stream_url)?"&":"?")+"consumer_key="+n;t.load();t.play()},play:function(){t.play()},pause:function(){t.pause()},stop:function(){if(t.currentTime){t.currentTime=0;t.pause()}},seek:function(e){t.currentTime=t.duration*e;t.play()},getDuration:function(){return t.duration*1e3},getPosition:function(){return t.currentTime*1e3},setVolume:function(e){t.volume=e/100}}},i=function(){var t="paScPlayerEngine",r,i=function(n){var r=(a?"https":"http")+"://player."+u+"/player.swf?url="+n+"&amp;enable_api=true&amp;player_type=engine&amp;object_id="+t;return e.browser.msie?'<object height="100%" width="100%" id="'+t+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" data="'+r+'">'+'<param name="movie" value="'+r+'" />'+'<param name="allowscriptaccess" value="always" />'+"</object>":'<object height="100%" width="100%" id="'+t+'">'+'<embed allowscriptaccess="always" height="100%" width="100%" src="'+r+'" type="application/x-shockwave-flash" name="'+t+'" />'+"</object>"};soundcloud.addEventListener("onPlayerReady",function(e,i){r=soundcloud.getPlayer(t);n.onReady()});soundcloud.addEventListener("onMediaEnd",n.onEnd);soundcloud.addEventListener("onMediaBuffering",function(e,t){n.onBuffer(t.percent)});soundcloud.addEventListener("onMediaPlay",n.onPlay);soundcloud.addEventListener("onMediaPause",n.onPause);return{load:function(t){var n=t.uri;r?r.api_load(n):e('<div class="pa-sc-player-engine-container"></div>').appendTo(document.body).html(i(n))},play:function(){r&&r.api_play()},pause:function(){r&&r.api_pause()},stop:function(){r&&r.api_stop()},seek:function(e){r&&r.api_seekTo(r.api_getTrackDuration()*e)},getDuration:function(){return r&&r.api_getTrackDuration&&r.api_getTrackDuration()*1e3},getPosition:function(){return r&&r.api_getTrackPosition&&r.api_getTrackPosition()*1e3},setVolume:function(e){r&&r.api_setVolume&&r.api_setVolume(e)}}};return t?r():i()}(),c,h=!1,p=[],d={},v,m=function(t,n,r){var i=0,s={node:t,tracks:[]},o=function(t){var r=f(t.url,c);e.getJSON(r,function(u){i+=1;u.href=t.href;if(u.tracks)s.tracks=s.tracks.concat(u.tracks);else if(u.duration){u.permalink_url=t.url;s.tracks.push(u)}else u.creator?n.push({url:u.uri+"/tracks"}):u.username?/favorites/.test(t.url)?n.push({url:u.uri+"/favorites"}):n.push({url:u.uri+"/tracks"}):e.isArray(u)&&(s.tracks=s.tracks.concat(u));n[i]?o(n[i]):s.node.trigger({type:"onTrackDataLoaded",playerObj:s,url:r})})};c=r;p.push(s);o(n[i])},g=function(e,t){return t?'<div class="sc-loading-artwork">Loading Artwork</div>':e.artwork_url?'<img src="'+e.artwork_url.replace("-large","-t300x300")+'"/>':'<div class="sc-no-artwork">No Artwork</div>'},y=function(n,r){e(".sc-duration",n).html(t(r.duration));e(".sc-waveform-container",n).html('<img src="'+r.waveform_url+'" />');n.trigger("onPlayerTrackSwitch.paScPlayer",[r])},b=function(e){var t=e.permalink_url;if(v===t)l.play();else{v=t;l.load(e,c)}},w=function(t){return p[e(t).data("pa-sc-player").id]},E=function(t,n){n&&e("div.pa-sc-player.playing").removeClass("playing");e(t).toggleClass("playing",n).trigger(n?"onPlayerPlay":"onPlayerPause")},S=function(t,n){var r=w(t).tracks[n||0];y(t,r);d={$buffer:e(".sc-buffer",t),$played:e(".sc-played",t),position:e(".sc-position",t)[0]};E(t,!0);b(r)},x=function(e){E(e,!1);l.pause()},T=function(){var e=d.$played.closest(".pa-sc-player"),n;d.$played.css("width","0%");d.position.innerHTML=t(0);E(e,!1);l.stop();e.trigger("onPlayerTrackFinish")},N=function(t,n){l.seek(n);e(t).trigger("onPlayerSeek")},C=function(t){var n=e(t);o("track finished get the next one");$nextItem=e(".sc-trackslist li.active",n).next("li");$nextItem.length||($nextItem=n.nextAll("div.pa-sc-player:first").find(".sc-trackslist li.active"));$nextItem.click()},k=function(){var e=80,t=document.cookie.split(";"),n=new RegExp("paScPlayer_volume=(\\d+)");for(var r in t)if(n.test(t[r])){e=parseInt(t[r].match(n)[1],10);break}return e}(),L=function(e){var t=Math.floor(e),n=new Date;n.setTime(n.getTime()+31536e6);k=t;document.cookie=["paScPlayer_volume=",t,"; expires=",n.toUTCString(),'; path="/"'].join("");l.setVolume(k)},A;s.bind("paScPlayer:onAudioReady",function(e){o("onPlayerReady: audio engine is ready");l.play();L(k)}).bind("paScPlayer:onMediaPlay",function(e){clearInterval(A);A=setInterval(function(){var e=l.getDuration(),n=l.getPosition(),r=n/e;d.$played.css("width",100*r+"%");d.position.innerHTML=t(n);s.trigger({type:"onMediaTimeUpdate.paScPlayer",duration:e,position:n,relative:r})},500)}).bind("paScPlayer:onMediaPause",function(e){clearInterval(A);A=null}).bind("paScPlayer:onMediaEnd",function(e){T()}).bind("paScPlayer:onMediaBuffering",function(e){d.$buffer.css("width",e.percent+"%")});e.paScPlayer=function(n,r){var i=e.extend({},e.paScPlayer.defaults,n),s=p.length,u=r&&e(r),a=u[0].className.replace("pa-sc-player",""),f=i.links||e.map(e("a",u).add(u.filter("a")),function(t){return{href:t.href,url:e(t).attr("scurl")||t.href,title:t.innerHTML}}),l=e('<div class="pa-sc-player loading"></div>').data("pa-sc-player",{id:s}),c=e('<ul class="sc-trackslist"></ul>').appendTo(l),d=e('<div class="sc-controls"></div>').appendTo(l);(a||i.customClass)&&l.addClass(a).addClass(i.customClass);o("$source",u);o("links",f);l.find(".sc-controls").append('<a href="#play" class="sc-play"><span>play</span></a> <a href="#pause" class="sc-pause"><span>pause</span></a>').end().append('<div class="sc-time-indicators"><span class="sc-position">00.00</span> | <span class="sc-duration"></span></div>').append('<div class="sc-time-span"><div class="sc-buffer"></div><div class="sc-played"></div></div>');m(l,f,i.apiKey);l.bind("onTrackDataLoaded.paScPlayer",function(n){o("onTrackDataLoaded.paScPlayer",n,s);e.each(n.playerObj.tracks,function(t,n){o("track",n);var r=t===0;e("<li>").append(e("<a>").attr("href",n.href).html(f[t].title)).data("sc-track",{id:t}).toggleClass("active",r).appendTo(c)});l.each(function(){e.isFunction(i.beforeRender)&&i.beforeRender.call(this,n.playerObj.tracks)});e(".sc-duration",l)[0].innerHTML=t(n.playerObj.tracks[0].duration);e(".sc-position",l)[0].innerHTML=t(0);y(l,n.playerObj.tracks[0]);i.continuePlayback&&l.bind("onPlayerTrackFinish",function(e){C(l)});l.removeClass("loading").trigger("onPlayerInit");if(i.autoPlay&&!h){S(l);h=!0}});u.each(function(t){e(this).replaceWith(l)});return l};e.paScPlayer.stopAll=function(){e(".pa-sc-player.playing a.sc-pause").click()};e.paScPlayer.destroy=function(){e(".pa-sc-player, .pa-sc-player-engine-container").remove()};e.fn.paScPlayer=function(t){h=!1;this.each(function(){e.paScPlayer(t,this)});return this};e.paScPlayer.defaults=e.fn.paScPlayer.defaults={customClass:null,beforeRender:function(t){var n=e(this)},onDomReady:function(){e("a.pa-sc-player, div.pa-sc-player").paScPlayer()},autoPlay:!1,continuePlayback:!0,randomize:!1,loadArtworks:5,apiKey:"965bd4363fdd909723749b003be67125"};e("a.sc-play, a.sc-pause").live("click",function(t){var n=e(this).closest(".pa-sc-player").find("ul.sc-trackslist");n.find("li.active").click();return!1});e(".sc-trackslist li").live("click",function(t){var n=e(this),r=n.closest(".pa-sc-player"),i=n.data("sc-track").id,s=r.is(":not(.playing)")||n.is(":not(.active)");s?S(r,i):x(r);n.addClass("active").siblings("li").removeClass("active");return!1});var O=function(t,n){var r=e(t).closest(".sc-time-span"),i=r.find(".sc-buffer"),s=r.closest(".pa-sc-player"),o=Math.min(i.width(),n-r.offset().left)/r.width();N(s,o)},M=function(e){if(e.targetTouches.length===1){O(e.target,e.targetTouches&&e.targetTouches.length&&e.targetTouches[0].clientX);e.preventDefault()}};e(".sc-time-span").live("click",function(e){O(this,e.pageX);return!1}).live("touchstart",function(e){this.addEventListener("touchmove",M,!1);e.originalEvent.preventDefault()}).live("touchend",function(e){this.removeEventListener("touchmove",M,!1);e.originalEvent.preventDefault()});e(function(){e.isFunction(e.paScPlayer.defaults.onDomReady)&&e.paScPlayer.defaults.onDomReady()})})(jQuery);