var items = {};
var i = 0;

function getHeader(initiative) {

  $.getJSON("http://" + initiative + ".tumblr.com/api/read/json?callback=?", 
    function(data) {       		
        $.each(data.posts, function(i,posts){
          var type  = posts.type;
          var photo = posts["photo-url-500"];
          var post  = {};
          if(type == "photo") {
			
			break;
          }
        }); 
    }); 
}

function getTumblr(initiative) {

  $.getJSON("http://" + initiative + ".tumblr.com/api/read/json?callback=?", 
    function(data) {       
        var x = 0;
		var y = 0;
		var postcount = 0;
        var alt_class = "";

        $.each(data.posts, function(i,posts){
          var type  = posts.type;
          var date = new Date(posts.date).getTime(); 
          var url   = posts.url; 
          var photo = posts["photo-url-100"];
          var post  = {};
          post[date] = {};
          if(type == "photo") {
            post[date]['photo'] = photo;
            post[date]['url']   = url;
            post[date]['initiative'] = initiative;
            items = jQuery.extend(true, items, post);
          }
        }); 
        i++;
        if(i >= 4) {
          var sorteditems = sortByDate(items).reverse();
          $('.spinner').remove();
          for (var item in sorteditems) {
            x++;
            
            if(x>=5) {
              alt_class="";
              x=1;
            }
            else if (x>1)
            {
              alt_class=" alt";
            } 
            
			if (y< 16) {
            	$('#process .left').append('<div class="initiative' + alt_class + '"><a href="' + items[sorteditems[item]].url  + '"<img src="' + items[sorteditems[item]].photo + '"/><h3>' + items[sorteditems[item]].initiative + '</h3></div>');
        		y++;
			}
          }
        }
    });  
}

function sortByDate(posts) {

  var unsorted = [];
  var dates = {};
  for(var post in posts) {
    unsorted.push(post);
  }
  unsorted = unsorted.sort();
  var sorted = [];
  $.each(unsorted, function(){
    var newdate = new Date(parseInt(this));
    
    sorted.push(newdate.getTime());
  });
  return sorted;
}

$(document).ready(function(){ 
  getTumblr("velosynth");
  getTumblr("envvv");
  getTumblr("prgrssvnhncmnt");
  getTumblr("fabricating");
  getTumblr("spaceframe");
  getHeader("objcts");
});
