//Array of HTML content describing each panel
var sectText = new Array();
sectText[1]='<p>The African Census Analysis Project (ACAP) is a collaborative initiative between the <a href="http://www.upenn.edu">University of Pennsylvania</a> and African institutions specializing in demographic research and training. This initiative was started as an effort to try and maximize the use of African census micro-data for academic and policy oriented research that will be beneficial both to African governments and individuals interested in African research.</p>';
sectText[2]='<style type="text/css">ul{margin-top:5px;margin-bottom:5px}</style><p>Upcoming Events:</p>\n<div id="agenda" style="font-size:15px "><p>Loading...</p></div>';
sectText[3]='<p>Census Data Quick Access:</p><form id="feedForm" action="censusLogin.php" method="post"><table width="100%"  border="0" cellspacing="0" cellpadding="0">\n<tr>\n<td align="right"><p>Service:</p></td>\n<td><select id="s" name="service" type="text"><option>Navigator</option><option>Guide</option><option>Explorer</option></td>\n</tr>\n<tr>\n<td align="right"><p>Login:</p></td>\n<td><input id="u" name="username" type="text"></td>\n</tr>\n<tr>\n<td align="right"><p>Password:</p></td>\n<td><input id="p" type="password" name="password"></td>\n</tr>\n<tr>\n<td>&nbsp;</td>\n<td><input type="submit" value="Submit"><input type="reset"></td>\n</table></form>';
//Array of URLs defining what page each panel links to
var sectLink = new Array();
sectLink[1]='about/';
sectLink[2]='events/';
sectLink[3]='census/';
var sect2Content = null;
var sect2IsSet = false;
/*var gCalXML = new Object();
function saveXML (root){
	gCalXML = root;
	insertAgenda(gCalXML);
}*/
//Sets which panel should be displayed and minimizes the other two
function setSection(tg){
	for(i=1;i<4;i++){
		td = document.getElementById('sect'+i);
		if(td.id == tg.id){
			td.style.cursor = "default";
			td.width = 340;
			table = '<table width="100%"  border="0" cellspacing="0" cellpadding="0">\n<tr>\n<td height="161" align="right" valign="bottom" style="cursor:default";><a href="'+sectLink[i]+'" style="text-decoration:none;"><p style="padding:6px;" class="panel">Read more...</p></a></td>\n</tr>\n<tr>\n<td style="border-bottom:1px solid #999; cursor:default " background="images/transpBack.png" class="transpBack">'+sectText[i]+'</td>\n</tr>\n</table>';
			td.innerHTML = table;
			td.onclick=null;
			if(i==2){
				/*if(document.getElementById('GCalScript')){
					
					insertAgenda(gCalXML);
				} else {*/
				if(sect2IsSet == false){
					//alert('goget');
					var e = document.createElement("script");
					e.id = 'GCalScript';
					e.src = 'http://www.google.com/calendar/feeds/info-acap@pop.upenn.edu/public/full?alt=json-in-script&callback=insertAgenda&orderby=starttime&max-results=3&singleevents=true&sortorder=ascending&futureevents=true';
					e.type="text/javascript";
					document.getElementsByTagName("head")[0].appendChild(e);
					sect2IsSet = true; 
				} else {
					td.innerHTML = sect2Content;
				}
				//}
			}
			if(i==3){
				fillForm();
			}
		} else {
			if((td.id == 'sect2')&&(sect2IsSet == true)&&(td.innerHTML != '&nbsp;')){
					//alert('boo');
					sect2Content = td.innerHTML;
				//sect2Content = td.innerHTML;
				//alert(sect2Content);
			}
			td.width = 84;
			td.innerHTML = '&nbsp;';
			td.style.cursor = "pointer";
			td.onclick=function(){setSection(this)};
		}
	}
}
/*Gets browser-saved login data from hidden fields filled on page load,
and copies content into dynamically created panel census login form*/
function fillForm(){
	var sF = document.getElementById('sourceForm');
	var fF = document.getElementById('feedForm');
	
	fF.s.value = sF.s.value;
	fF.u.value = sF.u.value;
	fF.p.value = sF.p.value;
}
/**
 * Converts an xs:date or xs:dateTime formatted string into the local timezone
 * and outputs a human-readable form of this date or date/time.
 *
 * @param {string} gCalTime is the xs:date or xs:dateTime formatted string
 * @return {string} is the human-readable date or date/time string
 */
function formatGCalTime(gCalTime) { 
  // text for regex matches
  var remtxt = gCalTime;

  function consume(retxt) {
    var match = remtxt.match(new RegExp('^' + retxt));
    if (match) {
      remtxt = remtxt.substring(match[0].length);
      return match[0];
    }
    return '';
  }

  // minutes of correction between gCalTime and GMT
  var totalCorrMins = 0;

  var year = consume('\\d{4}');
  consume('-?');
  var month = consume('\\d{2}');
  consume('-?');
  var dateMonth = consume('\\d{2}');
  var timeOrNot = consume('T');

  // if a DATE-TIME was matched in the regex 
  if (timeOrNot == 'T') {
    var hours = consume('\\d{2}');
    consume(':?');
    var mins = consume('\\d{2}');
    consume('(:\\d{2})?(\\.\\d{3})?');
    var zuluOrNot = consume('Z');

    // if time from server is not already in GMT, calculate offset
    if (zuluOrNot != 'Z') {
      var corrPlusMinus = consume('[\\+\\-]');
      if (corrPlusMinus != '') {
        var corrHours = consume('\\d{2}');
        consume(':?');
        var corrMins = consume('\\d{2}');
        totalCorrMins = (corrPlusMinus=='-' ? 1 : -1) * 
            (Number(corrHours) * 60 + 
	    (corrMins=='' ? 0 : Number(corrMins)));
      }
    } 

    // get time since epoch and apply correction, if necessary
    // relies upon Date object to convert the GMT time to the local
    // timezone
    var originalDateEpoch = Date.UTC(year, month - 1, dateMonth, hours, mins);
    var gmtDateEpoch = originalDateEpoch + totalCorrMins * 1000 * 60;
    var ld = new Date(gmtDateEpoch);

    // date is originally in YYYY-MM-DD format
    // time is originally in a 24-hour format
    // this converts it to MM/DD hh:mm (AM|PM) 
    dateString = (ld.getMonth() + 1) + '/' + ld.getDate() + ' ' + 
        ((ld.getHours()>12)?(ld.getHours()-12):(ld.getHours()===0?12:
	ld.getHours())) + ':' + ((ld.getMinutes()<10)?('0' + 
	ld.getMinutes()):(ld.getMinutes())) + ' ' + 
	((ld.getHours()>=12)?'PM':'AM');
  } else {
    // if only a DATE was matched
	ld = new Date(Date.UTC(year, month - 1, dateMonth));
    dateString =  (ld.getMonth() + 1) + '/' + (ld.getDate()+1);
  }
  return dateString;
}

/**
 * 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) {
  var feed = root.feed;
  var events = document.getElementById(divId);

  if (events.childNodes.length > 0) {
    events.removeChild(events.childNodes[0]);
  }	  

  // create a new unordered list
  var ul = document.createElement('ul');
  if(feed.entry == undefined){
  	document.getElementById("upcoming").innerHTML=" ";
  }
  

  // loop through each event in the feed
  for (var i = 0; i < feed.entry.length; i++) {
    var entry = feed.entry[i];
    var title = entry.title.$t;
    var start = entry['gd$when'][0].startTime;
	
	if(entry.content.$t == '') var content = '';
	else var content = ' - '+entry.content.$t;
	if(title.length > 38) title = title.substring(0,38)+'...';
	if(content.length > 80) content = content.substring(0,80)+'...';

    // 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'];
      }
    }

    var dateString = formatGCalTime(start);
    var li = document.createElement('li');

    // if we have a link to the event, create an 'a' element
    if (typeof entryLinkHref != 'undefined') {
      entryLink = document.createElement('a');
      entryLink.setAttribute('href', entryLinkHref);
      entryLink.appendChild(document.createTextNode(title));
      li.appendChild(entryLink);
      li.appendChild(document.createTextNode(' - ' + dateString + '\n ' + content));
    } else {
      li.appendChild(document.createTextNode(title + ' - ' + dateString + '\n' + content));
    }	    

    // append the list item onto the unordered list
    ul.appendChild(li);
  }
  events.appendChild(ul);
}

/**
 * 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) {
  agendaID = 'agenda';
  listEvents(root, agendaID);
}