/* 022809b.js.
   This version works.   It pulls the announcements   And the events. */

window.onload=doEverything;
var xhr = false;

function doEverything() // Runs all functions.
				 {
				 choosePic();
				 makeRequest();
				 insertInfo();
				 }

function choosePic () // Randomizes the splash pic.
				 {
				 var splashPics = new Array ("bells", "chasuble", "crosses", "cruets"); // When I have more class names (and therefore more pictures), add them to this array.
				 var randomNum = Math.floor((Math.random()*4)); // multiply "Math.random()" by however many images are in the array above.
				 document.getElementById("splash").className = splashPics[randomNum];
				 }
				 
function makeRequest () // Sets up xhr as and XMLHttpRequest object, or its IE equivalent.
				 {
				 if (window.XMLHttpRequest)
				 		{
						xhr = new XMLHttpRequest();
						}
				 else
				 		{
						if (window.ActiveXObject)
							 {
							 try
							 		{
									xhr = newActiveXObject ("Microsoft.XMLHTTP");
									}
							 catch (e) {}
							 }
					  }
				 
				 if (xhr)
				 		{
						xhr.onreadystatechange = checkReadiness;
						xhr.open("GET", "master.xml"+"?cachebuster="+new Date().getTime(), true);  // This "cachebuster" nonsense is to make sure it retrieves a live, rather than cached, copy of the XML file.
						xhr.send(null);
						}
				 else
				 		{
						alert ("Couldn't create the XMLHttpRequest object.");
						}
				 }
				 
function checkReadiness ()
				 {
				 if (xhr.readyState==4)
				 		{
						if (xhr.status==200)
							 {
							 if (xhr.responseXML) //  && xhr.responseXML.contentType=="text/xml"  //That used to be a condition.  But for some reason, when I include it, we don't get to this code block.  And it seems to work fine without this condition...
							 		{
  							  var newTitle1 = xhr.responseXML.getElementsByTagName("title")[0].firstChild.nodeValue;
									}
							 else
							 		{
									alert("We're sorry, but your browser is not fully supported.  Some elements may not work correctly.");
									}
							 }
						else
						 	 {
							 alert("We're sorry, but your browser is not fully supported.  Some elements may not work correctly.");
							 }
						// And here's the meat: if everything's ready, run my AJAX functions.
						insertAnnouncement();
						insertBooks();						}


					}	 				 

function insertBooks()
	{

	// Needed: (1)item page url (2)img file (3)Title (4)Price
	// Begin by doing this for just one book, and statically; i.e. no XML yet.
	// Points of insertion: bookLink0, bookPic0, bookTitle0, bookPrice0.
	// Now that this works, loop it.
	// Now that this works, the scary bit: rather than getting the info statically, get it from the XML file.
	for (var i=0; i<3; i++)
		
		{
		var urlBlock = "http://www.trinstore.com/ecom_2/item_view.cfm?inventoryid="; // This bit goes on every item page url.
		var picBlock = "http://www.trinstore.com/ecom_2/inventoryImages/"; // This bit goes on every img url (with a ".jpg" suffix).
		var newItemNumber = xhr.responseXML.getElementsByTagName("item")[i].firstChild.nodeValue;
		document.getElementById("bookLink"+i).href = (urlBlock + newItemNumber);
		document.getElementById("bookPic"+i).src = (picBlock + newItemNumber + "_t.jpg");
		var newBookTitle = xhr.responseXML.getElementsByTagName("title")[i].firstChild.nodeValue;
		document.getElementById("bookTitle"+i).innerHTML = newBookTitle;
		var newBookPrice = xhr.responseXML.getElementsByTagName("price")[i].firstChild.nodeValue;
		document.getElementById("bookPrice"+i).innerHTML = newBookPrice;
		}
	}

function insertAnnouncement()
				 {
				 /*var newAnnouncementTitle = xhr.responseXML.getElementsByTagName("announcementTitle")[0].firstChild.nodeValue;				 var newAnnouncementBody = xhr.responseXML.getElementsByTagName("announcementBody")[0].firstChild.nodeValue;
				 document.getElementById("announcementTitle").innerHTML = newAnnouncementTitle;				 document.getElementById("announcementBody").innerHTML = newAnnouncementBody;*/
				 }
				 
/**
 * 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
    dateString =  parseInt(month, 10) + '/' + parseInt(dateMonth, 10);
  }
  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]);
  }	  


  // loop through each event in the feed
  for (var i = 0; i < 4; i++) {
    var entry = feed.entry[i];
    var title = entry.title.$t;
    var start = entry['gd$when'][0].startTime;

    // 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'];
	// Add timezone string to GET request -- hardcoding in "America/New_York."
	// This is so that, on the event page itself, the time will be displayed correctly.
	entryLinkHref = entryLinkHref + "&ctz=America/New_York";
      }
    }

    var dateString = formatGCalTime(start);
	
	//.. Create the paragraphs.
	var datePar = document.createElement('p');
	var titlePar = document.createElement('p');

    // Create an 'a' element
      entryLink = document.createElement('a');
      entryLink.setAttribute('href', entryLinkHref);
      entryLink.appendChild(document.createTextNode(title));
      
	//.. Style them.
	datePar.className = "gray-small-invert";
	titlePar.className = "black-feature-2";

	//.. Grab the info and append it to the paragraphs.
	datePar.appendChild(document.createTextNode(dateString));
	titlePar.appendChild(entryLink);
	
	//.. Append the paragraphs to the div.
	document.getElementById("fromGoogle").appendChild(datePar);
	document.getElementById("fromGoogle").appendChild(titlePar);


  }
}

/**
 * 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, 'fromGoogle');
}				 

