google.load("gdata", "2.x");

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","include/cat.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML; 

var sundayTxt = "";
var catTxt = "";
var catArrows = "";
var catQandA = "";
var catechism=xmlDoc.getElementsByTagName("qanda");
var catIndex = 0;

function init()
{
  //Load sundaySchedule with HTML
 sundayTxt =
    "<h2>Sunday Schedule</h2>" +
    "<table><tr><td class=\"event\">Morning Worship</td>" +
    "<td class=\"time\">10:00 AM</td></tr>" +
    "<tr><td class=\"event\">Sunday School *</td>" +
    "<td class=\"time\">11:45 AM</td></tr>" +
    "<tr><td class=\"event\">Evening Worship *</td>" +
    "<td class=\"time\">6:00 PM</td></tr></table>" +
    "<span class=\"footnote\">* Except first Sunday of the month</span>";

  //initialize events list
  initEvents();
  
  //initialize catechism
  catTxt = "<div class=\"right_b\"><h2>Shorter Catechism Question</h2>";
  
  catArrows =  "<div class=\"right_text\">" +
  "<a href=\"javascript:previous()\"><b>&lt;&lt;</b></a>&nbsp;&nbsp;&nbsp;&nbsp;" +
  "<a href=\"javascript:next()\"><b>&gt;&gt;</b></a></div><br></div>";
  
  //pick a cat question based on day of year
  //  var today = new Date();
  //  var first = new Date(today.getFullYear(), 0, 1);
  //  var theDay = Math.round(((today - first) / 1000 / 60 / 60 / 24) + .5, 0);

  // Set to display question number 
  //  n = theDay % 107;
    n = 4; 
    
    found = false;
    while (catIndex<catechism.length && found == false) {
        num=(catechism[catIndex].getElementsByTagName("num")[0].childNodes[0].nodeValue);
        if (num == n) {
            setCat();
            found = true;
        }
        else {
            catIndex++;    
        }
    }
}

function setCat() {
  num=(catechism[catIndex].getElementsByTagName("num")[0].childNodes[0].nodeValue);
  question=(catechism[catIndex].getElementsByTagName("ques")[0].childNodes[0].nodeValue);
  answer=(catechism[catIndex].getElementsByTagName("ans")[0].childNodes[0].nodeValue);
  catQandA="<b>Question #" + num + ":</b>&nbsp;&nbsp;" + question + "<br /><b>Answer:</b>&nbsp;&nbsp;" + answer + "<br />";
}

function printCat() {
  document.getElementById("catechism").innerHTML= catTxt + catQandA + catArrows;
}

function next()
{
    if (catIndex < catechism.length-1) {
        catIndex++;
        setCat();
        printCat();        
    }
}

function previous()
{
    if (catIndex > 0) {
        catIndex--;
        setCat();
        printCat();                
    }
}

function initEvents() {
  // init the Google data JS client library with an error handler
  google.gdata.client.init(handleGDError);
  // load the code.google.com developer calendar
 loadMyCalendar();
}

/**
 * Loads the Google Developers Event Calendar
 */
function loadMyCalendar() {
  loadCalendarByAddress('e1m1hnv5s7jnnrd88806tnfne8@group.calendar.google.com');
}

/**
 * Adds a leading zero to a single-digit number.  Used for displaying dates.
 */
function padNumber(num) {
  if (num <= 9) {
    return "0" + num;
  }
  return num;
}

/**
 * Determines the full calendarUrl based upon the calendarAddress
 * argument and calls loadCalendar with the calendarUrl value.
 *
 * @param {string} calendarAddress is the email-style address for the calendar
 */ 
function loadCalendarByAddress(calendarAddress) {
  var calendarUrl = 'http://www.google.com/calendar/feeds/' +
                    calendarAddress + 
                    '/public/full';
  loadCalendar(calendarUrl);
}

/**
 * Uses Google data JS client library to retrieve a calendar feed from the specified
 * URL.  The feed is controlled by several query parameters and a callback 
 * function is called to process the feed results.
 *
 * @param {string} calendarUrl is the URL for a public calendar feed
 */  
function loadCalendar(calendarUrl) {
  var service = new 
      google.gdata.calendar.CalendarService('gdata-js-client-samples-simple');
  var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
  query.setOrderBy('starttime');
  query.setSortOrder('ascending');
  query.setFutureEvents(true);
  query.setSingleEvents(true);
  query.setMaxResults(10);

  service.getEventsFeed(query, listEvents, handleGDError);
}

/**
 * Callback function for the Google data JS client library to call when an error
 * occurs during the retrieval of the feed.  Details available depend partly
 * on the web browser, but this shows a few basic examples. In the case of
 * a privileged environment using ClientLogin authentication, there may also
 * be an e.type attribute in some cases.
 *
 * @param {Error} e is an instance of an Error 
 */
function handleGDError(e) {
  document.getElementById('jsSourceFinal').setAttribute('style', 
      'display:none');
  if (e instanceof Error) {
    /* alert with the error line number, file and message */
    alert('Error at line ' + e.lineNumber +
          ' in ' + e.fileName + '\n' +
          'Message: ' + e.message);
    /* if available, output HTTP error code and status text */
    if (e.cause) {
      var status = e.cause.status;
      var statusText = e.cause.statusText;
      alert('Root cause: HTTP error ' + status + ' with status text of: ' + 
            statusText);
    }
  } else {
    alert(e.toString());
  }
}


/**
 * Callback function for the Google data JS client library to call with a feed 
 * of events retrieved.
 *
 * Creates an unordered list of events in a human-readable form.  This list of
 * events is added into a div called 'events'.  The title for the calendar is
 * placed in a div called 'calendarTitle'
 *
 * @param {json} feedRoot is the root of the feed, containing all entries 
 */ 
function listEvents(feedRoot) {
  var entries = feedRoot.feed.getEntries();
  var eventDiv = document.getElementById('events');
  if (eventDiv.childNodes.length > 0) {
    eventDiv.removeChild(eventDiv.childNodes[0]);
  }	  
  /* set the calendarTitle div with the name of the calendar */
  /* loop through each event in the feed */

  var eventtxt = "<div class=\"right_b\"><h2>Upcoming Events</h2><table>";
  var len = entries.length;
  var j = 0;
  var guest = false;
  var guestPreacher = "";
  var guestDate = "";
  for (var i = 0; i < len; i++) {
    var entry = entries[i];
    var title = entry.getTitle().getText();
    var startDateTime = null;
    var startJSDate = null;
    var times = entry.getTimes();
    var description = entry.getContent().getText();
    
    if (times.length > 0) {
      startDateTime = times[0].getStartTime();
      startJSDate = startDateTime.getDate();
    }
    var entryLinkHref = null;
    if (entry.getHtmlLink() != null) {
      entryLinkHref = entry.getHtmlLink().getHref();
    }
    var dateString = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
    if (title != "Morning Worship" && title != "Sunday School"
        && title != "Evening Worship" && j < 5) {
    
      eventtxt = eventtxt + "<tr><td class=\"evt_title\"><a href=\"" + entryLinkHref +
          "&ctz=America/New_York" + "\">" + title +
          "</a></td><td class=\"date\">" + dateString + "</td></tr>";
      j++;
    }
    else {
      if (title == "Morning Worship" && guest == false) {
        guestPreacher = description;
        guestDate = dateString;
        guest = true;
      }
    }  
  }
  
  if (guest == true && guestPreacher.length > 0) {
    sundayTxt = "<div class=\"right_b\">" + sundayTxt +
          //"<hr class=\"horiz_line\" />" +
          "<div class=\"announcement\">" +
          guestPreacher + ", " + guestDate +
          "</div><br />";
  }
  else {
    sundayTxt = "<div class=\"right_b\">" + sundayTxt;
  }

  eventtxt = eventtxt + "</table><div class=\"right_text\"><a href=\"schedule.html\">Read more</a></div></div>";
  document.getElementById('sunday_schedule').innerHTML = sundayTxt;
  document.getElementById('events').innerHTML = eventtxt;
  printCat();

}

//google.setOnLoadCallback(init);
