var gCurrentProgObj = null; // object of currently selected programme in the schedule
var gCurrentDay = null; // the current day 0-6 set by clock
var gSchedulemenuObj = null; // menu object array
var gCurrentSelectedMenu = null; // the current selected schedule menu 0-6 equating to days
var gScheduleObj = []; // array holding schedule menu objects
var gCurrent_loaded_time = null; // server time loaded at start-up
var gCurrent_loaded_hour = null; // current hour 0-23
var gTimeNow = null; // current live date object fed by clock
var gTimeToNextServerCheck = 0; // count down to next time we check server for updates
var gCorrection = null; // time corrector value
var gTheminutes = null; // live minutes
var gServerLastChecked = null; // time at which the server was checked for changes
var timeID = null; // main clock loop timer
var gStartup = false;
var wotsplayingTick = 0; // keeps count of polling period for getting what's playing from server
var auctionUpdateTick = 0; // keeps count of polling period for auction system




	function setupAJAX() {
	if (window.XMLHttpRequest) {
	  // If IE7/8, Mozilla, Safari, etc: Uses native XMLHttpRequest
	var ajaxRequest = new XMLHttpRequest();
	return ajaxRequest;
	} else {
	if (window.ActiveXObject) {
	  // ...otherwise, use the ActiveX control for IE5.x and IE6 - do we need this anymore as we are not supporting these?
	 var ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
	 return ajaxRequest;
	  } else {
	alert("Sorry, this page won't work with this browser!\nYou need to upgrade to a recent version of\nFirefox, Safari, Opera or Internet Explorer.");
	
	  }
	 }
	}
	

	// displays current day's schedule on Schedule Page
	// called from menu on Home Page via specialJS system and from within this script
	function display_current_schedule(){
	if(top.window.location.hash != "#schedule.html") return;	// we are not currently showing Schedule Page so abort
	create_schedule_menu();
	gCurrentSelectedMenu = gCurrentDay; 
	latch_colour();
	display_schedule(gCurrentDay);
	displayData(gCurrentProgObj);
	}

	
	/** Schedule Menu in main page
	
	Don't run epg5.html directly in a browser as it will fail. It's for loading in an iframe
	
	
	**/
	
	function create_schedule_menu(){
	var navcontainerDiv = top.document.getElementById("navcontainerDiv");
	deleteprior(navcontainerDiv);
	gSchedulemenuObj = []; // reset
	var navlist = top.document.createElement("ul");// create unordered list element
	navlist.id = "navlist";
	for (var  i= 0; i <7; i++){
	var this_menu_obj = new schedule_menu_constructor(i); // create an li object
	gSchedulemenuObj.push(this_menu_obj); // push onto gSchedulemenuObj
	navlist.appendChild(this_menu_obj.li);
	}
	navcontainerDiv.appendChild(navlist);
	}
	
	function schedule_menu_constructor(i){
			var daylist = [
							["Monday",1],
							["Tuesday",2],
							["Wednesday",3],
							["Thursday",4],
							["Friday",5],
							["Saturday",6],
							["Sunday",0]
						  ];
							
			this.anchor = top.document.createElement("a");// create anchor
			this.anchor.href= "#";
			this.anchor.day = daylist[i][1];
			this.anchor.onclick = function() {select_schedule_menu(this); return false};
			this.anchor.onmouseout = function() {latch_colour();};
			this.anchor.onmouseover=function(){kill_schedule_menu_highlight(this);}; 
			this.li = top.document.createElement("li");
			var mytextnode = top.document.createTextNode(daylist[i][0]);
			this.anchor.appendChild(mytextnode);
			this.li.appendChild(this.anchor);
	}
			
	function select_schedule_menu(obj){
	gCurrentSelectedMenu = obj.day;
	obj.style.backgroundColor = "#369";
	display_schedule(obj.day);
	if (obj.day != gCurrentDay){
		deleteData();
		}else{
		displayData(gCurrentProgObj);
		}
	}
	
	function latch_colour(){
	for(var i = 0; i <7; i++) {
	if (gCurrentSelectedMenu == gSchedulemenuObj[i].anchor.day) {
		gSchedulemenuObj[i].anchor.style.backgroundColor = "#369";// change to light blue
		}
	}	
	}
	
	// kill highlight when mouse is over another item
	function kill_schedule_menu_highlight(){
	for(var i = 0; i <7; i++) {
		gSchedulemenuObj[i].anchor.style.backgroundColor = "";// kill to let CSS resume
	  }
	}
	
	/** Construct objects and import Schedule as iframe loads
		also used to re-import any changes found by polling the server every 10 minutes
		in this case the url is relative to the root and we need full path
	
	**/
	
	function get_schedule(){
	var url = "http://www.radiocaroline.co.uk/epg/get_full_prog_schedule.php";
	//var url = "http://192.168.0.100/~patrick/caroline_live_site/epg/get_full_prog_schedule.php";
	gScheduleObj = []; // clear in case we are reloading
	// get data from server and construct schecule objects
	var ajaxRequest = setupAJAX();// get XMLHttpRequest object
	var bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
	// we do a try here to catch if a user has left off the URL's leading 'www'
	try{
	ajaxRequest.open("GET", url+bustcacheparameter, true);
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			if (ajaxRequest.status == 200) {
			var returned_data = ajaxRequest.responseText;
			if(typeof returned_data != "string"){
			document.getElementById("showname").innerHTML = "Sorry, there was an error getting data";
			return; // abort
			}
			var day = returned_data.split('%%');// splits at each day
			if(day.length<7){
			document.getElementById("showname").innerHTML ="Sorry, there was an error";
			return; // abort	
			}
			for(var daynum = 0; daynum < 7; daynum++) {
			var sheduleObj = new sheduleObj_constructor(day[daynum]);
			gScheduleObj.push(sheduleObj); // push this show onto global obj making one obj for each day of the week
			}
			window.clearTimeout(timeID); // clear main clock loop
			start_clock();
			}else{
			document.getElementById("showname").innerHTML ="Sorry, there was an error";
			return; // abort
			}
			ajaxRequest = null;
		 }
	  }
	  ajaxRequest.send(null);
	  
		  }catch(e){
		 top.document.getElementById("showname").innerHTML ="Sorry, there was an error";
		 }
	}
	
	
	
	// makes a days schedule and sticks it in a tbody so we can swap them in and out of a table. We also make an array of progObj's to access.
	function sheduleObj_constructor(txt){
	var mytbody = top.document.createElement("tbody");// create table body	
	this.progArray = new Array; // array holding programme data
	var this_days_data = txt.split('&&');// splits full day at each show
				for(var j = 0; j < this_days_data.length-1; j++) {
				var progdata = this_days_data[j].split('|');//split at item delimiter
				this.progObj = new Object; // obj to add our values to
				this.progObj.prog_id = progdata[5]; // programme id number
				this.progObj.time = progdata[0]; // programmes time
				this.progObj.showname = progdata[1];// show name
				this.progObj.mail = progdata[2];// email address
				this.progObj.info = progdata[3];// info
				var mugshot = new Image();
				mugshot.src = progdata[4];// url of mugshot
				this.progObj.epgMug = mugshot; // image obj for EPG - only works within iframe
				this.progObj.mugshotURL = "epg/"+progdata[4]; // url needed for parent page as it can't use node created in iframe
				// add red bullet and its switching methods to progObj
				this.bullet = top.document.createElement("img");
				this.progObj.bullet = this.bullet; // tie bullet image with property in progOb so we can ultimately control it from outside
					this.bullet.src = "epg/images/red_bullet.png";
					this.bullet.style.display = "block";
					this.progObj.bulletOn = function(){
					this.bullet.style.display = "block";
					}
					this.progObj.bulletOff = function(){
					this.bullet.style.display = "none";
					}
				var mynewrow = top.document.createElement("tr");// create table row
				mynewrow.obj = this.progObj; // add obj to row so we can pass progObj via the onclick
				mynewrow.onclick = function() {displayData(this.obj);};
				if (j % 2 == 0) {
				mynewrow.style.backgroundColor="#ddd";		
				}else{
				mynewrow.style.backgroundColor="#eee";
				}
					// now create 4 cells for time, current show indicator, programme and email address
					for (var  k= 0; k <4; k++){
					var mynewcell = top.document.createElement("td");// create cell
					switch (k){
					case 0:
					var currenttext = top.document.createTextNode(this.progObj.time);// for prog time
					mynewcell.style.cssText = "padding-left: 10px; width: 40px;";
					mynewcell.appendChild(currenttext);// append text to cell
					break;
					case 1:
					mynewcell.width="20px"; // this is for red spot
					mynewcell.appendChild(this.progObj.bullet);
					break;
					case 2:
					var currenttext = top.document.createTextNode(this.progObj.showname); // for showname
					mynewcell.appendChild(currenttext);// append text to cell
					break;
					case 3:
					var newanchor = top.document.createElement("a"); // create <a> tag
					newanchor.href = "mailto:"+this.progObj.mail;
					var currenttext = top.document.createTextNode(this.progObj.mail); // for email addy
					newanchor.appendChild(currenttext);
					mynewcell.appendChild(newanchor);// append anchor to cell
					break;
					}
					mynewrow.appendChild(mynewcell);// append cell to row
			}
			mytbody.appendChild(mynewrow);
			this.progArray.push(this.progObj);
		  }
		  
	this.DOM = mytbody;	// this represents a table containing the whole day's schedule
	}
	
	
	
	function print_schedule_to_alert(){
	var schedule_string = "";
	for(var i = 0; i< gScheduleObj[gCurrentDay].progArray.length; i++) {
	schedule_string += gScheduleObj[gCurrentDay].progArray[i].showname + "\n";
	}
	alert(schedule_string);	
		
	}
							
							
	// place mugshot and info in area below schedule
	function displayData(obj){
	if(obj == null) return;
	var mugshotImage = top.document.getElementById("mugshotImage"); // node in main page
	mugshotImage.style.cssText = "width: 70px; height: 93px; border: 0; padding: 10px;";
	mugshotImage.src = obj.mugshotURL;
	top.document.getElementById("shownameDiv").innerHTML = obj.time +"<br />"+ obj.showname;
	top.document.getElementById("infoDiv").innerHTML = obj.info;
	}
	
	// get rid of data in area below schedule
	function deleteData(){
	top.document.getElementById("mugshotImage").src = "images/blank.jpg"; // fudge	
	var shownameDiv = top.document.getElementById("shownameDiv");	
	deleteprior(shownameDiv);
	var infoDiv = top.document.getElementById("infoDiv");	
	deleteprior(infoDiv);
	}
	
	
	// display current days schedule in table
	function display_schedule(day){
	if(isNaN(day) || gScheduleObj.length == 0) return;
	var scheduleTable = top.document.getElementById("scheduleTable");
	scheduleTable.style.cursor = "pointer";
	deleteprior(scheduleTable);
	for(var i = 0; i< gScheduleObj[day].progArray.length; i++) {
	gScheduleObj[day].progArray[i].bulletOff(); // make sure red spot is off
	}
	gCurrentProgObj.bulletOn(); // only turn red spot on for current show
	scheduleTable.appendChild(gScheduleObj[day].DOM);
	}
	
		
	// find gCurrentProgObj and then update on-air info in EPG display panel
	function display_epg_data(){
	gCurrentProgObj = null;
	var h = String(gCurrent_loaded_hour);
	var m = String (gTheminutes);
	var time_now = parseInt(h+m, 10); // convert to integer so we can easily compare it
	var showcount = gScheduleObj[gCurrentDay].progArray.length;
	for (var i=1; i< showcount; i++){
	var this_time =  gScheduleObj[gCurrentDay].progArray[i].time.replace(":", ""); // important: database uses colon as hours/minutes separator
	if (this_time > time_now){
	gCurrentProgObj = gScheduleObj[gCurrentDay].progArray[i-1];
	break;
	}
	if (gCurrentProgObj == null) gCurrentProgObj = gScheduleObj[gCurrentDay].progArray[showcount-1];// last show of the day
	}
	if (gCurrentProgObj != null){
	// Update EPG panel if we have a proper gCurrentProgObj (there is a bug somewhere that drops it)
	var epg_text = "Currently on-air:<br />"+gCurrentProgObj.showname+"<br /><a href='mailto:" +gCurrentProgObj.mail + "'>Send an e-mail</a>";
	document.getElementById("showname").innerHTML = epg_text;
	var epg_mugDiv = document.getElementById("epg_mug");
	deleteprior(epg_mugDiv);
	epg_mugDiv.appendChild(gCurrentProgObj.epgMug);
		/*if(gCurrentProgObj.showname == "Continuous Caroline Music"){
		top.slidedown('wots_playing');
		showingWotsPlaying = true;
		}else{
		top.slideup('wots_playing');
		showingWotsPlaying = false;
		} */
	}
	}
	
	function getWotsPlaying(){
	var ajaxRequest = setupAJAX(); // get XMLHttpRequest object
	var bustcacheparameter = "?"+new Date().getTime();
	var url = "../php/get_wotsplaying.php";
	ajaxRequest.open("GET", url+bustcacheparameter, true);
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
		if (ajaxRequest.status == 200) {
			top.document.getElementById("wots_playing").innerHTML = ajaxRequest.responseText;
			}
			ajaxRequest = null;
	      }
	    }
	   ajaxRequest.send(null); 
	}
	
	
	
	
	/** TEST & HELPER FUNCTIONS
	
	**/
	
	
	function write_log(text){
		return;
	var logDiv = top.document.getElementById('logDiv');
	var mytextnode = top.document.createTextNode(text);
	logDiv.appendChild(mytextnode);
	var mybr = top.document.createElement("br");
	logDiv.appendChild(mybr);
	}
	
	// duplicated from menu.js but running separately inside iframe
	function deleteprior(div){
	if(!div) return;
	while (div.firstChild){
    div.removeChild(div.firstChild);
 	}
	}
	
	///////////////////////////// Clock functions ///////////////////////////////////////////////////
	
	function start_clock(){
	var ajaxRequest = setupAJAX();// get XMLHttpRequest object
    var url = "check_for_updates.php"; // also gets server time
	var bustcacheparameter = "?"+new Date().getTime();
	ajaxRequest.open("GET", url+bustcacheparameter, true);
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			if (ajaxRequest.status == 200) {
			var splits = ajaxRequest.responseText.split("|");
			var t = splits[0]; // live server time
			gServerLastChecked = splits[1]; // passed on from check_for_updates.php
			top.emailSwitchState = (splits[2] == "1")? true : false; // pick up state from site prefs in database
			gTimeNow = new Date(t);
			gCorrection = (new Date() - gTimeNow);
			timeUpdate();
			gCurrentSelectedMenu = gCurrentDay; // needed for schedule menu highlighting
			display_epg_data();
			display_current_schedule();
       }else{
		//write_log("There was a server error");
		document.getElementById('showname').innerHTML = "An error occured<br />getting EPG data";	
	   }
	  }
	 }
	ajaxRequest.send(null); 
	}
	
	
	/* compute if we are in daylight saving time */
	
	function daylightSaving(){
	var dstinfo=new WhatDates(gTimeNow.getFullYear());
		with (dstinfo) {
  		currentYear = gTimeNow.getFullYear();
  		var startDST = new Date(currentYear,dstMonth1-1,dstMonth1Date,1,0);
  		var endDST   = new Date(currentYear,dstMonth2-1,dstMonth2Date,1,0);
  		if ((gTimeNow.getTime() > startDST.getTime()) && (gTimeNow.getTime() < endDST.getTime())) {
			var timeNowMs = gTimeNow.getTime();
			timeNowMs = timeNowMs + 3600000;
			gTimeNow.setTime(timeNowMs);
  		}
	 }
	}
	
	function WhatDates(year) {
	  	var thisYear = Math.round(parseInt(year));
		this.dstMonth1 = 3;
		this.dstMonth2 = 10;
		this.dstTime = 1;
		this.dstMonth1Date = (31-( Math.floor (thisYear * 5 / 4) + 4) % 7);
		this.dstMonth2Date = (31-( Math.floor (thisYear * 5 / 4) + 1) % 7);
		}
	
	 function timeUpdate() {
	 //Get current date
	 gTimeNow  = new Date(); // local time from computer
	 //Apply correction
	 var expdate = gTimeNow.getTime();
	 expdate -= gCorrection;
	 gTimeNow.setTime(expdate);
	 daylightSaving();
	 gCurrentDay = gTimeNow.getDay(); // set to number 0-6
	 // proceed to formatting hours, minutes and seconds
	 var thishour = gTimeNow.getHours();
	 if (thishour <10)   thishour = "0" + thishour;
	 if (thishour>=13) thishour-=12;
	 var meridian = (gTimeNow.getHours()>=12) ?  "pm" :  "am";
	 gTheminutes = gTimeNow.getMinutes();
	 if (gTheminutes < 10) gTheminutes = "0" + gTheminutes;
	 var theseconds = gTimeNow.getSeconds();
	 if (theseconds < 10) theseconds = "0" + theseconds;
	 var display_time = thishour+":"+gTheminutes+":"+theseconds+meridian+" (UK)";
	 if ((gTheminutes == "00") && (theseconds == "00")){
	 gCurrent_loaded_hour = gTimeNow.getHours();// bump up reference to last loaded hour
	 display_epg_data();
	 display_current_schedule();
	 write_log(gTimeNow+": Loaded data into view at Top of the Hour");
	 }
	 // if we are adrift by more than an hour we assume computer has just woken up
	 if (gCurrent_loaded_hour != gTimeNow.getHours()){
	 gCurrent_loaded_hour = gTimeNow.getHours();// set it now or we will cycle forever
	 write_log(gTimeNow+": Woken Up!");
	 display_epg_data();
	 setTimeout(display_current_schedule,2000); // allow time for internet connection to establish
	 }
	  /*auctionUpdateTick++;
	  if (top.window.location.hash == "#peoples_choice_auction.html" && auctionUpdateTick == 30){
		  auctionUpdateTick = 0; // reset
	 	 top.getAuctionDataForUpdate(false);
	  } */

	// We check the server for any changes every 10 minutes
	if (gTimeToNextServerCheck == 600){
	poll_server_for_changes("check_for_updates.php");
	gTimeToNextServerCheck = 0;//re-set
	}else{
	gTimeToNextServerCheck++;
	//top.document.getElementById('timenowDiv').innerHTML = "Server Check counter: "+gTimeToNextServerCheck;
	}
	document.getElementById('epg_time').innerHTML = display_time;
	//wotsplayingTick++; 
	//if(wotsplayingTick > 3) {
	//wotsplayingTick = 0; // 3 second counter
	//getWotsPlaying(); // get and display 'What's playing' data	
	//}
	timeID=window.setTimeout(timeUpdate,1000);
	}
	
	

	
	///////////////////////////// Check Server For Changes every 10 minutes ////////////////////////////////////////////////////////////////
	
	
	function poll_server_for_changes(url){
	var ajaxRequest = setupAJAX(); // get XMLHttpRequest object
	var bustcacheparameter = "?"+new Date().getTime();
	ajaxRequest.open("GET", url+bustcacheparameter, true);
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
		if (ajaxRequest.status == 200) {
			var splits = ajaxRequest.responseText.split("|");
			latestCheckTimeFromServer = splits[1];
			top.emailSwitchState = (splits[2] == "1")? true : false; // pick up state from site prefs in database
			write_log("Server Check at: "+new Date());
			write_log("Time saved on server is: "+latestCheckTimeFromServer+" Time at previous check was "+gServerLastChecked);
			if (gServerLastChecked != latestCheckTimeFromServer){
				write_log("Schedule changed! Reloaded at: "+new Date());	
				get_schedule(); // reboot clock and reload schedule
			}
			gServerLastChecked = latestCheckTimeFromServer; // set for next check in 10 mins time
			}else{
			document.getElementById('showname').innerHTML = "An error occured<br />getting EPG data";
			setTimeout(timeUpdate,3000);// reboot after 3 seconds
			//write_log("Error from poll_server_for_changes(): "+ajaxRequest.statusText);	
			}
			ajaxRequest = null;
	      }
	    }
	   ajaxRequest.send(null); 
	  }