// ==UserScript==
// @name           retweet
// @namespace      tzangms.com
// @description    twitter retweet function
// @include        http://twitter.com/*
// @include        https://twitter.com/*
// ==/UserScript==

// Check if jQuery's loaded
function GM_wait() {
  if(typeof unsafeWindow.jQuery == 'undefined') {
    window.setTimeout(GM_wait,100);
  } else {
    $ = unsafeWindow.jQuery;
    letsJQuery();
  }
}
GM_wait();

// update text chars count
function updateStatusTextCharCounter(value) {
  var len = value.length;
  var char_counter = $('#status-field-char-counter');
  char_counter.html('' + (140-len));
  if (len <= 0 || len > 140) {
    if(len == 0) { char_counter.css( 'color', '#cccccc'); }
    $('.status-btn .round-btn').attr('disabled', 'disabled').addClass('disabled');
  } else {
    $('.status-btn .round-btn').removeAttr('disabled').removeClass('disabled');
    if (len > 130) { char_counter.css( 'color', '#d40d12'); }
    else if (len > 120) { char_counter.css( 'color', '#5c0002'); }
    else { char_counter.css( 'color', '#cccccc'); }
  }
}
	
// fix url in tweet content
function fixUrl(content){
  arySearch = new Array;
  aryReplace = new Array;
  myRegExp = new RegExp(/<a href="(.*?)".*?>(.*?)<\/a>/gi);
  r = myRegExp.exec(content);
  while(r != null){
    arySearch.push(r[0]);
    if(r[1].search(/^https?:\/\//gi) > -1){
      aryReplace.push(r[1]);
    }else{
      aryReplace.push(r[2]);
    }
    r = myRegExp.exec(content);
  }
  for(i = 0; i < arySearch.length; i++){
    content = content.replace(arySearch[i], aryReplace[i]);
  }

  return content;
}

// main action
function letsJQuery() {
  var r = document.createElement('a');
  r.setAttribute('class', 'retweet');
  r.innerHTML = '<strong style="color: #aaa; cursor: pointer;">R</strong>';
  
  entry = $('.hentry .status_actions');
  $(entry).append(r);
  $('a[@class=retweet]', entry).click(function(){
    e = $(this).parents('tr.hentry').children('td div.status-body');
    id = $('strong a', e).text();
    
    //content = $('span.entry-content', e).text();
    content = $('span.entry-content', e).html();
    
    // fix url in tweet content
    content = fixUrl(content);
    
    msg = 'Retweet: @' + $.trim(id) + ' ' + $.trim(content);
    $('#status').val(msg).focus();
    updateStatusTextCharCounter(msg);
    window.scroll(0,0);
  });
}
