<?xml version="1.0" encoding="UTF-8" ?> 
<Module>
<ModulePrefs 
    title="BBC on now/next"
    description="What's currently/next showing on all UK BBC TV Channels"
    author="Mario Menti"
    author_email="mmenti+googlemodule@gmail.com"
    screenshot="http://google.bbcmodules.co.uk/bbcnownext.jpg"
    author_location="London, UK"
    author_affiliation="supported by backstage.bbc.co.uk"
    title_url="http://bbcmodules.co.uk/google.html"
    directory_title="BBC what's on now/next"
    height="350"
    
/> 
<UserPref name="init_view" display_name="Initial view" default_value="TV" datatype="enum" > 
<EnumValue value="TV" />
<EnumValue value="Radio" />
</UserPref>
<UserPref name="hidetv" display_name="Hide TV" datatype="bool" />
<UserPref name="hideradio" display_name="Hide Radio" datatype="bool" />
<Content type="html">
<![CDATA[ 
<style type="text/css">
body
{
font-family: Arial;
font-size: 11px;
}
.title
{
font-family: Arial;
font-size: 11px;
font-weight: bold;
}
.time
{
font-family: Arial;
font-size: 11px;
}
.channel_logo
{
border: 0;
margin: 1px 5px 0px 0px;
}
.channel
{
clear: both;
}
table
{
font-family: Arial;
font-size: 11px;
margin-top: 0px;
margin-bottom: 0px;
}
.btn
{
color:#ffffff;
font-weight:bold;
font-size:11px;
background-color:#CCCCFF;
border:1px solid;
border-top-color:#009999;
border-left-color:#009999;
border-right-color:#009999;
border-bottom-color:#009999;

}
.btn2
{
color:#CCCCFF;
font-weight:bold;
font-size:11px;
background-color:#ffffff;
border:1px solid;
border-top-color:#009999;
border-left-color:#009999;
border-right-color:#009999;
border-bottom-color:#009999;
}

a
{
border: 0;
}

.credits
{
text-align: center;
color: #999;
background: #eeeeee;
margin: 5px 0px 5px 0px;
}


</style>

<div id="gsrc"></div>
<script src="http://www.google.com/js/nxsl.1.js" type="text/javascript"></script>

<script type="text/javascript">


// The AttachEvent code is copyright 2003 by Gavin Kistner, gavin@refinery.com
// It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
// Reuse or modification is free provided you abide by the terms of that license.
// (Including the first two lines above in your source code satisfies the conditions.)


//Cross browser attach event function. For 'evt' pass a string value with the leading "on" omitted
//e.g. AttachEvent(window,'load',MyFunctionNameWithoutParenthesis,false);

function AttachEvent(obj,evt,fnc,useCapture){
    if (!useCapture) useCapture=false;
    if (obj.addEventListener){
    obj.addEventListener(evt,fnc,useCapture);
    return true;
} else if (obj.attachEvent) return obj.attachEvent("on"+evt,fnc);
else{
    MyAttachEvent(obj,evt,fnc);
    obj['on'+evt]=function(){ MyFireEvent(obj,evt) };
}
} 
//The following are for browsers like NS4 or IE5Mac which don't support either
//attachEvent or addEventListener
function MyAttachEvent(obj,evt,fnc){
    if (!obj.myEvents) obj.myEvents={};
    if (!obj.myEvents[evt]) obj.myEvents[evt]=[];
    var evts = obj.myEvents[evt];
    evts[evts.length]=fnc;
}
function MyFireEvent(obj,evt){
    if (!obj || !obj.myEvents || !obj.myEvents[evt]) return;
    var evts = obj.myEvents[evt];
    for (var i=0,len=evts.length;i<len;i++) evts[i]();
}

function ShowNowTV() {
    elResNowTV.style.display = 'block';
    elResNextTV.style.display = 'none';
    elResNowRadio.style.display = 'none';
    elResNextRadio.style.display = 'none';
    elBtnNowTV.className = "btn";
    elBtnNextTV.className = "btn2";
    elBtnNowRadio.className = "btn2";
    elBtnNextRadio.className = "btn2";
}
function ShowNextTV() {
    elResNowTV.style.display = 'none';
    elResNextTV.style.display = 'block';
    elResNowRadio.style.display = 'none';
    elResNextRadio.style.display = 'none';
    elBtnNowTV.className = "btn2";
    elBtnNextTV.className = "btn";
    elBtnNowRadio.className = "btn2";
    elBtnNextRadio.className = "btn2";
}
function ShowNowRadio() {
    elResNowTV.style.display = 'none';
    elResNextTV.style.display = 'none';
    elResNowRadio.style.display = 'block';
    elResNextRadio.style.display = 'none';
    elBtnNowTV.className = "btn2";
    elBtnNextTV.className = "btn2";
    elBtnNowRadio.className = "btn";
    elBtnNextRadio.className = "btn2";
}
function ShowNextRadio() {
    elResNowTV.style.display = 'none';
    elResNextTV.style.display = 'none';
    elResNowRadio.style.display = 'none';
    elResNextRadio.style.display = 'block';
    elBtnNowTV.className = "btn2";
    elBtnNextTV.className = "btn2";
    elBtnNowRadio.className = "btn2";
    elBtnNextRadio.className = "btn";
}

function RefreshTimer() { 
    getNowNext();
    setInnerHTML();
}

function bbcRadioPlayer(station) {

     if (station == "BBCROne") station = "radio1";
     if (station == "BBCRTwo") station = "radio2";
     if (station == "BBCRThree") station = "radio3";
     if (station == "BBCRFour") station = "radio4";
     if (station == "BBCRFiveL") station = "fivelive";
     if (station == "BBCRFiveX") station = "sportsextra";
     if (station == "BBCSixMU") station = "6music";
     if (station == "BBCSeven") station = "bbc7";
     if (station == "BBCAsian") station = "asiannet";
     if (station == "BBCWrld") station = "wservice";
     if (station == "OneXtra") station = "1xtra";

     var URL = 'http://www.bbc.co.uk/radio/aod/'+station+'_promo.shtml';
     window.open(URL,'aod','width=693,height=525,toolbar=no,personalbar=no,location=no,directories=no,statusbar=no,menubar=no,status=no,resizable=yes,left=60,screenX=60,top=100,screenY=100');
}

function APIgetProgrammes(ch_id, st, end) {

        _IG_FetchContent(api_root + 'method=bbc.schedule.getProgrammes&format=simple&detail=schedule&limit=2&channel_id=' + ch_id + '&start=' + st + '&end=' + end, function (responseText) {

        // parse XML
        var xml = xmlParse(responseText);


        // loop over programmes for channel
        for (var j=1; j<3; j++) {
    
		// get start time, synopsis and title
		// var nxsl = xmlParse('<span class="time" select="/rsp/schedule/programme[channel_id=\''+all_channels[currentChannel]+'\']['+j+']" content="start"></span><split/><syn select="/rsp/schedule/programme[channel_id=\''+all_channels[currentChannel]+'\']['+j+']" content="synopsis"></syn><split/><ttl select="/rsp/schedule/programme[channel_id=\''+all_channels[currentChannel]+'\']['+j+']" content="@title"></ttl>');
		var nxsl = xmlParse('<span class="time" select="/rsp/schedule/programme['+j+']" content="start"></span><split/><syn select="/rsp/schedule/programme['+j+']" content="synopsis"></syn><split/><ttl select="/rsp/schedule/programme['+j+']" content="@title"></ttl>');
	
                nxslProcess(xml, nxsl);
                var allTxt = xmlText( nxsl );
                var resArr = allTxt.split("<split/>");

                var startStr = resArr[0];
		var synopsis = resArr[1];
		var title = resArr[2];

		var startPos = startStr.indexOf( "T", 0 );
                hourStr = startStr.substr( startPos + 1, 2 );
                hour = stringToNumber( hourStr );
                hour += tzo;
		if (hour == 24) { hour = 0; }
                // startStr = startStr.substr( 0, startPos - 10 ) + hour + startStr.substr( startPos + 3, 3 ) + startStr.substr( startPos + 9, (startStr.length - startPos) );                           
                startStr = startStr.substr( 0, startPos - 10 ) + hour + startStr.substr( startPos + 3, 3 );
		if (startStr == "1") { startStr = ""; }

		var timeStr = startStr.replace(/<span class="time">/,"");
		timeStr = timeStr.replace(/<\/span>/,"");

                // get synopsis
                synopsis = synopsis.replace(/<syn>/,"");
		synopsis = synopsis.replace(/<\/syn>/,"");

                // get title
                title = title.replace(/<ttl>/,"");
		title = title.replace(/<\/ttl>/,"");
		title = title.replace(/\'/g,"\'");
		if (title == "") { title = "Service temporarily unavailable"; }

		var my_html = "<a onmouseover=\"javascript:document.getElementById('p_content_"+ch_id+"_"+j+"').innerHTML='"+synopsis.replace(/\'/g,"&quot;")+"'\" onmouseout=\"javascript:document.getElementById('p_content_"+ch_id+"_"+j+"').innerHTML='"+timeStr+"'\"><span class=\"title\">"+title+"</span></a><listenlink/><br/>";

      
		startStr = "<div id=\"p_content_"+ch_id+"_"+j+"\">" + startStr + "</div>";
                var result = my_html + startStr;
                result = result.replace(/\"/g, '\\"');
	
	        if (j == 1) {
                    eval(ch_id + "_now_html = \"" + result + "\";" );

	        }   
	        else {
                    eval(ch_id + "_next_html = \"" + result + "\";" );
	        }
		processedCh++;
	    }

        });
}

function getNowNext() {

    var prefs = new _IG_Prefs(__MODULE_ID__);

    // get the current time
    var current_time = new Date();
    var tomorrow_time = new Date();

    tomorrow_time.setDate(now.getDate() + 1);

    var month = NumberToString(current_time.getMonth() + 1);
    var month2 = NumberToString(tomorrow_time.getMonth() + 1);
    var date = NumberToString(current_time.getDate());
    var date2 = NumberToString(tomorrow_time.getDate());
    var hr = current_time.getHours();
    if (hr == 0)  {  hr=24; date=date-1; }
    hr -= tzo;
    var hr2 = tomorrow_time.getHours();
    if (hr2 == 0)  {  hr2=24; date=date-1; }
    hr2 -= tzo;
    var hour = NumberToString(hr);
    var hour2 = NumberToString(hr2);
    var minute = NumberToString(current_time.getMinutes());


    var start = "" + now.getFullYear() + "-" + month + "-" + date + "T" + hour + ":" + minute + ":00Z";
    var end = "" + tomorrow_time.getFullYear() + "-" + month2 + "-" + date2 + "T" + hour2 + ":" + NumberToString(tomorrow_time.getMinutes()) + ":00Z";


    for (i=0; i<all_channels.length; i++) {
        APIgetProgrammes(all_channels[i], start, end);
    }
}

function t_setInnerHTML() {

    // run this until all info received from proxy/ bbc web api

    var tot = all_channels.length;
    var tot = tot * 2;
    if (processedCh == tot) {

    // this means all the info has been received, so let's update the divs..

    var iHtmlTVNow = "<table>";
    var iHtmlTVNext = "<table>";
    var iHtmlRadioNow = "<table>";
    var iHtmlRadioNext = "<table>";
    for (var i=0; i < tv_channels.length; i++ ) {
        iHtmlTVNow += "<tr><td>";
        iHtmlTVNow += eval(tv_channels[i] + "_img");
	iHtmlTVNow += "</td><td>";
	iHtmlTVNow += eval(tv_channels[i] + "_now_html");
	iHtmlTVNow += "</td></tr>";

        iHtmlTVNext += "<tr><td>";
        iHtmlTVNext += eval(tv_channels[i] + "_img");
	iHtmlTVNext += "</td><td>";
	iHtmlTVNext += eval(tv_channels[i] + "_next_html");
	iHtmlTVNext += "</td></tr>";
    }
    iHtmlTVNow += "</table>";
    iHtmlTVNext += "</table>";
    elResNowTV.innerHTML = iHtmlTVNow;
    elResNextTV.innerHTML = iHtmlTVNext;
    for (var i=0; i < r_channels.length; i++ ) {
        iHtmlRadioNow += "<tr><td>";
        iHtmlRadioNow += eval(r_channels[i] + "_img");
	iHtmlRadioNow += "</td><td>";
	iHtmlRadioNow += eval(r_channels[i] + "_now_html");
	iHtmlRadioNow += "</td></tr>";
	iHtmlRadioNow = iHtmlRadioNow.replace(/<listenlink\/>/, "&nbsp;<a href=\"javascript:bbcRadioPlayer('"+r_channels[i]+"')\"><img src=\"http://www.bbc.co.uk/radio/aod/images/ico_audio.gif\" align=\"absMiddle\" border=\"0\" title=\"listen now\"></a>");

	iHtmlRadioNext += "<tr><td>";
        iHtmlRadioNext += eval(r_channels[i] + "_img");
	iHtmlRadioNext += "</td><td>";
	iHtmlRadioNext += eval(r_channels[i] + "_next_html");
	iHtmlRadioNext += "</td></tr>";
    }
    iHtmlRadioNow += "</table>";
    iHtmlRadioNext += "</table>";
    elResNowRadio.innerHTML = iHtmlRadioNow;
    elResNextRadio.innerHTML = iHtmlRadioNext;

    // remove the timer
    clearInterval(t2);

    }

}

function setInnerHTML() {

    elResNowTV.style.display = 'none';
    elResNextTV.style.display = 'none';
    elResNowRadio.style.display = 'none';
    elResNextRadio.style.display = 'none';

    var iHtmlTVNow = "<table>";
    var iHtmlTVNext = "<table>";
    var iHtmlRadioNow = "<table>";
    var iHtmlRadioNext = "<table>";
    for (var i=0; i < tv_channels.length; i++ ) {
        iHtmlTVNow += "<tr><td>";
        iHtmlTVNow += eval(tv_channels[i] + "_img");
	iHtmlTVNow += "</td><td>";
	iHtmlTVNow += eval(tv_channels[i] + "_now_html");
	iHtmlTVNow += "</td></tr>";

        iHtmlTVNext += "<tr><td>";
        iHtmlTVNext += eval(tv_channels[i] + "_img");
	iHtmlTVNext += "</td><td>";
	iHtmlTVNext += eval(tv_channels[i] + "_next_html");
	iHtmlTVNext += "</td></tr>";
    }
    iHtmlTVNow += "</table>";
    iHtmlTVNext += "</table>";
    elResNowTV.innerHTML = iHtmlTVNow;
    elResNextTV.innerHTML = iHtmlTVNext;
    for (var i=0; i < r_channels.length; i++ ) {
        iHtmlRadioNow += "<tr><td>";
        iHtmlRadioNow += eval(r_channels[i] + "_img");
	iHtmlRadioNow += "</td><td>";
	iHtmlRadioNow += eval(r_channels[i] + "_now_html");
	iHtmlRadioNow += "</td></tr>";
	iHtmlRadioNow = iHtmlRadioNow.replace(/<listenlink\/>/, "&nbsp;<a href=\"javascript:bbcRadioPlayer('"+r_channels[i]+"')\"><img src=\"http://www.bbc.co.uk/radio/aod/images/ico_audio.gif\" align=\"absMiddle\" border=\"0\" title=\"listen now\"></a>");

	iHtmlRadioNext += "<tr><td>";
        iHtmlRadioNext += eval(r_channels[i] + "_img");
	iHtmlRadioNext += "</td><td>";
	iHtmlRadioNext += eval(r_channels[i] + "_next_html");
	iHtmlRadioNext += "</td></tr>";
    }
    iHtmlRadioNow += "</table>";
    iHtmlRadioNext += "</table>";
    elResNowRadio.innerHTML = iHtmlRadioNow;
    elResNextRadio.innerHTML = iHtmlRadioNext;

        elRefreshHeader.style.display = 'none';

        // elBtn.style.display = 'block';
    
        // default view
        if (elBtnNowTV.className == "btn2" &&
            elBtnNextTV.className == "btn2" &&
    	    elBtnNowRadio.className == "btn2" &&
    	    elBtnNextRadio.className == "btn2") {

    	    var initShow = "TV";
    	    if (prefs.getString("init_view") == "TV") { initShow = "TV"; }
    	    if (prefs.getString("init_view") == "Radio") { initShow = "Radio"; }
    	    if (initShow == "TV" && prefs.getBool("hidetv") == true) { initShow = "Radio"; }
    	    if (initShow == "Radio" && prefs.getBool("hideradio") == true) { initShow = "TV"; }
    	    if (prefs.getBool("hideradio") == true && prefs.getBool("hidetv") == true) { alert("You have chosen to hide both TV and Radio, so there's nothing for me to show! You may want to change your preferences by clicking the edit link."); initShow = ""; }
    
    	    if (initShow == "TV") {
    	        elBtnNowTV.className = "btn";
    	    }
    	    if (initShow == "Radio")  {
    	        elBtnNowRadio.className = "btn";
            }
        }
    
        if (elBtnNowTV.className == "btn") {
            elResNowTV.style.display = 'block';
            elResNextTV.style.display = 'none';
            elResNowRadio.style.display = 'none';
            elResNextRadio.style.display = 'none';
        }
        if (elBtnNextTV.className == "btn") {
            elResNowTV.style.display = 'none';
            elResNextTV.style.display = 'block';
            elResNowRadio.style.display = 'none';
            elResNextRadio.style.display = 'none';
        }
        if (elBtnNowRadio.className == "btn") {
            elResNowTV.style.display = 'none';
            elResNextTV.style.display = 'none';
            elResNowRadio.style.display = 'block';
            elResNextRadio.style.display = 'none';
        }
        if (elBtnNextRadio.className == "btn") {
            elResNowTV.style.display = 'none';
            elResNextTV.style.display = 'none';
            elResNowRadio.style.display = 'none';
            elResNextRadio.style.display = 'block';
        }
        elRefreshHeader.innerHTML = "<p>Refreshing...</p>";
}

function addChannelId(channel_ids, channel_id) {
    if (channel_ids.length > 3) channel_ids += ",";
    channel_ids += channel_id;
    return channel_ids;
}

function NumberToString( number ) {
    if ( number < 10 ) {
        str = "0" + number;
    } else {
        str = number;
    }
    return str;
}

function stringToNumber( str ) {
    var num = 0;
    for (var i = 0; i<str.length; i++)
        num += (str.charCodeAt(i) - 48) * Math.pow(10, (str.length - i - 1) );
    return num;
}	

var prefs = new _IG_Prefs(__MODULE_ID__);

var api_root = 'http://www0.rdthdo.bbc.co.uk/cgi-perl/api/query.pl?';

// channels list
var tv_channels = new Array( 'BBCOne', 'BBCTwo', 'BBCThree', 'BBCFour', 'BBCCBBC', 'BBCCbeebies', 'BBCNewsTF', 'BBCParl');
var r_channels = new Array( 'BBCROne', 'BBCRTwo', 'BBCRThree', 'BBCRFour', 'BBCRFiveL', 'BBCRFiveX', 'BBCSixMU', 'BBCSeven', 'BBCAsian', 'BBCWrld', 'OneXtra' );
var all_channels = new Array( 'BBCOne', 'BBCTwo', 'BBCThree', 'BBCFour', 'BBCCBBC', 'BBCCbeebies', 'BBCNewsTF', 'BBCParl', 'BBCROne', 'BBCRTwo', 'BBCRThree', 'BBCRFour', 'BBCRFiveL', 'BBCRFiveX', 'BBCSixMU', 'BBCSeven', 'BBCAsian', 'BBCWrld', 'OneXtra' );

for (var i=0; i < all_channels.length; i++) {
    eval( "var " + all_channels[i] + "_now_html = \"retrieving...\";" );
    eval( "var " + all_channels[i] + "_next_html = \"retrieving...\";" );
    var imgsrc = '<a href="' + api_root + 'method=bbc.schedule.getProgrammes&amp;format=simple&amp;detail=schedule&amp;channel_id=' + all_channels[i] + '" target=\"_blank\"><img class="channel_logo" alt="' + all_channels[i] + ' logo" name="Get programme listing for this channel" src="http://www0.rdthdo.bbc.co.uk/services/api/res/images/'+all_channels[i]+'_small.gif"/></a>';
    eval( "var " + all_channels[i] + "_img = \'" + imgsrc + "\';" );

}

// check daylight saving 
var now = new Date();
var tzo = (now.getTimezoneOffset()/60)*-1;

var gsrc = document.getElementById("gsrc");
var elNav = document.createElement("div");

var elBtnNowTV = document.createElement("input");
elBtnNowTV.type = "submit";
elBtnNowTV.value = "TV now";
elBtnNowTV.className = "btn2";
AttachEvent(elBtnNowTV,"click",ShowNowTV,false); 

var elBtnNextTV = document.createElement("input");
elBtnNextTV.type = "submit";
elBtnNextTV.value = "TV next";
elBtnNextTV.className = "btn2";
AttachEvent(elBtnNextTV,"click",ShowNextTV,false); 

var elBtnNowRadio = document.createElement("input");
elBtnNowRadio.type = "submit";
elBtnNowRadio.value = "radio now";
elBtnNowRadio.className = "btn2";
AttachEvent(elBtnNowRadio,"click",ShowNowRadio,false); 

var elBtnNextRadio = document.createElement("input");
elBtnNextRadio.type = "submit";
elBtnNextRadio.value = "radio next";
elBtnNextRadio.className = "btn2";
AttachEvent(elBtnNextRadio,"click",ShowNextRadio,false); 

if (prefs.getBool("hidetv") == false) { elNav.appendChild(elBtnNowTV); }
if (prefs.getBool("hidetv") == false) { elNav.appendChild(elBtnNextTV); }
if (prefs.getBool("hideradio") == false) { elNav.appendChild(elBtnNowRadio); }
if (prefs.getBool("hideradio") == false) { elNav.appendChild(elBtnNextRadio); }

gsrc.appendChild(elNav);
var elRefreshHeader = document.createElement("div");
elRefreshHeader.innerHTML = "<p>Loading...</p>";
gsrc.appendChild(elRefreshHeader);
var elRefresh = document.createElement("div");
// var elBtn = document.createElement("input");
// elBtn.type = "submit";
// elBtn.value = "Refresh";
// elBtn.className = "btn";
// AttachEvent(elBtn,"click",RefreshTimer,false); 
var elCredits = document.createElement("span");
elCredits.innerHTML = "<div class=\"credits\">supported by <a href=\"http://backstage.bbc.co.uk\" target=\"_blank\">backstage.bbc.co.uk</a>  - using the <a href=\"http://www0.rdthdo.bbc.co.uk/services/api/index.html\" target=\"_blank\">BBC Web API</a></div>"; 

var elResNowTV = document.createElement("div");
elResNowTV.style.overflow="auto";
elResNowTV.style.height="310";
if (prefs.getBool("hidetv") == true) { elResNowTV.style.display = "none"; }
gsrc.appendChild(elResNowTV);
var elResNextTV = document.createElement("div");
elResNextTV.style.overflow="auto";
elResNextTV.style.height="310";
if (prefs.getBool("hidetv") == true) { elResNextTV.style.display = "none"; }
gsrc.appendChild(elResNextTV);
var elResNowRadio = document.createElement("div");
elResNowRadio.style.overflow="auto";
elResNowRadio.style.height="310";
if (prefs.getBool("hideradio") == true) { elResNowRadio.style.display = "none"; }
gsrc.appendChild(elResNowRadio);
var elResNextRadio = document.createElement("div");
elResNextRadio.style.overflow="auto";
elResNextRadio.style.height="310";
if (prefs.getBool("hideradio") == true) { elResNextRadio.style.display = "none"; }
gsrc.appendChild(elResNextRadio);

// elRefresh.appendChild(elBtn);
elRefresh.appendChild(elCredits);
gsrc.appendChild(elRefresh);
timer = setInterval(RefreshTimer,300000);  // auto-refresh every 5 minutes

var processedCh = 0;

getNowNext();
setInnerHTML();

// keep checking for the info having been passed by by the proxy
var t2 = setInterval(t_setInnerHTML,100);

</script>
]]>
</Content> 
</Module>
