/*
 * twitterCounter
 *
 * Displays a counter with the remaining text.
 *
 * Example:
 *  $('#description').twitterCounter(
 *  {
 *    limit: 140,
 *    counter: '#textcounter',
 *
 *    okSize: 140,
 *    okStyle: '.ok',
 *
 *    watchSize: 20,
 *    watchStyle: '.watch',
 *
 *    warningSize: 10,
 *    warningStyle: '.warning',
 *
 *    errorSize: 0,
 *    errorStyle: '.error',
 *  });
 *
 * $Version: 2008-10-24
 * Copyright (c) 2008 Ali Karbassi
 * ali.karbassi@gmail.com
 */
jQuery.fn.twitterCounter = function(options) {
   var curSize = $(this).val().length;
   var charsLeft = options['limit'] - curSize;
   var types = ['ok', 'watch', 'warning', 'error'];
   var x = {};
   $.each(types,
   function() {
      var el = this.toString();
      x[el] = {
         'Max': options[el + 'Size'],
         'Style': options[el + 'Style'].substring(0, 1) == '.' || options[el + 'Style'].substring(0, 1) == '#' ? options[el + 'Style'].substring(1, options[el + 'Style'].length) : options[el + 'Style'],
         'Type': options[el + 'Style'].substring(0, 1) == '.' ? 'class': 'id'
      }
   });
   for (var i = 0; i < types.length; i++) {
      var el = types[i].toString(); // Last Element check
      if (i + 1 < types.length) {
         var nextEl = types[i + 1].toString();
         if (charsLeft > x[nextEl]['Max'] && charsLeft < x[el]['Max'] + 1) {
            clean();
         }
      } else {
         if (charsLeft < x[el]['Max']) {
            clean();
         }
      }
   }
   $(options['counter']).text(charsLeft); // Add an event so the counter updates when the user types.
   $(this).one('keyup',
   function() {
      $(this).twitterCounter(options);
   });
   function clean() {
      if (x[el]['Type'] == 'class') {
         $.each(types,
         function() {
            var temp = this.toString();
            if ($(options['counter']).hasClass(temp)) {
               $(options['counter']).removeClass(temp);
            }
         });
         $(options['counter']).addClass(x[el]['Style']);
      } else {
         $(options['counter']).id(x[el]['Style']);
      }
   }
};

var counter_options = {
  limit: 140, counter: '#textcounter', 
  okSize: 140, okStyle: '.ok',
  watchSize: 20, watchStyle: '.watch',
  warningSize: 10, warningStyle: '.warning',
  errorSize: 0, errorStyle: '.error'
};

var length = 30;
var data_debug;

var last_entry;
var active = false;
var itens = 0;
var have_item = false;

$(document).ready( function() {
  $('.origins a').qtip({
    style: {
      width: { min:150, max:320 },
      fontSize: '0.9em',
      fontWeight: 'bold', 
      background: '#000000', 
      color: '#ffffff',
      padding: 0,
      border: {
         width: 0,
         radius: 10,
         color:'#000000'
      },
      classes: { tooltip: 'qtip1' }, 
      tip: 'topLeft',
      name: 'dark'
    }, 
    position: { corner: { target:'bottomMiddle', tooltip:'topLeft' } }
  });

  if ($('#textarea_update').length > 0) {
    $('#textarea_update').autogrow({maxHeight: 100, minHeight: 24, lineHeight: 16});
    $('#textarea_update').css('height', '40px');
    $('#textarea_update').twitterCounter(counter_options);
  }
  
  function trendtime() {
    if (!active) {
      active = !active
      $("#listing").everyTime(1000, function() {
        var last_entry = $("#listing ul li.entry").attr("id");
        if (active && itens == 0) {
          $.getJSON('/' + key + '/' + last_entry + '/recent/' + origin, function(data) {
            itens = data.count;
            $.each(data.entries, function(i, item) {
              setTimeout(function() {
                if (active) {
                  if ($("#listing ul li[origin="+item.origin+"]").length == 0) {
                    $("#listing ul").prepend(item.entry);
                    $("#listing ul li[origin="+item.origin+"]").hide();
                    $("#listing ul li[origin="+item.origin+"]").slideDown(1000);
                  }
                  if (itens == i+1) { itens = 0; }
                }
              }, 1500 * (i + 1));
              if (i == 0) { $("#listing ul li:first").css("border-bottom", "2px solid #aaa"); }
            });
          });
        }
        return true;
      });
    }
  }
  
  trendtime();

  $("#pause").live("click", function() {
    if (active) {
      $("#listing").stopTime();
      active = !active;
      $("#pause span").html(pause_off);
      $("#pause").attr('title', pause_title_off);
      $("#pause").attr('class', 'off');
    } else {
      trendtime();
      $("#pause span").html(pause_on);
      $("#pause").attr('title', pause_title_on);
      $("#pause").attr('class', 'on');
    }
    return false;
  });

  $(document).everyTime(120000, function() {
    $('.vcard a').each(function (i) {
      if ($(this).data("qtip")) $(this).qtip("hide");
    });
    $.getJSON('/' + key + '/users', function(data) {
      var content = "<h3>Top Users</h3><ul>";
      $.each(data, function(i, item) {
        content = content + '<li class="vcard">';
        content = content + '<a class="url" href="http://twitter.com/' + item.user + '" rel="contact">';
        content = content + '<img class="photo fn" height="48" src="' + item.profile_image_url + '" width="48" \/>';
        content = content + '<\/a><div><strong>';
        content = (item.name == null || item.name == '') ? content + item.user : content + item.name;
        content = content + '<\/strong><br \/>';
        if (item.location != null && item.location != '') { content = content + item.location + '<br \/>'; }
        if (item.url != null && item.url != '') { content = content + item.url + '<br \/>'; }
        if (item.description != null && item.description != '') { content = content + item.description + '<br \/>'; }
        if (item.followers_count != null) { content = content + item.followers_count + ' followers<br \/>'; }
        if (item.friends_count != null) { content = content + item.friends_count + ' following<br \/>'; }
        if (item.statuses_count != null) { content = content + pluralize(item.statuses_count, 'update', 'updates') + '<br \/>'; }
        content = content + '<strong>trendti.me: ' + pluralize(item.posts, 'update', 'updates') + '<\/strong>';
        content = content + '<\/div><\/li>';
      });
      content = content + '<\/ul>';
      $(".users").html(content);
    });
    return true;
  });
});

reform = function(strdate) {
  dt = ((strdate.substring(0,10)).split('-')).reverse().join('/') +' às '+ strdate.substring(11,16);
  return dt;
}

pluralize = function(count, singular, plural) {
  sentence = count + ' ';
  sentence = ((count == 1) || (count == '1')) ? sentence + singular : sentence + plural;
  return sentence;
}

function updateMyTimeline() {
  $("#submit_update").val("Enviando ...");
  $("#submit_update").attr("disabled", "disabled");
  $.post(update_url, $("#form_update").serialize(), function(data){
    $("#listing ul").prepend(data.entry);
    $("#listing ul #" + data.id).hide().show("slow");
    $("#textarea_update").val("");
    $("#submit_update").val("Enviar");
    $("#submit_update").removeAttr("disabled");
    $("#textarea_update").twitterCounter(counter_options);
    $('#textarea_update').autogrow({maxHeight: 100, minHeight: 24, lineHeight: 16});
    $('#textarea_update').css('height', '40px');
  }, "json");
}

$('.twitter a.rt').live('click', function() {
  postid = $(this).parent().parent().attr('origin');
  $("#textarea_update").val("RT @" + $.trim($("#message-" + postid).html().replace(/<\/?[^>]+>/gi, '')));
  $("#textarea_update").twitterCounter(counter_options);
  $("#textarea_update").focus();
  return false;
});
 
$('.twitter a.reply').live('click',function() {
  postid = $(this).parent().parent().attr('origin');
  user = $('.from_user', $(this).parent().parent()).text();
  $("#in_reply_to_status_id").val(postid);
  $("#textarea_update").val("@" + user + " ");
  $("#textarea_update").twitterCounter(counter_options);
  $("#textarea_update").focus();
  return false;
});

$('a[rel*=external]').live('click',function() {
  $(this).attr('target', '_blank');
});

$('a[rel*=contact]').live('click',function() {
  $(this).attr('target', '_blank');
});

$('a[rel*=facebox]').live('click',function() {
  $.facebox('<img src="' + $(this).attr('href') + '" />');
  return false;
});

$('.vcard a').live('mouseover', function() {
  if ($(this).data("qtip")) $(this).qtip("destroy");
  $(this).qtip({
    style: {
      width: { min:150, max:350 },
      fontSize: '0.9em',
      background: '#000000', 
      color: '#ffffff',
      border: { width:0, radius:10, color:'#202020' }, 
      classes: { tooltip: 'qtip2' }, 
      tip:'topRight', 
      name: 'dark'
    },
    position: { corner: { target:'bottomMiddle', tooltip:'topRight' } }, 
    content: $(this).next("div").html(),
    show: { when: false, ready: true },
    hide: 'mouseout'
  });
});

moreT = function (login){
  var ultimo = $("#listing ul li:last").attr("id");

  $('.more').html('<img src="/images/indicator.gif" class="wait" alt="carregando..." />');
  $.getJSON('/' + key + '/' + ultimo + '/more/' + origin, function(data) {
    if (data.length > 0) {
      $.each(data, function(i, item) {
        $("#listing ul").append(item);
      });
      length = length + 30;
    } else {
      $(".more").hide();
    }
    $('.more').html('mostrar mais');
    $("#" + ultimo).css("border-bottom", "1px solid #aaa");
    $.scrollTo($("#" + ultimo), 800);
  });
};
