/**
 * Helpers
**/
// Write a flash message
function flash(message)
{
  $("#flashes")
    .html($('<p class="notice">' + message + '</p>'))
    .removeClass('empty')
    .pause(3000)
    .fadeOut(2000)
    .addClass('empty');
}

// Linkify text from Identi.ca notices (thanks someone :)
function markup(text)
{
  var start = 0; var d = $('<div class="content"></div>');
  
  text.replace(/((http|https):\/\/|\!|@|#)(([\w_]+)?[^\s]*)/g,
    function(sub, type, scheme, url, word, offset, full) {
      if (!scheme && !word) return; // just punctuation
      var anchor = ''; 
      var href   = '';
      var b4Text = full.substr(start, offset - start);
      
      moniker = word.split('_'); // behavior with undescores differ
      if (type == '#') moniker = moniker.join('');
      else word = moniker = moniker[0].toLowerCase();
      
      switch(type) {
        case 'http://': case 'https://': // Web links
	  href = scheme + '://' + url; break;
	case '@': // User links
	  href = 'http://' + statusnet_server + '/' + moniker; break;
	case '!': // Group links
	  href = 'http://' + statusnet_server + '/group/' + moniker; break;
	case '#': // Hashtag links
	  href = 'http://' + statusnet_server + '/tag/' + moniker; break;
	default: // Bad call, just reset offset
	  start = offset;
      }
      
      if (scheme) { // URL
        anchor = sub; 
	start = offset + sub.length;
      } else {
        anchor  = word; 
	b4Text += type;
	start   = offset + word.length + type.length;
      }
     
      d.append(b4Text + '<a href="' + href + '">' + anchor + '</a>');
    }
  );
  
  if (start != text.length) {
    d.append(text.substr(start));
  }
  return d;
}

// Return HH:MM from timestamp
function clock(timestamp)
{
  var d = new Date();
  d.setTime(timestamp * 1000);
  
  var h = d.getHours();
  if (h < 10) h = '0' + h;
  
  var m = d.getMinutes();
  if (m < 10) m = '0' + m;
    
  return h + ':' + m;
}

// Return relative time (thanks someone :)
function relative_time(time_value) 
{
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  
  if (typeof(time_value) == 'number') {
    var parsed_date = new Date();
    parsed_date.setTime(time_value * 1000);
  } else {
    var values = time_value.split(" ");
    time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
    var parsed_date = Date.parse(time_value);
  }
  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;
}

// Pause the script execution (thanks someone else :)
$.fn.pause = function(duration) {
  $(this).animate({ dummy: 1 }, duration);
  return this;
};	

var statusnet_server = "identi.ca";

function jsonCop15Feed(json)
{
  $.each(json.results, function() {
    $("#cop15imc")
      .append($('<div class="headline"></div>')
      .append(markup(this.text))
      .append('<div class="created_at"><a href="http://twitter.com/'+this.from_user+'/statuses/'+this.id+'" title="View notice '+this.id+'">'+relative_time(this.created_at)+'</a></div>'));
  });
}

function jsonFlickrFeed(json)
{
  $.each(json.items, function() {
    $('#flickr')
      .append($('<div class="photo"></div>')
      .append($('<a href="' + this.link + '" title="' + this.title + '"></a>')
      .append($('<img src="' + this.media['m'] +'" width="240" height="180" alt="Photo by '+this.author+'" />'))));
  });
}

function jsonIdenticaFeed(json)
{
  $.each(json, function() {
    $("#feed")
      .append($('<div class="headline"></div>')
      .append(markup(this.text))
      .append('<div class="created_at"><a href="http://'+statusnet_server+'/notice/'+this.id+'" title="View notice '+this.id+'">'+relative_time(this.created_at)+'</a></div>'));
  });
}

function jsonPsycFeed(json)
{

  var topicflag;

  $.each(json, function() 
  {
    if (!topicflag) {
      $("#psyc")
        .append($('<h3>'+this[2]+'<span class="topicinfo">Topic set '+relative_time(this[0])+'</span></h3>'))
        .append(how_to_enter_the_place());
	
      topicflag = 1;
    } else {
      if (this[2] == 'says') {
        var text = '[' + clock(this[0]) + '] ' + this[3];
      } else {
	var text = '* ' + this[1] + ' ' + this[2];
      }
      if (text.indexOf('!f1x') != -1)
        $("#psyc")
          .append(markup(text));
    }
  });
}

function how_to_enter_the_place()
{
  var server = 'hinezumi.im';
  var place  = 'f1x';
  var html   = '<p>You can'
    + ' <nobr><a href="https://' + server + ':8443/?channels=' + place + '">ENTER THIS ROOM</a>'
    + ' via <a href="psyc://' + server + '/@' + place + '">PSYC</a>,'
    + ' <a href="xmpp:*' + server + '@' + place + '">XMPP</a>'
    + ' or <a href="irc://' + server + '/#' + place + '">IRC</a></nobr>'
    + ' <nobr>using <code>/server -ssl ' + server + ' 9999</code></nobr>'
    + ' <nobr>and <code>/join #' + place + '</code>.</nobr></p>';
  return html;
}

function jsonWikileaksFeed(json)
{
  $.each(json, function() {
    $("#wikileaks")
      .append($('<div class="headline"></div>')
      .append(markup(this.text))
      .append('<div class="created_at"><a href="http://twitter.com/wikileaks/statuses/'+this.id+'" title="View notice '+this.id+'">'+relative_time(this.created_at)+'</a></div>'));
  });
}

/**
 * Run Time!
**/

$(document).ready(function()
{
  // Remove CSS for MSIE and add a BIG warning
  if ($.browser.msie == true) {
    $('link').each(function()
    {
      if (this.rel.indexOf("stylesheet") != -1)
        this.parentNode.removeChild(this);
    });

    var warning = $('<div id="msie_sucks"></div>')
      .append('You\'re currently viewing the site without any stylesheet.<br />Why? Because ')
      .append('<a href="http://freedom.f1x.eu">your browser is obsolete</a>!');
    $('#header').prepend(warning);
    $('#msie_sucks')
      .css({ 
        backgroundColor: '#fff', 
        border: '5px solid red',
        color: '#000',
        margin: '0 auto',
	padding: '1em',
        fontSize: '1.5em',
        fontWeight: 'bold'
      });
    if ($('#fu').length) // We're on the Freedom Upgrade page
      $('.msie').css({ display: 'block' });
  }
  // Make flashes invisible when we don't use them
  $('#flashes').addClass('empty');
  // False Positives
  $('#fp.feature').click(function(e) {
    document.location.href = 'http://false-positives.f1x.eu/';
  });
  // Waste Management
  $('#wm.feature').click(function(e) {
    document.location.href = 'http://waste-management.f1x.eu/';
  });
  // Get #cop15imc updates
  if ($('#cop15imc').length)
    $.jsonp({
      "url": "http://search.twitter.com/search.json?q=%23cop15imc&callback=?",
      "data": { "count": 10 },
      "success": function(json) { jsonCop15Feed(json); },
      "error": function(d,msg) { flash('Feed is not available at this time.'); }
    });
  // Get Flickr updates
  if ($('#flickr').length) {
    $.jsonp({
      "url": "http://api.flickr.com/services/feeds/groups_pool.gne?id=886208@N24&lang=en-us&format=json&jsoncallback=?",
      "data": {},
      "success": function(json) { jsonFlickrFeed(json); },
      "error": function(d,msg) { flash('Feed is not available at this time.'); }
    });
  }  
  // Get Identi.ca updates
  if ($('#feed').length)
    $.jsonp({
      "url": "http://identi.ca/api/statusnet/groups/timeline/f1x.json?callback=?",
      "data": { "count": 3 },
      "success": function(json) { jsonIdenticaFeed(json); },
      "error": function(d,msg) { flash('Feed is not available at this time.'); }
    });
  // Get Psyc updates
  if ($('#psyc').length)
    $.jsonp({
      "url": "http://hinezumi.im/@f1x?format=json&callback=C",
      "data": {},
      "success": function(json) { jsonPsycFeed(json); },
      "error": function(d,msg) { flash('Feed is not available at this time.'); }
    });
  // Get Wikileaks updates
  if ($('#wikileaks').length)
    $.jsonp({
      "url": "http://twitter.com/statuses/user_timeline/16589206.json?callback=?",
      "data": { "count": 7 },
      "success": function(json) { jsonWikileaksFeed(json); },
      "error": function(d,msg) { flash('Feed is not available at this time.'); }
    });
		    
});

