jQuery(function($){

    	// Setup UI
		$("div.page").hide();

		// Bind events to handle page switching via the main nav.
		$('ul#mainNav li a, #siteLogo a').live( "click", function(e){
			var $target = $(e.target);
		    vto.loadPage($target.attr("href"));
//		    elements.workspace.updatePageNav($target.attr("href"));
			e.preventDefault();
		});

        // If hash in URL then load that page, otherwise default to first page in nav
        if(window.location.hash) {
            vto.loadPage(window.location.hash);
        } else {
            $('ul#mainNav li:first a').trigger("click");
        }



        
        var url = "http://www.google.com/calendar/feeds/k20gdjk5se73d8te98qv8jjbd8@group.calendar.google.com/public/full?alt=json&callback=?";
		$.getJSON(url,
        function(data){
/*    			$.each(data, function(i, item) {
				$("#eventsList").append("<li>" + item.text.linkify() + " <span class='created_at'>" + relative_time(item.created_at) + "</span></li>");
			});
*/
        });


		var url = "http://twitter.com/status/user_timeline/bmorevegan.json?count=15&callback=?";
		$.getJSON(url,
        function(data){
/*
            <li id="status_7222591070" class="hentry u-juxton status">
              <span class="thumb vcard author"><a class="tweet-url profile-pic url" href="http://twitter.com/juxton"><img height="48" width="48" src="http://a3.twimg.com/profile_images/496765381/cookiehead_normal.jpg" class="photo fn" alt="Justin"/></a></span>  <span class="status-body">
                      <strong><a title="Justin" class="tweet-url screen-name" href="http://twitter.com/juxton">juxton</a></strong>
                  <span title="Justin&amp;rsquo;s tweets are protected." class="lock-icon"/>
                          <span class="actions"><div>      <a title="favorite this tweet" class="fav-action non-fav" id="status_star_7222591070">  </a>
            </div></span>
                    <span class="entry-content">Slave Scene and Nazi Dust are making me feel better.</span>
                    <span class="meta entry-meta">
                  <a href="http://twitter.com/juxton/status/7222591070" rel="bookmark" class="entry-date">
                    <span data="{time:'Thu Dec 31 04:55:06 +0000 2009'}" class="published timestamp">about 1 hour ago</span>
                  </a>
                  <span>from web</span>

                      </span>
              </span>
            </li>
*/

            // If tweet is not a reply, then parse json and create html
			$.each(data, function(i, item) {
			    if(item.in_reply_to_screen_name == null){
    				$("#tweets").append("<li class='tweet'>" +
    				        "<img class='thumb' src='" + item.user.profile_image_url + "' height='48' width='48' />" +
    				        "<strong>" + item.user.name + "</strong> " +
    				        item.text.linkify() +
    				        "<div class='meta'>" + relative_time(item.created_at) + "</div>" +
    				    "</li>");
    			}
			});
        });




});






var vto = {

	updatePageNav : function(hash){

		// highlight active page in page nav
/*		$('div#mainNav ul li').removeClass("active")
			.children()
			.filter("a[href$="+ hash +"]").parent().addClass("active");
*/
	},


	loadPage : function(hash){

	    // hide all pages, then show the requested page
        var pageName = hash + "Page";
		$("div.page").hide().filter(pageName).fadeIn();

        // update url with hash for page
        document.location.hash = hash;
	}	

};



















function insertAgenda(root) {
  listEvents(root, 'agenda');
}


/**
 * 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');

  // 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;

    // 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));
    } else {
      li.appendChild(document.createTextNode(title + ' - ' + dateString));
    }	    

    // append the list item onto the unordered list
    ul.appendChild(li);
  }
  events.appendChild(ul);
}


    	String.prototype.linkify = function() {
    		return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
        return m.link(m);
      });
     }; 
      function relative_time(time_value) {
    	  var values = time_value.split(" ");
    	  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
    	  var parsed_date = Date.parse(time_value);
    	  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    	  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    	  delta = delta + (relative_to.getTimezoneOffset() * 60);

    	  var r = '';
    	  if (delta < 60) {
    	    r = 'a minute ago';
    	  } else if(delta < 120) {
    	    r = 'couple of minutes ago';
    	  } else if(delta < (45*60)) {
    	    r = (parseInt(delta / 60)).toString() + ' minutes ago';
    	  } else if(delta < (90*60)) {
    	    r = 'an hour ago';
    	  } else if(delta < (24*60*60)) {
    	    r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
    	  } else if(delta < (48*60*60)) {
    	    r = '1 day ago';
    	  } else {
    	    r = (parseInt(delta / 86400)).toString() + ' days ago';
    	  }

    	  return r;
    }
    function twitter_callback ()
    {
    	return true;
    }
    
    




