//radioplayer
var RadioPlayer = MediaPlayer.extend({
	onPlay:null, // define this if is necessary to retrieve the event TvPlayer.onPlay = function() {}
	onStop:null, // define this if is necessary to retrieve the event TvPlayer.onStop = function() {}
	
	elapsedTime:1, // in seconds
	elapsedTimeIntervalID:-1,
	
	init: function(id){
		this._super(id);
	},
	
	play: function() {
		var self = this;
		if (this._super()) {
			if (this.onPlay && typeof(this.onPlay)=='function') this.onPlay(); //call onPlay event handler, if defined
			this.elapsedTimeIntervalID = setInterval(function(){
				self.elapsedTime++;
			},1000);
			return true;
		};
		return false;
	},
	
	isPlaying: function() {
		return (this.getState() == 3) ? true : false;
	},
	
	stop: function() {
		if (this._super()) {
			if (this.onStop && typeof(this.onStop)=='function') this.onStop(); //call onStop event handler, if defined
			this.resetElapsedTime();
			return true;
		};
		return false;
	},
	
	resetElapsedTime: function() {
		clearInterval(this.elapsedTimeIntervalID);
		this.elapsedTimeIntervalID = -1;
		this.elapsedTime = 1;
	},
	
	pauseElapsedTime: function() {
		clearInterval(this.elapsedTimeIntervalID);
	},
	
	resumeElapsedTime: function() {
		var self = this;
		this.elapsedTimeIntervalID = setInterval(function(){
			self.elapsedTime++;
		},1000);
	},
	
	getElapsedTime: function() {
		return this.elapsedTime;
	}
});

//radioplayerskin
function RadioPlayerSkin(mediaPlayer) {
	this.controls = new Array();
	this.controls['togglePlay'] = 'ppp';
	this.controls['stop'] = 'ppp';
	this.controls['mute'] = 'speaker';
	this.controls['volume'] = 'volume';
	
	this.defaultVolume = 50;
	this.elapsedTimeIntervalID = -1;
	
	this.init = function(mediaPlayer) {
		var self = this;
		
	    $('#'+this.controls['togglePlay']).click(function () {
	    	if (mediaPlayer.stop()) {
	    		$(this).removeClass('pause').addClass('play');
	    	} else {
		    	if (mediaPlayer.play()) {
		    		$(this).removeClass('play').addClass('pause');
		    	}
	    	}
	    });
	    
	    $('#'+this.controls['mute']).click(function () {
	    	var vol = mediaPlayer.getVolume();
	    	if (vol) mediaPlayer.toggleMute();
	    	var speaker = $('#speaker');
	    	if (!mediaPlayer.isMuted && !vol) {
	    		mediaPlayer.setVolume(self.defaultVolume);
	    		vol = self.defaultVolume;
	    		$('#'+self.controls['volume']).slider('value',vol);
	    	}
	    	speaker.attr('class', self.getVolumeIcon((mediaPlayer.isMuted) ? 0 : vol));
	    });
	    
	    $('#'+this.controls['fullscreen']).click(function () {
	    	mediaPlayer.fullScreen();
	    });
	    
	    $('#'+this.controls['volume']).slider({
			range: "min",
			value: self.defaultVolume,
			min: 0,
			max: 100,
			slide: function(event, ui) {
	    		var speaker = $('#speaker');
	    		var vol = parseInt(ui.value,10);
	    		speaker.attr('class', self.getVolumeIcon(vol));
	    		mediaPlayer.setVolume(vol);
			}
		});
	};
	
	this.getVolumeIcon = function(vol) {
		if (vol <= 0) return 'spe';
		if (vol > 0 && vol <= 30) return 'spd';
		if (vol > 30 && vol <= 50) return 'spc';
		if (vol > 50 && vol <= 80) return 'spb';
		return 'spa';
	};
	
	this.showElapsedTime = function() {
		$('#playedtotaltime').show();
	};
	
	this.hideElapsedTime = function() {
		$('#playedtotaltime').hide();
	};
	
	this.clearElapsedTime = function() {
		$('#playedtotaltime').html('');
	};
	
	this.updateElapsedTime = function() {
		this.elapsedTimeIntervalID = setInterval(function(){
			var _time = getTimeFromSeconds(mediaPlayer.getElapsedTime());
			var time_str = (_time[0] > 0) ? _time[0]+":"+_time[1]+":"+_time[2] : _time[1]+":"+_time[2];
			$('#playedtotaltime').html(time_str);
		},1000); 
	};
	
	this.pauseElapsedTime = function() {
		clearInterval(this.elapsedTimeIntervalID);
	};
	
	this.init(mediaPlayer);
}

//radiocustom
bufferIntervalID = -1;
function updateBufferStatus() {
	var progress = rPlayer.getBufferingProgress();
	var bufferStatus = $('#buffering');
	bufferStatus.html(progress+'% ????????. ????, ?????????...');
	if (progress == 100 && rPlayer.getState() == 3) {
		clearInterval(bufferIntervalID);
		bufferIntervalID = -1;
		bufferStatus.hide();
		radioPlayerSkin.updateElapsedTime();
		rPlayer.resumeElapsedTime();
		radioPlayerSkin.showElapsedTime();
	}
}

function OnDSPlayStateChangeEvt(NewState) {
	if (!rPlayer) {
		setTimeout(function(){
			OnDSPlayStateChangeEvt(NewState);
		},150);
		return;
	}
}

function OnDSBufferingEvt(Start) {
	if (!rPlayer) {
		setTimeout(function(){
			OnDSBufferingEvt(Start);
		},150);
		return;
	}
	mediaPlayerStats.buffering(Start);
	if (Start) {
		if (bufferIntervalID <0) bufferIntervalID = setInterval("updateBufferStatus()",100);
		$('#showData').hide();
		$('#buffering').show();
		radioPlayerSkin.pauseElapsedTime();
		rPlayer.pauseElapsedTime();
		radioPlayerSkin.hideElapsedTime();
	} else {
		$('#showData').show();
		$('#buffering').hide();
	}
	rPlayer.buffering(Start);
}

function changeHeaderRadio(radio){
	$("[name^='radioicon'] a").removeClass();
	$("[name='radioicon" + radio + "'] a").attr("class", "TVact");
	$.ajax({
		type: 'POST',
		url: rootURL + "ajax/getradio/",
		data: {
			'radio': radio
		},
		dataType: 'json',
		jsonp:'jsonp_callback',
		success: function(data){
			if (data){
				var currUrl = document.location.toString();
 				currUrl = currUrl.split('#')[0];
 				document.location.href = currUrl + "#" + radio;
				$('#radioTop h2').html('<span class="imIcR r' + data['title'] + ' png" /></span>' + data['title_display']);
				//$('#radioLogoBig').css("backgroundImage", "url("+data['image_path']['big']+")");
				$('#showTitle').html(data['title_display']);
				stream_type = data.stream_type; 
			}
		}
	});
}

rPlayer = new RadioPlayer('wmpradioplayer');

rPlayer.onPlay = function() {
	mediaPlayerStats.startRunning();
};

rPlayer.onStop = function() {
	mediaPlayerStats.stopRunning(2);
};

window.onbeforeunload = function() {
	mediaPlayerStats.stopRunning(1);
};

mediaPlayerStats = new MediaPlayerStats();
mediaPlayerStats.url = rootURL + "ajax/updaterunningtimeradio/";
mediaPlayerStats.onTooManyBufferings = function() {
	displayErrorMessage(3);
};
radioPlayerSkin = new RadioPlayerSkin(rPlayer);

function getRadioByUrl(){
	var currUrl = document.location.toString();
	if (currUrl.match('#')){
 		var currRadio = currUrl.split('#')[1];
 		$.ajax({
			type: 'POST',
			url: rootURL + "ajax/getradiocc/",
			data: {
				'radio': currRadio
			},
			dataType: 'json',
			jsonp:'jsonp_callback',
			success: function(data){
				if (data){
					radio_name = data['title'];
					radioChange(data['title'], data['cc'], data['type']);
				}
			}
		});
	}
}

function getTimeFromSeconds(_time){
	var milliseconds = _time*1000;
	var hours = Math.floor(milliseconds / 3600000);
	if (hours < 10) hours = "0"+hours;
	
	var minutes = Math.floor((milliseconds - (hours * 3600000)) / 60000);
	if (minutes < 10) minutes = "0"+minutes;
	
	var seconds = parseInt((milliseconds - (hours * 3600000) - (minutes * 60000)) / 1000);
	if (seconds < 10) seconds = "0"+seconds;
	
	return Array(hours, minutes, seconds);
}

$(document).ready(function(){
	$(".radioheadericon").click(function(e){
		e.preventDefault();
		var radioname = $(this).attr("alt");
		document.location.href = rootURL + "radio/#" + radioname;
		getRadioByUrl();
	});
	getRadioByUrl();
});

function radioChange(currRadio, currCode, currType){
	changeHeaderRadio(currRadio);
	var flashVars = "rooturl=" + rootURLEncoded + "&thecode=" + currCode + "&radioname=" + currRadio;
	var radioLink = rootURL + "radiostream/" + currRadio + "/" + currCode;

	rPlayer.resetElapsedTime();
	radioPlayerSkin.pauseElapsedTime();
	radioPlayerSkin.clearElapsedTime();
	radioPlayerSkin.hideElapsedTime();
	if (currType == "w"){
		setTimeout(function() {
			$('#wrapper_wmpradioplayer').show();
			$('#wrapper_flashradioplayer').hide();
			rPlayer.setSrc(radioLink);
			mediaPlayerStats.startRunning();
		},200);
	} else {
		if (rPlayer.isPlaying()) rPlayer.stop();
		$('#wrapper_wmpradioplayer').hide();
		$('#wrapper_flashradioplayer').show();
	}
}
