TwitterHelper = function(feed_container, tweet_users, hide_li, hide_links, avatar_size, rpp, params){
  this.tweetUsers = new Array(tweet_users);
  this.container_id = feed_container;
  this.hide_li_elements = "";
  this.hide_link_elements = "";
  this.avatar_current_size = "normal";
  this.avatar_img_sizes = {"mini" : "24", "normal" : "48", "bigger" : "73"};
  this.rpp_size = 3;
  this.count = 0;
  this.ticker = null;
  this.layout = 'normal';
  
  if(hide_li)
  {
    this.hide_li_elements = " style=\"display: none;\"";
  }
  
  if(hide_links)
  {
    this.hide_link_elements = " style=\"display: none;\"";
  }
  
  if(avatar_size)
  {
    this.avatar_current_size = avatar_size;
  }
  
  if(rpp)
  {
    this.rpp_size = rpp;
  }
  
  if(params){
    if(params.ticker && (typeof params.ticker == 'object') && (params.ticker instanceof TickerHelper == true)){
      this.ticker = params.ticker;
    }
    if(params.layout && params.layout != ''){
      this.layout = params.layout;
    }
  }
};

TwitterHelper.prototype.StartFeed = function(){
  this.container = $('#' + this.container_id);
  if(this.container.length>0){
    var buildString = "";

    var utenti = this.tweetUsers;
    for(var i=0;i<utenti.length;i++)
    {
      if(i!=0) buildString+='+OR+';
      buildString+='from:'+utenti[i];
    }

    $.getJSON(
      "http://search.twitter.com/search.json?q="+buildString+"&callback=?&rpp=" + this.rpp_size + "&result_type=recent",
      {},
      $.proxy(this.TweetTick, this)
    );
  }
}


TwitterHelper.prototype.TweetTick = function(ob){
  var thisc = this;
	thisc.container.html('');
  
	$(ob.results).each(function(){
    
    thisc.count++;
    var hli = "";
    if(thisc.count>1){
      hli = thisc.hide_li_elements;
    }
    
    var first_twitter = thisc.GetFirstTwitter(this.text);
    this.text = thisc.StringCleanFromRetweets(this.text);
    var tweet_id = this.id_str;
    var tweet_elem = "";
    var link_foto = "";
    var dim_img = ""
    if(thisc.layout == "mini"){
      dim_img = "width=\"48\" height=\"48\"";
    }
    if(first_twitter == "")
    {
      //link_foto = " <a href=\"http://twitter.com/"+this.from_user+"\" rel=\"external\"><img " + dim_img + " src=\"http://api.twitter.com/1/users/profile_image/"+this.from_user+"?size=" + thisc.avatar_current_size + "\" alt=\"\" title=\"\" /></a>";
      link_foto = " <a href=\"http://twitter.com/"+this.from_user+"\" rel=\"external\"><img " + dim_img + " src=\"/gui-images/logo-pdl-twitter.png\" alt=\"\" title=\"\" /></a>";
    }
    else
    {
      link_foto = " <a href=\"http://twitter.com/"+first_twitter+"\" rel=\"external\"><img " + dim_img + " src=\"http://api.twitter.com/1/users/profile_image/" + first_twitter + "?size=" + thisc.avatar_current_size + "\" alt=\"\" title=\"\" /></a>";
    }
    
    var link_tweet = "";
    link_tweet += "  <div class=\"links\"" + thisc.hide_link_elements + ">";
    link_tweet += "    <a href=\"http://twitter.com/ilpdl/status/" + tweet_id + "\" rel=\"external\" title=\"\">" + thisc.relativeTime(this.created_at) + "</a>&nbsp;&ndash;";
    link_tweet += "    <a href=\"http://twitter.com/intent/tweet?in_reply_to=" + tweet_id + "\" rel=\"external\" title=\"\">rispondi</a>&nbsp;&ndash;";
    link_tweet += "    <a href=\"http://twitter.com/intent/retweet?tweet_id=" + tweet_id + "\" rel=\"external\" title=\"\">retweet</a>&nbsp;&ndash;";
    link_tweet += "    <a href=\"http://twitter.com/intent/favorite?tweet_id=" + tweet_id + "\" rel=\"external\" title=\"\">favoriti</a>";
    link_tweet += "  </div>";
    
    tweet_elem += "<li" + hli + ">";
    
    if(thisc.layout == "normal"){
      tweet_elem += "  <div class=\"avatar\">";
      tweet_elem += link_foto;
      tweet_elem += "  </div>";
    }
    
    tweet_elem += "  <div class=\"testo\">";
    if(thisc.layout == "mini"){
      tweet_elem += link_foto;
    }
    if(first_twitter == "")
    {
      tweet_elem += " <span class=\"titolo\"><a href=\"http://twitter.com/"+this.from_user+"\" rel=\"external\">@"+this.from_user+"</a></span>";
    }
    else
    {
      tweet_elem += " <span class=\"titolo\"><a href=\"http://twitter.com/"+first_twitter+"\" rel=\"external\">@"+first_twitter+"</a></span>";
    }
    tweet_elem += "  " + thisc.formatTwitString(this.text);
    if(thisc.layout == "normal"){
      tweet_elem += link_tweet;
    }
    tweet_elem += "  </div>";
    if(thisc.layout == "mini"){
      tweet_elem += link_tweet;
    }
    tweet_elem += "</li>";
    
//    var new_li = $(tweet_elem);
//    $('a[rel="external"]', new_li).click(function(){
//        window.open(this.href);
//        return false;
//    });
    thisc.container.append(tweet_elem);
	});
  $('a[rel="external"]', thisc.container).click(function(){
      window.open(this.href);
      return false;
  });
  if(this.ticker != null){
    this.ticker.StartTicker()
  }
}

TwitterHelper.prototype.GetFirstTwitter = function(str){
  var profilo =  "";
  if(str.indexOf("RT @") == 0){
    var pos_dp = str.indexOf(":");
    profilo = str.substring(4, pos_dp);
  }
  return profilo;
}

TwitterHelper.prototype.StringCleanFromRetweets = function(str)
{
  var stringa_pulita = str;
  var pos_dp = 0;
  while(stringa_pulita.indexOf("RT @") == 0){
    pos_dp = stringa_pulita.indexOf(":");
    stringa_pulita = stringa_pulita.substring(pos_dp+2);
  }
  return stringa_pulita;
}

TwitterHelper.prototype.formatTwitString = function (str){
	str=' '+str;
	str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" rel="external">$1</a>');
	str = str.replace(/([^\w])\@([\w\-]+)/gm,'$1<a href="http://twitter.com/$2" rel="external">@$2</a>');
	str = str.replace(/([^\w])\#([\w\-]+)/gm,'$1<a href="http://twitter.com/search?q=%23$2" rel="external">#$2</a>');
	return str;
}

TwitterHelper.prototype.relativeTime = function(pastTime){	
	var origStamp = Date.parse(pastTime);
	var curDate = new Date();
	var currentStamp = curDate.getTime();
	
	var difference = parseInt((currentStamp - origStamp)/1000);

	if(difference < 0) return false;

	if(difference <= 5)				return "Ora";
	if(difference <= 20)			return "secondi&nbsp;fa";
	if(difference <= 60)			return "Un&nbsp;minuto&nbsp;fa";
	if(difference < 3600)			return parseInt(difference/60)+"&nbsp;minuti&nbsp;fa";
	if(difference <= 1.5*3600) 		return "Un'ora&nbsp;fa";
	if(difference < 23.5*3600)		return Math.round(difference/3600)+"&nbsp;ore&nbsp;fa";
	if(difference < 1.5*24*3600)	return "Un&nbsp;giorno&nbsp;fa";
	
	var dateArr = pastTime.split(' ');
	return dateArr[4].replace(/\:\d+$/,'')+' '+dateArr[2]+' '+dateArr[1]+(dateArr[3]!=curDate.getFullYear()?' '+dateArr[3]:'');
}
