// generic enumeration
Function.prototype.forEach = function(object, block, context) {
  for (var key in object) {
    if (typeof this.prototype[key] == "undefined") {
      block.call(context, object[key], key, object);
    }
  }
};

// globally resolve forEach enumeration
var forEach = function(object, block, context) {
  if (object) {
    var resolve = Object; // default
    if (object instanceof Function) {
      // functions have a "length" property
      resolve = Function;
    } else if (object.forEach instanceof Function) {
      // the object implements a custom forEach method so use that
      object.forEach(block, context);
      return;
    } else if (typeof object.length == "number") {
      // the object is array-like
      resolve = Array;
    }
    resolve.forEach(object, block, context);
  }
};

jQuery.extend(String.prototype, {
  databaseId: function() { return jQuery.trim(this.split('_').last()); }
});

jQuery.extend(Array.prototype, {
  last: function() { return this[this.length-1]; }
});

jQuery.authenticity_token = function() {
  return jQuery('#authenticity_token').attr('content');
};

function log() {
  if (window && window.console && window.console.log)
    for(var i=0, len=arguments.length; i<len; i++)
      console.log(arguments[i]);
};

jQuery(function(jQuery) {
  var countdown = jQuery('#countdown');
  var allowed = parseInt(countdown.text());
  jQuery('#text').keydown(function() {
    var length = jQuery(this).val().length;
    countdown.text(allowed - length);
    
    if (length == 0) {
      jQuery('#in_reply_to_status_id').val('');
      var label = jQuery('label[for=text]')
      label.text(label.data('original_text'));
    }
  });
  
  jQuery('a.dm').click(function() {
    window.scrollTo(0, 0);
    jQuery('#text').focus().val('d ' + jQuery(this).attr('rel') + ' ');
    return false;
  });
  
  var label = jQuery('label[for=text]')
  label.data('original_text', label.text());
  
  jQuery('a.reply').click(function() {
    window.scrollTo(0, 0);
    var pieces = jQuery(this).attr('rel').split(':');
    var screen_name = pieces[0];
    var id = pieces[1];
    jQuery('#text').focus().val('@' + screen_name + ' ');
    jQuery('#in_reply_to_status_id').val(id);
    jQuery('label[for=text]').text('Replying to ' + screen_name + "'s tweet #" + id);
    return false;
  });
});