//rounded corners
YUI({combine: true, timeout: 10000}).use("node",
function(Y) {
   var roundCorners = function(e) {
      var panels = Y.all('.rounded_panel');
      Y.each(panels, function(panel) {
        var tl = document.createElement("div");
        tl.className = 'corner_tl';
        panel.appendChild(tl);
        var tr = document.createElement("div");
        tr.className = 'corner_tr';
        panel.appendChild(tr);
        var bl = document.createElement("div");
        bl.className = 'corner_bl';
        panel.appendChild(bl);
        var br = document.createElement("div");
        br.className = 'corner_br';
        panel.appendChild(br);
      });
   }

 Y.on("domready", roundCorners);
});


// TopNav stuff
YUI({combine: true, timeout: 10000}).use("node",
function(Y) {

   var displaySubNav = function(e) {
      var menuID = this.get('id').substr(7);
      var subMenus = Y.all('.secondarynav');
      subMenus.setStyle('display', 'none');
      var selectedSubMenu = Y.one('#navmenu' + menuID);
      selectedSubMenu.setStyle('display', 'block');
      var topMenus = Y.all('.primarynav');
      topMenus.removeClass('active');
      var selectedTopMenu = Y.one('#navlink' + menuID);
      selectedTopMenu.addClass('active');
      var selectedTopMenuX = selectedTopMenu.get('offsetLeft');
      var selectedTopMenuWidth = selectedTopMenu.get('clientWidth');
      var selectedSubMenuWidth = selectedSubMenu.get('clientWidth');
      var selectedTopMenuCenter = 802-selectedTopMenuX-selectedTopMenuWidth/2;
      var selectedSubMenuRight = selectedTopMenuCenter-selectedSubMenuWidth/2;
      if (selectedSubMenuRight < -192) {
         selectedSubMenu.setStyle('right', '192px');
      } else if (selectedSubMenuRight + selectedSubMenuWidth > 802) {
         selectedSubMenu.setStyle('right', (800-selectedSubMenuWidth) + 'px');
      } else {
         selectedSubMenu.setStyle('right', parseInt(selectedSubMenuRight) + 'px');         
      }
   }

   var interceptLink = function(e) {
        e.preventDefault();
   }

   var loadTopNav = function(e) {
      Y.on("click", displaySubNav, ".primarynav");
      Y.on("click", interceptLink, ".primarynav");
   }

 Y.on("domready", loadTopNav);
});


// Homepage functions
var page_context;
var blogFormat = "short";
function initializeBlogFeedHome() {
  blogFormat = "long";
  page_context = 'home';
  initializeBlogFeed();
  page_context = 'events';
  initializeBlogFeed();
}
function initializeBlogEventFeed() {
  blogFormat = "long";
  page_context = 'volunteer';
  initializeBlogFeed();
}
function initializeEventsHome() {
  page_context = 'home';
  initializeEvents();
}


// Loads Latest on our Blog section
function initializeBlogFeed() {
  var containerID = "feed";
  if (page_context == 'home') {
		blogURL = "http://afacblog.wordpress.com/category/afac-info/feed/";
  } else if  (page_context == 'events') {
		blogURL = "http://afacblog.wordpress.com/category/events/feed/";
		containerID = "events";
  } else if  (page_context == 'volunteer') {
		blogURL = "http://afacblog.wordpress.com/category/volunteer/feed/";
		containerID = "events";
  } else {
		blogURL = "http://afacblog.wordpress.com/feed/";
  }
  var feed = new google.feeds.Feed(blogURL);
  feed.load(function(result) {
    if (!result.error) {
      var container = document.getElementById(containerID);
      if (container) {
      for (var i = 0; i < 1; i++) {
        var entry = result.feed.entries[i];
        var div = document.createElement("div");
        var date = new Date(entry.publishedDate);
        var h4 = document.createElement("h4");
        h4.appendChild(document.createTextNode(date.format('F j, Y')));
        div.appendChild(h4);
        var href = document.createElement("a");
        href.setAttribute('href', 'http://afacblog.wordpress.com/');
        href.setAttribute('target', '_blog');
        href.appendChild(document.createTextNode(entry.title));
        var h3 = document.createElement("h3");
        h3.appendChild(href);
        div.appendChild(h3);
        if (blogFormat == 'long') {
          var d2 = document.createElement("div");
          d2.innerHTML = entry.content;
          div.appendChild(d2);
        }
        container.appendChild(div);
      }
      }
    }
  });
}


function initializeEvents() {
  // init the Google data JS client library with an error handler
  google.gdata.client.init(handleGDError);
  // load the code.google.com developer calendar
  loadCalendarByAddress('afac.org_7uo9kgp5p40si89loqrvo47v38%40group.calendar.google.com');
}

/**
 * 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'.
 *
 * @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]);
   }
  /* loop through each event in the feed */
  var len = entries.length;
  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();
    if (times.length > 0) {
      startDateTime = times[0].getStartTime();
      startJSDate = startDateTime.getDate();
      endDateTime = times[0].getEndTime();
      endJSDate = endDateTime.getDate();
    }
    var entryLinkHref = null;
    if (entry.getHtmlLink() != null) {
      entryLinkHref = entry.getHtmlLink().getHref() + '&KeepThis=true&TB_iframe=true&height=310&width=592';
    }

   var div = document.createElement("div");
   var startdate = new Date(startJSDate);
   var enddate = new Date(endJSDate);
   var h4 = document.createElement("h4");
	var starttext = startdate.format('F j, Y');
	var endtext = enddate.format('F j, Y');
	var datetext = starttext;
	//Set 1 day in milliseconds
	var one_day = 1000*60*60*24;
	if (Math.ceil((enddate.getTime()-startdate.getTime())/(one_day)) > 1) {
		datetext = starttext + ' - ' + endtext;
	}
   h4.appendChild(document.createTextNode(datetext));
   div.appendChild(h4);
   var href = document.createElement("a");
   href.setAttribute('href', entryLinkHref);
   href.setAttribute('class', 'event_thickbox');
   href.setAttribute('target', 'event');
   href.appendChild(document.createTextNode(title));
   var h3 = document.createElement("h3");
   h3.appendChild(href);
   div.appendChild(h3);
/*
    if (page_context == 'home') {
     var p = document.createElement("p");
     p.innerHTML = entry.getContent().getText();
     div.appendChild(p);
   }
*/
   eventDiv.appendChild(div);
  }
//  tb_init('a.event_thickbox');
}


// Simulates PHP's date function
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar]) {
			returnStr += replace[curChar].call(this);
		} else {
			returnStr += curChar;
		}
	}
	return returnStr;
};
Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 11 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return "Not Yet Supported"; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() % 12 || 12; },
	G: function() { return this.getHours(); },
	h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
	T: function() { return "Not Yet Supported"; },
	Z: function() { return this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return "Not Yet Supported"; },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
};
