/**
 * charReplace function to fix IE6 related bug*
 * @param {textstring} string to be formatted
 */
function charReplace(textstring)
{
    // correcting apostrophe error in IE6 by replacing these below displayed characters with '
	textstring =  textstring.replace(/â€™/,"");
	textstring =  textstring.replace(/’/,"'");
	return textstring;
}

var win=null;
function NewWindow(mypage,myname,w,h,scroll){
var winl = (screen.width-w)/2;
var wint = (screen.height-h)/2;
var settings ='height='+h+',';
settings +='width='+w+',';
settings +='top='+wint+',';
settings +='left='+winl+',';
settings +='scrollbars='+scroll+',';
settings +='resizable=yes';
settings +='menubar=no';
win=window.open(mypage,myname,settings);
if(parseInt(navigator.appVersion) >= 4){win.window.focus();}
}

/**
 * Creates an unordered list of events in a human-readable form
 *
 * @param {json} root is the root JSON-formatted content from GData
 * @param {string} divId is the div in which the events are added
 */
function listEvents(root, divId) 
{
  // reading the feed from the root element
  var feed = root.feed;
  
  // reading events from agenda which is being passed by JSON code written in required asp page, in this case the object is divId
  var events = document.getElementById(divId);

  
  //Replace the tables current contents.   
  if (events.childNodes.length > 0) {
    events.removeChild(events.childNodes[0]);
  }

/* create a new Table */
  var tab = document.createElement('table');
  tab.border = 0;
  tab.className = "calendar";
  
  /* create a new TBODY */
  var tbdy = document.createElement('tbody');

/* create a new TBODY */
  var tbdy2 = document.createElement('tbody');

//Create a header row, add the Calendar title and add it to the Table.
  var headerRow = document.createElement('tr');
  var headerCell = document.createElement('th');
  headerCell.colSpan = 2;
  var calTitle = document.createElement('span');
  calTitle.appendChild(document.createTextNode(feed.title.$t));
  headerCell.appendChild(calTitle);
  headerRow.appendChild(headerCell);
  tbdy2.appendChild(headerRow);
  tab.appendChild(tbdy2);

 //Check if there are events in the feed
 if (typeof feed.entry != 'undefined') 
 {
  
  // loop through each event in the feed
  for (var i = 0; i < feed.entry.length; i++) 
  {
     /* get corresponding event */
    var entry = feed.entry[i];
     /* get title of the event */
    var title = entry.title.$t;
     /* get summary of event which includes datetime and event confirmation */
    var rawsummary	= entry.summary.$t;

     /* seprating datetime from any other text in summary feed */
    var summary = rawsummary.split("<br>");
    
    /* picking location from summary feed */
    var locationsummary = "";

    /* Identifying location feed from summary feed */
    var locationkeyword = 'Where:';

    //Location check
    var locationCheck = -1;


  // Extracting the location text out of the summary
    if (summary != null)
    {
        for (var isum = 0;isum < summary.length;isum++)
         {
	 
	  locationCheck = summary[isum].indexOf(locationkeyword); 

         // -1 means search did not find 'where:' keyword
         if (locationCheck != -1)
          {
          locationsummary = summary[isum];
          }
	 }

    }

    var summarytime = "";
    var summarydate = "";
    if (summary!=null)
    {
     /* replacing unwanted text in the summary feed to get date and time formatting right */
    summary[0]= summary[0].replace(/When:/,"");
    summary[0]= summary[0].replace(/&nbsp;/,"");
    summary[0]= summary[0].replace(/NZST/,"");
    //extract date and time out of summary-> Mon Apr 21, 2008 2:30pm to 5pm
    summarydate = summary[0].substring(0,17);
    /* extract time out of the summary*/
    summarytime = summary[0].substring(17,summary[0].length);
    }
    
   //Get the entire content feed
    var content = entry.content.$t;
    
   //Get DESCRIPTION text
    var descriptionfeed =content.split("Event Description:");
    var descriptiontext = "";
   
   //Get all content from content feed from DESCRIPTION onwards
   if (descriptiontext!=null)
    {
    descriptiontext = descriptionfeed[1];
    }
	
   //Get STATUS text
	var statusfeed =content.split("Event Status:");
	var statustext = "";
	
	//Get all content from content feed from STATUS onwards
    if (statustext!=null)
    {
    statustext = statusfeed[1];
	//statustext = statustext.replace(//,"")
    }
	
	//Get WHERE text
	var wherefeed =content.split("Where:");
	var wheretext = "";
	
	//Get all content from content feed from WHERE onwards
    if (wheretext!=null)
    {
    wheretext = wherefeed[1];
	}
	
    // get the URL to link to the event
    for (var linki = 0; linki < entry['link'].length; linki++) {
      if (entry['link'][linki]['type'] == 'text/html' &&
          entry['link'][linki]['rel'] == 'alternate') {
        var entryLinkHref = entry['link'][linki]['href'];
      }
    }

    //Create a row and two cells.
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    var td2 = document.createElement('td');

    // set alignment of these cells and width for first column of date and time
    td.align = "left";
	// make date and time left aligned,set their width and make the text bold
    td2.align = "left";
    td2.width = "30%";
	td2.style.verticalAlign = "text-top";
    td2.style.fontWeight="bold";
	
    // if we have a link to the event, create an 'a' element
    if (typeof entryLinkHref != 'undefined') 
    {
     
	  if(navigator.appName != "Microsoft Internet Explorer")
	  {
	  entryLink = document.createElement('a');
	  entryLink.setAttribute('onclick', 'return NewWindow("'+entryLinkHref+'","googlecal",600,300,"yes");');
	  entryLink.setAttribute('href', 'javascript:void(0);');
	  }
	  else
	  {
		entryLink = document.createElement('a');
	  	entryLink.setAttribute('href', entryLinkHref);
	  	entryLink.setAttribute('target', '_blank');
	  }
	  
      entryLink.appendChild(document.createTextNode(charReplace(title)));
      // append google calendar event URL
      td.appendChild(entryLink);
      
      if (descriptiontext !=null)
      {
      // To add new line between rpice tags and description
       var formatword=descriptiontext.split("*");
       for (var k = 0; k < formatword.length; k++)
       {
       td.appendChild(document.createElement("BR"));
       td.appendChild(document.createTextNode(charReplace(formatword[k])));
       }
      }
     
   if (locationsummary != null)
      {
        td.appendChild(document.createElement("BR"));
	td.appendChild(document.createElement("BR"));
	td.appendChild(document.createTextNode(charReplace(locationsummary)));
      }
 	
 	  if (summarydate!=null)
	 	{
	 	//To add new line before date
	 		 td2.appendChild(document.createElement("BR"));
	         td2.appendChild(document.createTextNode(summarydate));
	 	}
 
 	  if (summarytime!=null)
 	   {
 	   //To add new line between date and time
 		 td2.appendChild(document.createElement("BR"));
       	 td2.appendChild(document.createTextNode(summarytime));
 	   }
 	   
    } 
    else 
    {
    //Just incase if link fails,then we are displaying raw summary feed and title of the event
      td.appendChild(document.createTextNode(title));
      td2.appendChild(document.createTextNode(summary));
    }
    // append the list item onto the unordered list
    tr.appendChild(td2);
    // if you want more cells, just create them above and append them here.  
    tr.appendChild(td); 
    //use tbody to avoid IE6 bug with apostrophe
	tbdy.appendChild(tr);
    tab.appendChild(tbdy);
  }
 }
else
{
//To display information when there are no events in the calendar
  var headerRow1 = document.createElement('tr');
  var headerCell1 = document.createElement('td');
  headerCell1.colSpan = 2;
  var calTitle1 = document.createElement('span');
  calTitle1.appendChild(document.createTextNode("There are no scheduled events in the calendar. The calendar may yet to be updated. Please contact the Leisure Centre for more information."));
  headerCell1.appendChild(calTitle1);
  headerRow1.appendChild(headerCell1);
  tbdy2.appendChild(headerRow1);
  tab.appendChild(tbdy2);
}

  //adding table to the events
  events.appendChild(tab);
}

/**
 * Callback function for the GData json-in-script call
 * Inserts the supplied list of events into a div of a pre-defined name
 *
 * @param {json} root is the JSON-formatted content from GData
 */
function insertAgenda(root) 
{
  listEvents(root, 'agenda');
}


/*
Added the four centre insert calendar calls, require separate calls when loading all onto one page.
*/

function insertAgendaActiveZone(root) 
{
  listEvents(root, 'activezone');
}

function insertAgendaEcb(root) 
{
  listEvents(root, 'ecb');
}

function insertAgendaBirkenhead(root) 
{
  listEvents(root, 'birkenhead');
}

function insertAgendaBeachhaven(root) 
{
  listEvents(root, 'beachhaven');
}

function insertECBNSLDance(root) 
{
  listEvents(root, 'ecbnsldance');
}

function insertGlenfieldNSLDance(root) 
{
  listEvents(root, 'glenfieldnsldance');
}
