function twitterCallback2(twitters) {
  $("ul#twitter_update_list").css("display", "none");
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    }).replace(/\B#([_a-z0-9]+)/ig, function(hashtag) {
        return  hashtag.charAt(0)+'<a href="http://twitter.com/#!/search?q=%23'+hashtag.substring(1)+'">'+hashtag.substring(1)+'</a>';
    });
    statusHTML.push('<li><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li>');
  }
  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
  $("#twitter_update_list").fadeIn(1000);
}

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

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}

function tumblr_cb(data) {
  $("ul#clip_list").css("display", "none");
  var tmpl = {
    'link': '<p><a href="{{link-url}}">{{link-text}}</a><br/> (<i>{{date}}</i>) ' +
            '<a href="{{url-with-slug}}">#</a></p> {{{link-description}}}',
    'regular': '<p>(<i>{{date}}</i>) <a href="{{url-with-slug}}">#</a></p>{{{regular-body}}}',
    'conversation': '<p>{{conversation-title}} (<i>{{date}}</i>) <a href="{{url-with-slug}}">#</a></p>{{{conversation-text}}}',
    'video': '<p>(<i>{{date}}</i>) <a href="{{url-with-slug}}">#</a></p> {{{video-player}}} {{{video-caption}}}',
    'quote': '<p>{{{quote-source}}}<br/> (<i>{{date}}</i>) <a href="{{url-with-slug}}">#</a></p> {{{quote-text}}}',
    'text': '<p>{{{quote-source}}}<br/> (<i>{{date}}</i>) <a href="{{url-with-slug}}">#</a></p> {{{quote-text}}}',
    'photo': '<p>(<i>{{date}}</i>) <a href="{{url-with-slug}}">#</a></p>' +
            '<p class="tumble_item"><img class="tumble_img" src="{{{photo-url-500}}}"><br>{{{photo-caption}}}</p>'
  };

  $.each(data.posts, function(i,posts){
    try {
      var item = $("<li>").html(Mustache.to_html(tmpl[this.type], this)).attr('class', 'list_' + this.type);
      $("#tumblr_widget ul").append(item);      
    }
    catch(err) {
      console.log(err);
    }
  });

  $("#clip_list").fadeIn(1000);
}

function init_readmore(parent_tag) {
  // http://css-tricks.com/text-fade-read-more/

  var $el, $ps, $up, totalHeight;

  $(".read_more .button").click(function() {
    $("#twitter_div").remove();
    $("#tumblr_widget").remove();
      
    totalHeight = 0

    $el = $(this);
    $p  = $el.parent();
    $up = $p.parent();
    $ps = $up.find(parent_tag);

    // measure how tall inside should be by adding together heights of all inside paragraphs (except read-more paragraph)
    $ps.each(function() {
      totalHeight += $(this).outerHeight();
    });

    // this is the height of an H1
    totalHeight += $("#rss_widget h1").outerHeight() + $("#now_page_blog_title").outerHeight();

    $up
      .css({
        // Set height to prevent instant jumpdown when max height is removed
        "height": $up.height(),
        "max-height": 9999
      })
      .animate({
        "height": totalHeight
      });

    // fade out read-more
    $p.fadeOut();

    // prevent jump-down
    return false;
  });
}

function main() {

  var blog = true;
  var twitter = true;
  var tumblr = true;

  if (blog) {
    $(".post_prose").css("display", "none");
    $(".read_more .button").css("display", "none");
    $('.post_prose').simplerss({
      url:'/blog/feed/index.xml',
      html: '<div id="now_page_blog_title"><a href="{link}">{title}</a></div>{content}',
      wrapper: 'div',
      display: 0
    }).fadeIn(1000);
    $(".read_more .button").delay(1000).fadeIn(1000);

    init_readmore(".post_prose");    
  }

  if (twitter) {
    $.ajax({ 
          async: true,
          dataType: 'jsonp',
          url: "http://twitter.com/statuses/user_timeline/IanDennisMiller.json?count=5&callback=?", 
          jsonpCallback: "twitterCallback2"
      });    
  }

  if (tumblr) {
    $.ajax({
        async: true,
        dataType: 'jsonp',
        url: "http://iandennismiller.tumblr.com/api/read/json?num=5&callback=?", 
        jsonpCallback: "tumblr_cb"
    });
  }
}

$(document).ready(function () {    
    main();
});


