var passpage = document.URL 
/*
	document.write(passpage+'<br>');
if (top.location == self.location) { 
	var contentURL = passpage.substring(passpage.indexOf('?')+location.hostname.length+8, passpage.length)
	document.write(contentURL);
	exit;
	if (contentURL == '/') {
		contentURL = '/index.php';
	} 
	top.location.replace('/page.htm?' + contentURL); 
*/
if (top.location == self.location) { 
	top.location.replace('/page.htm?' + passpage); 
} 

var rateactive		= 0;
var tryreconnect	= 0;
var trycount		= 0;
$(document).ready(function() {
		 if (parent.tfmplayer.pVU)
		 {
		 	setVU(parent.tfmplayer.pVU);
		 } else {
//			 play('tc','high','usa');
		 }
		
		 $("#ct_external_players .wtc a.hi").click(function(event){
			   event.preventDefault();
			   play('tc','high');
 		 });

		 $("#ct_external_players .wtc a.low").click(function(event){
			   event.preventDefault();
			   play('tc','low');
 		 });

		 $("#ct_external_players .wdj a.hi").click(function(event){
			   event.preventDefault();
			   play('dj','high');
 		 });

		 $("#ct_external_players .wdj a.low").click(function(event){
			   event.preventDefault();
			   play('dj','low');
 		 });

		 $("#player_tc #player_buttons a.start").click(function(event){
			   event.preventDefault();
			   play('tc','high');
 		 });

		 $("#player_dj #player_buttons a.start").click(function(event){
			   event.preventDefault();
			   play('dj','high');
 		 });

		 $("#player_tc #player_buttons a.buy").click(function(event){
			   event.preventDefault();
			   play('tc','high');
 		 });


		 $("#player_tc #player_buttons a.stop").click(function(event){
			   event.preventDefault();
			   stopplayer();
 		 });

		 $("#player_dj #player_buttons a.stop").click(function(event){
			   event.preventDefault();
			   stopplayer();
 		 });

		 $("#ct_external_players a").click(function(event){
			   stopplayer();
 		 }); 		 

		if (parent.tfmplayer.pChannel == "tc")
		{
			$("#player_tc #player_buttons #volslider").flash({src: '/tfm_v600/flash/volslider.swf',width: 80,height: 27, wmode: 'transparent',flashvars: { vol: parent.tfmplayer.pVolume} });
		} else {
			$("#player_dj #player_buttons #volslider").flash({src: '/tfm_v600/flash/volslider.swf',width: 80,height: 27, wmode: 'transparent',flashvars: { vol: parent.tfmplayer.pVolume} });
		}
		/***** Rate button Trance Channel ******/
			$("#player_tc #player_rating .btn_rate").click(function(e){
				if (rateactive == 0)
				{
					rateactive = 1;
					$("#rate_tc").css({"position": "absolute","top": 35,"left":-180});
					$("#rate_tc").show();
					buildRating("#rate_tc #rate_slider",$('#player_tc #player_songplaying').html());
				}
			});
				
			$("#player_tc #player_rating #rate_close").click(function(){
				$("#rate_tc").hide();
				rateactive = 0;
			});
		
			/***** Rate button DJ Channel ******/
			$("#player_dj #player_rating .btn_rate").click(function(e){
				if (rateactive == 0)
				{
					rateactive = 1;
					$("#rate_dj").css({"position": "absolute","top": 35,"left":-180});
					$("#rate_dj").show();
					buildRating("#rate_dj #rate_slider",$('#player_dj #player_songplaying').html());
				}
			});
				
			$("#player_dj #player_rating #rate_close").click(function(){
				$("#rate_dj").hide();
				rateactive = 0;
			});

		updateCurrentsong();
		$.timer(1000*30, function (timer) { updateCurrentsong(); });

		updateListeners();
		$.timer(1000*60, function (timer) { updateListeners(); });

});

$(function () {
	var tabContainers = $('div.tabs > div');
	$('div.tabs ul.tabSelect a').click(function () {
		tabContainers.hide();
		tabContainers.filter(this.hash).fadeIn('normal');
		$('div.tabs ul.tabSelect a').removeClass('selected');
		$(this).addClass('selected');
		return false;
	});
});

function buildRating (container,trackid) {

   $(container).text("");
   $(container).css({'font-size':'15px','padding-left':'10px','padding-top':'3px'});
   for ( var i = 1; i <= 10; i++ )
     $(container).append("<a href='#'>"+i+"</a>&nbsp;&nbsp;");
     $(container).append("<img src=\"/tfm_v600/images/ratingbar.gif\">");
   
   $(container+" a").click(function(e){
     // stop normal link click
     e.preventDefault();
     
     $.post("/tfm_v600/scripts/ratetrack.php", {track:trackid,rating:$(this).html(),user:$('#sysinfo #user').text()}, function(xml) {
       // format and output result
       $(container).css({'font-size':'12px','padding-left':'0px','padding-top':'13px'}).html($("response", xml).text());
     });
   });
}

function showPlaylist(){

	buildPlaylist();
	$.timer(1000*60, function (timer) {
		buildPlaylist();
	});

}

function updateListeners(){
	var rnd 		= Math.floor( Math.random()*100000000 ); 
	$.get("/tfm_v600/xml/c.xml?"+rnd,{},function(xml)
	{
		cListeners = $('connections:eq(0)',xml).find("totalconnects").text();
		$("#footer01 span").text(cListeners);
	});
}

function updateCurrentsong(){
	var rnd 		= Math.floor( Math.random()*100000000 ); 
	$.get("/tfm_v600/xml/currentsong.xml?"+rnd,{},function(xml)
	{
		cArtist = $('tc:eq(0)',xml).find("artist").text();
		cTitle = $('tc:eq(0)',xml).find("title").text();
		cOrderlink = $('tc:eq(0)',xml).find("orderlink").text();
		cTrackid = $('tc:eq(0)',xml).find("trackid").text();
		cScore = $('tc:eq(0)',xml).find("score").text();

		if (cOrderlink != '') {
			$("#player_tc #player_buy").show();
		} else {
			$("#player_tc #player_buy").hide();
		}

		$("#player_tc #player_songplaying").html('<a href=\"/vb_search4poll2.php?tid='+ cTrackid +'\">'+truncate(cArtist,50)+'<br />'+truncate(cTitle,50)+'</a>');
		$("#player_tc #player_rating > span.unum").text(cScore);
		$("#player_tc #player_buy").html('<a href=\"'+ cOrderlink +'\" target=\"_blanc2buy\"><img src=\"/tfm_v610/images/btn_buy.gif\" border=\"0\" alt=\"buy this track\"></a>');
	
		cArtist = $('dj:eq(0)',xml).find("artist").text();
		cTitle = $('dj:eq(0)',xml).find("title").text();
		cTrackid = $('dj:eq(0)',xml).find("trackid").text();
		cScore = $('dj:eq(0)',xml).find("score").text();
		$("#player_dj #player_songplaying").html('<a href=\"/vb_search4poll2.php?tid='+ cTrackid +'\">'+truncate(cArtist,50)+'<br />'+truncate(cTitle,50)+'</a>');
		$("#player_dj #player_rating > span.unum").text(cScore);
	});
}
 
function buildPlaylist(){
	var rnd 		= Math.floor( Math.random()*100000000 ); 
	var	altClass 	= 'alt1';
	$.get("/tfm_v600/xml/playlist.xml?"+rnd,{},function(xml){

		plTable = '';
	 	plTable += '<table width="100%" border="0" cellspacing="2">';
	  	plTable += '<tr><td class="thead" width="50%" align="left" bgcolor="#dddddd">Last tracks on the trance channel</td><td class="thead" width="50%" align="left" bgcolor="#dddddd">Last tracks on the DJ channel</td></tr></table>';
		plTable += '<table cellspacing="0" width="100%"><tr><td width="50%"><table cellpadding="2" cellspacing="0" border="0" width="100%">';
		$('tc',xml).each(function(i) {
			if (altClass == 'alt1playlist')
			{ 
				altClass = 'alt2playlist';
			} else {
				altClass = 'alt1playlist';
			}
			plArtist = $(this).find("artist").text();
			plTitle = $(this).find("title").text();
			plTime = $(this).find("time").text();
			plTrackid = $(this).find("trackid").text();
			plTable += '<tr><td class="'+altClass+'" align="left" title="Click for track comments">';
			plTable += '<div class="smallerfont"><a href="/vb_search4poll2.php?tid='+ plTrackid +'"><strong>'+ truncate(plArtist,40) + '</strong></a></div>';
			plTable += '<div class="smallerfont">'+truncate(plTitle) +'</div></td>';
			plTable += '<td class="'+altClass+'" align="right" title="Click for track comments">';
			plTable += '<div class="smallerfont">'+ plTime +'</div>';
			plTable += '</td></tr>';
		});
		teller = 0;
		plTable += '</table></td><td width="50%"><table cellpadding="2" cellspacing="0" border="0" width="100%">';
		$('dj',xml).each(function(i) {
			if (altClass == 'alt1playlist')
			{ 
				altClass = 'alt2playlist';
			} else {
				altClass = 'alt1playlist';
			}
			plArtist = $(this).find("artist").text();
			plTitle = $(this).find("title").text();
			plTime = $(this).find("time").text();
			plTrackid = $(this).find("trackid").text();
			plTable += '<tr><td class="'+altClass+'" align="left" title="Click for track comments">';
			plTable += '<div class="smallerfont"><a href="/vb_search4poll2.php?tid='+ plTrackid +'"><strong>'+ truncate(plArtist,40) + '</strong></a></div>';
			plTable += '<div class="smallerfont">'+truncate(plTitle) +'</div></td>';
			plTable += '<td class="'+altClass+'" align="right" title="Click for track comments">';
			plTable += '<div class="smallerfont">'+ plTime +'</div>';
			plTable += '</td></tr>';
		});
		plTable += '</table></td></tr></tbody></table><div id="spacer5"></div>';
		$("#ct_playlist").html(plTable);
	});
}

jQuery.timer = function (interval, callback)
{

	var interval = interval || 100;
	if (!callback)
		return false;
	_timer = function (interval, callback) {
		this.stop = function () {
			clearInterval(self.id);
		};
		this.internalCallback = function () {
			callback(self);
		};
			this.reset = function (val) {
			if (self.id)
				clearInterval(self.id);
			var val = val || 100;
			this.id = setInterval(this.internalCallback, val);
		};
		this.interval = interval;
		this.id = setInterval(this.internalCallback, this.interval);
		var self = this;
	};
	return new _timer(interval, callback);
};

function truncate (txt, length, suffix){
	length = length || 44; 
	suffix = suffix === undefined ? "..." : suffix; 
	return txt.length > length ? txt.slice(0, length - suffix.length) + suffix : txt; 
}; 

function setVolume(volval) {
	parent.tfmplayer.pVolume  = volval;
	parent.tfmplayer.setVolume();
}

function play(channel,quality,country) {
	channel = channel || parent.tfmplayer.pChannel;
	quality = quality || parent.tfmplayer.pQuality;
	country = country || parent.tfmplayer.pCountry;
	parent.tfmplayer.pChannel = channel;
	parent.tfmplayer.pQuality = quality;
	parent.tfmplayer.pCountry = country;
	parent.tfmplayer.startPlayer();
	if (channel == 'tc') {
		$("#player_dj #player_buttons #volslider").text("");
		$("#player_tc #player_buttons #volslider").text("");
		$("#player_tc #player_buttons #volslider").flash({src: '/tfm_v600/flash/volslider.swf',width: 80,height: 27, wmode: 'transparent',flashvars: { vol: parent.tfmplayer.pVolume} });
	}
	if (channel == 'dj') {
		$("#player_tc #player_buttons #volslider").text("");
		$("#player_dj #player_buttons #volslider").text("");
		$("#player_dj #player_buttons #volslider").flash({src: '/tfm_v600/flash/volslider.swf',width: 80,height: 27, wmode: 'transparent',flashvars: { vol: parent.tfmplayer.pVolume} });
	}
}

function reconnectPlayer() {
	if (trycount == 10 )
	{	
		trycount= 0;
		if (parent.tfmplayer.pCountry == 'nl')
		{
			parent.tfmplayer.pCountry = 'usa';
		} else {
			parent.tfmplayer.pCountry = 'nl';
		}
	}
	trycount++;
	parent.tfmplayer.startPlayerForced();
}

function stopplayer() {
	tryreconnect = 1;
	parent.tfmplayer.stopPlayer();
	$("#player_tc #player_buttons #fstatus").hide();
	$("#player_dj #player_buttons #fstatus").hide();
}
 
function setVU(value) {
	parent.tfmplayer.pVU = value;
	if (parent.tfmplayer.pChannel == "tc")
	{
		$("#player_dj #player_buttons #fstatus").hide();
		switch(value)
		{
		       case '1': /* playing */
				$("#player_tc #player_buttons #info").text("");
				$("#player_tc #player_buttons #fstatus").text("");
				$("#player_tc #player_buttons #fstatus").flash({src: '/tfm_v600/flash/vumeter.swf',width: 55,height: 15, wmode: 'transparent'});
		         break;
		       case '2': /* waiting on buffer fill */
				$("#player_tc #player_buttons #fstatus").text("");
				$("#player_tc #player_buttons #fstatus").flash({src: '/tfm_v600/flash/connecting.swf',width: 15,height: 15, wmode: 'transparent'});
				$("#player_tc #player_buttons #info").text("Buffering...");
		         break;
		       case '4': /* lost connection */
				$("#player_tc #player_buttons #fstatus").text("");
				$("#player_tc #player_buttons #fstatus").flash({src: '/tfm_v600/flash/connecting.swf',width: 15,height: 15, wmode: 'transparent'});
				$("#player_tc #player_buttons #info").text("Connecting...");
		         break;
		       default: /* stopped */
				$("#player_tc #player_buttons #info").text("");
				$("#player_tc #player_buttons #fstatus").text("");
		         break;
		}
		$("#player_tc #player_buttons #fstatus").show();

	} else {
		$("#player_tc #player_buttons #fstatus").hide();
		switch(value)
		{
		       case '1':
				$("#player_dj #player_buttons #info").text("");
				$("#player_dj #player_buttons #fstatus").text("");
				$("#player_dj #player_buttons #fstatus").flash({src: '/tfm_v600/flash/vumeter.swf',width: 55,height: 15, wmode: 'transparent'});
		         break;
		       case '2':
				$("#player_dj #player_buttons #fstatus").text("");
				$("#player_dj #player_buttons #fstatus").flash({src: '/tfm_v600/flash/connecting.swf',width: 15,height: 15, wmode: 'transparent'});
				$("#player_dj #player_buttons #info").text("Buffering...");
		         break;
		       case '4': /* lost connection */
				$("#player_dj #player_buttons #fstatus").text("");
				$("#player_dj #player_buttons #fstatus").flash({src: '/tfm_v600/flash/connecting.swf',width: 15,height: 15, wmode: 'transparent'});
				$("#player_dj #player_buttons #info").text("Connecting...");
		         break;
		       default:
				$("#player_dj #player_buttons #info").text("");
				$("#player_dj #player_buttons #fstatus").text("");
		         break;
		}
		$("#player_dj #player_buttons #fstatus").show();
	}
}

var countBlocks = 0;

function openVideochatWindow(roomId, uid, langId)
{
    if(!roomId) roomId = '';
    if(!uid) uid = 'Guest';
	if(!langId) langId = '';
    var name = 'videochat_' + uid;
    var url = 'flashcoms/videochat/server/php/videochat.php?roomId=' + roomId + '&uid=' + uid + '&langId=' + langId;
    opencWindow(url, name, 765, 560, true);
}

function makeStyle(left, top, width, height, isResizeAble)
{
    var styleStr = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no';
    styleStr += ',resizable=' + (isResizeAble ? 'yes' : 'no');
    styleStr += ',width=' + width + ',height=' + height;
    styleStr += ',left=' + left + ',top=' + top;
    styleStr += ',screenX=' + left + ',screenY=' + top;
    return styleStr;
}

function opencWindow(url, name, width, height, isResizeAble)
{
    url = 'http://www.trance.fm/' + url;
    name = name.replace(/[^\w\d]/g, "_"); // added flag g
    name = name.replace(/undefined/, '_');
    name = name.replace(/\./, '_');
    url = encodeURI(url);// added to fix bug in IE 7 with usernames which has spaces
    var left = Math.round((screen.width - width) / 2);
    var top = Math.round((screen.height - height) / 2);
    var styleStr = makeStyle(left, top, width, height, isResizeAble);
    var res = window.open(url, name, styleStr);
    return res;
}
