var MusicDetail = new Class({
	options: {
		track: null,
		playlist: null,		
		onLoad: Class.empty,
		onStart: Class.empty,
		onSongChange: Class.empty
	},
	initialize: function (options) {
		this.setOptions(options);
		this.fireEvent('onStart');
	},
	openPlaylist: function (playlistId) {
		var me = this;
		var folderId = 'playlist'+playlistId;
		if (!$(folderId)) {
			var folder = $('folders').getFirst();
			if (folder){
				/*startModalWindow({
				    cssClass: 'error',
				    body  : 'No es posible escuchar la canción ya que el Álbum que la contiene es privado.', 
				    title :'Error', 
				    hideOnClick:true
				});*/
					folderId = $(folder).getProperty('id');
					playlistId = folderId.split('playlist')[1];
					if (this.currentPlaylist) {
						return;
					}
			}else{
				startModalWindow({
				    cssClass: 'error',
				    body  : 'No es posible escuchar la canción ya que el álbum que la contiene es privado. Éste usuario no tiene álbumes de música que ud. pueda visualizar', 
				    title :'Error', 
				    hideOnClick:true
				});
			}
			window.rateStars.disable();
		}
		if (this.currentPlaylist == playlistId) {
			return true;
		} else {
			if ($('playlist'+this.currentPlaylist)) {
				$('playlist'+this.currentPlaylist).removeClass('open');
			}
			this.currentPlaylist = playlistId;
		}
		
		if ($(folderId) != null){
		
		if (!$(folderId).hasClass('open')) {
			$(folderId).addClass('open');
		}
		var jSonRequest = new Json.Remote('/music/openPlaylistJSON/', {/*async: false,*/ onComplete: function (request) {
			if (request.status == 1) {
				if (!$('content'+folderId)){
					$(folderId).adopt(new Element('ul').addClass('folder selectable music').setProperty('id','content'+folderId));
				}
				$('content'+folderId).setHTML(request.songs);
				if ($('content'+folderId).getFirst()){
					$('content'+folderId).getFirst().addClass('playing');
				}
				var folder = $('playlist' + playlistId);
				if (folder) {
					//var folderTitle = $('playlist' + playlistId).getElement('a').getText();
					var folderTitle = $('playlist' + playlistId).getElement('a').getAttribute('title');
					$('albumName').setText(folderTitle);
				}else{
					$('albumName').setHTML("&nbsp;");
				}
				if (request.embed && $('HTMLCode')) {
					$('HTMLCode').value = request.embed;
				}
				me.loadComments(request.comments);
				me.loadPlayer(playlistId);
				$$('.ratingTotalCount').setHTML(""+request.totalRate+"");
				window.rateStars.setRated(request.rated);
				window.rateStars.setRate(request.rate);
			} else {
				alert(request.result);				
			}
			stopWaiter();
		}}).send({'i': playlistId});
		this.fireEvent('onOpenPlaylist',playlistId);
		
		}
		
		
	},
	playTrack: function (trackId) {
		var me = this;
		if (trackId != this.currentTrackId) {
			var position = 0;
			$('playlist'+this.currentPlaylist).getElements('a').each(function(a, i) {
				list = a.getProperty('href').split(',');
				if (list[1] == trackId) {
					position = i-1;
					$(a.parentNode).addClass('playing');
				} else {
					$(a.parentNode).removeClass('playing');
				}
			});
			if (position > 0) {
				this.currentTrackId = trackId;
			}
			window.myFmPlayer.sendEvent('playitem',position);
		}
	},
	currentSong: function (trackId) {
		if (trackId != this.currentTrackId) {
			this.currentTrackId = trackId;
			this.fireEvent('onSongChange', trackId);
		}
	},
	selectTrack: function (trackId) {
		var me = this;
		window.location = '#'+this.currentPlaylist+','+this.currentTrackId;
		$('playlist'+this.currentPlaylist).getElements('a').each(function(a, i) {
			list = a.getProperty('href').split(',');
			if (list[1] == trackId) {
				$(a.parentNode).addClass('playing');
			} else {
				$(a.parentNode).removeClass('playing');
			}
		});
	},
	loadComments: function (request) {
		request = Json.evaluate(request);
		result = request.result;
		$$('.paggingList').each(function (obj){
			obj.remove();
		});
    	commentsModule = new CommentsModule({	
    								"item"		: result.item,
    								"ui"		: result.ui, 
		    						"type"		: result.type, 
		    						"count"		: result.count, 
		    						"page"		: result.page, 
		    						"pagesize"	: result.pageSize,
		    						"list"		: result.list,
		    						'usernick'	: result.un,
		    						'userimg'	: result.uimg,
		    						'userurl'	: result.uurl,
		    						'reply'		: result.reply,
		    						'post'		: result.post});
	},
	loadPlayer: function (playlistId) {
		var me = this;
		window.myFmPlayer = new FmPlayer({
			swfContainer		: 'container',
			swfPlayerId			: 'mySwfPlayer',
			autostart			: 'true',
			playListLocation	: location.protocol + '//' + location.hostname + '/music/getPlaylistXML/'+playlistId,
			//Esto se dispara cuando se pasa a una nueva una canción en el FmPlayer
			onSongUpdate		: function(obj) {
				if (window.loadingSong == true) {
					window.loadingSong = false;
					window.location = window.firstLocationState;
					window.musicDetail.playTrack(window.song);
				} else {
					if (window.firstTime == true){
						window.firstTime = false;
						window.loadingSong = false;
					}
					window.musicDetail.currentSong(obj.id);
					
					me.setPageTitle(obj);
					
					//Actualizo el texto de la ventana modal
					window.myFmPlayer.timeLeft.setHTML('00:00');
					window.myFmPlayer.elapsedTime.setHTML('00:00');
					
					//Guardo temporalmente el objeto recibido en "onSongUpdate" para recuperarlo en el evento "onSongEnd" */
					window.myFmPlayer._tmpObj = obj;

					//Quito la clase que indica si el bot�n obtuvo la URL remota a la cual tiene que linkear */
					if (window.myFmPlayer.aSpace.hasClass('ready')) {
						window.myFmPlayer.aSpace.removeClass('ready');
					}
					
					if (window.myWaiter && $('fmPlayer')){
						window.myWaiter.stop();
					}
				}
			},
			
			//Este evento se dispara al culminar una canci�n */
			onSongEnd			: function() {
				//Notifico al server que se visit� una canci�n para incrementar el contador de visitas de la misma */
				var remote 	= '/music/addVisitPlaylistTrackJSON';
				var jsonObj	= {'pti':parseInt(window.myFmPlayer.songId)};
				new Json.Remote(remote).send(jsonObj);
				
				//Hago que contin�e la reproducci�n del siguiente tema una vez que llega al final de un tema */
				window.myFmPlayer.sendEvent('next');
				window.myFmPlayer.sendEvent('play');
			},
			
			onAResultsClick		: function(event) {
				var event			= new Event(event);	
				var btn				= event.target;
				if (!btn.hasClass('ready')) {						
					url = "/wambafm/artist/" + window.myFmPlayer._tmpObj.author + "#" + window.myFmPlayer._tmpObj.title;
					btn.setProperties({'href': url}).addClass('ready').fireEvent('click', event);
				}					
			},
			
			onASpaceClick		: function(event) {					
				setPlayerButtonsUrls (event, '/wambafm/getArtistProfileUrlJSON/' + window.myFmPlayer._tmpObj.author);
			}
		});
		//Pongo el mensaje de "Cargando..." 
		window.myFmPlayer.song.setHTML("Cargando resultados (sin i18n)");
	},
	setPageTitle: function(request){
		document.title = pageTitle+' # '+request.title;
	}
});
MusicDetail.implement(new Events, new Options);


window.addEvent('domready', function(){

	var sendToFriend = $('sendToFriend');
	if ($type(sendToFriend) == 'element') {
		sendToFriend.addEvent('click', function (ev) {
			var event = new Event(ev).stop();
			startVM('music');
		});
	} 
	window.rateStars = new RateStars({
		i: '1',
		rate: '0',
		rated: '0',
		starsWidht: 25,
		layerWidth: 125,
		container: 'ratingStars',
		selection: 'starSelectionContainer',
		onRate: function (rate) {
			var jSonRequest = new Json.Remote('/music/saveCalificationJSON/', {onComplete: function (request) {
			if (request.status == 1) {
				window.rateStars.setRated(request.rated);
				window.rateStars.setRate(request.rate);
				window.rateStars.setTotalRate(request.totalRate);
			}
			if (request.status != 1) {
				alert(request.result);				
			}
		}}).send({'r': rate, 'p': musicDetail.currentPlaylist});
			
		}
	});
	window.musicDetail = new MusicDetail({
		onOpenPlaylist: function (playlistId) {
			//window.treeView.expand($('playlist'+playlistId));
		},
		onSongChange: function (trackId) {
			this.selectTrack(trackId);
		}
	});
	window.treeView = new TreeView({
		id					: 'folders',
	 	collapsable			: true,
	 	onExpand			: function(){
	 		startWaiter($("folders"));	
	 	}
	});	
	window.firstTime = true;
	window.HistoryManager.setOptions({
		onObserverChange: function() {
			//document.title = pageTitle+' # '+this.getState();
			if ($('URLLink')) {
				$('URLLink').value = URLLink+'#'+this.getState();
			}
			if (this.getState()== '') {
				window.location = '#'+defaultPlaylistId;				
			} else {
				items = this.getState().split(',');
				if (items[0]) {
					window.playlist = items[0];
					window.musicDetail.openPlaylist(window.playlist);
				}
				if (items[1]) {
					window.song = items[1];
					if (window.firstTime == true) {
						window.firstTime = false;
						window.loadingSong = true;
						window.firstLocationState = '#'+this.getState();
					} else {
						window.musicDetail.playTrack(window.song);
					}					
				} else {
					window.loadingSong = false;
				}
			}
		}
	});
	window.HistoryManager.initialize();
	window.HistoryManager.start();
	
	//if (window.showLinkAndEmbedded) {
		/* Agrego los eventos de copy to clipboard si se despliegan los boxes */
	if (window.Clipboard && $('URLLink') && $('HTMLCode')) {
		if ($type(Clipboard) == "object") {
			window.Clipboard.setMessage(jsLang.MSG_COPIED_TO_CLIPBOARD);
			var linkBox = $('URLLink');
			var linkLabel = 'copied_box_1';
			var embedBox = $('HTMLCode');
			var embedLabel = 'copied_box_2'
			if ($type(linkBox) == 'element') {
				linkBox.addEvent('click' , function () {
					this.select();
					window.Clipboard.copyFromElement(linkBox.id, linkLabel);
				});
			}
			if ($type(embedBox) == 'element') {
				embedBox.addEvent('click' , function () {
					this.select();
					window.Clipboard.copyFromElement(embedBox.id, embedLabel);
				});
			}
		}
	}
	//}
});

var itemParam = window.location.href.split('#');
var itemParamJson = itemParam[1].split(',');
var jSonRequest = new Json.Remote('/music/openPlaylistJSON/', { 
				onComplete: function (request) {
					if (request.status == 0) {
						alert(request.result);				
					}
				}
			}).send({'i': itemParamJson[1]});