// Transforma URLs em links
function linkify(text) {
  if( !text ) return text;
  text = text.replace(/((https?\:\/\/|ftp\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,function(url){
  	nice = url;
  	if( url.match('^https?:\/\/') )
  	{
  		nice = nice.replace(/^https?:\/\//i,'')
  	}
  	else
  		url = 'http://'+url;
  	return '<a target="_blank" href="'+ url +'">'+ nice.replace(/^www./i,'') +'</a>';
  });
  return text;
  }

// Transforma @user em link para o twitter do usuário	
function link_twitter(text) {
  return  text.replace(/[@]+[a-zA-z0-9_]+/gi, function(user){
    var username = user.replace('@','');
    var link = "http://www.twitter.com/"+username + "/";
    var url = '<a href="'+link+'" target="_blank">' + user + "</a>";
    return url;
  });
}

function link_hashtag(text) {
  return  text.replace(/[#]+[a-zA-z0-9_]+/gi, function(hashtag){
    var hash = hashtag.replace('#','');
    var link = "http://twitter.com/#!/search/"+hash;
    var url = '<a href="'+link+'" target="_blank">' + hashtag + "</a>";
    return url;
  });
}

function formatTweet(text) {
  text = link_hashtag(link_twitter(linkify(text)));
  return text;
}

// Transforma o formato de tempo do twitter em ... atrás
var K = function () {
    var a = navigator.userAgent;
    return {
        ie: a.match(/MSIE\s([^;]*)/)
    }
}();
 
var H = function (a) {
    var b = new Date();
    var c = new Date(a);
    if (K.ie) {
        c = Date.parse(a.replace(/( \+)/, ' UTC$1'))
    }
    var d = b - c;
    var e = 1000,
        minute = e * 60,
        hour = minute * 60,
        day = hour * 24,
        week = day * 7;
    if (isNaN(d) || d < 0) {
        return ""
    }
    if (d < e * 7) {
        return "agora"
    }
    if (d < minute) {
        return Math.floor(d / e) + " segundos atrás"
    }
    if (d < minute * 2) {
        return "aproximadamente 1 minuto atrás"
    }
    if (d < hour) {
        return Math.floor(d / minute) + " minutos atrás"
    }
    if (d < hour * 2) {
        return "aproximadamente 1 hora atrás"
    }
    if (d < day) {
        return Math.floor(d / hour) + " horas atrás"
    }
    if (d > day && d < day * 2) {
        return "ontem"
    }
    if (d < day * 365) {
        return Math.floor(d / day) + " dias atrás ago"
    } else {
        return "há mais de um ano"
    }
};

var tweetList = $('<ul></ul>');

function parseTweets(tweets) {
	$.each(tweets,function(t, tweet){
		tweetList.append('<li>'+formatTweet(tweet.text)+ '<span class="box-twitter-criado-em">' + H(tweet.created_at) + '</span></li>');
	});
}

function getTweets(quantidade) {
  $.ajax({
		url:'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=vinildigital&count='+quantidade+'&include_rts=1&callback=?',
		success: function(response) {
			parseTweets(response);
		},
		dataType: 'jsonp',
		error: function(error) {
			alert(error);
		}
	});
  $('#tweets').append(tweetList);
}
