$(document).ready(function() {

    $('.entry').each(function() {  
        var id = $(this).attr('id');
        var entry_id = id.replace(/^entry-/,'');
        var permalink = $(this).find("a.entry-link").attr("href");
        var title = $(this).find("a.entry-link").attr("title");
        if (!permalink) return;
        var sUrl = 'http://urls.api.twitter.com/1/urls/count.json?url='+encodeURIComponent(permalink);
        $.ajax({
            type: 'get',
            url: sUrl,
            dataType: 'jsonp',
            context: $("#tweets-"+entry_id),
            success: function(data) {
               var count = data.count.toString();
               $(this).html(count);
               $(this).hover(
                   function(){
                       $(this).html('Tweet');
                   },
                   function(){
                       $(this).html(count);
                   }
               );
            }                
        });
        $("#tweets-"+entry_id+",#tweettext-"+entry_id).click(function(){
            var W = 550,
            d = 450;
            var Z = screen.height;
            var Y = screen.width;
            var X = Math.round((Y / 2) - (W / 2));
            var c = 0;
            var V = 'http://twitter.com/share' + "?" + "count=horizontal&text=" + encodeURIComponent(title) + "&url=" + encodeURIComponent(permalink);
            var via;
            
            var related = "&related=mthacks:Mark%20Carey";
            var V = 'http://twitter.com/share' + "?" + "count=horizontal&text=" + encodeURIComponent(title) + "&url=" + encodeURIComponent(permalink) + via + related;
            if (Z > d) {
                c = Math.round((Z / 2) - (d / 2))
            }
            var a = window.open(V, "twitter_tweet", "left=" + X + ",top=" + c + ",width=" + W + ",height=" + d + ",personalbar=no,toolbar=no,scrollbars=yes,location=yes,resizable=yes");
            if (a) {
                a.focus()
            } else {
                window.location.href = V
            }
            return false;
        });
    });

});
