/**********************************************************************************/
/* 15/04/2009 ArenaMobile - Hilari Peña - JSmp3Player over SoundManager 2 and YUI */
/**********************************************************************************/
// Required Libs:
// YUI:
//	yahoo-min.js 
//	yahoo-dom-event.js
//	animation-min.js
//	dragdrop-min.js
//	slider-min.js
// OTHERS:
//	flash_detect.js
//	soundmanager2.js

// Sound manager ini
var sm = soundManager; // soundManager instance
sm.waitForWindowLoad = true;
sm.url = './swf/';
sm.debugMode = false;
sm.consoleOnly = false;
sm.flashVersion = 8; //9
//sm.flash9Options.useWaveformData = true;
//sm.flash9Options.useEQData = true;
//sm.flash9Options.usePeakData = true;
sm.onload = function() {initPlayer();}
sm.onerror = function() {/*alert('No ha carregat sound manager');*/}

// Global vars
// Playlist -> Matrix : id_song, title, album, urlcover, urlmp3
var playlist = Array();
var playlistpos = 0;
var song = null; // soundManager Song Object
var songID = "";  // soundManager Song ID
var coverX = 85;
var coverY = 85;
var playvolume = 75;
var songPos = 0;
var Dom   = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var lang  = YAHOO.lang;
var slider1 = null;
var slider2 = null;
var scaleFactor2 = 0.5;
var damuntTH2 = 0;
// size of the text for the playlist
var playlist_title_length = 11;
var playlist_album_length = 9;

// Start the Player
function StartPlayer()
{
	var i = playlist.length;
	playlistpos = 0;
	if (i > 0) PlaySong();
}

// Stop the Player
function StopPlayer()
{
	if (song != null) sm.stopAll();
}

// Pause the Player
function PausePlayer()
{
	if (song != null) song.togglePause();
}

function msg(mis)
{
	var zoneps = Dom.get('playerstatus');
	zoneps.innerHTML = mis;
}

function msgbuffer()
{
	msg('Playstate: Buffering');
}
function msgstop()
{
	msg('Playstate: Stop');
}
function msgpause()
{
	msg('Playstate: Pause');
}
function msgplay()
{
	msg('Playstate: Playing');
}

// Play songs with the flash player
function PlaySong()
{
	if (planacarregada && playlist.length > 0)
		{
		//var zonecv = Dom.get('plysongcover');
		var zonenm = Dom.get('plysongname');
		var n = playlistpos;
		if (n == playlist.length) {n = 0; playlistpos = 0;}
		//Per veure la url del mp3
		//alert (playlist[n][4]);
		StopPlayer();
		songID = playlist[n][0];
		song = null;
		song = sm.createSound({
			id: songID,
			url: playlist[n][4],
			onfinish: NextSong,
			whileplaying: msgplay,
			onbufferchange: msgbuffer,
			onpause: msgpause,
			onplay: msgplay,
			onstop: msgstop,
			whileloading: msgbuffer
			});
		// Put the cover
		//zonecv.innerHTML = "<img src='"+playlist[n][2]+"' width='"+coverX+"' height='"+coverY+"'>";
		//zonenm.innerHTML = "<ul><li>"+playlist[n][1]+" - "+playlist[n][2]+"</li></ul>";
		//var namsongsize = 24;
		var namesong = ""+playlist[n][1]+" - "+playlist[n][2]+"";
		//if (namesong.length > namsongsize) sufix = '...';
		//else sufix = '';
		//namesong = namesong.substr(0, namsongsize) + sufix;
		zonenm.innerHTML = namesong;
		document.forms.fply.iply.value = namesong;
		// Encenem el ticker del titol de la canço
		PlayerTicker();
		song.setVolume(playvolume);
		song.setPosition(0);
		songPos = 0;
		//if (slider2 != null) slider2.setValue(songPos);
		// Actualitzem el color de la pista que esta sonant
		MarcaPistaActual();
		song.play();
		}
}

function MarcaPistaActual()
{
	var i = playlist.length;
	var x = 0;
	for (x=0;x<i;x++)
	{
		var pistaactual = Dom.get('music'+playlist[x][0]);
		if (x == playlistpos)
			{
			YAHOO.util.Dom.setStyle(pistaactual, "background-color", "#B5FFC8");
			}
		else 
			{
			YAHOO.util.Dom.setStyle(pistaactual, "background-color", "#f0f0f0");
			}
	}
}

// Print the duration of the song in the player
function DurationSong()
{
	var zonetm = Dom.get('plysongtime');
	var position = Milisecon2Human(song.position); 
	var duration = Milisecon2Human(song.duration);
	var lack = Milisecon2Human(song.duration - song.position);
	zonetm.innerHTML = position+" / "+duration+ " -"+lack;
	if (damuntTH2 == 0) MoveBar();
	// Graphic EQ
	//Eqg();
}

// Move Bar
function MoveBar()
{
	songPos =  parseInt(song.position/(song.duration/100));
	slider2.setValue(songPos/scaleFactor2);
}

// Convers milisecons on Human time
function Milisecon2Human(m)
{
	var sec = m/1000;
	var min = sec/60;
	min = parseInt(min);
	sec = parseInt(sec - (min*60));
	if (sec < 10) sec = "0"+sec;
	if (min < 10) min = "0"+min;
	var human = min +":"+sec;
	if (m == null) return "";
	else return human;
}

function PlayPause()
{
	//alert(x);
	if (song != null) 
		{
		if (song.playState == 1)
			{
			var p = Dom.get('playpause');
			song.togglePause();
			if (song.paused)
				{
				p.innerHTML = '<a href=\"javascript:PlayPause();\"><img src=\"images/icon_pause.gif\" width=\"16\" height=\"16\" alt=\"pause\" /></a>';
				}
			else
				{
				p.innerHTML = '<a href=\"javascript:PlayPause();\"><img src=\"images/icon_play-black.gif\" width=\"16\" height=\"16\" alt=\"play\" /></a>';
				}
			}
			else
			{
			PlaySong();
			}
		}
}

// When the song end or the user want next song
function NextSong()
{
	var i = playlist.length;
	var n = playlistpos + 1;
	if (i > n)
		{
		playlistpos = n;
		if (song != null) if (!song.paused) PlaySong();
		}
	else
	{
	//End of playlist
	if (i > 0)
		{
		playlistpos = 0;
		// Segons l'ultim W.R quan s'acaba la canço s'ha d'aturar el player
		//if (song != null) if (!song.paused) PlaySong();
		StopPlayer();
		msgstop();
		}
	}
}

function BackSong()
{
	var i = playlist.length;
	var n =  playlistpos - 1;
	if (n < 0)
		{
		playlistpos = (i-1);
		if (song != null) if (!song.paused) PlaySong();
		}
	else
	{
	playlistpos = n;
	PlaySong();
	}
}

// Add Song to the playlist matrix
function PlayerAddSong(id_song, title, album, urlcover, urlmp3)
{
//alert(urlmp3);
// Nomes deixem afegir cançons quan la plana est`a carregada
if (planacarregada)
	{
		var i = playlist.length;
		// Search for repeated song
		var songid = id_song;
		if(SameSong(songid))
		{
			//Same Song!
			//alert("¡La canción ya esta en la playlist!");
		}
		else
		{
			// Add trak
			playlist[i] = new Array(id_song, title, album, urlcover, urlmp3);
			ReloadDomPlaylist();	
			// First Song on the playlist? Runs the player
			if (playlist.length == 1) 
				{
				StartPlayer();
				}
			// Si el player te mes d'una canço i esta aturat al afegir em de colocarnos en la noca canço i fer play
			if (song.playState == 0)
			{
			GoToSound(id_song);
			}
		}
	}
}

function PlayerAddSongMultiple(id_song, title, album, urlcover, urlmp3)
{
// Nomes deixem afegir cançons quan la plana est`a carregada
if (planacarregada)
	{
		var i = playlist.length;
		// Search for repeated song
		var songid = id_song;
		if(SameSong(songid))
		{
			//Same Song!
			//alert("¡La canción ya esta en la playlist!");
		}
		else
		{
			// Add trak
			playlist[i] = new Array(id_song, title, album, urlcover, urlmp3);
			//ReloadDomPlaylist();
			// First Song on the playlist? Runs the player
			/*
			if (playlist.length == 1) 
				{
				StartPlayer();
				}
			// Si el player te mes d'una canço i esta aturat al afegir em de colocarnos en la noca canço i fer play
			if (song.playState == 0)
				{
				GoToSound(id_song);
				}
			*/
		}
	}
}



function PlayerRemoveAllPlaylist()
{
if (song != null)
	{
	StopPlayer();
	// esborrem el display del player
	var zonenm = Dom.get('plysongname');
	zonenm.innerHTML = '';
	document.forms.fply.iply.value = '';
	playlist = new Array();
	ReloadDomPlaylist();
	}
}

function GoToSound(id_song)
{
	StopPlayer();
	var pos = PosSong(id_song);
	playlistpos = pos;
	PlaySong();
}

function PosSong(id_song)
{
	var i = playlist.length;
	var pos = 0;
	var x = 0;
	for (x=0;x<i;x++)
	{
		if(id_song == playlist[x][0]) pos = x;
	}
	return pos;
}

function PlayerRemoveAllSongs()
{
	var i = playlist.length;
	var id_song = 0;
	for (x=0;x<i;x++)
		{
		var id_song = playlist[x][0];
		var pistaactual = Dom.get('music'+id_song);
		pistaactual.innerHTML = '';
		}
	StopPlayer();
	// esborrem el display del player
	if (parent.tmot != null) clearTimeout(parent.tmot);
	var zonenm = Dom.get('plysongname');
	zonenm.innerHTML = '';
	var zoneat = Dom.get('apagartodas');
	zoneat.innerHTML = '';
	document.forms.fply.iply.value = '';
	playlist = new Array();
}

// Remove Song for the playlist matrix
function PlayerRemoveSong(id_song)
{
	var i = playlist.length;
	var flag = 0;
	var pos = PosSong(id_song);
	if (playlist[playlistpos][0] == id_song && i > 0)
		{
		if (i >= 1)
			{ 
			flag = 1; 
			//StopPlayer();
			}
		else flag = 2;
		}

	if (i > 0)
		{

		var tmpplaylist = new Array();
		var z = 0;
		for (x=0;x<i;x++)
			{
			if (playlist[x][0] != id_song) 
				{
				tmpplaylist[z] = playlist[x];
				z++;
				}
			}
		playlist = new Array();
		playlist = tmpplaylist;
		//ReloadDomPlaylist();
		var pistaactual = Dom.get('music'+id_song);
		pistaactual.innerHTML = '';
		if (pos < playlistpos) playlistpos--;
		if (playlistpos < 0) playlistpos = 0;
		}
	if (flag == 1) 
		{
		PlaySong();
		}
	if (flag == 2 || playlist.length == 0) 
		{
		StopPlayer();
		// esborrem el display del player
		if (parent.tmot != null) clearTimeout(parent.tmot);
		var zonenm = Dom.get('plysongname');
		zonenm.innerHTML = '';
		document.forms.fply.iply.value = '';
		playlist = new Array();
		}
}

// Search for repeated song
function SameSong(songid)
{
	var i = playlist.length;
	var songdtmp = "";
	var same = 0;
	for (x=0;x<i;x++)
		{
		songidtmp = playlist[x][0];
		if (songid == songidtmp) same++;
		}
	if (same == 0) return false;
	else return true;
}

// Reload the Dom of the playlist
function ReloadDomPlaylist()
{
	var zonepl = Dom.get('plylsongs');
	var i = playlist.length;
	var stitle = '';
	var salbum = '';
	var html = "";
	html = "";
	html += "<div class=\"head\"><img src=\"images/txt_a-seguir.gif\" alt=\"A seguir\" /></div>\n";
	for (x=0;x<i;x++)
	{
		var sufix = '';
		stitle = playlist[x][1];
		if (stitle.length > playlist_title_length) sufix = '...';
		else sufix = '';
		stitle = stitle.substr(0, playlist_title_length) + sufix;
		salbum = playlist[x][2];
		if (salbum.length > playlist_album_length) sufix = '...';
		else sufix = '';
		salbum = salbum.substr(0, playlist_album_length) + sufix;
		//if (playlistpos == x) html += "<div class=\"playListAreaDark\">\n";
		//else html += "<div class=\"playListArea\">\n";
		html += "<div class=\"playListArea\" id=\"music"+playlist[x][0]+"\">\n";
		html += "<ul>\n";
		html += "<li class=\"nameMusic\"><a href=\"javascript:GoToSound("+playlist[x][0]+");\">"+stitle+" <span>- "+salbum+"</a></span></li>\n";
		html += "<li><a href=\"javascript:DownFromPl("+playlist[x][0]+");\"><img src=\"images/icon_download.gif\" width=\"16\" height=\"16\" alt=\"download\" id=\"lipd"+playlist[x][0]+"\"/></a></li>\n";
		html += "<li><a href=\"javascript:PlayerSMSPush("+playlist[x][0]+");\"><img src=\"images/icon_download-mobile.gif\" width=\"16\" height=\"16\" alt=\"mobile\" id=\"lipe"+playlist[x][0]+"\" /></a></li>\n";
		html += "<li><a href=\"javascript:PutOnPlayList("+playlist[x][0]+");\"><img src=\"images/icon_put-on-playlist.gif\" width=\"16\" height=\"17\" alt=\"putpl\" id=\"lipa"+playlist[x][0]+"\" /></a></li>\n";
		html += "<li><a href=\"javascript:PlayerRemoveSong("+playlist[x][0]+");\"><img src=\"images/icon_delete-music.gif\" width=\"16\" height=\"16\" alt=\"apagar\"   /></a></li>\n";
		html += "</ul>\n";
		html += "<div class=\"clear\"></div>\n";
		html += "</div>\n";
	}
	if (i>0) html += "<DIV class=\"apagartodas\" id=\"apagartodas\"><img src=\"./images/blank.gif\" height=\"2\" width=\"2\"><BR><a href=\"javascript:PlayerRemoveAllSongs();\" class=\"apagartodaslink\">Apagar todas</a><BR><img src=\"./images/blank.gif\" height=\"5\" width=\"5\"></DIV>";
	zonepl.innerHTML = html;
	MarcaPistaActual();
	TooltipsPlayer();
}

function TooltipsPlayer()
{
	var i = playlist.length;
	var el1 = '';
	var el2 = '';
	var el3 = '';
	var z = 0;
	for (z=0;z<i;z++)
	{
	var el1 = 'lipd'+playlist[z][0]+'';
	var el2 = 'lipe'+playlist[z][0]+'';
	var el3 = 'lipa'+playlist[z][0]+'';
	AddTooltip(el1,'Download','');
	AddTooltip(el2,'Enviar para telemóvel','');
	AddTooltip(el3,'Adiccionar à playlist','');
	//alert(x);
	}
	GeneraTooltips('');
}

/*****************/
/* SLIDERS (YUI) */
/*****************/
function VolumeSlider() 
{
	var bg="slider-bg1";
	var thumb="slider-thumb1"; 
	// The slider can move 0 pixels up
	var topConstraint = 0;
	// The slider can move 200 pixels down
	var bottomConstraint = 200;
	// Custom scale factor for converting the pixel offset into a real value
	var scaleFactor = 0.5;
	// The amount the slider moves when the value is changed with the arrow
	// keys
	var keyIncrement = 10;

	Event.onDOMReady(function() {
	slider1 = YAHOO.widget.Slider.getVertSlider(bg, 
			thumb, topConstraint, bottomConstraint);
	slider1.getRealValue = function() {
		return Math.round(this.getValue() * scaleFactor);
	}

	slider1.subscribe("change", function(offsetFromStart) {
		// use the scale factor to convert the pixel offset into a real
		// value
		var actualValue = (bottomConstraint*scaleFactor)-slider1.getRealValue();
		// update the text box with the actual value
		//fld.value = actualValue;
		if (song != null) song.setVolume(actualValue);
		playvolume = actualValue;       
		// Update the title attribute on the background.  This helps assistive
		// technology to communicate the state change
		Dom.get(bg).title = "Volume : " + actualValue;
		});

		slider1.subscribe("slideStart", function() {
			YAHOO.log("slideStart fired", "warn");
		});

		slider1.subscribe("slideEnd", function() {
			YAHOO.log("slideEnd fired", "warn");
		});

		// set an initial value
		var initpos = bottomConstraint-(playvolume*(bottomConstraint/100));
		//alert(initpos);
		slider1.setValue(initpos);

		// Use setValue to reset the value to white:
		Event.on("putval", "click", function(e) {
			slider1.setValue(100, false); //false here means to animate if possible
		});

		// Use the "get" method to get the current offset from the slider's start
		// position in pixels.  By applying the scale factor, we can translate this
		// into a "real value
		Event.on("getval", "click", function(e) {
			YAHOO.log("Current value: "   + slider1.getValue() + "\n" + 
			"Converted value: " + slider1.getRealValue(), "info", "example"); 
		});
	});
};

/*************************************************************************************************/

function SongSlider() {

	var bg="slider-bg2";
	var thumb="slider-thumb2"; 
	//var valuearea="slider-value"; 
	//var textfield="slider-converted-value";
	// The slider can move 0 pixels up
	var topConstraint = 0;
	// The slider can move 200 pixels down
	var bottomConstraint = 200;
	// Custom scale factor for converting the pixel offset into a real value
	var scaleFactor = scaleFactor2;
	// The amount the slider moves when the value is changed with the arrow
	// keys
	var keyIncrement = 10;

	YAHOO.util.Event.addListener(thumb,"mouseover", OverTH2);
	YAHOO.util.Event.addListener(thumb,"mouseout", OutTH2);

	function OverTH2()
	{
	damuntTH2 = 1;     
	}

	function OutTH2()
	{
	damuntTH2  = 0;
	if (song != null)
		{
		//var info = Dom.get('info');
		var actualValue = slider2.getRealValue();
		var posE = Math.round(actualValue * (song.duration/100));
		var posA = song.position;
		var d = Math.abs(posA-posE);
		var m = Math.round(song.duration/(100*scaleFactor));
		if (d > m && posE<song.duration) 
			{
			song.setPosition(posE);
			songPos = parseInt(posE/(song.duration/100));
			}
		//info.innerHTML = "posE: "+posE+"<BR\>posA:"+posA+  "<BR\>duration : "+song.duration+"<BR\>d: "+d+" m "+m
		}
	}

	Event.onDOMReady(function() {

	slider2 = YAHOO.widget.Slider.getHorizSlider(bg, 
			thumb, topConstraint, bottomConstraint);

	slider2.getRealValue = function() {
		return Math.round(this.getValue() * scaleFactor);
        }

	slider2.subscribe("change", function(offsetFromStart) {
		var actualValue = slider2.getRealValue();
		Dom.get(bg).title = "Pos : " + actualValue;
		});

	slider2.subscribe("slideStart", function() {
		YAHOO.log("slideStart fired", "warn");
		});

	slider2.subscribe("slideEnd", function() {
		YAHOO.log("slideEnd fired", "warn");
		});

	// set an initial value
	var initpos = songPos;
	//alert(initpos);
	slider2.setValue(initpos);

	});
};

/*********************************************************************************************/

function Eqg() {
	if (soundManager.flashVersion<9) return false;
	var eq  = Dom.get('eqg');
	var y = 0;
	var i = 0;
	var t = 0;
	var g = Array();
	var d = 10;
	//eq.innerHTML = "";
	t = 0;
	for (i=0; i<64; i++) {t += song.waveformData[i];}
	g[0] = Math.round((t/64)*1000);
	t = 0;
	for (i=64; i<128; i++) {t += song.waveformData[i];}  
	g[1] = Math.round((t/64)*1000);
	t = 0;
	for (i=128; i<192; i++) {t += song.waveformData[i];}
	g[2] = Math.round((t/64)*1000);
	t = 0;
	for (i=192; i<256; i++) {t += song.waveformData[i];}
	g[3] = Math.round((t/64)*1000);
	for (i=0; i<4; i++)
		{
		g[i] = g[i]/d;
		y = Dom.getY("eqg"+i);
		Dom.setY('eqg'+i,y+g[i]);	
		}
}

// Available Flash?
function AvailableFlash()
{
	var flashok = 0;
	// Flash detection
	if(FlashDetect.installed) 
	{
		if (FlashDetect.major >= 8) flashok = 1;
        }
	if (flashok == 0)
	{
		var msg = "You need Flash Player 8 or higher<BR\> <a href='http://get.adobe.com/flashplayer/' target='_blank'>Get Flash Player</a>";
		//alert(msg);
		var z = Dom.get('container');
		z.innerHTML = msg;
	}
//alert(FlashDetect.major);
}

function InitialSong()
{
	/*
	if (playlist.length == 0)
		{
		var sa = window.opener.sa;
		var sb = window.opener.sb;
		var sc = window.opener.sc;
		var sd = window.opener.sd;
		if (sa != "" && sb != "" && sc != "" && sd != "")
				{
				PlayerAddSong(sa, sb, sc, sd);
				}	
		}
	*/
}

function AddAllPl()
{
	var i = playlist.length;
	if (parent.usuarilogat)
		{
		if (i > 0)
			{
			// Agafem les pistes del playlist
			var pistas = '';
			var z = 0;
			for (z=0;z<i;z++)
				{
				pistas = pistas + playlist[z][0] + ",";
				}
			//alert(pistas);
			// Obrim l'aplicacio
			window.open('pista2playlist.php?pistas='+pistas,'popl','width=430, height=250, left=460, top=500, resizable=0, scrollbars=yes');
			}
		else
			{
			alert('Adicione música ao leitor.');
			}
		}
	else 
		{
		down_alta('');
		}
}

/**************************************/
// init Functions

function initPlayer()
{
	//VolumeSlider();
	//SongSlider();
	//InitialSong();
}

function initBodyFlashMP3()
{
	// Check if Flash is available
	AvailableFlash();
	playlist = Array();
	// Clear the playlist.
	var zonepl = Dom.get('plylsongs');
	zonepl.innerHTML = '';
}
/**************************************/
