

	var toMove;
	var toMoveTimeline;
 
   $(document).ready(function(){
   
	toMove = document.getElementById('epgCanvas');
	toMoveTimeline = document.getElementById('epgTimeline');
   
 	$('#epgCanvas').empty();
	buildTimeline(0);
    buildServices();
	positionNowBar();
	
	// create listeners for zoom in/out controls and other control buttons
	$('#epgGlass').bind('mousewheel', function(e,d){
		if (d>0) epgZoom('in');
		if (d<0) epgZoom('out');
		return false;
	});
	$('#epgZoomIn').click(function(){ epgZoom('in'); });
	$('#epgZoomOut').click(function(){ epgZoom('out'); });
	$('#epgGotoNow').click(function(){
		now = new Date();
		var offset = 0 - (now.getHours()*60+now.getMinutes())*pixelsPerMinute;
		offset = offset + getFrameWidth()/2
		moveToPosition(toMove,offset,null,toMoveTimeline, true);
		return false;
	});
	$('#epgPrevDay').click(function(){
		moveToPosition(toMove,curX+pixelsPerMinute*60*24,null,toMoveTimeline, true);
		return false;
	});
	$('#epgPrev').click(function(){
		moveToPosition(toMove,curX+pixelsPerMinute*60*4,null,toMoveTimeline, true);
		return false;
	});
	$('#epgNext').click(function(){
		moveToPosition(toMove,curX-pixelsPerMinute*60*4,null,toMoveTimeline, true);
		return false;
	});
	$('#epgNextDay').click(function(){
		moveToPosition(toMove,curX-pixelsPerMinute*60*24,null,toMoveTimeline, true);
		return false;
	});
	
	//bind events to the mouse moving around the Glass layer
	$('#epgGlass').bind("mousedown", function(e){setClickPos(e, toMove, toMoveTimeline)} );
	$('#epgGlass').bind("mouseup", function(e){mouseup(e, toMove, toMoveTimeline)} );
	$('#epgGlass').bind("mousemove", function(e){moveTarget(e, toMove, toMoveTimeline)} );
	
  });
 
 
  clickposx = 0;
  clickposy = 0;

  scrollstartleft = 0;
  scrollstarttop = 0;

  ismousedown = false;

  maxleft = 0;
  maxtop = 0;
  
  curX = 0;
  curY = 0;
 


// this sets the horizontal scale of the rendered schedule
	var pixelsPerMinute = new Number(2);
// this sets the vertical spacing between the services
	var pixelsPerService = new Number(70);
// this holds an array of every element in the canvas
	var epgElements = new Array(new Array()); // with blank 0 array for 'today'
// this holds an array of the services to get
	var epgServices = new Array("radio1", "radio2", "radio3", "radio4", '6music');


	
  function setClickPos(event, targetDiv) {
    clickposx = event.screenX;
    clickposy = event.screenY;
    scrollstartleft = parseInt(targetDiv.style.left);
    scrollstarttop = parseInt(targetDiv.style.top);
    var framingDiv = document.getElementById("epgFrame");
    maxleft = parseInt(targetDiv.style.width) - parseInt(framingDiv.style.width);
    maxtop = parseInt(targetDiv.style.height) - parseInt(framingDiv.style.height);
    ismousedown = true;
  }


  function mouseup(event, target, timeline) {
	//if (event.screenX == clickposx && event.screenY == clickposy) alert('that was a click not a drag');
	ismousedown = false;
	fillCanvas();
  }

function positionNowBar(){
	
	//alert(new Date());
	var now = new Date();
	var offset = (now.getHours()*60+now.getMinutes())*pixelsPerMinute;
	
	$('#epgNowBar').css("left", offset);
	$('#epgNowBar').show();
	setTimeout("positionNowBar()",60000); // run this every minute
}

	function fillCanvas(){
	
		// this function interrogates the current viewport of the canvas, and check which days
		//  should be viewable, checks to see if they exist, and loads new data if not present
		
		var frameWidth = getFrameWidth();
		var dayWidth = pixelsPerMinute*60*24;

		
		var leftEdge  = Math.floor(((dayWidth-curX)/dayWidth)-1);
		var rightEdge = Math.floor(((dayWidth-curX+frameWidth)/dayWidth)-1);
		var i = leftEdge;
		for( var i=leftEdge; i<=rightEdge; i++){
			//check to see if this dayOffset exists on the canvas 
			if (!epgElements[i]){
				epgElements[i] = new Array();
				$(epgServices).each(function(j){
					// create an array for each service's data in the epgElements array
					epgElements[i][j] = new Array();
					getScheduleData(i,j);
				});	
			};
		}
		
	
	}

  function moveTarget(event, target, timeline) {
    if (ismousedown == true) {
      var newposx = event.screenX;
      var newposy = event.screenY;
      var difx = newposx - clickposx;
      var dify = newposy - clickposy;
      var newleft = scrollstartleft + difx;
      var newtop = scrollstarttop + dify;
      if (newtop > 0) { newtop = 0; }
      moveToPosition(target, newleft, newtop, timeline);
    }
  }

  function moveToPosition(target, x, y, timeline, animate) {
    
	var done = 0;
	
	var fill = function(){ if(done>2) fillCanvas(); }

	if (y==null) y=curY;
	if (x==null) x=curX;
	if(animate==true){
		$(target).animate({left:x,top:y}, function(){  done++; fill(); });
		$(timeline).animate({left:x}, function(){  done++; fill(); });
		$('#epgNow').animate({left:x}, function(){  done++; fill(); });
		curX = x;
		curY = y;
		$('#draggable_offset_x').html(x+'px');
		$('#draggable_offset_y').html(y+'px');
	}
	else{
		target.style.left = "" + x + "px";
    	target.style.top = "" + y + "px";
		timeline.style.left = "" + x + "px";
		$('#epgNow').css("left", x);
		curX = x;
		curY = y;
		$('#draggable_offset_x').html(x+'px');
		$('#draggable_offset_y').html(y+'px');
	}
	
	
	
 	//
  }
  
  // THATS THE OLD CODE HERES SOME NEWER STUFF
  

  
  function epgZoom(dir){
  	
	// update our scale variable
	var old = pixelsPerMinute;
	var change = 0;
	if (dir=='in') change=old*0.2//change = 0.2;
	if (dir=='out') change=0-(old*0.2)//change = -0.2;
	pixelsPerMinute = pixelsPerMinute + change;
	pixelsPerMinute = Math.round(pixelsPerMinute*10);
	pixelsPerMinute = pixelsPerMinute/10;
	if (pixelsPerMinute<=0.4) pixelsPerMinute = 0.4;
	$('#pixels_per_minute').html(pixelsPerMinute);

	
	// now we've set the new value, recalculate all blocks on the canvas
	// first each day
	$(epgElements).each(function(h){
		// then each service
		$(epgElements[h]).each(function(i){
			
			var serviceKeyname = epgServices[i];
			//alert(epgElements.min);
			//$('#'+serviceKeyname+'-'+dayOffset).css("left", pixelsPerMinute*60*24*dayOffset+'px');
			
			// finally each element
			$(epgElements[h][i]).each(function(j){
				var newPos = ((this[2].getHours()*60)+this[2].getMinutes()) * pixelsPerMinute; 
				var newWidth = Math.round(this[1]/60*pixelsPerMinute);
				$('#element-'+h+'-'+i+'-'+j).css("left", newPos);
				$('#element-'+h+'-'+i+'-'+j).width(newWidth);
				
			})
		})
	})
	
	// and now recalculate the Timeline Scale
	$('#epgTimeline ol').each(function(i){
		// get every timeline day
		var dayOffset = this.id.substr(12);
		$('#epgTimeline-'+dayOffset+' li').each(function(j){
			this.style.left = dayOffset*pixelsPerMinute*60*24 + j*pixelsPerMinute*60;
		})
	})
	
	// and now move the NowBar
	positionNowBar();
	
	// and now move the canvas in the X direction so that we're still centered where we were before
	var halfWidth = getFrameWidth() / 2;
	
	// recenter the canvas to appear like we're zooming into the center of where we were before
	var oldTimeCentered = (curX-halfWidth) / old ;
	var newTimeCentered = (oldTimeCentered * pixelsPerMinute) + halfWidth
	moveToPosition(toMove, Math.round(newTimeCentered), null, toMoveTimeline, false)

	// redraw the canvas
	fillCanvas();
	
	return false; // to block default action of link click
	
  }
  
  function getFrameWidth(){
  	var frameWidth = $('#epgFrame').css("width");
	return new Number(frameWidth.substr(0,frameWidth.length-2));
  }
  
  function getScheduleData(dayOffset,serviceId){
  
	  var serviceKeyname = epgServices[serviceId];
	 
	  // check a timeline for this dayOffset exists, if not, create one
	  if( !$('#epgTimeline-'+dayOffset).length>0 ) buildTimeline(dayOffset);
	  
	  // add a new ul for this day's data, show a spinner and place it correctly on the canvas
	  $('#'+serviceKeyname).append('<ul id="'+serviceKeyname+'-'+dayOffset+'" />');
	  $('#'+serviceKeyname+'-'+dayOffset).css("left", pixelsPerMinute*60*24*dayOffset+'px');
	  $('#'+serviceKeyname+'-'+dayOffset).append('<li class="epgLoader"><span>Loading...</span></li>');
			  
	  var dataUrl = serviceKeyname+".json";
	  dataUrl = 'programmes.php?n='+serviceKeyname+'&d='+dayOffset;
	  $.getJSON(dataUrl,
			function(data){
				 
			  $.each(data.schedule, function(i,sched){
			  // add a new ul for this data and hide it
			 
			  $('#'+serviceKeyname+'-'+dayOffset).empty();
			  $('#'+serviceKeyname+'-'+dayOffset).hide();
				
				$.each(sched.broadcasts, function(j,prog){
					var start = new Date();
					start.setISO8601(prog.start);
					var end = new Date();
					end.setISO8601(prog.end);
					var startPixels = ((start.getHours()*60)+start.getMinutes()) * pixelsPerMinute;
					if(prog.episode.brand) prog.episode.title = prog.episode.brand.title
					prog.startPixels = startPixels;
					prog.startStamp = start;
					prog.endStamp = end;
					
					// add this to the epgElements array of programme data
					epgElements[dayOffset][serviceId][j] = new Array(prog.episode.title, prog.duration, start, end);
					
					// plot this element on the canvas
					broadcast_plot(dayOffset, serviceId, j, prog);
					
					
				});
				// fade in this services row on the canvas
				$('#'+serviceKeyname+' ul').fadeIn(1500);
			  });
			});
	};

		
		broadcast_plot = function(dayOffset, serviceId, elementId, prog){
			// plot an element on the canvas
			$('#'+epgServices[serviceId]+'-'+dayOffset).append('<li id="element-'+dayOffset+'-'+serviceId+'-'+elementId+'" style="left:'+prog.startPixels+'; width:'+Math.floor(prog.duration/60*pixelsPerMinute)+'px"><div><a href="#">'+prog.episode.title+'</a> ('+prog.duration/60+' mins)<br />'+prog.episode.short_synopsis+'</div></li>');
		};
		
		function buildTimeline(dayOffset){
			
			// plot the timeline on it's layer
			 $("#epgTimeline").append('<ol style="left: '+dayOffset*pixelsPerMinute*60*24+'" id="epgTimeline-'+dayOffset+'"><li><span>12am</span></li><li>1am</li><li>2am</li><li>3am</li><li>4am</li><li>5am</li><li>6am</li><li>7am</li><li>8am</li><li>9am</li><li>10am</li><li>11am</li><li>12pm</li><li>1pm</li><li>2pm</li><li>3pm</li><li>4pm</li><li>5pm</li><li>6pm</li><li>7pm</li><li>8pm</li><li>9pm</li><li>10pm</li><li>11pm</li></ol>');
			 $('#epgTimeline-'+dayOffset+' li').each(function(i){
				this.style.left = (dayOffset*pixelsPerMinute*60*24) + i*pixelsPerMinute*60;
			 });
			 
		};
		
		function buildServices(){
					
			$(epgServices).each(function(i){
				// create an array for each service's data in the epgElements array
				epgElements[0][i] = new Array();
				// create a horizonal diz for each service, and fill it with today's schedule data
				var fromTop = i*pixelsPerService;
				$('#epgCanvas').append('<div class="service" id="'+this+'" style="top:'+fromTop+'px"></div>')
				getScheduleData(0,i);
			});	
		};
		
