var TwitterFeed = Class.create({
  
  // PROPERTIES ___
  
  // ELEMENTS _____
  // outputElement
  
  initialize: function(handler, outputElementId) {
    
    this.handler       = handler;
    this.outputElement = $(outputElementId);
    this.currTweetsArr = [];
    
    this.requestTweets();
    
    //this.startUpdateTimeExecuter();
  },
  
  startUpdateTimeExecuter: function() {
    this.stopUpdateTimeExecuter();
    this.updateTimeExecuter = new PeriodicalExecuter(this.updateTimeSince.bind(this), 65);
  },
  stopUpdateTimeExecuter: function() {
    if (this.updateTimeExecuter) {
      this.updateTimeExecuter.stop();
    };
  },
  
  updateTimeSince: function(pe) {
    this.stopUpdateTimeExecuter();
    var currDate = new Date();
    this.currTweetsArr.each(function(tweet) {
      tweet.updateTimeSince(currDate);
    });
    this.startUpdateTimeExecuter();
  },
  
  requestTweets: function() {
    
    new Ajax.Request(this.handler, {
      parameters: {
      },
      method: "GET",
      onSuccess: this.handleResponse.bind(this)
    });
    
  },
  
  handleResponse: function(response) {
    
    var jsonData = (response.responseJSON) ? response.responseJSON : response.responseText.evalJSON();
    
    if (jsonData.results.length) {
      jsonData.results = [jsonData.results[0]]; // only want newest tweet
      this.processTweets(jsonData.results);
      this.updateTimeSince();
      //this.delayMult = 1;
    }
  },
  
  
  processTweets: function(tweetsArray) {
    
    tweetsArray.clone().each(function(data) {
      var dupeTweet = this.currTweetsArr.find( function(tweetInstance){ return tweetInstance.id_str == data.id_str; } );
      if (dupeTweet) {
        tweetsArray.splice(tweetsArray.indexOf(dupeTweet), 1);
      };
    }, this);
    
    if (tweetsArray.length) {
      
      this.lastTweetId = tweetsArray[0].id_str;
      
      tweetsArray.reverse().each(function(data){
        
        var tweet = new Tweet(data);
        this.currTweetsArr.splice(0,0,tweet);
        this.outputElement.insert({top: tweet.getDisplayElement() });
        
      }, this);
      
    };
    
    var currNumTweets = this.currTweetsArr.length;
    if (currNumTweets > 15) {
      for (var i = 15; i < currNumTweets; i++) {
        var tweetToRemove = this.currTweetsArr[i];
        tweetToRemove.getDisplayElement().remove();
        tweetToRemove.destroy();
      }
      this.currTweetsArr.splice(15, currNumTweets);
    };
  }
  
});

var Tweet = Class.create({

  // PROPERTIES ___
  // id_str
  // date
  
  // ELEMENTS _____
  // displayElement
  // timeSinceElement
  
  initialize: function(data) {
    
    this.id_str = data.id_str;
    this.date = (Prototype.Browser.IE) ? Date.parse(data.created_at.replace(/( \+)/, ' UTC$1')) : new Date(data.created_at);
    
    this.displayElement   = new Element("div", {"class": "tweetCell"});
    this.timeSinceElement = new Element("span", {"class": "tweetTimeSince"});
    
    var bodyElement   = new Element("div").addClassName("tweetCellBody");
    bodyElement.insert(TwitterText.auto_link(data.text));
    
    this.displayElement.insert(this.timeSinceElement);
    this.displayElement.insert(bodyElement);
    
    this.displayElement.select("a").each(function(anchor){
      anchor.setAttribute("target", "_blank");
    });
    
    return this;
  },
  
  updateTimeSince: function(currDate) {
    //this.timeSinceElement.update(this.timeSince(this.date) + " ago ");
    //this.timeSinceElement.update(this.H(this.created_at));
    this.timeSinceElement.update(this.timeSince(this.date, currDate));
  },
  
  getDisplayElement: function() {
    return this.displayElement;
  },
  
  destroy: function() {
    this.displayElement = null;
    this.timeSinceElement = null;
  },
  
  
  timeSince: function (dateA, dateB) {
    
    dateB = dateB || new Date();
    
    var d = dateB - dateA;
    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 "Right now";
    }
    if (d < minute) {
        return Math.floor(d / e) + " seconds ago";
    }
    if (d < minute * 2) {
        return "About 1 minute ago";
    }
    if (d < hour) {
        return Math.floor(d / minute) + " minutes ago";
    }
    if (d < hour * 2) {
        return "About 1 hour ago";
    }
    if (d < day) {
        return Math.floor(d / hour) + " hours ago";
    }
    if (d > day && d < day * 2) {
        return "Yesterday";
    }
    if (d < day * 365) {
        return Math.floor(d / day) + " days ago";
    } else {
        return "Over a year ago";
    }
  }
});







