var Cloudy = new (Class.create({
	initialize: function()
	{
		this.createAudio();
		if(this.current)
			this.useOgg = this.current.canPlayType("audio/mpeg") == "" && this.current.canPlayType("audio/aac") == "";
		this.next = null;
		this.previous = null;
		
		this.createItem = this._createItem.bind(this);
		
		Event.observe(window, "load", this._init.bind(this));
	},
	
	createAudio: function()
	{
		try
		{
			if(this.current)
			{
				if(!this.current.paused)
					this.current.pause();
				Event.stopObserving(this.current, "waiting");
				Event.stopObserving(this.current, "canplay");
				Event.stopObserving(this.current, "ended");
				Event.stopObserving(this.current, "play");
				Event.stopObserving(this.current, "pause");
				Event.stopObserving(this.current, "timeupdate");
				delete this.current;
			}
		
			this.current = new Audio();
			Event.observe(this.current, "waiting", this.waiting.bind(this));
			Event.observe(this.current, "canplay", this.canPlay.bind(this));
			Event.observe(this.current, "ended", this.trackEnded.bind(this));
			Event.observe(this.current, "play", this.startPlay.bind(this));
			Event.observe(this.current, "pause", this.doPause.bind(this));
			Event.observe(this.current, "timeupdate", this.updateProgress.bindAsEventListener(this));
		}
		catch (e)
		{
			//alert(e.message);
		}
	},
	
	_init: function()
	{
		if(this.current)
		{
			Event.observe($("transportPlayBtn"), "click", this.toggle.bind(this));
			Event.observe($("transportPrevBtn"), "click", this.previousSong.bind(this));
			Event.observe($("transportNextBtn"), "click", this.nextSong.bind(this));
		
			var progressBar = $("progressBar");
			this.progressBar = new S2.UI.ProgressBar(progressBar);
				
			var player = $("player");
			player.on("click", ".song .play-btn", this.go.bindAsEventListener(this));
			new Ajax.Request('/likeknives.xml', { onSuccess: this._init2.bind(this) })
		}
		else
		{
			$("player").update("Sorry, it looks like your browser doesn't support this fancy HTML5 stuff. You should definitely consider upgrading to a newer browser, like Safari, Chrome, or Firefox 4, so you, too, can enjoy the streaming audio fun!");
		}
	},
	
	_init2: function(ajaxResponse)
	{
		var items = ajaxResponse.responseXML.getElementsByTagName("track");
		$A(items).each(this.createItem);
		
		this.next = $$(".song")[0];
	},
	
	_createItem: function(item)
	{
		var location, songDiv, playDiv, titleDiv, artwork, artworkDiv, artistDiv, artist, albumDiv, album, songlist;
		songlist = $("songlist");
		try
		{
			location = item.getElementsByTagName('location')[0].textContent;
			if(this.useOgg)
				location = location.gsub(/\.(mp3|m4a|aac)$/, '.ogg');
				artist = item.getElementsByTagName('creator')[0].textContent;
				title = item.getElementsByTagName('title')[0].textContent;
				artwork = item.getElementsByTagName('image')[0].textContent;
				album = '';

				songDiv = new Element("div", { 'class': 'song' });
				playDiv = new Element("div", { 'class': 'play-btn', id: escape(location) })
				songDiv.insert(playDiv);

				titleDiv = new Element("div", { 'class': 'title' });
				songDiv.insert(titleDiv);
		
				artworkDiv = new Element("div", { 'class': 'artwork' });
				artworkDiv.insert("<img src='" + artwork + "'>")
				titleDiv.insert(artworkDiv);
		
				titleDiv.insert(title);
		
				artistDiv = new Element("div", { 'class': 'artist' });
				artistDiv.insert(artist);
				songDiv.insert(artistDiv);
		
				albumDiv = new Element("div", { 'class': 'album' });
				songDiv.insert(albumDiv);
		
				songlist.insert(songDiv);
		}
		catch (e)
		{
			alert(e.message);
		}
	},
	
	startPlay: function()
	{
		$("transport").addClassName("playing");
		if(this.currentSong)
			this.currentSong.addClassName("playing");
	},
	
	doPause: function()
	{
		$("transport").removeClassName("playing");
		if(this.currentSong)
			this.currentSong.removeClassName("playing");
	},
	
	toggle: function()
	{
		if(!this.current.src && this.next)
			this.goToSong(this.next);
		else if(this.current.paused)
			this.current.play();
		else
			this.current.pause();
			
	},
	
	nextSong: function()
	{
		if(this.next)
			this.goToSong(this.next);
	},
	
	previousSong: function()
	{
		var prev = this.currentSong.previous(".song");
		if(prev)
			this.goToSong(prev);
	},
		
	go: function(evt)
	{
		var tgt = Event.findElement(evt);
		if(tgt)
		{
			var song = tgt.up(".song");
			if(this.currentSong && this.currentSong.down(".play-btn").id == tgt.id)
			{
				if(this.current.paused)
				{
					this.current.play();
				}
				else
				{
					this.current.pause();
				}
			}
			else
			{
				this.goToSong(song);
			}
		}
	},
	
	goToSong: function(songElement)
	{
		var ua = navigator.userAgent.toLowerCase();
		if(ua.include("macintosh") && ua.include("firefox/3.6"))
		{
			this.createAudio();
		}
		
		this.current.src = unescape(songElement.down(".play-btn").id);
			
		if(this.currentSong) {
			this.currentSong.removeClassName("playing");
			this.currentSong.removeClassName("waiting");
		}
			
		this.next = songElement.next(".song");
				
		this.currentSong = songElement;
		this.updateTrackInfo();
			
		this.current.play();
	},
	
	updateTrackInfo: function()
	{
		$("songName").update(this.currentSong.down(".title").innerHTML);
		$("artistName").update(this.currentSong.down(".artist").innerHTML);
		$("albumName").update(this.currentSong.down(".album").innerHTML);
	},
	
	trackEnded: function()
	{
		if(this.next)
			this.goToSong(this.next);
		else
		{
			this.currentSong.removeClassName("playing");
		}
	},
	
	waiting: function()
	{
		if(this.currentSong)
			this.currentSong.addClassName("waiting");
	},
	
	canPlay: function()
	{
		if(this.currentSong)
			this.currentSong.removeClassName("waiting");
			
		if(this.progressBar)
		{
			this.progressBar.options.value.max = this.current.duration;
			//console.debug(this.progressBar.options.value.max);
			this.progressBar.setValue(0);
		}
		
		$("currentTime").update("0:00");
		$("totalTime").update(this.parseTime(this.current.duration));
	},
	
	updateProgress: function(evt)
	{
		var pct = Math.floor(this.current.currentTime/this.current.duration *100);
		if(this.progressBar.getValue() != pct)
		{
			this.progressBar.setValue(pct);
		}
		$("currentTime").update(this.parseTime(this.current.currentTime));
		$("totalTime").update(this.parseTime(this.current.duration));
	},
	
	parseTime: function(t)
	{
		var min = Math.floor(t/60);
		var sec = Math.floor(t%60);
		
		return min + ":" + sec.toPaddedString(2);
	}
	
}))();
