function nowInUsersTime() {
  var now = new Date();
  now.setMinutes(now.getMinutes()+now.getTimezoneOffset());
  return now;
}

/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
  var date = new Date(time.replace(/(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d:\d\d:\d\d)(.*)/,"$2/$3/$1 $4"));
  var diff = Math.floor((new nowInUsersTime() - date.getTime()) / 1000);
  var day_diff = Math.floor(diff / 86400);
      
  if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
    return;
      
  return day_diff == 0 && (
      diff < 60 && "just now" ||
      diff < 120 && "1 minute ago" ||
      diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
      diff < 7200 && "1 hour ago" ||
      diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
    day_diff == 1 && "Yesterday" ||
    day_diff < 7 && day_diff + " days ago" ||
    day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
  jQuery.fn.prettyDate = function(){
    return this.each(function(){
      var date = prettyDate(this.title);
      if ( date )
        jQuery(this).text( date );
  });
};


function addAuthenticityToken(){
  jQuery("body").bind("ajaxSend", function(elm, xhr, s) {
      console.log( s.type);
      if (s.type == "GET") return;
      if (s.data && s.data.match(new RegExp("\\b" + window._auth_token_name + "="))) return;
      if (s.data) {
        s.data = s.data + "&";
      } else {
        s.data = "";
        // if there was no data, $ didn't set the content-type
        xhr.setRequestHeader("Content-Type", s.contentType);
      }
      s.data = s.data + encodeURIComponent(window._auth_token_name)
                      + "=" + encodeURIComponent(window._auth_token);
    });
}

function Admin () {
  var admin=/admin=/.exec(document.cookie);
  function loggedIn(){
    return admin!=null;
  }
  
  if (loggedIn()){
    $('.anonymous').hide();
    $('.logged_in').show();
  } else {
    $('.logged_in').hide();
    $('.anonymous').show();
  }

  return admin;
};

var admin;
$(document).ready(function() {
  admin=Admin();
  $('abbr').prettyDate();
  
  wireCommentForm();
  
  $('a.delete').click(function(){
    function delete_element() {
      $(this.element).parent().parent().slideUp('fast',function(){$(this).remove();});
    };
    
    $.ajax({
      type: "POST",
      url:this.action,
      data:"_method=delete",
      success:delete_element,
      element:this
      });
      return false;
  });
});

function wireCommentForm() {
  $('form#new_comment').submit(submitComment);
}
function unwireCommentForm() {
  $('form#new_comment').unbind('submit',submitComment);
}

function submitComment(){
  $.post(this.action, $(this).serialize(),rewireComments, "script");
  return false;
};
function rewireComments(){
  $('.comments abbr').prettyDate();
  wireCommentForm();
}

function twitterCallback(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    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>';
    });
    statusHTML.push('<li><span>'+status+'</span> <a href="http://twitter.com/pelleb/statuses/'+twitters[i].id+'">'+prettyDate(twitters[i].created_at)+'</a></li>');
  }
  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

