/*
player.js
2005/10/28 - v. 0
2006/11/10 - Playlist added

Get live broadcast informations about the 4 channels of Radio Suisse Romande, play live streams in Real format, get the current song if we are on Couleur3 or Option Musique

Copyright (c) 2005 Manuel Spuhler et Radio Suisse Romande http://rsr.ch

Feel free to use this code, but be aware that it is so poorly written that I have to include this notice to protect yourself, you've been warned, use it at your own risk ;-)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", sWITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var Player = {
	Version: '0.7',
	emptyFunction: function() {}
}

// Globals config
var time = new Date().getTime();
var blinkFrequency = 3; // in sec
var programRefreshInterval = 1000 * 60 * 5; // x mn refresh of program rss
var songRefreshInterval = 1000 * 60 * 0.5 // x mn Couleur3 and OM only
var debugMode = false;
var subjectTextWidth = 29;
var xmlBroadcastRequest;
var xmlSongRequest;
var aBroadcasts = new Array(); // hold broadcast objects
var aSongs = new Array(); // hold songs objects
var channel = -1; // !! channel la1ere = 0 etc. !!
var params = document.location.hash; // get #x parameter in the url
var init = true; //
var resizeStatus = true;
var toggleCounter= 0; // toggle broadcast/song counter
var displayTimer = -1; // display listener (refresh)
var songsTimer = -1; // songs listener
var rsr = ["rsr1","rsr2","rsr3","rsr4","rsr5","rsr6","rsr7"]; // channels id
var channelView = ["channelView1","channelView2","channelView3","channelView4","channelView5","channelView6","channelView7"]
var rsrlink = ["rsrlink1","rsrlink2","rsrlink3","rsrlink4","rsrlink5","rsrlink6","rsrlink7"]; // channels id
var bcastplaying = false; // onchange of channel
var baseurl = 'http://rsr.infomaniak.ch/player/'; 
var rss_c3 = baseurl + 'sekicouleur3.xml';
var rss_e2 = baseurl + 'sekiespace2.xml';
var rss_om = baseurl + 'sekioptionmusique.xml'; 
var real_url = '';
var onair_url = baseurl + 'onair.xml';
var popup = ''; // popup playlist window
var sSong = ''; // current playlist

var player1ere ="<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\" width=\"150\" height=\"128\" id=\"playerdebug\" align=\"middle\"><param name=\"allowScriptAccess\" value=\"sameDomain\" /><param name=\"allowFullScreen\" value=\"false\" /><param name=\"movie\" value=\"playerdebug.swf\" /><param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"#ffffff\" /><param name=\"FlashVars\" value=\"channel=La 1ère&aac=rsr-la1ere-high.aac&mp3=rsr-la1ere-high.mp3\" /><embed src=\"playerdebug.swf?channel=La 1ère&aac=rsr-la1ere-high.aac&mp3=rsr-la1ere-high.mp3\" quality=\"high\" bgcolor=\"#ffffff\" width=\"150\" height=\"128\" name=\"playerdebug\" align=\"middle\" wmode=\"window\" allowScriptAccess=\"sameDomain\" allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.adobe.com/go/getflashplayer_fr\" /></object>";

var playerE2  ="<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\" width=\"150\" height=\"128\" id=\"playerdebug\" align=\"middle\"><param name=\"allowScriptAccess\" value=\"sameDomain\" /><param name=\"allowFullScreen\" value=\"false\" /><param name=\"movie\" value=\"playerdebug.swf\" /><param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"#ffffff\" /><param name=\"FlashVars\" value=\"channel=Espace 2&aac=rsr-espace2-high.aac&mp3=rsr-espace2-high.mp3\" /><embed src=\"playerdebug.swf?channel=Espace 2&aac=rsr-espace2-high.aac&mp3=rsr-espace2-high.mp3\" quality=\"high\" bgcolor=\"#ffffff\" width=\"150\" height=\"128\" name=\"playerdebug\" align=\"middle\" wmode=\"window\" allowScriptAccess=\"sameDomain\" allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.adobe.com/go/getflashplayer_fr\" /></object>";

var playerC3 ="<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\" width=\"150\" height=\"128\" id=\"playerdebug\" align=\"middle\"><param name=\"allowScriptAccess\" value=\"sameDomain\" /><param name=\"allowFullScreen\" value=\"false\" /><param name=\"movie\" value=\"playerdebug.swf\" /><param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"#ffffff\" /><param name=\"FlashVars\" value=\"channel=Couleur 3&aac=rsr-couleur3-high.aac&mp3=rsr-couleur3-high.mp3\" /><embed src=\"playerdebug.swf?channel=Couleur 3&aac=rsr-couleur3-high.aac&mp3=rsr-couleur3-high.mp3\" quality=\"high\" bgcolor=\"#ffffff\" width=\"150\" height=\"128\" name=\"playerdebug\" align=\"middle\" wmode=\"window\" allowScriptAccess=\"sameDomain\" allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.adobe.com/go/getflashplayer_fr\" /></object>";

var playerOM = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\" width=\"150\" height=\"128\" id=\"playerdebug\" align=\"middle\"><param name=\"allowScriptAccess\" value=\"sameDomain\" /><param name=\"allowFullScreen\" value=\"false\" /><param name=\"movie\" value=\"playerdebug.swf\" /><param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"#ffffff\" /><param name=\"FlashVars\" value=\"channel=Option Musique&aac=rsr-optionmusique-high.aac&mp3=rsr-optionmusique-high.mp3\" /><embed src=\"playerdebug.swf?channel=Option Musique&aac=rsr-optionmusique-high.aac&mp3=rsr-optionmusique-high.mp3\" quality=\"high\" bgcolor=\"#ffffff\" width=\"150\" height=\"128\" name=\"playerdebug\" align=\"middle\" wmode=\"window\" allowScriptAccess=\"sameDomain\" allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.adobe.com/go/getflashplayer_fr\" /></object>";

var playerInfo = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0\" width=\"150\" height=\"128\" id=\"loadMP3_rsr\" align=\"middle\"><param name=\"allowScriptAccess\" value=\"sameDomain\" /><param name=\"allowFullScreen\" value=\"false\" /><param name=\"movie\" value=\"playerinfo.swf?channel=info&time="+time+"\" /><param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"#ffffff\" />	<embed src=\"playerinfo.swf?channel=info&time="+time+"\" quality=\"high\" bgcolor=\"#ffffff\" width=\"150\" height=\"128\" name=\"loadMP3_rsr\" align=\"middle\" allowScriptAccess=\"sameDomain\" allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" /></object>";


var oBrodcast7 = new Object();
oBrodcast7 = {
	fulltitle: "Dernier flash",
	link: "http://info.rsr.ch/",
	srtDate: "",
	description: "",
	enclosureurl: "http://real.xobix.ch/ramgen/rsr/podcast/flash/flash.rm",
	channel: "Dernier Flash",
	title: "Dernier Flash",
	subject: "",
	starttime: "00:00",
	endtime: "24:00"
}

// initialisation
window.onload = function (e) {

	//new
		$("loading").style.visibility = "hidden" ;
		$("container").style.visibility = "visible" ;
	toggleDebug(); // debug on/off
	// get params from url to set the channel
	switch ( params ) {
		case "#1":
		channel = 0;
		playerContent = player1ere;
		break;
		
		case "#2":
		channel = 1;
		playerContent =  playerE2;
		break;
		
		case "#3":
		channel = 2;
		playerContent = playerC3;
		break;
		
		case "#4":
		channel = 3;
		playerContent = playerOM;
		break;
				
		case "#6":
		channel = 5;
		playerContent = playerInfo;
		break;
		
		default:
		channel = 0;
		playerContent = player1ere;
		break;
	}
	//displayPlayer();
	
	loadEventsInterface();
	getBroadcasts(); 
	// launch biz proccess
	setInterval( "getBroadcasts();" , programRefreshInterval ); // refresh bdcasts
	// resize the window

	if(location.href.search("noresize") == -1){
		toggleResize();	
	}
	
	window.focus();
	playFlash(playerContent, channel);
	
}

/* ----------------- UI Process ----------------- */
function loadEventsInterface () {
	$("rsr1").onclick = function () { playerContent = player1ere; channel=0; playFlash(playerContent, channel); return false; };
	$("rsr2").onclick = function () { playerContent =  playerE2; channel=1; playFlash(playerContent, channel); return false; };
	$("rsr3").onclick = function () { playerContent = playerC3; channel=2; playFlash(playerContent, channel); return false; };
	$("rsr4").onclick = function () { playerContent = playerOM; channel=3; playFlash(playerContent, channel); return false; };

	$("rsr7").onclick = function () { playerContent = playerInfo; channel=7; playFlash(playerContent, channel); return false; };

	$("resize").onclick = function () { toggleResize(); return false; };
	$("playlist").onclick = function () { toggleSongList(); return false; };
	
	// external target
	if ( document.getElementsByTagName ) {
		var anchors = document.getElementsByTagName("a");
		for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
		anchor.target = "_blank";
		}
	}
}

function displayPlayer () {
	
	var playerId = $('player');
	playerId.innerHTML = playerContent;
;
}
function playFlash ( playerContent, channel ) {

	var playerId = $('player');

	playerId.innerHTML = playerContent;
	channel = parseInt( channel );
	display( channel );
}
function display ( channel ) {
	bcastplaying = false;
	if ( displayTimer ) clearInterval( displayTimer );
	if ( songsTimer ) clearInterval( songsTimer );
	
	
	switch ( channel ){
		case 2: // couleur 3
		$("playlist").style.display = "block" ;
		getSongs();
		displayBroadcast();
		displayTimer = setInterval( 'toggleDisplay();', 1000 * blinkFrequency );
		songsTimer = setInterval( 'getSongs();', songRefreshInterval );
		break;
		
		case 1: // espace 2
		now = new Date();
		var hours = now.getHours() ;
		hours = hours + (now.getMinutes()/60) ;
		var hstart = 1 ;
		var hstop = 8.5;
		
		// dimanche et lundi début a 0h00
		if (now.getDay() == 1 || now.getDay() == 0){
			hstart = 0 ;
		} 
		
		// dimanche fin à 6h00
		if (now.getDay()==0){
			hstop = 6 ;
		}
		
		
		if(hstart < hours && hours < hstop){
			$("playlist").style.display = "block" ;
			getSongs();
			displayBroadcast();
			displayTimer = setInterval( 'toggleDisplay();', 1000 * blinkFrequency );
			songsTimer = setInterval( 'getSongs();', songRefreshInterval );
		}
		else{
			$("playlist").style.display = "none" ;
			displayBroadcast();
			displayTimer = setInterval( 'displayBroadcast();', 1000 * 60 * 3 );
			break;			
		}		


		break;		
		
		case 3: // option musique
		$("playlist").style.display = "block" ;
		getSongs();
		displayBroadcast();
		displayTimer = setInterval( 'toggleDisplay();', 1000 * blinkFrequency );
		songsTimer = setInterval( 'getSongs();', songRefreshInterval );
		break;
		
		default:
		$("playlist").style.display = "none" ;
		displayBroadcast();
		displayTimer = setInterval( 'displayBroadcast();', 1000 * 60 * 3 );
		break;
	}
}

function toggleDisplay () {
	toggleCounter++;
	if ( toggleCounter % blinkFrequency == 0 ) {
	displayBroadcast();
	toggleCounter = 0;
	}
	else if ( toggleCounter % blinkFrequency == 1 ) displaySong();
}

function zap (){
	var realId = $("realEmbed");
	realId.DoNextEntry();
}

function displayBroadcast () {
	var logoId = $("logo");
	var labelId = $("label");
	var timeId = $("time");
	var titleId = $("title");
	var subjectId = $("subject");

	clearContent(labelId);
	clearContent(timeId);
	clearContent(titleId);
	clearContent(subjectId);
	var labelTag = document.createElement( 'span' ); //moz hack =innerText
	labelTag.innerHTML = 'Vous ecoutez';
	var titleTag = document.createElement( 'span' );
	if (aBroadcasts[channel] && aBroadcasts[channel].title)
	{
		titleTag.innerHTML = aBroadcasts[channel].title;
	}
	else
	{
		titleTag.innerHTML = "";
	}
	//titleTag.innerHTML = ( aBroadcasts[channel].title ) ? aBroadcasts[channel].title : "";
	var timeTag = document.createElement( 'span' );
	if (aBroadcasts[channel] && aBroadcasts[channel].starttime && aBroadcasts[channel].endtime){
		if (channel != 4 && channel!=5 && channel!=6 ) timeTag.innerHTML = aBroadcasts[channel].starttime + " - " + aBroadcasts[channel].endtime;
	}
	//if (channel != 4 && channel!=5 && channel!=6 ) timeTag.innerHTML = aBroadcasts[channel].starttime + " - " + aBroadcasts[channel].endtime;
	var subjectTag = document.createElement( 'span' );
	
	if (aBroadcasts[channel] && aBroadcasts[channel].subject){
		subjectTag.innerHTML = aBroadcasts[channel].subject;
	}
	else{
		subjectTag.innerHTML = "";
	}
	//subjectTag.innerHTML = ( aBroadcasts[channel].subject ) ? aBroadcasts[channel].subject : "";
	
	labelId.appendChild(labelTag);
	titleId.appendChild(titleTag);
	timeId.appendChild(timeTag);
	subjectId.appendChild(subjectTag);
	
	if ( !bcastplaying )
	{
		bcastplaying = true;
		switch ( channel )
		{
			case 0:
			logoId.style.background = "url('images/player-logo-LP.gif') top left no-repeat";
			labelId.style.color = "rgb(250,0,44)";
			break;
			
			case 1:
			logoId.style.background = "url('images/player-logo-E2.gif') top left no-repeat";
			labelId.style.color = "rgb(8,72,135)";
			break;
			
			case 2:
			logoId.style.background = "url('images/player-logo-C3.gif') top left no-repeat";
			labelId.style.color = "rgb(197,220,10)";
			break;
			
			case 3:
			logoId.style.background = "url('images/player-logo-OM.gif') top left no-repeat";
			labelId.style.color = "rgb(255,217,57)";
			break;
			
			case 4:
			logoId.style.background = "url('images/logo-rsr-ch.gif') top left no-repeat";
			labelId.style.color = "rgb(255,255,255)";
			break;
			
			case 5:
			logoId.style.background = "url('images/logo-rsr-ch.gif') top left no-repeat";
			labelId.style.color = "rgb(255,255,255)";
			break;
			
			case 6:
			logoId.style.background = "url('images/player-logo-Info.gif') top left no-repeat";
			labelId.style.color = "rgb(255,255,255)";
			break;
		}
	}
}

function displaySong () {
	var labelId = $("label");
	var timeId = $("time");
	var titleId = $("title");
	var subjectId = $("subject");
	clearContent(labelId);
	clearContent(timeId);
	clearContent(titleId);
	clearContent(subjectId);
	var labelTag = document.createElement( 'span' );
	var timeTag = document.createElement( 'span' );
	var titleTag = document.createElement( 'span' );
	var subjectTag = document.createElement( 'span' );
	labelTag.innerHTML = "Dernier titre";
	if (aSongs[0])
	{
		timeTag.innerHTML = ( aSongs[0].begintime != null ) ? aSongs[0].begintime : "";
		titleTag.innerHTML = ( aSongs[0].artist != null ) ? aSongs[0].artist : "" ;
		subjectTag.innerHTML = ( aSongs[0].title != null ) ? aSongs[0].title : "Indisponible actuellement";
		labelId.appendChild(labelTag);
		timeId.appendChild(timeTag);
		titleId.appendChild(titleTag);
		subjectId.appendChild(subjectTag);
	}
	
}

function displayBroadcastList () {
	DEBUG(getTime());
	if ( aBroadcasts[0].channel != null ) { // hack if xml is empty FIXME
		for ( var i=0; i<rsr.length; i++ ) {
			if (aBroadcasts[i].channel){
				var channelTxt = aBroadcasts[i].channel;
			}
			else{
				channelTxt = "";
			}
			
			var html = "";
			if ( i < 4 ) { // 5Ëme et 6Ëme dont need infos
			//	html += "<br />"
				html += aBroadcasts[i].title;
				
				if ( aBroadcasts[i].subject != null ) html += ": "+ aBroadcasts[i].subject;
				if ( html.length > subjectTextWidth ) {
					html = html.substr(0, subjectTextWidth) + "...";
					$( rsr[i] ).title = aBroadcasts[i].subject ;
				} // cut long text
			}
			$(channelView[i]).innerHTML = channelTxt+"<br/>";
			$( rsr[i] ).innerHTML = html ;
			//info link
			if (i == 6){
				$(channelView[i]).style.display = "none";
				$( rsr[i] ).innerHTML = channelTxt ;
			}
			$( rsrlink[i] ).href = aBroadcasts[i].link;
		}
	}
}

function getStyle( el, styleProp ) {
	var x = $( el );
	var y = -1;
	if ( x.currentStyle ) {
		y = x.currentStyle[styleProp];
	} else if ( window.getComputedStyle ) {
		y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	}
	return y;
}

function toggleResize () { // sould be generic but its a browser war
	resizeStatus = !resizeStatus;
	var containerW = parseInt( getStyle("container", "width") ) + 10;
	var listenW = parseInt( getStyle("listen", "width") );
	var containerH = parseInt( getStyle("container", "height") ) + 120;
	//var listenH = parseInt( getStyle("listen", "height") );
	var detect = navigator.userAgent.toLowerCase();
		
	// Add offsets for different browsers
	if ( $("container").currentStyle ) { // IE
		//IE7
		if (detect.indexOf("msie 7") >= 0){
			//containerH +=45;
			containerH +=10;
			listenW+=0;
			//alert("IE7");
		}
		//IE6
		if (detect.indexOf("msie 6") >= 0){
			//containerH +=42;
			containerH +=43;
			listenW+=40;
		}
		else {
			//containerH +=42;
			containerH +=70;
			listenW+=40;
		}
		
		containerW +=10;
		
		//alert("IE guess");
	} else if ( window.getComputedStyle ) { // firefox, moz
		if ( detect.indexOf("win")+1 ) { // IE
			//containerH += 70;
			containerH += 70;
			containerW += 5;
			listenW += 30;
			
	//		alert("windows");
			
		} 
		//mac
		else {
			//containerH += 30;
			containerH += 30;
			listenW += 20;
			
	//		alert("mac")
			 
		}
	} else { // a cheap hack for Safari
		//containerH = 355;
		containerH = 402;
		containerW = 510; listenW=200;
		//alert("safari");
	}
	
	DEBUG(containerW + "-" + containerH );
	DEBUG(listenW + "-" + containerH );
	
	if ( !resizeStatus ) {
		window.resizeTo( containerW, containerH );
		$("resizeImg").src = "images/moins-13x13.gif";
	}
	else {
	    Windows.closeAll();
		window.resizeTo( listenW, containerH );
		$("resizeImg").src = "images/plus-13x13.gif";
		
	}
}

function toggleSongList(){
    var exists_pi = $('playlist_id')
    if ( exists_pi) Windows.closeAll(); 
    else displaySongList();
}

function displaySongList() {

    var exists_pi = $('playlist_id')
    if ( resizeStatus ) toggleResize();

    sSong = '';
    for (var i=0; i < aSongs.length; i++) {
	if ( aSongs[i].title != null ) {
            sSong = sSong + '<h6>' + aSongs[i].artist +'</h6><p>'+ aSongs[i].title +'</p>';
        }
    }
    
    if ( !exists_pi) { 
			popup = new Window(
				'playlist_id', 
				{
					className: 'theme1', 
					title: "Derniers titres", 
					top:2, 
					right:2,
					width:300, 
					height:213	, 
					resizable:false,
					minimizable:false,
					maximizable:false
				}
			);
        popup.getContent().innerHTML =  sSong;
        popup.setDestroyOnClose();
        popup.show();
        songListTimer = setInterval("displaySongList()", songRefreshInterval);
    } else {
    	popup.getContent().innerHTML = sSong;
    }
    // Set up a windows observer, clear timer
	myObserver = {
		onDestroy: function(eventName, popup) 
		{
		  	if (songListTimer) 
		  	{
				clearInterval( songListTimer );
				Windows.removeObserver(this);
		  	}
		  	DEBUG(eventName + " on " + popup.getId())
		}
	}
	Windows.addObserver(myObserver);
    
}



/* ----------------- Services Interface ----------------- */
// update aBroadcasts array asynchronously, so the array is global
function getBroadcasts () {
	var url = onair_url  + "?" + encodeURIComponent( ( new Date() ).getTime() ); // time: force cache reload
	xmlBroadcastRequest = setXMLHTTPObject();
	if ( xmlBroadcastRequest ) {
		xmlBroadcastRequest.onreadystatechange = processReqChange;
		xmlBroadcastRequest.open( "GET", url, true );
		xmlBroadcastRequest.send( null );
	}
}

// update aSongs array asynchronously, so the array is global
function getSongs () {

	DEBUG( "getSongs: " + channel );
	var link;
	if ( channel == 2 ) link = rss_c3
	else if ( channel == 1) link = rss_e2
	else link = rss_om;
	link = link + "?"+ encodeURIComponent( ( new Date() ).getTime() ); // time: force cache reload
	DEBUG(link)
	xmlSongRequest = setXMLHTTPObject();
	if ( xmlSongRequest ) {
		xmlSongRequest.onreadystatechange = processReqChange2;
		xmlSongRequest.open( "GET", link, true );
		xmlSongRequest.send( null );
	}
}

function getTime () {
	var now = new Date();
	var nmins = now.getMinutes();
	if ( nmins<10 ) nmins="0"+nmins;
	var dateString = now.getHours() + ":" + nmins;
	return dateString;
}

/* ----------------- Business Workflow ----------------- */
/* ----------------- Business Components ----------------- */
function processReqChange () {
	DEBUG('processReqChange');
	if ( xmlBroadcastRequest.readyState == 4 ) { // only if req shows "loaded"
		if ( xmlBroadcastRequest.status == 200 ) { // only if "OK"
			parseXml( xmlBroadcastRequest );
		} else {
			DEBUG( "Problème de connexion, réessayez plus tard:\n" + xmlBroadcastRequest.statusText );
		}
		DEBUG(xmlBroadcastRequest.status);
	}
}

function setXMLHTTPObject () { // branch ie || mozilla
	var xRequest = false;
	var msg = "";
	if( window.XMLHttpRequest ) {
		try {
		xRequest = new XMLHttpRequest();
		}
		catch(e) {
		xRequest = false;
		msg = ( typeof e == "string" ) ? e : ( (e.message) ? e.message : "Erreur inconnue" );
		$("updateLastTime").innerHTML = ("Problème de navigateur " + msg);
		return null;
		}
	}
	else if( window.ActiveXObject ) { // branch for IE/Windows ActiveX version
		try {
			xRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e) {
		try {
			xRequest = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e) {
			xRequest = false;
			msg = ( typeof e == "string" ) ? e : ((e.message) ? e.message : "Erreur inconnue");
			$("updateLastTime").innerHTML = ("Problème de navigateur " + msg);
			return null;
		}
		}
	}
	return xRequest;
}

function processReqChange2 () { // FIXME try "this" to abstract this function
	if ( xmlSongRequest.readyState == 4 ) { // only if req shows "loaded"
		if ( xmlSongRequest.status == 200 ) { // only if "OK"
		//DEBUG("processReqChange2");
			parseXml2 ( xmlSongRequest );
		} else {
			DEBUG ( "Problème de connexion, réessayez plus tard:\n" + xmlSongRequest.statusText );
		}
	}
}

// parse items, make an array of objects, FIXM refactor both parseXml
function parseXml2 ( request ) {
    if ( request.responseXML ) {
        //DEBUG(request.responseXML);
        aSongs = new Array(); // reinitialize the array
        var rssTag = findChild ( request.responseXML, "rss" );
        if( rssTag ) {
            var channelTag = null;
            channelTag = findChild ( rssTag, "channel" );
                if( channelTag ) {
                    var childCounter = 0;
                        for ( var child = channelTag.firstChild; child != null && childCounter<40; child = child.nextSibling ) {
                            if ( child.nodeName == "item" ) {
                                var oItem = new Object();
                                var title = ( title = findChild( child, "rsrd:title") ) ? getFirstChildData( title ) : null;
                                var artist = ( artist = findChild( child, "rsrd:artist") ) ? getFirstChildData( artist ) : null;
                                var begintime = ( begintime = findChild( child, "rsrd:begintime") ) ? getFirstChildData( begintime ) : null;
                                var strDate = ( strDate = findChild( child, "pubDate") ) ? getFirstChildData( strDate ) : null;
                                oItem = {
                                         title: title,
                                         artist: artist,
                                         begintime: begintime,
                                         strDate: strDate
                                        }
                                aSongs.push(oItem);
                                childCounter++;
                            }
                        }
                    }
                }
    	var exists_pi = $('playlist_id')
    	if ( exists_pi) { 
     		displaySongList();
     	}
     }
}

// parse items, make an array of objects
function parseXml ( request ) {
	if ( request.responseXML ) {
		DEBUG(request.responseText);
		aBroadcasts = new Array(); // reinitialize the array
		var rssTag = findChild ( request.responseXML, "rss" );
		DEBUG("parseXml: "+ typeof rssTag );
		if( rssTag ) {
			var channelTag = null;
			channelTag = findChild ( rssTag, "channel" );
			if( channelTag ) {
				var childCounter = 0;
				for ( var child = channelTag.firstChild; child != null && childCounter<40; child = child.nextSibling ) {
					if ( child.nodeName == "item" ) {
						var oItem = new Object();
						var fulltitle = ( fulltitle = findChild (child, "title") ) ? getFirstChildData( fulltitle ) : null;
						var link = ( link = findChild (child, "link") ) ? getFirstChildData( link ) : null;
						var strDate = ( strDate = findChild (child, "pubDate") ) ? getFirstChildData( strDate ) : null;
						var description = ( description = findChild(child,"description", true) ) ? getFirstChildData( description ) : null;
						var enclosureurl = ( enclosureurl = findChild (child, "enclosure") ) ? enclosureurl.getAttribute("url") : null;
						var _channel = ( _channel = findChild (child, "rsrb:channel") ) ? getFirstChildData( _channel ) : null;
						var title = ( title = findChild (child, "rsrb:title") ) ? getFirstChildData( title ) : null;
						var subject = ( subject = findChild(child,"rsrb:subject") ) ? getFirstChildData( subject ) : null;
						var starttime = ( starttime = findChild (child, "rsrb:starttime") ) ? getFirstChildData( starttime ) : null;
						var endtime = ( endtime = findChild (child, "rsrb:endtime") ) ? getFirstChildData( endtime ) : null;
						oItem = {
							fulltitle: fulltitle,
							link:link,
							srtDate:strDate,
							description:description,
							enclosureurl:enclosureurl,
							channel:_channel,
							title:title,
							subject:subject,
							starttime:starttime,
							endtime:endtime
						}
						aBroadcasts.push( oItem );
							childCounter++;
							// 5 and 6 channel
							if (childCounter == 4) {
								//remove schr 22.09.09
							/*aBroadcasts.push( oBrodcast5 );
							aBroadcasts.push( oBrodcast6 );
							aBroadcasts.push( oBrodcast7 );*/
							break;
						}
					//DEBUG(channel + ":::" + title + " // " + subject + endtime);
					
					}
				}
			displayBroadcastList();
			displayBroadcast();
			$("loading").style.visibility = "hidden" ;
			$("container").style.visibility = "visible" ;
			
			if ( init ) { /*DEBUG("parseXml channel: "+ channel); play( channel ); init = false;*/ } // fired only after the parsing, at page load
			}
			
		}
	}
}

function findChild ( element, nodeName ) {
	for ( var child = element.firstChild; child != null; child = child.nextSibling ) {
	if ( child.nodeName == nodeName ) return child;
	}
	return null;
}

function getFirstChildData ( element ) {
	if ( element.hasChildNodes() ) {
		return element.firstChild.data;
	}
		return null;
}

function clearContent ( node ) {
	while ( node.hasChildNodes() )
	node.removeChild( node.childNodes[0] );
}

// from Prototype http://prototype.conio.net/
function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

/*Apple widget debug code*/
/*
****************
* debug code *
****************
*/

// write to the debug div.
function DEBUG( str ) {
	if ( debugMode ) {
		var debugDiv = $("debug");
		debugDiv.appendChild(document.createTextNode(str));
		debugDiv.appendChild(document.createElement("br"));
		debugDiv.scrollTop = debugDiv.scrollHeight;
	}
}

// toggle the debugMode flag
function toggleDebug() {
	if ( debugMode == true ) {
		$("debug").style.display = "block";
	} else {
		$("debug").style.display = "none";
	}
}
