String.prototype.toCapitalCase = function() {
var re = /\s/;
var words = this.split(re);
re = /(\S)(\S+)/;
for (i = words.length - 1; i >= 0; i--) {
re.exec(words[i]);
words[i] = RegExp.$1.toUpperCase()
+ RegExp.$2.toLowerCase();
}
return words.join(' ');
} 

function capitalise(a) {
var b="";
var notyet=true;
for (i=0;i<=a.length;i++) {
m = a.substr(i,1)
b += (notyet)?m.toUpperCase():m.toLowerCase();
notyet = (m.toUpperCase() == m.toLowerCase());
}
b=b.replace("I'M","I'm");
b=b.replace("n'T","n't"); // will handle Don't, Ain't, Can't, Won't, Couldn't, Wouldn't
b=b.replace("t'S","t's"); // will handle It's, Let's
b=b.replace("e'S","e's"); // will handle She's, He's
b=b.replace("'N'","'n'"); // will handle Rock 'N' Roll
b=b.replace("'Re","'re"); // will handle You're, You'res
b=b.replace("l'S","l's"); // will handle School's
return b;
}

function Replace ( target, todo, withwhat) 
  { var fixme = target;                // load string to alter (into fixme) 
    var atpos = fixme.indexOf(todo);   // find position of string to replace 
    while ( atpos > -1)                // while still to replace.. 
      { fixme = fixme.substring(0,atpos)  
                + withwhat 
                + fixme.substring(todo.length + atpos); //replace 
        atpos = fixme.indexOf(todo);     // find next position (if exists) 
      };                                // .. end while 
    return fixme;                       // return altered string 
  }

function toggleImg() {
	var imgs = document.getElementsByClassName('switchable');
	(imgs.length).times(function(i) {
			imgs[i].switchState = switchState;
			imgs[i].onmouseup = function() { imgs[i].switchState(); };
			imgs[i].onmousedown = function() { imgs[i].switchState(); };
		}
	);
}

function switchState() {
	var regexp = new RegExp("_o[nf]{1,2}", "g");
	try {
		var results = regexp.exec(this.src);
		if(results[0] == '_off') {
			this.src = this.src.replace(regexp, "_on");
		} else if(results[0] == '_on') {
			this.src = this.src.replace(regexp, "_off");
		}
	} catch(e) { }
}


function allStateOff() {
	var regexp = new RegExp("_o[nf]{1,2}", "g");
	var imgs = document.getElementsByClassName('switchable');

	for(i=0; i<imgs.length; i++) {
		var results = regexp.exec(imgs[i].src);
		imgs[i].src = imgs[i].src.replace(regexp, "_off");

	}
}

function switchStateOn(element) {
	toggleImg();
	allStateOff();
	var regexp = new RegExp("_o[nf]{1,2}", "g");
	$(element).src = $(element).src.replace(regexp, "_on");
	$(element).onmouseup = null;
	$(element).onmousedown = null;
}

function reload(url) {
	try {
		var tmp = url.split("?");
		var now = new Date();
		this.src = tmp[0] + '?' + now.getTime();
	} catch(e) { }
}

function RLMediaPlayer(element) {

	isQuickTime = detectQuickTime();
	if(BrowserDetect.OS != "Windows") {
		this.quicktime = true;
	}

	// Prototype hack : dunno why I can't use $(element) call with IE ...
	this.player = document.getElementById(element);

	this.isPlaying = true;
	this.isMuted = false;
	this.addControl = addControl;
	this.play = play;
	this.pause = pause;
	this.soundUp = soundUp;
	this.soundDown = soundDown;
	this.autoReconnect = autoReconnect;
}

function addControl(obj) {
	var player = this;
	try {
		if(obj.type == 'default') {
			if(obj.state == 'on') {
				$(obj.element).onclick = function() {
						switchStateOn(obj.element);
						eval('player.'+obj.action+'()');
					};
			} else {
				$(obj.element).onclick = function() {eval('player.'+obj.action+'()');};
			}
		} else {
			$(obj.element).onclick = obj.action;
		}
	} catch(e) { }
}

// hack to autoreconnect QT plugin on disconnect
function autoReconnect() {
	if(this.quicktime && Browser.browser != "Safari") {
		if(this.player.GetPluginStatus().indexOf(",") != -1) {
			this.player.Play();
		}
	}
}

function play() {
	if(!this.isPlaying && this.isMuted) {
		if(this.quicktime) {
			this.player.SetMute(false);
		} else {
			this.player.Mute = 0;
		}
//		this.player.Play();
		this.isPlaying = true;
	}
}

function pause() {
	if(this.isPlaying) {
		if(this.quicktime) {
			this.player.SetMute(true);
		} else {
			this.player.Mute = 1;
		}
		this.isPlaying = false;
		this.isMuted = true;
	}
}


function soundUp() {
	if($('volumeLayer').style.width == '') $('volumeLayer').style.width = "15px";
	var _width_ = parseInt(($('volumeLayer').style.width).replace("px", ""));
	_width_ += 5;
	if(this.quicktime) {
		if (this.player.GetVolume() + 64 <=448) {
			this.player.SetVolume(this.player.GetVolume() + 64);
			$('volumeLayer').style.width = _width_ + 'px';
		} else this.player.SetVolume(448);

	} else {
		try {
			var volume = this.player.Volume;
			if(volume >= -602 && volume <= -1) {
				this.player.Volume = this.player.Volume + 200;
				$('volumeLayer').style.width = _width_ + 'px';
			} else if(volume < -602) {
				this.player.Volume = this.player.Volume + 725;
				$('volumeLayer').style.width = _width_ + 'px';
			} else {
				this.player.Volume = -2;
			}
		} catch(e) { }
	}
}

function soundDown() {
	if($('volumeLayer').style.width == '') $('volumeLayer').style.width = "15px";
	var _width_ = parseInt(($('volumeLayer').style.width).replace("px", ""));
	_width_ -= 5;

	if(this.quicktime) {
		try {
			if (this.player.GetVolume() - 64 >= 0) {
				this.player.SetVolume(this.player.GetVolume() - 64);
				if(_width_ >= "0") {
					$('volumeLayer').style.width = _width_ + 'px';
				}	
			} else this.player.SetVolume(0);
		} catch(e) { }
	} else {
		try {
			var volume = this.player.Volume;
			if(volume > -602) {
				this.player.Volume = this.player.Volume - 200;
				$('volumeLayer').style.width = _width_ + 'px';
			} else if(volume <= -602 && volume - 725 > -3503) {
				this.player.Volume = this.player.Volume - 725;
				$('volumeLayer').style.width = _width_ + 'px';
			} else if (volume - 725 <= -3503) {
				this.player.Volume = -3500;
				$('volumeLayer').style.width = '0px';
			}
		} catch(e) { }
	}
}

function getData() {
	var now = new Date();
	var url = "../music_schedule/playing_nowSP.xml";
	var opts = { method : "get",
		parameters : "tmp="+now.getTime(),
		onComplete : updateDataLayout,
		asynchronous : true };
	var req = new Ajax.Request(url, opts);
}

function getDJData() {

	var now = new Date();
	var url = "../tmp/djnow.xml";
	var opts = { method : "get",
		parameters : "tmp="+now.getTime(),
		onComplete : updateDJDataLayout,
		asynchronous : true };
	var req = new Ajax.Request(url, opts);
}

var doc, timer = 0, cpt = 0;

function updateDataLayout(remote) {

	if(remote.responseXML.documentElement != doc) {
		doc = remote.responseXML.documentElement;
		if (doc && cpt == 0) {
			var artist = nodeValue(doc, 0, "artist");
			$("artist").innerHTML = artist;
			var songTitle = nodeValue(doc, 0, "title");
	//		songTitle = songTitle.toCapitalCase(); 
	//		songTitle = Replace(songTitle, artist, "");
	//		songTitle = Replace(songTitle, " - ", "");
   			songTitle = capitalise(songTitle); 
			if (artist == "Live") {songTitle="More music coming up..";}


			$("title").innerHTML = songTitle;
			var imageIsPresent = nodeValue(doc, cpt, "picture");
			var imageToUse = Replace(imageIsPresent, "%20", " ");

			var atpos = imageToUse.indexOf('0000000000');   // if image is not  output from stationplaylist cos missing from track properties
			if (atpos > 0)
			      { imageIsPresent = ''; }  

			if ((imageIsPresent.length)>0) 
		//		{$("cover").src = ("../music_schedule/"+imageToUse);}
				{$("cover").src = (imageToUse);}
				else {$("cover").src = "../music_schedule/images/exampleAlbumCover.gif";}

		}
	}
}

function updateDJDataLayout(remote) {

	if(remote.responseXML.documentElement != doc) {
		doc = remote.responseXML.documentElement;
		if (doc && cpt == 0) {
			$("live").innerHTML = nodeValue(doc, 0, "deejay");
			$("deejaypicture").src = nodeValue(doc, 0, "deejaypicture");
		}
	}
}

function nodeValue(node, child, name) {
    var childs = node.getElementsByTagName(name);
    if (childs.length > 0 && childs.item(child).childNodes.length > 0)
        return childs.item(child).childNodes.item(0).nodeValue;
    return "";
}

function fadeLastTitle() {
	Effect.Fade('cover');
	setTimeout("displayLastTitle()", 1000);
}

function fadeTitle() {
	Effect.Fade('cover');
	setTimeout("displayActualTitle()", 1000);
}

function displayLastTitle() {
	if(cpt >= 4) {
		cpt = 0;
		$("live").innerHTML = "The Best In Classic Rock !!";
	} else {
		cpt++;
		$("live").innerHTML = "DIFFUSE A " + nodeValue(doc, cpt, "broadcastTime");
	}
	try {
		$("artist").innerHTML = nodeValue(doc, cpt, "artist");
		$("title").innerHTML = nodeValue(doc, cpt, "title");

			var imageIsPresent = nodeValue(doc, cpt, "albumPicture");
			var imageToUse = Replace(imageIsPresent, "%20", " ");
			if ((imageIsPresent.length)>0) 
				{$("cover").src = ("../music_schedule/"+imageToUse);}
				else {$("cover").src = "../music_schedule/images/exampleAlbumCover.gif";}

		timer = 20;
	} catch(e) { }
	Effect.Appear('cover');
}

function displayActualTitle() {
	cpt = 0;
	try {
		$("artist").innerHTML = nodeValue(doc, cpt, "artist");
		$("title").innerHTML = nodeValue(doc, cpt, "title");
		$("live").innerHTML = "The Best In Classic Rock !!";
	} catch(e) { }
	Effect.Appear('cover');
}

function refreshTitle() {
	timer--;
	if(timer <= 0 && cpt != 0) {
		fadeTitle();
	}
}

var playerVersion = 1;
var isQuickTime = detectQuickTime();

/*
if(!isQuickTime && BrowserDetect.OS == "Windows" && BrowserDetect.browser == "Explorer") {
	playerVersion = 1;
}

if(isQuickTime && BrowserDetect.OS == "Windows" && BrowserDetect.browser == "Explorer") {
	playerVersion = 2;
}

if(isQuickTime && BrowserDetect.OS == "Windows" && BrowserDetect.browser != "Explorer") {
	playerVersion = 3;
}

if(!isQuickTime && BrowserDetect.OS == "Windows" && BrowserDetect.browser != "Explorer") {
	playerVersion = 1;
}
*/

if(BrowserDetect.OS == "Mac" && BrowserDetect.browser == "Safari") {
	playerVersion = 3;
}

if(BrowserDetect.OS == "Mac" && BrowserDetect.browser != "Safari") {
	playerVersion = 3;
}

if(BrowserDetect.OS == "Linux") {
	playerVersion = 3;
}

function insertPlayer(index) {
	var htmlPlayer = "";
	switch(index) {
		case 1: // No QuickTime Windows IE
			htmlPlayer = '<ob'+'ject id="NSPlay" name="NSPlay" classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95" width="0" height="0"\ codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,1,5,217"\ standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject">\
			<param name="Filename" value="http://s8.mediastreaming.it:7050/">\
			<param name="AudioStream" value="-1">\
			<param name="AutoSize" value="0">\
			<param name="AutoStart" value="true">\
			<param name="AnimationAtStart" value="0">\
			<param name="AllowScan" value="-1">\
			<param name="AllowChangeDisplaySize" value="-1">\
			<param name="AutoRewind" value="0">\
			<param name="Balance" value="0">\
			<param name="BaseURL" value> <param name="BufferingTime" value="5">\
			<param name="CaptioningID" value> <param name="ClickToPlay" value="-1">\
			<param name="CursorType" value="0">\
			<param name="CurrentPosition" value="-1">\
			<param name="CurrentMarker" value="0">\
			<param name="DefaultFrame" value> <param name="DisplayBackColor" value="0">\
			<param name="DisplayForeColor" value="16777215">\
			<param name="DisplayMode" value="0">\
			<param name="DisplaySize" value="4">\
			<param name="Enabled" value="-1">\
			<param name="EnableContextMenu" value="-1">\
			<param name="EnablePositionControls" value="0">\
			<param name="EnableFullScreenControls" value="0">\
			<param name="EnableTracker" value="0">\
			<param name="InvokeURLs" value="-1">\
			<param name="Language" value="-1">\
			<param name="Mute" value="0">\
			<param name="PlayCount" value="1">\
			<param name="PreviewMode" value="0">\
			<param name="Rate" value="1">\
			<param name="SelectionEnd" value="-1">\
			<param name="SendOpenStateChangeEvents" value="-1">\
			<param name="SendWarningEvents" value="-1">\
			<param name="SendErrorEvents" value="-1">\
			<param name="SendKeyboardEvents" value="0">\
			<param name="SendMouseClickEvents" value="0">\
			<param name="SendMouseMoveEvents" value="0">\
			<param name="SendPlayStateChangeEvents" value="-1">\
			<param name="ShowCaptioning" value="0">\
			<param name="ShowControls" value="1">\
			<param name="ShowAudioControls" value="1">\
			<param name="ShowDisplay" value="0">\
			<param name="ShowGotoBar" value="0">\
			<param name="ShowPositionControls" value="0">\
			<param name="ShowStatusBar" value="1">\
			<param name="ShowTracker" value="0">\
			<param name="TransparentAtStart" value="-1">\
			<param name="VideoBorderWidth" value="0">\
			<param name="VideoBorderColor" value="0">\
			<param name="VideoBorder3D" value="0">\
			<param name="Volume" value="50000">\
			<param name="WindowlessVideo" value="-1">\
			<embed type="application/x-mplayer2"\ pluginspage="http://www.microsoft.com/isapi/redir.dll?prd=windows&amp;sbp=mediaplayer&amp;ar=Media&amp;sba=Plugin&amp;" src="http://s8.mediastreaming.it:7050/" name="NSPlay" width="0" height="0" showstatusbar="1" showcontrols="1" showdisplay="0" showgotobar="0" autosize="0" showcaptioning="0" enabletracker="0" showtracker="0" enablecontextmenu="0" volume="0" showpositioncontrols="0" showaudiocontrols="1">\
			</ob'+'ject>';
			break;

		case 2: // Quicktime Windows IE
			htmlPlayer = '<ob'+'ject id="NSPlay" CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"  CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab" WIDTH="0" HEIGHT="0" ><PARAM NAME="src" VALUE="http://s8.mediastreaming.it:7050/listen.pls" ><PARAM NAME="autoplay" VALUE="true" ><EMBED PLUGINSPAGE="http://www.apple.com/quicktime/download/"                     TYPE="image/x-quicktime" WIDTH="0" HEIGHT="0" QTSRC="http://s8.mediastreaming.it:7050/listen.pls" AUTOPLAY="true" ></EMBED></ob'+'ject>';
			break;

		case 3: // QuickTime Windows Not IE | QuickTime MacOS Firefox
			htmlPlayer = '<ob'+'ject id="NSPlay" type="video/quicktime" data="http://s8.mediastreaming.it:7050/listen.pls" width="0" height="0"><param name="src" value="http://s8.mediastreaming.it:7050/listen.pls" /><param name="autoplay" value="true" /><param name="controller" value="true" /><param name="cache" value="true" /><param name="href" value="http://s8.mediastreaming.it:7050/listen.pls" /><param name="target" value="myself" /></ob'+'ject>';
			break;

		default:
			htmlPlayer = '<ob'+'ject id="NSPlay" name="NSPlay" classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95" width="0" height="0"\ codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,1,5,217"\ standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject">\
			<param name="Filename" value="http://s8.mediastreaming.it:7050/">\
			<param name="AudioStream" value="-1">\
			<param name="AutoSize" value="0">\
			<param name="AutoStart" value="true">\
			<param name="AnimationAtStart" value="0">\
			<param name="AllowScan" value="-1">\
			<param name="AllowChangeDisplaySize" value="-1">\
			<param name="AutoRewind" value="0">\
			<param name="Balance" value="0">\
			<param name="BaseURL" value> <param name="BufferingTime" value="5">\
			<param name="CaptioningID" value> <param name="ClickToPlay" value="-1">\
			<param name="CursorType" value="0">\
			<param name="CurrentPosition" value="-1">\
			<param name="CurrentMarker" value="0">\
			<param name="DefaultFrame" value> <param name="DisplayBackColor" value="0">\
			<param name="DisplayForeColor" value="16777215">\
			<param name="DisplayMode" value="0">\
			<param name="DisplaySize" value="4">\
			<param name="Enabled" value="-1">\
			<param name="EnableContextMenu" value="-1">\
			<param name="EnablePositionControls" value="0">\
			<param name="EnableFullScreenControls" value="0">\
			<param name="EnableTracker" value="0">\
			<param name="InvokeURLs" value="-1">\
			<param name="Language" value="-1">\
			<param name="Mute" value="0">\
			<param name="PlayCount" value="1">\
			<param name="PreviewMode" value="0">\
			<param name="Rate" value="1">\
			<param name="SelectionEnd" value="-1">\
			<param name="SendOpenStateChangeEvents" value="-1">\
			<param name="SendWarningEvents" value="-1">\
			<param name="SendErrorEvents" value="-1">\
			<param name="SendKeyboardEvents" value="0">\
			<param name="SendMouseClickEvents" value="0">\
			<param name="SendMouseMoveEvents" value="0">\
			<param name="SendPlayStateChangeEvents" value="-1">\
			<param name="ShowCaptioning" value="0">\
			<param name="ShowControls" value="1">\
			<param name="ShowAudioControls" value="1">\
			<param name="ShowDisplay" value="0">\
			<param name="ShowGotoBar" value="0">\
			<param name="ShowPositionControls" value="0">\
			<param name="ShowStatusBar" value="1">\
			<param name="ShowTracker" value="0">\
			<param name="TransparentAtStart" value="-1">\
			<param name="VideoBorderWidth" value="0">\
			<param name="VideoBorderColor" value="0">\
			<param name="VideoBorder3D" value="0">\
			<param name="Volume" value="50000">\
			<param name="WindowlessVideo" value="-1">\
			<embed type="application/x-mplayer2"\ pluginspage="http://www.microsoft.com/isapi/redir.dll?prd=windows&amp;sbp=mediaplayer&amp;ar=Media&amp;sba=Plugin&amp;" src="http://s8.mediastreaming.it:7050/" name="NSPlay" width="0" height="0" showstatusbar="1" showcontrols="1" showdisplay="0" showgotobar="0" autosize="0" showcaptioning="0" enabletracker="0" showtracker="0" enablecontextmenu="0" volume="0" showpositioncontrols="0" showaudiocontrols="1">\
			</ob'+'ject>';
			break;
	}

	$('player').innerHTML = htmlPlayer;
}
