//**********
//config

function rand ( n )
{
  return ( Math.floor ( Math.random ( ) * n + 1 ) );
}

var secondsBuffer = 1 + rand(7);
var retrySecondsDelay = 10;

//end config
//**********
$(document).ready(function(){
  // dcg: Grab the url parameters
          var urlParams = {};
          (function () {
              var e,
                  a = /\+/g,  // Regex for replacing addition symbol with a space
                  r = /([^&=]+)=?([^&]*)/g,
                  d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
                  q = window.location.search.substring(1);

              while (e = r.exec(q))
                 urlParams[d(e[1])] = d(e[2]);
          })();
          
  var radio = "http://sj128.hnux.com:80" //dcg: hardcoded only for hardcoded radios
            
	// Local copy of jQuery selectors, for performance.
	var jpPlayTime = $("#play_time");
	var jpTotalTime = $("#total_time");
	var timer = null;

	$("#jplayer").jPlayer({
		ready: function () {
			$(this).jPlayer("setMedia", { mp3: radio + "/;" }).jPlayer("play");  
		},
		//errorAlerts: true,
		solution: 'html, flash',
		supplied: 'mp3',
		volume: 0.75,
		swfPath: 'http://cdn.hnux.com/flashplayer/js/',
		cssSelectorAncestor: '#player'
	});
	
  	var updatePlayerInfo = function () {
		var tmpRadioStrip = ( radio.toLowerCase().indexOf('http://') == 0) ? radio.substring(7) : radio;
	    $.get('getmusicinfo.php?nocache=' + new Date().getTime() + "&" + 'radio=' + tmpRadioStrip, function(data) {
			var info = $.parseJSON( data );
			
			if( info.secondsLeft == null || info.secondsLeft == undefined || data.toLowerCase().indexOf( "connection timed out" ) != -1 ) {
			
				timer = null;
				setTimeout( function() {
					updatePlayerInfo();
				}, retrySecondsDelay*1000 );
			
			} else {
			
				$('#album_cover').html(info.cover.replace("\\",""));
				$('#current_song').html(info.current.replace("\\",""));
				$('#song_title').html(info.songs.replace("\\",""));
				$('#buynow').html(info.buyLink.replace("\\",""));
				$('#download').html(info.downloadLink.replace("\\",""));
				
				//update seconds left.
				timer = new Date();
				timer.setTime(timer.getTime() + parseInt(info.secondsLeft)*1000 + secondsBuffer*1000);
							
			}
			
			
		});
	};
	
	$("#jplayer").bind($.jPlayer.event.timeupdate, function() {
		if( timer != null ) {
			var timer2 = new Date();
			if (timer < timer2 ) {
				timer = null;
				updatePlayerInfo();
			}

		}
	
	/*
		var timer2 = new Date();
			if (timer2 - timer> 5000) {
				timer = timer2;
				updatePlayerInfo();
			}*/
	});
  
  $("#jplayer").bind($.jPlayer.event.pause, function() {
    $(this).jPlayer("clearMedia");
    $(this).jPlayer("setMedia", { mp3: radio + "/;" });
  });
  
	updatePlayerInfo();
  
	// $("#jplayer_inspector").jPlayerInspector({jPlayer:$("#jplayer")}); //dcg: debugger if needed
});
