function toTimestamp(strDate){
 var datum = Date.parse(strDate);
 return datum/1000;
}
function toTimestampshizzle(year,month,day,hour,minute,second){
   var datum = new Date(Date.UTC(year,month-1,day,hour,minute,second));
   return datum.getTime()/1000;
}
function linkTwitter(text) {
	return text.replace(/http:\/\/\S+/g,  '<a href="$&" target="_blank">$&</a>').
      replace(/@([a-zA-Z0-9äöÅÄÖ]+)/g,    '<a href="http://twitter.com/$1" target="_blank">@$1</a>').
      replace(/#([a-zA-Z0-9åäöÅÄÖ]+)/g,    '<a href="http://search.twitter.com/search?q=%23$1" target="_blank">#$1</a>'
    );
}
var htmlToFragment = function(html)
{
    var retval = document.createDocumentFragment();
    var currentParent = retval;

    HTMLParser(html,
    {
        start : function(tag, attrs, unary)
        {
            var node = document.createElement(tag);
            for (var i = 0 ; i < attrs.length ; i++)
                node.setAttribute(attrs[i].name, attrs[i].value);
            currentParent.appendChild(node);
            if (!unary)
                currentParent = node;
        },

        end : function(tag)
        {
            currentParent = currentParent.parentNode || retval;
        },

        chars : function(text)
        {
            currentParent.appendChild(document.createTextNode(text));
        },

        comment : function(text)
        {
            currentParent.appendChild(document.createComment(text));
        }
    });

return retval;
};
$.fn.safeHtml = function(html)
{
    // This is a workaround for bug #336, also seen in:
    // http://blog.johnmckerrell.com/2007/03/07/problems-with-safari-and-innerhtml/
    for (var i = 0 ; i < this.length ; i++)
    {
        var element = this[i];
        element.innerHTML = html;
        if (html != "" && element.childNodes.length < 1)
            element.appendChild(htmlToFragment(html));
    }

    return this;
};

var jQueryHtml = $.fn.html;
$.fn.html = function(html)
{
    if (typeof(html) != "string" || arguments.length != 1)
        return jQueryHtml.apply(this, arguments);
    return this.safeHtml(html);
};
var lastWord = function(o) {
  var date = (""+o).replace(/[\s-]+$/,'').split(/[\s]/).pop();
  var last = (""+date).replace(/[\s-]+$/,'').split(/[\s-]/);
  meep = last[0] + '-' + last[1] + '-'  + last[2];
  var de = (""+meep).replace(/[\s-]+$/,'').split(/[\sT]/);
  return de[0] + '-' + de[1];
};
function getTwitter(f) {
	$.getJSON("http://twitter.com/statuses/user_timeline.json?screen_name=martnu&count=10&callback=?", function(tweetdata) { 
    var arr = new Array();
    $.each(tweetdata, function(i,v) {
      feedobj = new Object();
      feedobj.date = toTimestamp(v.created_at);
      feedobj.body = linkTwitter(v.text);
      arr.push(feedobj)
    })

	  if (typeof f == "function") f(arr);
	});
}
function getLoopcam(f) {
  $.getJSON("http://loopc.am/api/read/json?tagged=martnu&num=5&filter=none&callback=?", function(loopcamdata) {
    var arr = new Array();
    $.each(loopcamdata.posts, function(i,v) {
      feedobj = new Object();
      feedobj.date = v['unix-timestamp'];
      feedobj.body = v['regular-body'];
      arr.push(feedobj);
    })
    if (typeof f == "function") f(arr);
	});
}
function getInstagram(f) {
  var instA = new Array(11);
  $.ajax({
      url: 'http://instagram.heroku.com/users/2764.atom',
      type: 'GET',
      success: function(res) {
        var inst = $(res.responseText);
        c = 0;
        for(i=7;i<=2*10+7;i=i+2) {
          instA[c] = new Array(3);
          instA[c][0] = $(inst[i]).html();
          c++;
        }
        c = 0;
        for(k=47;k<=88;k=k+4) {
          instA[c][1] = $(inst[k]).html(); 
          instA[c][2] = $(inst[k+2]).html();
          c++;
        }
        var arr = new Array();
        $.each(instA, function(i,v) {   
          date = lastWord(v[1]).split('-');
          timeN = date[3].split(':');
          newdate = toTimestampshizzle(date[0], date[1], date[2], timeN[0], timeN[1]+1, timeN[2]);
          if(!isNaN(newdate)) {
            feedobj = new Object();
            feedobj.date = newdate;
            feedobj.body = v[2] + '<br>' + v[0];
            arr.push(feedobj);
          }
        });
        if (typeof f == "function") f(arr);
      }      
  });
}

function compare(a,b) {
  if (a.date > b.date)
     return -1;
  if (a.date < b.date)
    return 1;
  return 0;
}

$(function() {
var windowheight = window.innerHeight;
$("#feed").css('min-height',  windowheight - 200);

$("span.timeago").timeago();
$("#hand").fadeIn(2000);
$("#hand").click(function() {
  window.scrollTo(0,60);
});
$.ajaxSetup({ cache: false });
var didScroll = false;
//change later
var once = false;
  
  $(window).scroll(function() {
      if(!once) { 
        $("#hand").fadeOut('fast');
        $('#feed').append('<div id="ajax"></div>');
        once = true;
    	  getTwitter(function(twitter) {
          getLoopcam(function(loopc) {
        	  getInstagram(function(insta) {
        	    $("#ajax").slideUp('fast');
        	    $("#twitter").fadeIn(2000);
              $.merge(twitter, loopc); 
              $.merge(twitter, insta);
              total = twitter;
              total.sort(compare);    
              $.each(total, function(i,v) {
                var elem = $('<li><span class="timeago" title="' + v.date + '">' + v.date + '</span>' + v.body + '</li>').hide();
                $('#feed').append(elem.fadeIn(500));
              });
              $("span.timeago").timeago();
          	});
        	});
      	});
      }
  });

  

	
	
	
	

/*	
	$.each(twitter, function(i,v) {
	  dump(v);
	  console.log(v);
	});
/*	$.each(loopcam, function(i,v) {
	  dump(v);
	});
	$.each(instagram, function(i,v) {
	  dump(v);
	});
	*/
})




