
var ag = navigator.userAgent;
var chrome = ag.indexOf("Chrome") > -1;
var iPhone = ag.indexOf("iPhone OS") > -1;
var iPad   = ag.indexOf("iPad") > -1;
var mac    = (ag.indexOf("Macintosh;") > -1) || (ag.indexOf("OS X") > -1);
var iPhoneFix = (iPhone || iPad) && ag.indexOf("OS 3_")>0;
var loaded = false;
var PNGfix = false;
var updateTimer=null, liveTimer=null;
var PNGfix = (/MSIE (5|6)/.test(ag));
if(ag.indexOf('Opera')>0) PNGfix=false;

window.onerror = handleError;
//window.onerror = null;
function handleError(sMsg,sUrl,sLine) {
  var e=" javascript error: "+sMsg+' line '+sLine+' of '+sUrl;
  //if(loaded) alert(e); else document.writeln('<div style="background-color:#BBB;color:#E00;"><b>'+e+'</div>');
  if(debug && e.indexOf('twitter')<0) {
  	if(loaded) document.getElementById('debug').innerHTML = '<font color="#FFFF44">'+e+'</font>';
  	else document.writeln('<div style="background-color:#BBB;color:#E00;"><b>'+e+'</div>');  	
  }
	return true; //cancel error display
}

var useJplayer = 0;
//if(debug) admin_forcejp=1;
var jpPlayTime;
var scanmode = 0, scant = 0;
var scanInterval = 30;
var clickID = '', clickindex = 1;
var wmp;
var maxCount = 42; //for png fix
var preload1 = new Image(); preload1.src = 'img/cell_54_in.png';

onload = function() {
	loaded = true;
  if(introtext!="per") liveTimer = setInterval("checkLive()", 400);

	$("a.tt").tooltip({
		bodyHandler: function() {
			var txt =$(this).attr("rev").split("|");
			if(!txt[1]) txt[1] ='';
			return "<b>"+txt[0]+"</b><br/>"+txt[1];
    },
    left:-98, top:-110,
    showURL : false,
    fixPNG: true
  });

  if(PNGfix) {
  	fixpng('fb_w');
  	fixpng('twit_w');
  	fixpng('tum_w');
  	for(var i=0; i<document.images.length; i++) fixpng(document.images[i]);
  	// doesnt work on icon graphics for some reason
  	for(i=1; i<maxCount; i++) fixpng('ic'+i);
  }
}

function clicki(index) {
	var so;
	var id=stations[index];
	if(clickID) {
		if(clickID=='off')
			document.getElementById('off').src='img/4buttons_off.gif';
		else {
			var c = document.getElementById('cell'+clickID)
			if(c) c.src='img/cell_54v2.png';
			if(c) fixpng('cell'+clickID);
  	}
	}
	clickindex = index;
	clickID = id;
	var c = document.getElementById('cell'+id);
	if(c) c.src='img/cell_54_in.png';
	if(c) fixpng(c);
	if(wmp) if(wmp.versionInfo) wmp.controls.stop();
	wmp = null;
	clearInterval(updateTimer); updateTimer=null;
	document.getElementById('lowerbox').innerHTML='';
	var siteDiv = document.getElementById('site');
	if(id=='off') {
		siteDiv.innerHTML='&nbsp;';
		document.getElementById('player').innerHTML='';
		useJplayer = 0;
		if(scanmode) click4('scan');
		clickindex = 1;
		return false;
	}
	siteDiv.innerHTML=id;
	var a = document.getElementById('a_'+id);
  siteDiv.innerHTML='Station: <a href="'+a.href+'" target="_blank">'+a.title+'</a>&nbsp;'+a.rev;

	if(iPhoneFix) {
		var pls = a.name;
		if(pls=='errorfm.com') {
			if(a.className=='8005') a.className = '8015';
			if(a.className=='8002') a.className = '8012';
		}
		if(pls.indexOf('/')<0) pls = "http://"+pls+":"+a.className+"/listen.pls";
		if(a.target == '365') pls= "http://www.live365.com/cgi-bin/play.pls?stationid="+a.name;
		//if(a.title == "Radio Dentata") pls = "http://www.radiodentata.com/RDplayer/mini/radiodentata.pls";
		if(a.title == "Candy103.com")  pls = "http://jmprod.selfip.net:8004/stream.m3u";
		top.location = pls;
		return false;
	}
	if(a.target == 'MP') { //load media player :P
    so=null; useJplayer=0;
    var osxMsg = mac ? ' <a href="http://www.microsoft.com/windows/windowsmedia/player/mac/" target="_blank">Download Media Player for Mac</a>':'';
  	document.getElementById('player').innerHTML='<object id="wmpo" name="wmpo" width="290" height="63" CLASSID="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6">'
    +'<param name="URL" value="'+a.name+'">'
    +'<param name="autoStart" value="true">'
    +'<param name="uiMode" value="mini">'
    +'<param name="AutoSize" value="false">'
    +'<embed type="application/x-ms-wmp" Xtype="application/x-mplayer2" src="'+a.name+'" id="wmpo" width="290" height="63"></embed>'
    +'<span id="wmpmsg" class="sm">This is a Windows Media stream. It might not work on all computers.'+osxMsg+'</span>'
    +'</object>'
    +'<div class="jp-fake"><div id="nowPlaying"></div></div>';
		$("#jplayer_showhist").click(function () {
			var d = document.getElementById("jplayer_showhist");
		  d.style.backgroundPosition = (document.getElementById("history").style.display=='block')? "0 0":"-12px 0";
		  $("#history").slideToggle("fast");
		});
		wmp = document.getElementById('wmpo');
    if(wmp) if(wmp.addEventListener) wmp.addEventListener('onDSPlayStateChangeEvt',wmp_playstate,false); //non-IE. This doesnt work
    if(wmp) if(wmp.attachEvent) wmp.attachEvent('PlayStateChange',wmp_playstate); //IE
    if(wmp) if(document.getElementById('wmpmsg') && !mac) document.getElementById('wmpmsg').innerHTML='';
    if(wmp.versionInfo) {
      //Wmp9 fix: playstate 10:ready 6:buffer 3:playing 2:paused 1:stopped
    	var t = setTimeout(function(){ if(wmp.playState==10) wmp.controls.play();}, 500);
    }
    updateTimer = setInterval("updateNowPlaying()", 18000);
    updateNowPlaying();

	} else if(a.target=='365') {
		document.getElementById('player').innerHTML='<div class="sm" style="margin:4px">Live365: To skip an ad, click again.<br>Ad blocking may need to be disabled.</div>';
		useJplayer = 0;
		var pu = 'http://www.live365.com/cgi-bin/mini.cgi?station_name='+a.name;
		document.getElementById('lowerbox').innerHTML='<iframe class="l365" border=0 marginheight=0 marginwidth=0 src="'+pu+'"></iframe>';

  } else {
		var jpsource = a.name;
		if(jpsource.indexOf('/')<0) jpsource = "http://"+jpsource+":"+a.className+"/;/stream.mp3";
		if(useJplayer==0) {
			if(!admin_forcejp) 
			  var so = new SWFObject("http://www.errorfm.com/flash/shoutcast.swf", "shout", "290", "151", "8", "#FFFFFF");
			if(so && so.installedVer && so.installedVer.major>=8) {
				// use flash
				so.addParam("wmode", "transparent");
				so.addParam("align", "middle");
				so.addParam("FlashVars","xml=http://www.errorfm.com/flash/shout_swfxml.php?host="+a.name+"%26port="+a.className+"%26format="+a.target+"%26id="+id+"%26name="+a.title.replace('&','and'));
				so.write("player");
				so = null;
				//document.title="Backyard Party Radio Network"; //ie8 fix
	
			} else {
				// Flash failed. Load jplayer
				useJplayer = 1;
				$("#player").html('<div id="jquery_jplayer"></div>'
				+'<div class="jp-single-player"><div class="jp-interface">'
				+'<ul class="jp-controls">'
				+'<li><a href="javascript:" id="jplayer_play" class="jp-play" tabindex="1">play</a></li>'
				+'<li><a href="javascript:" id="jplayer_pause" class="jp-pause" tabindex="1">pause</a></li>'
				+'<li><a href="javascript:" id="jplayer_volume_min" class="jp-volume-min" tabindex="1">min volume</a></li>'
				+'<li><a href="javascript:" id="jplayer_volume_max" class="jp-volume-max" tabindex="1">max volume</a></li>'
				+'<li><a href="javascript:" id="jplayer_showhist" class="jp-showhist" tabindex="1">show history</a></li></ul>'
			  +'<div id="nowPlayingshow" class="nowPlayingshow"></div><div id="nowPlaying"></div><div id="jplayer_volume_bar" class="jp-volume-bar"><div id="jplayer_volume_bar_value" class="jp-volume-bar-value"></div></div>'
				+'<div id="jplayer_play_time" class="jp-play-time"></div><div id="history"></div>'
				+'</div></div>');
				$("#jplayer_showhist").click(function () {
					var d = document.getElementById("jplayer_showhist");
				  d.style.backgroundPosition = (document.getElementById("history").style.display=='block')? "0 0":"-12px 0";
				  $("#history").slideToggle("fast");
				});
			  // Load player. Chrome doesn't play streams, add nativeSupport:false to fix this
				$("#jquery_jplayer").jPlayer({
					ready: function () {
						this.element.jPlayer("setFile", jpsource).jPlayer("play");
					},
					volume: 50,
					oggSupport: false,
					nativeSupport: chrome?false:true })
				.jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
					jpPlayTime.text($.jPlayer.convertTime(playedTime));
				})
				.jPlayer("onSoundComplete", function() {
					this.element.jPlayer("play");
				});
				jpPlayTime = $("#jplayer_play_time"); // Local copy of jQuery selectors, for performance.
	  		updateTimer = setInterval("updateNowPlaying()", 18000);
			}
		}
		if(useJplayer) {
			$('#nowPlayingshow').html(a.title);
			$("#jquery_jplayer").jPlayer("stop");
			$("#jquery_jplayer").jPlayer("setFile", jpsource).jPlayer("play");
			$("#jquery_jplayer").jPlayer("play");
			updateNowPlaying();
		}
  }
	return false;
}

function wmp_playstate(NewState) {
	//playstate 10:ready  9:loading 3:playing 2:paused 1:stopped
  if(NewState == 3) {
  	clearInterval(updateTimer);
  	updateTimer = setInterval("updateNowPlaying()", 18000);
  }
  if(NewState <= 2) clearInterval(updateTimer);
  //var p = document.getElementById('debug');
  //if(!p || !debug) return;
  //if(NewState == 6) p.innerHTML = 'Buf '+NewState;
  //else if(NewState == 3) p.innerHTML = 'Playing '+NewState;
  //else if(NewState) p.innerHTML = 'Stopped? '+NewState;
}

var snr=1;
function updateNowPlaying() {
 	var a = document.getElementById('a_'+clickID);
	//snr= is to avoid caching
	var u = 'http://www.errorfm.com/shout_swf.php?id='+clickID+'&url='+a.name+'&port='+a.className+'&format='+a.target+'&s='+snr++;
	if((useJplayer || wmp) && a.name) $.get(u, function(res){
  	if(res && res.responseText) {
    	var a = res.responseText.split('&');
    	var song = a[1].split('=')[1];
    	var pref=(wmp && song>' ') ? 'Now playing: ' : '';
      $("#nowPlaying").html(pref+song);
      h = a[2].split('=')[1];
      if(h) h = '<b>Past Playlist</b><br>'+h;
      $("#history").html(h);
     }
	}, 'text');
}

function popup(url,w,h,name) {
	if(!name) name="_blank";
	window.open(url, name, "width="+w+",height="+h+",scrollbars=no,resizable=yes");
}

function click4(sel) {
	if(sel=='prev') {
		clickindex--;
		if(clickindex<2) clickindex=stationscount;
		clicki(clickindex);
	}
	if(sel=='next') {
		clickindex++;
		if(clickindex>stationscount) clickindex=2;
		clicki(clickindex);
		if(scanmode) {
			clearTimeout(scant);
			scant = setTimeout("click4('next')",scanInterval*1000);
		}
	}
	if(sel=='scan') {
		sb = document.getElementById('scan');
		if(scanmode) {
			clearTimeout(scant);
			scanmode = 0;
			sb.src="img/4buttons_scan.gif";
		} else {
			click4('next');
			scant = setTimeout("click4('next')",scanInterval*1000);
			scanmode = 1;
			sb.src="img/4buttons_scan_in.gif";
		}
  }
}

function checkLive() {
	clearInterval(liveTimer);
	if(admin_hidelive) return;
  liveTimer = setInterval("checkLive()", 30000);
	$.get('http://www.errorfm.com/shoutcastinfo-8010bprn.php',
	function(data,txt) {
		var t = data.responseText;
		var dj = t.substr(t.indexOf('<a>')+3);
		dj = dj.substr(0,dj.indexOf('</a>'));
		var img = (clickindex==1)?'cell_54_in.png' : 'cell_54v2.png';
		var liveHtml='<div id="live1"><fieldset><legend class="c" style="margin-left:9px">&nbsp;Special Live Event: ErrorFM Front Row LIVE&nbsp;</legend>'
		+'<table id="live2" cellspacing="0" cellpadding="0" style="margin-top:-11px;margin-bottom:11px"><tr><td>'
		+'<table id="icons" style="width:65px;height:61px;margin:0 6px" cellspacing="0" cellpadding="0"><tr><td><img src="img/'+img+'" width="60" height="60" class="cell" id="cellefmchX"><a href="javascript:" onclick="clicki(\'1\')" class="over"><img id="ic1" src="logo/efmchX.png" class="overimg" style="margin-top:2px;margin-bottom:-25px" alt="ErrorFM Front Row LIVE" title="ErrorFM Front Row LIVE"></a></td></table></td>'
		+'<td id="liveright">'+dj+'</td></tr></table></fieldset></div>';
		if(dj) $('#introtext').html(liveHtml);
		else $('#introtext').html(introtext);
	});

}
function fixpng(img) { // manual fixing of an img tag. Give object or ID
	if(!PNGfix) return;
	if(typeof img=="string") img = document.getElementById(img);
	if(!img) return;
  var imgName = img.src.toUpperCase();
  if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
    var imgID = (img.id) ? "id='" + img.id + "' " : "";
    var imgClass = (img.className) ? "class='" + img.className + "' " : "";
    var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
    var imgStyle = "display:inline-block;" + img.style.cssText;
    if (img.align == "left") imgStyle = "float:left;" + imgStyle;
    if (img.align == "right") imgStyle = "float:right;" + imgStyle;
    if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
    var strNewHTML = "<span " + imgID + imgClass + imgTitle
    + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
    + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
    + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
    img.outerHTML = strNewHTML;
  }
}

