var twit;
var chrome = navigator.userAgent.indexOf("Chrome") > -1;
var playing = 0;
var curtime=0, curtimec=0, buffering=0;
var playvolume = -1, playtime = 0;
var playhead = 0, playdur = 0;
var artmode = false;
var song = [0, "","","",""];
var artsave = [0, "","","",""];
var arttimer, arttime = 6000, artzoomtimer;
var loaded = false;
var seq = Math.floor(Math.random()*901000);
//window.onerror = handleError;
//window.onerror = null;
function handleError(sMsg,sUrl,sLine) {
  var e=" javascript error: "+sMsg+' in '+sUrl+' line '+sLine;
  if(loaded) alert(e); else document.writeln('<div style="background-color:#BBB;color:#E00;"><b>'+e+'</div>');
  window.status=e;
	return true;
}
// preload images
var img1=new Image; img1.src='images/listen_greenact.png';

window.onload = loadme;
window.onunload = unloadme;
document.onkeydown = handleKey;
// break out of frameset
if (self != top) top.location = self.document.location;

function loadme() {
	loaded = true;
	var r = document.getElementById('refresher');
  if(r) r.src = "refresher.php?"+query_string;
	clearTimeout(abxtimer);
	abxtimer = setTimeout('abxnext()', abxdelay);
	abxnext();
  if(stream) clickplay(stream); //load player.
  if(activatePods) tabswitch(2);
  fixpng('hea-live'); //ie 5,6
  fixpng('bhelp');
  fixpng('bchat');

	arttimer = setTimeout('artswitch()', arttime);
  //db('debug');
}
function unloadme() {
	clearTimeout(arttimer);
	window.onerror = null;
}

function artswitch() {
  var i, e, imgtag;
	var img = [0,0,0,0,0];
	clearTimeout(arttimer);
	if(!artmode) {
		for(var i=1; i<=4; i++) {
			if(song[i].length < 5) continue;
			img[i] = new Image();
			img[i].name = i;
			img[i].onerror = function() {
				i = this.name;
				//if(i==1) alert('error '+img[i].src);
			}
			img[i].onload = function() {
			  i = this.name;
				var e = document.getElementById('icon'+i);
				if(!e) return;
				//if(i==1) alert('load '+img[i].src);
				artsave[i] = e.innerHTML;
				var amazon = 'http://www.amazon.com/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.com%2Fs%3Fie%3DUTF8%26x%3D0%26ref_%3Dnb_sb_noss%26y%3D0%26field-keywords%3D'
				+encodeURIComponent(song[i])+'%26url%3Dsearch-alias%253Ddigital-music&tag=er0bf-20&linkCode=ur2&camp=1789&creative=390957';
				e.innerHTML='<div class="artpic"><a target="_blank" href="'+amazon+'" title="'+song[i]+' - Click to buy this mp3"><img src="'+img[i].src+'" width=94 height=92 onmouseover="zoom(this)"></a></div>';
			}
			img[i].src = 'albumart.php?key='+song[i];
		}
	} else {
		for(var i=1; i<=4; i++) {
			e = document.getElementById('icon'+i);
			if(e && artsave[i]) e.innerHTML = artsave[i];
		}
	}
	artmode = !artmode;
	arttimer = setTimeout('artswitch()', arttime);
}

function zoom(e) {
	clearTimeout(artzoomtimer);
	artzoomtimer = setTimeout(function(){
		document.getElementById('artzoom').style.display='none';
	}, 4000);
	var im = document.getElementById('artzoom');
	if(e.src && im) {
		im.src = e.src;
		im.style.display = 'inline';	
	}
}

function handleKey(e) {
	var keynum;
	if(!e) e = window.event; // IE
	if(window.event) keynum = e.keyCode; // IE
	else keynum = e.which;
	switch(keynum) {
	case 107: clickplus(); break;
	case 109: clickminus(); break;
	case 27: clickstop(); break;
	case 37: abxprev(); break;
	case 39: abxnext(); break;
	case 83: //s seeks to end of buffer (removes delay)
	  $("#player1").jPlayer("playHead",99); break;
	//default: alert(keynum); break;
	}
}

function popchat(whatirc,server) { //whatirc from php
	if(!server) server='irc.irctoo.net';
	//popup('chat/?nick='+nick,615,450);
	if(whatirc==1) popup('http://widget.mibbit.com/?settings=d76f6880f3495f764c91fd24928b2b6c&server='+server+'&channel=%23errorfm&noServerMotd=true',745,580,"mib");
	if(whatirc==2) popup('http://chat.mibbit.com/?server='+server+'&channel=%23errorfm&autoConnect=true',745,580,"mib");
	if(whatirc==3) popup('http://www.errorfm.com/chat/old.php',745,580,"cgiirc");
	return false;
}

function popsched(stream) {
	popup('schedule.php?s='+stream,840,610);
	return false;
}

function twitSearch() {
	if(twit) twit.destroy();
	twit=null;
	TWTR.Widget.WIDGET_NUMBER=0;
	twit = new TWTR.Widget({
	  version:2, id:'twtr-widget-o', type:'search', rpp:80, interval:30000, width:'auto', height: 186,
	  search:'@errorfm OR #errorfm OR from:errorfm',
	  theme: {
	    shell: { background: '#e6e6e6', color: '#991a1a' },
	    tweets: { background: '#e6e6e6', color: '#5e5e5e', links: '#0074CA' }
	  },
	  features: {scrollbar:true, loop:false, live:true, hashtags:true, timestamp:true, avatars:true, toptweets:false, behavior:'all'}
	}).render().start();
	var i=document.getElementById('onde1'); if(i) i.src="images/heading-onde1.png";
	i    =document.getElementById('onde2'); if(i) i.src="images/heading-onde2act.png";
}

function db(text) {
	document.getElementById('debug').innerHTML=text;
}

// for banner slideshow. abxdelay, abxindex, abxcount is set by php
var abximg = new Image(), abxtimer;
function abxnext() {
	if(++abxindex >= abxcount) abxindex=0;
	abxset();
	clearTimeout(abxtimer);
	abxtimer = setTimeout('abxnext()', abxdelay);
	abxpreload(abxindex+1);
}
function abxprev() {
	if(--abxindex < 0) abxindex=abxcount-1;
	abxset();
	clearTimeout(abxtimer);
	abxtimer = setTimeout('abxnext()', abxdelay);
	abxpreload(abxindex+1);
}
function abxpreload(i) {
	if(i >= abxcount) i=0;
	abximg.src = document.getElementById('abx'+i).href;
}
function abxset() {
	var src = document.getElementById('abx'+abxindex).href;
	abximg.src = src;
	var d = document.getElementById('abx'+abxindex).name.split('|');
	var type = d[0], w = d[1], h = d[2], href = d[3], label = d[4], cap1 = d[5], cap2 = d[6], style = d[7];
	var cnt = document.getElementById('aboxcontent');
	if(type=='img') {
		a1 = a2 = '';
		if(href) { a1 = '<a href="'+href+'" target="_blank">'; a2='</a>'; }
		d = a1+'<img src="'+src+'"';
		if(w) d += ' width="'+w+'"';
		if(h) d += ' height="'+h+'"';
		d += ' alt="'+label+'"'+' title="'+label+'">'+a2;
		cnt.innerHTML = d;
	}
	var cap = document.getElementById('aboxcap');
	document.getElementById('cap1').innerHTML=cap1;
	document.getElementById('cap2').innerHTML=cap2;
	if(cap1+cap2) cap.style.display='block';
	else cap.style.display='none';
	if(!style) style=1;
	cap.className='capstyle'+style;
}

function loadplayer(src) {
	playvolume = 70;
	playtime = 0;
  // Load player object. Chrome doesn't play streams, add nativeSupport:false to fix this
	$("#player1").jPlayer({
		ready: function () {
			this.element.jPlayer("setFile", src).jPlayer("play");
		},
		timeupdate: function(event) {
			playhead = event.jPlayer.status.currentPercentRelative;
			playdur = event.jPlayer.status.duration * event.jPlayer.status.seekPercent/100;
			//$("#debug").html('.timeupdate '+(seq++)+' buffering:'+buffering+' '+event.jPlayer.status.currentTime.toFixed(2)+' head:'+playhead);
			//console.debug(event.jPlayer.status.seekPercent); //Firebug
			//detect buffering
			if(curtime == event.jPlayer.status.currentTime) curtimec++
			else curtimec = 0;
			if(curtimec > 1) {
				buffering++;
				//$('#current-time').html('(loading)');
			} else {
				//$('#current-time').html($.jPlayer.convertTime(event.jPlayer.status.currentTime));
			}
			if(buffering > 16) {
				buffering = curtimec = 0; //restart player
				//$("#jp1").jPlayer("setMedia", {mp3:stream}).jPlayer("play");
				playing = 0;
				clickplay(stream);
			}
			curtime = event.jPlayer.status.currentTime;
		},
		volume: 70,
		oggSupport: false,
		nativeSupport: chrome?false:true,
		swfPath : "flash" })
	.jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
		if(playtime==0 && playedTime>300) {
		  playtime = 1;
		  document.getElementById('player_play').className = 'player_minus';
		}
	})
	.jPlayer("onSoundComplete", function() {
		this.element.jPlayer("play");
	});
}

function clickstop() {
	b = document.getElementById('playbtn8005');
	if(b) b.src = 'images/listen_green.png';
	b = document.getElementById('playbtn8002')
	if(b) b.src = 'images/listen_green.png';
	b = document.getElementById('playbtn8008')
	if(b) b.src = 'images/listen_green.png';
	b = document.getElementById('playbtn8010');
	if(b) b.src = 'images/listen_green.png';
	$("#player1").jPlayer('stop');
	playing = 0; playtime = 0;
}

function clickplay(stream) {
	if(playing==stream) {
		clickstop();
	} else {
		clickstop();
		var src1 = src[stream].replace('%r',seq++);
		if(playvolume<0) loadplayer(src1);
		else $("#player1").jPlayer("setFile", src1).jPlayer("play");
		if(document.getElementById('playbtn'+stream)) document.getElementById('playbtn'+stream).src = 'images/listen_greenact.png';
		playing = stream;
		clickplus();
	}
}

function clickplus() {
	if(playing && $("#player1")) {
		playvolume += 4;
		if(playvolume>25) playvolume += 16;
		if(playvolume>100) playvolume = 100;
		$("#player1").jPlayer("volume", playvolume);
	}
}

function clickminus() {
	if(playing && $("#player1")) {
		playvolume -= 4;
		if(playvolume>25) playvolume -= 16;
		if(playvolume<0) playvolume = 0;
		$("#player1").jPlayer("volume", playvolume);
	}
}

function tabswitch(nr) {
	var t = document.getElementById('tabcontent');
	var im1 = document.getElementById('tab1');
	var im2 = document.getElementById('tab2');
	var im3 = document.getElementById('tab3');
	if(!t) return false;
	$('#tabcontent').html('');
	if(nr==1) {
		if(t) t.className = '';
	  if(im1) im1.src = "images/tabswitcher_radio_act.png";
	  if(im2) im2.src = "images/tabswitcher_pods.png";
	  if(im3) im3.src = "images/tabswitcher_pl.png";
		$.ajax({url:"inc_tab_channels.php", dataType:'html', success:function(data,tStatus) {
			$('#tabcontent').html(data);
		}});
	}
	if(nr==2) {
		if(t && !touchdevice) t.className = 'scrollcontent';
	  if(im1) im1.src = "images/tabswitcher_radio.png";
	  if(im2) im2.src = "images/tabswitcher_pods_act.png";
	  if(im3) im3.src = "images/tabswitcher_pl.png";
		$.ajax({url:"inc_tab_podcasts.php", dataType:'html', success:function(data,tStatus) {
			$('#tabcontent').html(data);
		}});
	}
	if(nr==3) {
		if(t && !touchdevice) t.className = 'scrollcontent';
	  if(im1) im1.src = "images/tabswitcher_radio.png";
	  if(im2) im2.src = "images/tabswitcher_pods.png";
	  if(im3) im3.src = "images/tabswitcher_pl_act.png";
		$('#tabcontent').html(playlistHtml);
	}
	return false;
}

