var MPlayer = {
	currentSong: "",
	currentArtist: "",

	updateData: function()
	{
		if (config.playlist == "1") {
			setInterval("MPlayer.getPlaylist()",3000);
		}else{
			jQuery("#playlist, #playlistSwitch, #artistFoto, #currentTrack").hide();
		}
	},

	updateBrowserTitle: function()
	{
	    jQuery("title").text(this.currentArtist + ' - ' + this.currentSong + ' (' + config.title + ')');
	},

	setPlayer: function(streamURI, playerUrl)
	{
		playerUrl = playerUrl || '/swf/RadioP.swf';

		jQuery('#flashPlayer').flash(
			{ 
				src: HTTP_SITE_ROOT + playerUrl,
				wmode: 'transparent',
				allowscriptaccess: 'always',
				flashvars: {
					stream: streamURI,
					autoplay: config.autoplay
				},
				width: 160,
				height: 120 },
			{ version: 9,
				expressInstall: true }
    	);
   	jQuery('.stationLogo img').attr("src",HTTP_SITE_ROOT + '/design/logos/' + config.station + '.gif');
	},

	getPlaylist: function() {
		jQuery.ajax({
			async: false,
			type: "GET",
			url: HTTP_SITE_ROOT + "/radio/station/" + config.station + "/playlist.json",
			dataType: "json",
			success: function(songlist){
				MPlayer.updatePlaylist(songlist);
			}
		});
	},

	updatePlaylist: function(songlist) {
		output = '';
		songStatus = "";

		for(i = 0; i < songlist.length; i++) {
			tmp = '<span>' + songlist[i].time + '</span> ' + songlist[i].artist + ' - ' + songlist[i].title;

			switch(songlist[i].status) {
				case 'history':
					tmp = '<li class="back">' + tmp + '</li>';
					break;
				case 'current':
					tmp = '<li class="now">' + tmp + '</li>';
					if (this.currentSong == songlist[i].title) return;
					this.currentSong = songlist[i].title;
					songStatus = this.prepareCurrent(songlist[i]);
					songLength = new Date(songlist[i].song_duration);
					songSeconds = songLength.getSeconds();
					songSeconds = (songSeconds < 10) ? "0" + songSeconds : songSeconds;

					songLength = songLength.getMinutes() + ":" + songSeconds;
					break;
				default:
					tmp = '<li class="next">' + tmp + '</li>';
					break;
			}

			output += tmp;
		}

		if (jQuery("#mjoy_radio_cur_track").html().indexOf(this.currentArtist) < 0) {
			jQuery("#thumb img").attr("src",HTTP_SITE_ROOT + "/radio/foto.php?a=" + encodeURIComponent(this.currentArtist));
			jQuery("#mjoy_radio_cur_track").html(songStatus);
			jQuery("#mjoy_radio_cur_length").html(songLength);
			jQuery("#mjoy_radio_playlist").html(output);

			// Favorites
			jQuery('.player_artist #fav_holder_up img').attr('src', '/images/rating_up.gif');
			jQuery('.player_artist #fav_holder_down img').attr('src', '/images/rating_down.gif');
			jQuery('.player_artist #fav_holder_up img').unbind();
			jQuery('.player_artist #fav_holder_down img').unbind();

			//
			jQuery('.player_artist #fav_holder_up img').bind('mouseenter', function(){
					jQuery(this).attr('src', '/images/rating_up_over.gif');
				});
			jQuery('.player_artist #fav_holder_up img').bind('mouseleave', function(){
					jQuery(this).attr('src', '/images/rating_up.gif');
				});
			jQuery('.player_artist #fav_holder_up img').bind('click', function(){
					jQuery(this).attr('src', '/images/rating_up_over.gif');
					jQuery.ajax({
						type: "POST",
						url: HTTP_SITE_ROOT + "/songvote.php",
						data: "song_artist=" + MPlayer.currentArtist + "&song_title=" + MPlayer.currentSong + "&song_mark=up&song_station=" + config.station + "&song_filename="
					});
					jQuery('.player_artist #fav_holder_up img').unbind();
					jQuery('.player_artist #fav_holder_down img').unbind();
				});

			jQuery('.player_artist #fav_holder_down img').bind('mouseenter', function(){
					jQuery(this).attr('src', '/images/rating_down_over.gif');
				});
			jQuery('.player_artist #fav_holder_down img').bind('mouseleave', function(){
					jQuery(this).attr('src', '/images/rating_down.gif');
				});
			jQuery('.player_artist #fav_holder_down img').bind('click', function(){
					jQuery(this).attr('src', '/images/rating_down_over.gif');
					jQuery.ajax({
						type: "POST",
						url: HTTP_SITE_ROOT + "/songvote.php",
						data: "song_artist=" + MPlayer.currentArtist + "&song_title=" + MPlayer.currentSong + "&song_mark=down&song_station=" + config.station + "&song_filename="
					});
					jQuery('.player_artist #fav_holder_up img').unbind();
					jQuery('.player_artist #fav_holder_down img').unbind();
				});

			this.updateBrowserTitle();
		}

	},

	prepareCurrent: function(song) {
		this.currentArtist = song.artist;
		return '<h2>' + song.artist + '</h2><h3>' + song.title + '</h3><em>' + song.album + '</em>';
	}
};

function getMaskPosition(element) {
	var position = element*250;
	position = (position > 0) ? position : 0;
	return "-" + position + "px 0px";
}

var stations_timer = new Array();

function updateRadioBlocks() {
	var url = HTTP_SITE_ROOT + "/design/config.json";
	var radio_cnt = 0;
	jQuery.getJSON(url, function(data){
		var list = jQuery('#radiocarousel_holder ul');
		list.html("");
        jQuery.each(data, function(item,stream){
			if (item != "player") {
				radio_cnt++;
				var logo = '<div class="stationLogo"><a class="startbutton" href="' + HTTP_SITE_ROOT + '/radio/' + item + '#" target="_blank"><img src="' + HTTP_SITE_ROOT + '/design/logos/' + item + '.png" alt="' + stream.title + '" /></a></div>';
				var strt_button = '<a class="startbutton" href="' + HTTP_SITE_ROOT + '/radio/' + item + '#" target="_blank"><img src="images/play_button_red.png" alt="" /></a>';
				var track_title = '<span class="trackName" id="slider_radio_' + item + '"></span>';
				var track_length = '<span class="trackLenght" id="slider_tracklng_' + item + '"></span>';
				list.append('<li>' + logo + '<div class="stationDescr">' + strt_button + track_title + track_length +'</div></li>');
				if (stream.playlist == "1") setCurrentSong(item);
			}
		});
        jQuery.each(data, function(item,stream){
			if (item != "player") {
				radio_cnt++;
				var logo = '<div class="stationLogo"><a class="startbutton" href="' + HTTP_SITE_ROOT + '/radio/' + item + '#" target="_blank"><img src="' + HTTP_SITE_ROOT + '/design/logos/' + item + '.png" alt="' + stream.title + '" /></a></div>';
				var strt_button = '<a class="startbutton" href="' + HTTP_SITE_ROOT + '/radio/' + item + '#" target="_blank"><img src="images/play_button_red.png" alt="" /></a>';
				var track_title = '<span class="trackName" id="slider_duplicate_radio_' + item + '"></span>';
				var track_length = '<span class="trackLenght" id="slider_duplicate_tracklng_' + item + '"></span>';
				list.append('<li>' + logo + '<div class="stationDescr">' + strt_button + track_title + track_length +'</div></li>');
				if (stream.playlist == "1") setCurrentSong(item);
			}
		});
		jQuery('#radiocarousel_holder').mousemove (function (e) {
			var item_width = 0;
			jQuery('#mjoy_radios li').each(function(item){
				item_width += jQuery(this).width();
			});
			var sw = document.body.scrollWidth;
			var x = e.clientX;
			var overflow = (item_width - sw) / 2 * 5;
			var mv = (((sw/4) - x) / sw ) * overflow;
			jQuery('#mjoy_radios').css ({left: (overflow > 0)? (mv + 'px') : 0 });
		});

	});
}

function setCurrentSong(station) {
	var result = '';
	var song_duration = '';
	var hours, minutes, seconds, durationU;
		jQuery.ajax({
			async: false,
			type: "GET",
			url: HTTP_SITE_ROOT + "/radio/station/" + config.station + "/playlist.json",
			dataType: "json",
			success: function(songlist){
				jQuery.each(songlist, function(i,song) {
					if (song.status == 'current' && jQuery('#slider_radio_'+station).html().indexOf(song.artist.substr(0,5)) < 0) {
						result = song.artist + ' - ' + song.title;
						if(result.length > 18) {
							result = result.substr(0,18) + '...';
						}
						var j = stations_timer.length;
						stations_timer[j] = {};
						stations_timer[j].station = station;
						stations_timer[j].song_duration = song.song_duration;
						stations_timer[j].song_begin = song.song_begin;

						var d = new Date();
						durationU = (song.song_duration/1000) - (d.getTime()/1000 - song.song_begin)+5;
						if(durationU > 0) {
							hours = Math.floor(durationU/3600);
							minutes = Math.floor(durationU/60) - (hours*60);
							seconds = Math.floor(durationU - (hours*3600) - (minutes*60));
							song_duration = minutes + ':' + ((seconds < 10) ? '0' + seconds : seconds);
						} else {
							song_duration = '0:00';
						}
						jQuery('#slider_radio_'+station).html(result);
						jQuery('#slider_tracklng_' + station).html(song_duration);
					}
				});
				jQuery.each(songlist, function(i,song) {
					if (song.status == 'current' && jQuery('#slider_duplicate_radio_'+station).html().indexOf(song.artist.substr(0,5)) < 0) {
						result = song.artist + ' - ' + song.title;
						if(result.length > 18) {
							result = result.substr(0,18) + '...';
						}
						var j = stations_timer.length;
						stations_timer[j] = {};
						stations_timer[j].station = station;
						stations_timer[j].song_duration = song.song_duration;
						stations_timer[j].song_begin = song.song_begin;

						var d = new Date();
						durationU = (song.song_duration/1000) - (d.getTime()/1000 - song.song_begin)+5;
						if(durationU > 0) {
							hours = Math.floor(durationU/3600);
							minutes = Math.floor(durationU/60) - (hours*60);
							seconds = Math.floor(durationU - (hours*3600) - (minutes*60));
							song_duration = minutes + ':' + ((seconds < 10) ? '0' + seconds : seconds);
						} else {
							song_duration = '0:00';
						}
						jQuery('#slider_duplicate_radio_'+station).html(result);
						jQuery('#slider_duplicate_tracklng_' + station).html(song_duration);
					}
				});
				updateSongTimer();
			}
		});
}

var currentUpdateTry = 0;

function updateHomeBlocks() {
	var currentSong = "";
	currentUpdateTry++;
	var list = jQuery('#radiocarousel_holder ul');
	list.html("");

	jQuery.ajax({
		async: false,
		type: "GET",
		url: "/design/config.json",
		dataType: "json",
		success: function(data){
			if (currentUpdateTry == 1) {
				list.html("");
				jQuery.each(data, function(item,stream){
					if (item != "player") {
						list.append('<li class="rb_' + item + '"><a href="/radio/' + item + '#" style="background-image: url(../design/logos/' + item + 	'.png);">' + stream.title + '</a></li>');
					}
				});
			}
		jQuery.ajax({
			async: false,
			type: "GET",
			url: "/radio/station/current.json",
			dataType: "json",
			success: function(currentSongs){
				list.html("");

				jQuery.each(data, function(item,stream){
					if (item != "player") {
						currentSong = currentSongs[item];
						if (currentSong != undefined) {
							if(currentSong.length > 25) {
								currentSong = currentSong.substr(0,23) + '...';
							}
						}else{
							currentSong = stream.title;
						}

						// Add block to list
						list.append('<li class="rb_' + item + '"><a href="/radio/' + item + '#" style="background-image: url(../design/logos/' + item + '.png);">' + currentSong + '</a></li>');
					}
				});

				jQuery("#radiocarousel_holder").jCarouselLite({auto: 250,speed: 2500,start: 1,visible: 4,circular: true,mouseWheel: true});
			},
			error: function(x,y,z) {
				if (currentUpdateTry < 4)
					setTimeout(updateHomeBlocks,1000);
				else
					jQuery("#radiocarousel_holder").jCarouselLite({auto: 250,speed: 2500,start: 1,visible: 4,circular: true,mouseWheel: true});
			}
		});
		},
		error: function(x,y,z) {
			if (currentUpdateTry < 4)
				setTimeout(updateHomeBlocks,1000);
			else
				jQuery("#radiocarousel_holder").jCarouselLite({auto: 250,speed: 2500,start: 1,visible: 4,circular: true,mouseWheel: true});
		}
	});
}

function getHomeCurrentSongs(data, currentSongs, list) {
			jQuery.each(data, function(item,stream){
				if (item != "player") {
					currentSong = currentSongs[item];
					if (currentSong != undefined) {
						if(currentSong.length > 25) {
							currentSong = currentSong.substr(0,23) + '...';
						}
					}else{
						currentSong = stream.title;
					}

					// Add block to list
					list.append('<li class="rb_' + item + '"><a href="/radio/' + item + '#" style="background-image: url(../design/logos/' + item + '.png);">' + currentSong + '</a></li>');
				}
			});
}

function setHomeCurrentSong(station) {
	var result = '';
	var song_duration = '';
	jQuery.getJSON(HTTP_SITE_ROOT + "/radio/station/" + station + "/playlist.json", function(songlist) {
		jQuery.each(songlist, function(i,song) {
			if (song.status == 'current' && jQuery('#sr_'+station).html().indexOf(song.artist.substr(0,5)) < 0) {
				result = song.artist + ' - ' + song.title;
				var debugLine = station + ": " + result;
				if(result.length > 25) {
					result = result.substr(0,23) + '...';
				}
				debugLine += "\n" + result;

				jQuery('#sr_'+station).html(result);

				debugLine += "\n\n" + jQuery('#sr_'+station).html();

			}
		});
	});
}

function updateSongTimer() {
	var hours, minutes, seconds, durationU;
	jQuery.each(stations_timer, function(i,song) {
		var d = new Date();
		durationU = (song.song_duration/1000) - (d.getTime()/1000 - song.song_begin)+10;
		if(durationU > 0) {
			hours = Math.floor(durationU/3600);
			minutes = Math.floor(durationU/60) - (hours*60);
			seconds = Math.floor(durationU - (hours*3600) - (minutes*60));
			song_duration = minutes + ':' + ((seconds < 10) ? '0' + seconds : seconds);
		} else {
			song_duration = '0:00';
		}
		jQuery('#slider_tracklng_'+song.station).html(song_duration);
		jQuery('#slider_duplicate_tracklng_'+song.station).html(song_duration);
	});
}

function updateSongOffers() {
	var song_title, offer_star, play_button, result;
	var song_offer_id = 0;

	jQuery.getJSON(HTTP_SITE_ROOT + "/wp-content/uploads/mp3/offers.json", function(songlist) {
		jQuery.each(songlist, function(i,song) {
			song_offer_id++;
			song_title = '<div class="song_holder"><span  class="c00">'+song.artist+'</span><span  class="c999"> - '+song.title+'</span></div>';
			offer_star = '<div class="rating_star_holder"><img src="images/greystar.png" alt="" width="9" height="9" class="custom_mtop_star" data-song-filename="'+ song.filename +'" data-song-artist="'+song.artist+'" data-song-title="'+song.title+'" id="song_offer_id_'+song_offer_id+'"/></div>';
			play_button = '<a href="javascript:;" class="play" data-song-filename="'+ song.filename +'"><img src="images/play_button.png" class="right5" alt="play" width="22" height="22" /></a>';
			result = '<div class="grid_4 alpha omega mtop_element"><div class="grid_3  alpha" >' + offer_star + song_title + '</div><div class="grid_1 omega left30 align_right">' + play_button + '</div></div>';
			jQuery('#offers').append(result);
		});
		jQuery('.custom_mtop_star').hover(function(){
			jQuery(this).attr('src', 'images/star.png');
		},function(){
			jQuery(this).attr('src', 'images/greystar.png');
		});
		jQuery('.custom_mtop_star').click(function(){
			jQuery(this).attr('src', 'images/star.png');
			jQuery(this).unbind();
			jQuery.ajax({
			   type: "POST",
			   url: HTTP_SITE_ROOT + "/songvote.php",
			   data: "song_artist=" + jQuery(this).attr('data-song-artist') + "&song_title=" + jQuery(this).attr('data-song-title') + "&song_filename="+jQuery(this).attr('data-song-filename'),
			   success: function(msg){

			   }
			 });
		});

		var mtop_flash = window.document.getElementById( "castSoundComponent" );
		//var mtop_flash = window.document.getElementById( "soundComponent" );
		jQuery('.play').click(function(){
			mtop_flash.PauseSong();
			if(jQuery(this).find('img').attr('src') == 'images/play_button.png') {
				var path = 'wp-content/uploads/mp3/'+jQuery(this).attr('data-song-filename');
				jQuery('.play').find('img').attr('src', 'images/play_button.png');
				jQuery('.song_holder').removeClass('bold');
				jQuery(this).parent().parent().find('.song_holder').addClass('bold');
				jQuery(this).find('img').attr('src', 'images/stop_button.png');
				mtop_flash.Load( path );
			} else {
				jQuery(this).find('img').attr('src', 'images/play_button.png');
				jQuery(this).parent().parent().find('.song_holder').removeClass('bold');
				mtop_flash.PauseSong();
			}
			return false;
		});
	});
}

function getMovie(movieName) {
	var M$ =  navigator.appName.indexOf("Microsoft")!=-1
	return (M$ ? window : document)[movieName]
}

function updateSongTitles() {
	var url = HTTP_SITE_ROOT + "/design/config.json";
	jQuery.getJSON(url, function(data){
        jQuery.each(data, function(item,stream){
			if (item != "player") {
				if (stream.playlist == "1") setCurrentSong(item);
			}
		});
	});
}

function updateTitles() {
	setInterval('updateSongTitles()', 5000);
}

