var Player = new Class(
		{
			Implements : [ Events, Options ],
			options : {
				onStart : $empty
			},

			initialize : function(options) {
				if (!navigator.userAgent.match(/firefox/i) && !navigator.userAgent.match(/msie/i) && !navigator.userAgent.match(/chrome/i)) {
					UI.unsupportedBrowser();
				}
				this.setOptions(options);
				this.syncVolume = (RadioBeta.readCookie("radiovolume")!='') ? parseInt(RadioBeta.readCookie("radiovolume")) : 80;
				this.volControl = $empty;
				this.makeVolSlide();
				GlobalEvents.addListener('ClientPlayerSetInfo', this.updateInfoExternal);
				this.updateInfoTimer = this.updateInfoHandle.periodical(500);
				this.setSongText('');
				if (navigator.userAgent.toLowerCase().indexOf('msie') == -1) {
					$$('.onlyIE').setStyle('opacity','0');
					this.songTextCache = 'noIE';
				}				
			},

			buttonStatus : 0,
			updateInfoTimer : 0,
			songTextCache : '',
			songMarquee : $empty,
			syncVolume : 0,
			backVolume : 0,
			currentRadio : false,
			isPlaying : false,
			ajaxNP : '',

			setSongText : function(text) {
				var _this = this;
				if (_this.songTextCache == 'noIE') return;
				var text = text || ' No Data ';
				if (text == _this.songTextCache) return;

				
				if (document.getElementById('mooquee-text')!=null) {
					
					text = text || "";
					if(document.getElementById("songDisplay1")!=null){
						$("songDisplay1").inneHTML=text;
					}
					
					//$("songDisplay1").setStyle('left', 296);
				} else {
					if(document.getElementById("songDisplay1"!=null)){
						$("songDisplay1").innerHTML=text;
						this.songMarquee = new mooquee($("songDisplay1"), {
							direction : 'left',
							marWidth : 296,
							marHeight : 24
						});
					}
				}

				this.songTextCache = text;
			},

			updateInfoHandle : function() {
				GlobalEvents.fireEvent('ClientPlayerUpdateInfo', {
					'active' : ClientPlayer.activePlugin
				});
			},

			updateInfoExternal : function(params) {
				if ($defined(RBPlayer)) {
					RBPlayer.updateInfo(params);
				}
			},
			setBoton: function(state) {
				var state = state || 0;
				if (state!=0) state = 1;
				
				this.buttonStatus = state;
				$("playStop").className = state==0?"play":"stop";
			},
			updateInfo : function(params) {
				var bitrate = '';

				var statep = params.state;

				if (typeof statep == 'string') {
					if (statep == 'Playing' || statep == 'Buffering' || statep == 'Waiting' || statep == 'Connecting' || statep == 'Reconnecting') {
						if (statep == 'Connecting') statep = '<blink>Connecting</blink>';
						this.setBoton(1);
					}else{ 
						this.setBoton(0);
					}
				}
				
				if (params.playing == true) {
					if (params.bitrate > 0) bitrate = ' | ' + Math.round(params.bitrate * 8) + ' Kb/s';
					this.setSongText(params.title);
					this.isPlaying = true;
				} else {
					this.setSongText('');
					this.isPlaying = false;
					$clear(this.ajaxNP);
				}

				if ($defined(params.state) && params.state!=0) { 
					
					params.state = params.state || "Stopped";
					bitrate = bitrate || "";
					$("playerDisplay2").setHTML( params.state + bitrate ); 
				} else { 
					$("playerDisplay2").innerHTML=""; 
				}
			},

			setVolume : function(vol) {
				if (vol==0) {
					$('mute').setStyle('opacity', 0.2);
				} else {
					$('mute').setStyle('opacity', 1);
				}
				GlobalEvents.fireEvent('ClientPlayerVolume', { 'value' : vol });
				RadioBeta.setCookie('radiovolume',vol,365);
				this.syncVolume = vol;
			},

			mute : function(item) {
				if (this.syncVolume == 0) {
					if (this.backVolume==0) this.backVolume = 80;
					this.volControl.set(this.backVolume);
				} else {
					this.backVolume = this.syncVolume;
					this.volControl.set(0);
				}
			},

			pause : function() {
				if (window.URLDaemon && URLDaemon.module=='info' && URLDaemon.task>0) {
					this.play(URLDaemon.task);
					return;
				} 
				if (!this.currentRadio) { //Si no hay radio, reprodusco la 1ra del playlist o la 1ra del pais.
					this.play(FrontPlaylist.getFirst() || (FrontGeo.location.firstRadio||0));
					return;
				} 
					
				if (this.buttonStatus == 0) {
					GlobalEvents.fireEvent('ClientPlayerPlay', {});
					this.setBoton(1);
				} else {
					GlobalEvents.fireEvent('ClientPlayerStop', {});
					this.setBoton(0);
					$clear(this.ajaxNP);
				}				
			},

			playAction : function(Radio) {
				var Radio = Radio || false;
				
				if (typeof Radio == 'object') {
					if(Radio._originalResponse && Radio._originalResponse.radio_transmite==0) 
						return RadioBeta.dialog('', '', lang.noTransmite(Radio.id), 500, 135, function() { });
					lang.loading = lang.loading || "";
					Radio.name = Radio.name || "";
					
					$("playerDisplay1").setHTML(lang.loading + " " + Radio.name);
					GlobalEvents.fireEvent('ClientPlayerStop');
					$clear(this.ajaxNP);
					this.setSongText('');
					
					var playing = ClientPlayer.setPlayer(Radio.streams, this.syncVolume);
					
					RadioBeta.setCookie('radiobetaID', Radio.id, 365);

					if (!playing) {
						lang.errorConnect = lang.errorConnect || "ERROR 000x01";
						Radio.name = Radio.name || "";
						$("playerDisplay1").setHTML(lang.errorConnect + " " + Radio.name);
						$("playerDisplay2").innerHTML="";
						this.setBoton(0);
						
					} else {
						lang.listeningTo = lang.listeningTo || "";
						Radio.name = Radio.name || "";
						$("playerDisplay1").setHTML(lang.listeningTo + " " + Radio.name);
						$("playerDisplay2").innerHTML="";
						this.setBoton(1);

						this.currentRadio = Radio;

						//Radios.nowPlaying(Radio.id, FrontUser.data.id);
						Radios.nowPlaying(Radio.id, _USERID);
						
						this.ajaxNP = setInterval("Radios.nowPlaying("+ Radio.id + ", " + FrontUser.data.id + ")",30000);
					}

					FrontClock.setTZ(Radio);

					RadioBeta.addPop(Radio.id);
					$("problemLink").setStyle('visibility', 'visible');
				}
			},

			play : function(idradio) {
				GlobalEvents.fireEvent('ClientPlayerStop');
				this.isPlaying = false;
				if (!idradio) return;
				//mmm, esto es sincronico o asincronico???
				var Radio = Streams.getFromLocalhost(idradio);

				if (Radio) {
					this.playAction(Radio);
				} else {
					Radios.getInfo(idradio, function(r) {
						this.playAction(r);
					}.bind(this), 0);
				}

			},
			makeVolSlide : function() {
				if(document.getElementById("volSlider")==null) return;
				$("volSlider").setStyle("cursor", "pointer");
				defVolume = this.syncVolume;

				var mySlider = new Slider($("volSlider"), $('knob'), {
					snap : false,
					steps : 20,
					wheel : false,
					range : [ 0, 100 ]
				}).set(defVolume);

				this.setVolume(defVolume);

				mySlider.addEvent("change", function() {
					this.setVolume(this.volControl.step);
				}.bind(this));

				mySlider.addEvent("onComplete", function() {
					this.setVolume(this.volControl.step);
				}.bind(this));

				this.volControl = mySlider;
			},
			getcid : function() {
				var _this = this;

				if ($defined(_this.currentRadio)
						&& $defined(_this.currentRadio.id)) {
					return parseInt(_this.currentRadio.id);
				} else {
					return 0;
				}

			},
			bookmark : function() {
				var _this = this;
				var id = _this.getcid();
				if (id < 1 || !$defined(FrontUser)) return false; 

				FrontUser.dbAddBookmark(id);
			},

			info : function() {
				var _this = this;
				var id = _this.getcid();
				if (id < 1 || !$defined(URLDaemon)) return false;

				URLDaemon.change('info/' + id + '/');
			},
			'random' : function() {
				var _this = this;
				var id = _this.getcid();

				if (!$defined(FrontPlaylist)) return false;

				var jump = FrontPlaylist.doRandom(id);

				if (jump === false) return false;

				_this.play(jump);
			},
			forward : function() {
				var _this = this;
				var id = _this.getcid();

				if (!$defined(FrontPlaylist)) return false;

				var jump = FrontPlaylist.doForward(id);

				if (jump === false) return false;
				_this.play(jump);
			},
			rewind : function() {
				var _this = this;
				var id = _this.getcid();

				if (!$defined(FrontPlaylist)) return false;

				var jump = FrontPlaylist.doRewind(id);

				if (jump === false) return false;

				_this.play(jump);
			},

			userbtn : function() {
				var rid = this.currentRadio.id;
				if (!$defined(rid) || rid < 1)
					return false;

				RadioBeta.dialog('Who play this', 'Who play this', '#/iframe/whoplaythis?rid=' + rid, 500, 300, function() { });
			},
			detach : function() {
				if (this.buttonStatus != 0) this.pause();
				var windowWidth = 700;
				var windowHeight = 430;
				var rid = this.currentRadio.id;

				if (navigator.appVersion.indexOf('Chrome') > 0) {
					windowHeight = windowHeight + 4;
					windowWidth = windowWidth + 2;
				} 
				var RBwindow = window.open('/jswidget/era3/?autoplay='+rid, 'RBPlayer', 'width=' + windowWidth + ',height=' + windowHeight + ',toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=no,copyhistory=no,resizable=no');
				if (this.currentRadio.id && this.buttonStatus != 0) RBwindow.previousRadio = this.currentRadio.id;
			},
			apple : function() {
				var _this = this;
				if (_this.songTextCache.length > 0) {
					var url = 'http://ax.itunes.apple.com/WebObjects/MZSearch.woa/wa/search?term=';
					url += escape(_this.songTextCache);
					window.open(url, 'itunesrb');
				} else {
					alert(lang.nosong);
					return;
				}
			},
			amazon : function() {
				var _this = this;
				if (_this.songTextCache.length > 0) {
					var url = 'http://www.amazon.com/s/?node=163856011&linkCode=qs&tag=radiobeta-20&keywords=';
					url += escape(_this.songTextCache);
					window.open(url, 'amazonrb');
				} else {
					alert(lang.nosong);
					return;
				}
			},

			flag : function() {
				if (!$defined(URLDaemon)) return false;
				var id = this.getcid();
				if (id < 1) { URLDaemon.change(''); return false; }
				Users.problems(id);
			},

			dialog : function(title, summary, body, width) {
				if (!$defined(title)) {
					title = '';
				}
				if (!$defined(summary)) {
					summary = '';
				}
				if (!$defined(body)) {
					body = '';
				}
				if (!$defined(width)) {
					width = document.documentElement.clientWidth;
				} else if (width > document.documentElement.clientWidth)
					width = document.documentElement.clientWidth;

				try {
					$('pop_dialog_table').setStyle('width', width);
					$('fb-modal-title').setHTML(title);
					$('fb-modal-summary').setHTML(summary);
					$('fb-modal-body').setHTML(body);

					$('fb-modal').fade('in');
				} catch (e) {
						alert(e);
				}
			}
		});

// Eventos

// Errores
GlobalEvents.addListener('ClientPlayerError', function(params) {
	RadioBeta.dialog('Player Error', lang.problemToPlay, params.description/* +' <em>(Code: '+params.code+')</em>' */, 400, 250);
});
GlobalEvents.addListener('ClientPlayerPluginError', function(params) {
	RadioBeta.dialog('Player Error', lang.problemToPlay, params.description/* +' <em>(Code: '+params.code+')</em>' */, 400, 250);
});

window.onbeforeunload = function() {
	if (!$defined(RBPlayer)) return;
	if (RBPlayer.isPlaying) return lang.onbeforeunload;
};

