var effective_height = 0;
var max_displayed = 0;
var feedback_cat = 'idea';
var user_box_timeout;
var _twitter_user_profile_pic = null;
$(document).ready(function(e) {
        $('.alpha_alert').click(function(e) {
                $('.modal-mask').fadeTo(250, 0.6);
                $('.modal-window').fadeIn(350);
        });
        $('#login_link').click(function(e) {
                $('.modal-mask').fadeTo(250, 0.6);
                $('.register_details').hide();
                $('.login_details').show();
                $('.modal-register').fadeIn(350);
                window.location.href = '/api/twitter/oauth';
        });
        $('.save_me_too').click(function(e) {
                $('.modal-mask').fadeTo(250, 0.6);
                $('.register_details').show();
                $('.login_details').hide();
                $('.modal-register').fadeIn(350);
        });
        $('.close-modal').click(function(e) {
                $('.modal-div').fadeOut(250);
        });
        $('.header_user').click(function(e) {
          $('.header_user_open_bottom').toggle();
        });
        $('.header_user_open_bottom, .header_user').hover(
            function(e) {
              clearTimeout(user_box_timeout);
            },
            function(e) {
              user_box_timeout = setTimeout("$('.header_user_open_bottom').hide()", 4000);
            }
        );
        $('#post_intro_squib').click(function(e) {
          var re = new RegExp(/(^|[^\w])!\S+/);
          if($('#intro_squib').val().match(re)) {
            $('.register_error').text('');
            $('#form_followus').val(($('#followus:checked').val())?'1':'0');
            $('#squib_form').submit();
          } else {
            $('.register_error').text('You need to use an actiontag ("!") to tell Squibr save your tweet (e.g. !playing around, just !woke up, etc.)')
          }

        });
        $('.followus_text').click(function(e) {
          $('#followus').click();
        });

        if (profile_page) {
          $('.feedback_tab').click(function(e) {
                  $('.modal-mask').fadeTo(250, 0.6);
                  $('.modal-feedback').fadeIn(350);
          });
          while ($('.user_full_name > a').width()>280) {
            $('.user_full_name > a').css('font-size', (parseInt($('.user_full_name > a').css('font-size'))-1)+"px");
          }
          $('.feedback_category').click(function(e) {
                  $('.feedback_category').removeClass('f_c_active');
                  $(this).addClass('f_c_active');
                  var cat_text = $(this).text();
                  feedback_cat = cat_text.substr(cat_text.lastIndexOf(" ")+1);
          });
          $('.feedback_submit').click(function(e) {
                  if ($('#feedback_message').val() == "") {
                    $('.feedback_error').text('You need to enter some feedback text.');
                    return;
                  }
                  $.post('/feedback', {type:feedback_cat, content:$('#feedback_message').val()});
                  $('.feedback_ty').fadeIn(250);
                  $('#feedback_message').val('');
                  $('.feedback_category').eq(0).click();
                  $('.feedback_error').text('');
                  setTimeout('$(".close-modal").eq(0).click()', 2000);
          });
          $('.twitter_switch').click(function(e) {
            var value;
            if ($(this).hasClass('switch_off')) {
              // turn on
              $(this).removeClass('switch_off').addClass('switch_on');
              value = true;
            } else {
              // turn off
              $(this).removeClass('switch_on').addClass('switch_off');
              value = false;
            }
            $.post('/settings', {key:'twitter_in', value:value}, function(data) {
            });
          });
          
          // Controlling load of more items if scroll reaches below threshold
          // TODO: add handler for resize to check for short content (i.e. no scroll at all)
          $(document).scroll(function(e) {
            if ($(document).scrollTop()+$(window).height()>effective_height) {
              // load more content
              if (active_panel == '_timeline') {
                create_timeline_boxes();
              } else {
                create_verb_items(active_panel);
              }
              
            }
          });
          
          // set data from server
          if (user_profile_pic) {
            set_profile_pic(user_profile_pic);
          }
          if (user_location) {
            $('#user_map').html('<img src="http://maps.google.com/maps/api/staticmap?center='+user_location+'&size=280x180&maptype=mobile&sensor=false&mobile=true" /><div class="my_location"></div>');
          }
  
          // Go get up to date user details from twitter
          if (x_uid>0) {
            $.getJSON('http://twitter.com/users/show/'+x_uid+'.json?callback=?',
                   function(data) {
                            if (!user_location) {
                              $('#user_map').html('<img src="http://maps.google.com/maps/api/staticmap?center='+data.location+'&size=280x180&maptype=mobile&sensor=false&mobile=true" /><div class="my_location"></div>');
                            }
                            
                            // set bio and web
                            if (data.url!=null) {
                                    $('#user_web').html('<a href="'+data.url+'" target="_blank">'+data.url+'</a>');
                            } else {
                                    $('#web_data').hide();
                            }
                            if (data.description!=null) {
                                    $('#user_bio').html(data.description);
                            } else {
                                    $('#bio_data').hide();
                            }
                            if (data.profile_image_url!=null) {
                              if (!user_profile_pic) {
                                // we don't have a valid profile pic so we load the one from Twitter
                                var image = data.profile_image_url;
                                set_profile_pic(image, true);
                              } else {
                                // otherwise, we just save for later
                                _twitter_user_profile_pic = image;
                              }
                            }
            });
          }
          // contingency for getting profile data via jsonp (unused)
          if (profile_data == null) {
            $.getJSON(site_base+'v2/get_profile_data/'+uid+'?callback=?', function(data) {
              profile_data = data;
              create_timeline();
            });
          } else {
            if (active_panel=='_timeline') {
              create_timeline();
            } else {
              load_verb(profile_data.verbs._main_verb);
            }
          }
          if (typeof community_sampler != 'undefined') {
            create_community_boxes(0);
          }
          
          $('#back_to_all').click(function(e) {
                  effective_height = 0;
                  max_displayed = 0;
                  create_timeline();
          });
          
        }

});

$('.timeline_box:not(.timeline_box_main)').live('click', function(e) {
        // check if click is on box_live
        // if so, run like functions
        var target = $(e.target);
        if (target.hasClass('box_like') || target.hasClass('external_link')) {
          return;
        }
        $('.timeline_box:not(#'+$(this).attr('id')+')').fadeOut(500);
        $(this).delay(500).fadeOut(5000);
        window.location.href='/'+screen_name+'/feed/'+$(this).data('verb').toLowerCase();
});

$('.main_verb_link').live('click', function(e) {
        $('.timeline_box:not(#'+$(this).parent().parent().attr('id')+')').fadeOut(500);
        $(this).delay(500).fadeOut(5000);
        window.location.href='/'+screen_name+'/feed/'+$(this).parent().parent().data('verb').toLowerCase();

});
$('.box_like').live('click', function(e) {
        var target = $(e.target);
        if (target.hasClass('box_like')) {
          if (!target.hasClass('like_voted')) {
            add_like($(e.target));
          }
        }
});
var del_timeout = null;
$('.delete_yes').live('click', function(e) {
  if ($(this).parent().hasClass('delete_comment')) {
    delete_comment(/\d+/.exec($(this).parents('.one_comment').attr('id'))[0]);
  } else {
    delete_squib($(this).parent().data('id'), $(this).parent().data('type'));
  }
  $(this).parent().html('Deleting...').removeClass('delete_red');
});
function delete_squib(squib, type)
{
    $.post('/-delete/squib', {id:squib}, function(data) {
      if (data=='1') {
        if (type=='main') {
          window.location.href = "/"+screen_name;
        } else {
          if ($('.verb_list .verb_item').length<=1) {
            window.location.href = "/"+screen_name;
          }
          $('.verb_list #item_'+squib).slideUp(1000).remove();
        }
      }
    });
}
function delete_comment(id)
{
    $.post('/-delete/comment', {id:id}, function(data) {
      if (data=='1') {
        var comment = $('#comment_'+id);
        // deleting thread under current comment
        comment.nextAll().each(function() {
          if ($(this).data('level')<=comment.data('level')) {
            return false;
          }
          $(this).remove();
        });
        var container = comment.parent();
        comment.remove();
        color_comments(container);
      }
    });
}
$('.delete_no').live('click', function(e) {
    $(this).parent().html('Delete this Squib').removeClass('delete_red');
});
$('.delete_squib, .delete_comment').live('click', function(e) {
    clearTimeout(del_timeout);
    if (e.target!=this)
      return;
    $(this).html('Are you sure? <span class="delete_yes">Yes</span> <span class="delete_no">No</span>').addClass('delete_red');
    del_timeout = setTimeout(function() {$('.delete_no').click();}, 7000);
});
$('.share_on_facebook').live('click', function(e) {
  window.open($(this).data('u'), 'fb_share', 'width=650,height=400');
});

$('.box_comments').live('click', function(e) {
  if ($(this).hasClass('box_comment_open')) {
    $(this).removeClass('box_comment_open');
    $(this).parent().parent().find('.the_comments').addClass('hidden');
    $(this).parent().parent().find('.comment_input').addClass('hidden');
  } else {
    $(this).addClass('box_comment_open');
    $(this).parent().parent().find('.the_comments').removeClass('hidden');
    $(this).parent().parent().find('.comment_input').removeClass('hidden');
  }
});
$('.comment_reply').live('click', function() {
  var comment = $(this).parents('.one_comment');
  if (comment.data('reply')) {
    return;
  }
  comment.data('reply', true);
  var new_reply = create_comment_input(comment.attr('id'), 'comment_reply_input');
  var level = new_reply.parent().data('level');
  new_reply.css('left', 20)
  .find('.comment_input_textarea').css('width', 478-20*(level+2)).end()
  .find('.comment_input_cancel').removeClass('hidden').end()
  .removeClass('hidden');
  new_reply.find('.comment_input_textarea').focus();
  comment.css('padding-bottom', 170);
});
$('.comment_input_cancel').live('click', function() {
  $(this).parents('.one_comment').css('padding-bottom', '').data('reply', false).find('.comment_reply_input').remove();
});
$('.comment_submit').live('click', function() {
  if ($(this).hasClass('disabled')) {
    return;
  }
  var text = $(this).parent().parent().find('.comment_input_textarea').val();
  if (text=='') {
    return;
  }
  submit_comment($(this).parents('.comment_input'), text);
});
function submit_comment(comment, text)
{
  comment.find('.comment_submit').addClass('disabled');
  comment.fadeTo('fast', 0.3);
  var parent = comment.parent();
  var id = /\d+/.exec(parent.attr('id'))[0];
  var reply_to_comment = 0;
  if (parent.hasClass('one_comment')) {
    id = /\d+/.exec(parent.parent().parent().attr('id'))[0];
    reply_to_comment = /\d+/.exec(parent.attr('id'))[0];
  }
  $.post('/-comment', {
    id:id,
    text:text,
    reply_to_comment:reply_to_comment
    }, function(data) {
      var new_id = parseInt(data);
      if (new_id>0) {
        comment.find('.comment_input_textarea').val('');
        comment.find('.comment_submit').removeClass('disabled');
        comment.fadeTo('fast', 1);
        // create the new comment
        var new_comment = {
          created: 'Just now',
          id: new_id,
          foreign_id: my_details.foreign_id,
          user_profile: {profile_pic:my_details.pic,name:my_details.rel_name},
          text: text,
          screen_name: '',
          tweet_id:0
        }
        var container;
        if (reply_to_comment > 0) {
          var replied_to = $('#comment_'+reply_to_comment);
          new_comment.level = replied_to.data('level')+1;
          create_one_comment(new_comment).insertAfter(replied_to);
          replied_to.css('padding-bottom', '');
          comment.addClass('hidden');
          container = comment.parents('.the_comments');
        } else {
          new_comment.level = 0;
          container = comment.prev();
          create_one_comment(new_comment).appendTo(container);
        }
        color_comments(container);
      }
  });
}
function add_like(like)
{
  like.addClass('like_voted');
  var like_id = like.attr('id').substring(5);
  profile_data.likes[like_id].voted = true;
  profile_data.likes[like_id].likes++;
  like.html(profile_data.likes[like_id].likes);
  $.post('/vote', {
    id:like_id,
    type:'like'
  })
}


$('.verb_anchor').live('click', function(e) {
        $('#timeline_proto').fadeOut(500);
        $('.timeline_popular').fadeOut(500);
        load_verb($(this).text().ucFirst());
})

$('.permalink > input').live('click', function(e) {
  $(this).focus().select();
  
});
// Loading of initial verb data
// Check if verb exists within profile_data, if not - go ajax
function load_verb(verb)
{
  if (typeof profile_data.verbs[verb] == 'undefined') {
          data_ajax[verb] = true;
          $.post('/get_verb/',
                 {
                    uid: uid,
                    verb: verb,
                    count:15
                  },
                  function (data) {
                    profile_data.verbs[verb] = data;
                    for (var i=0;i<data.data.length;i++) {
                      profile_data.likes[data.data[i].id] = {
                        likes: data.data[i].likes,
                        voted: data.data[i].voted
                      }
                    }
                    data_ajax[verb] = false;
                    create_verb(verb);
          }, 'json');
  } else {
          create_verb(verb);
          // initiate verb item rescan here
  }
}


// Create initial timeline
function create_timeline()
{
  if (uid==0) return;
  var full_name = "";
  active_panel = "_timeline";
  effective_height = 0;
  max_displayed = 0;
        $('#verb_proto').fadeOut(200);
        $('.ajax-loader').fadeOut(200);
        $('#timeline_proto > .timeline_box_main').remove();
        $('#timeline_proto > .timeline_popular, #timeline_proto > .timeline_boxes').html('');
        $('#timeline_proto').show();
        $('.timeline_popular').show();
        var pop_str = (is_owner) ? "You've mostly been " : full_name.substring(0, full_name.indexOf(" "))+" has mostly been ";
        pop_str += profile_data.popverbs.data.join(', ') + ".";
        pop_str = pop_str.replace(/\,(?!.*\,.*)/, ' and ');
        $('.timeline_popular').html(pop_str);
        
        create_timeline_boxes();
}

// Create boxes for timeline
// This function takes care of loading extra content if needed
// Adds more boxes from profile_data.timeline 
var data_ajax = {
      '_timeline':false
};
var main_verb = '';
function create_timeline_boxes()
{
        // check if we need to ajax in some more boxes
        if (max_displayed>profile_data.timeline.length-3 && profile_data.timeline.length<profile_data.popverbs.total && !data_ajax._timeline) {
          data_ajax._timeline = true;
          $.post('/get_timeline/', {
            to: profile_data.timeline[profile_data.timeline.length-1].date,
            uid: uid,
            count: 9
            }, function(data) {
              for (var i=0;i<data.length;i++) {
                profile_data.timeline.push(data[i]);
                profile_data.likes[data[i].id] = {
                  likes: data[i].likes,
                  voted: data[i].voted
                }
              }
              if (data.length>0) {
                data_ajax._timeline = false;
              }
              create_timeline_boxes();
          }, 'json');
        }
        var top = Math.floor(max_displayed/3);
        var left = max_displayed%3;
        var box_width = 215;
        var box_height = 305;
        var offset_top = 271;

        for (var i=max_displayed;i<profile_data.timeline.length;i++) {
                data = profile_data.timeline[i];
                if (left>=3) {
                        left -=3;
                        top++;
                        // we want at least 9 boxes and more if there's room
                        // checking that the last row is below the fold
                        if (i>8 && $(window).height()+$(document).scrollTop() < (offset_top+(top-1)*box_height)) {
                          effective_height = offset_top+(top-1)*box_height;
                          // we have a scrollbar - can stop now
                          break;
                        }
                }
                if (top>2) {
                        $('#timeline_proto > .timeline_boxes').css('height', (top+1)*box_height+"px");
                }
                if (data.main_verb) {
                  // need to create a main box and update left and max_displayed accordingly
                  main_verb = data.verb;
                  mvre = new RegExp("(!"+data.o_verb+")", "gi");
                  $('#box_proto').clone().attr('id', 'box_'+data.id).hide().addClass('timeline_box_main').removeClass('pointer')
                    .css({top:top*box_height+"px", left:left*box_width+"px"})
                    .find('.box_title_text').addClass('main_verb_link').html("View " + owner_with_s+ " " + data.verb.toLowerCase() + " feed " + ((data.count>1)?" ("+(data.count-1)+" more)":"")).end()
                    .find('.box_title_number').html("").end()
                    .find('.box_text').html(data.text.replace(mvre, '<span class="main_verb_link">$1</span>')).end()
                    .find('.box_timestamp').html('<a href="http://twitter.com/'+screen_name+'/status/'+data.external_id+'" target="_blank">'+data.timestamp+'</a>').end()
                    .find('.delete_squib').removeClass('hidden').data('id', data.id).data('type','main').end()
                    .find('.box_views').html(data.views+" views").end()
                    .find('.box_like').attr('id','like_'+data.id).html(profile_data.likes[data.id].likes).addClass((profile_data.likes[data.id].voted)?'like_voted':'nullClass').end()
                    .find('.timeline_main_padder').removeClass('hidden').end()
                    .find('.box_share').removeClass('hidden')
                      .find('.share_on_twitter').attr('href', 'http://twitter.com/home?status='+data.verb+' on Squibr (via @'+screen_name+') http://mo.nu/'+data.monurl).end()
                      .find('.share_on_facebook').data('u', "http://www.facebook.com/sharer.php?u=http://mo.nu/"+data.monurl).end()
                      .find('.permalink input').val('http://mo.nu/'+data.monurl).end()
                    .end()
                    .data('verb', data.verb)
                    .find('.box_comments').text((data.comments.length>0?data.comments.length+" ":"")+'Comment'+(data.comments.length==1?'':'s')).removeClass('hidden').addClass('box_comment_open').end()
                    .prependTo($('#timeline_proto')).delay(50*i).fadeIn(200);
                  links = data.links;
                  for (j in links) {
                    switch(links[j].type) {
                      case 'image':
                        $('#box_'+data.id+' .timeline_main_padder').before('<a class="external_media e_m_large" href="'+links[j].url+'" target="_blank"><img src="'+links[j].src+'" /></a>');
                        break;
                      case 'flash':
                        $('#box_'+data.id+' .timeline_main_padder').before('<div class="external_media e_m_large" ><div id="flash_'+data.id+'" ></div></div>');
                        swfobject.embedSWF(links[j].src, "flash_"+data.id, "600", "450", "9.0.0", "/public/static/expressInstall.swf", false, {allowfullscreen:true, allowscriptaccess:'always',wmode:'opaque'});
                        break;
                    }
                  }
                  var others = data.others;
                  var verb = data.verb;
                  $('#box_'+data.id+' .box_buttons').before(show_others(others, verb));
                  
                  // create comments
                  create_comments(data.comments, 'box_'+data.id);
                  max_displayed++;
                } else {
                  if (data.verb != main_verb) {
                    $('#box_proto').clone().attr('id', 'box_'+data.id).hide()
                      .css({top:top*box_height+"px", left:left*box_width+"px"})
                      .find('.box_title_text').html(data.verb).end()
                      .find('.box_title_number').html((data.count-1>0)?" "+(data.count-1)+" more":"").end()
                      .find('.box_text').html(data.abbr).end()
                      .find('.box_timestamp').html('<a href="http://twitter.com/'+screen_name+'/status/'+data.external_id+'" target="_blank">'+data.timestamp+'</a>').end()
                      .find('.box_views').html(data.views+" views").end()
                      .find('.box_like').attr('id','like_'+data.id).html(profile_data.likes[data.id].likes).addClass((profile_data.likes[data.id].voted)?'like_voted':'nullClass').end()
                      .data('verb', data.verb)
                      .appendTo($('#timeline_proto > .timeline_boxes')).delay(50*i).fadeIn(200);
                    // only showing first link
                    var show_people = true;
                    if (data.links) {
                      link = data.links[0];
                      switch(link.type) {
                        case 'image':
                          $('#box_'+data.id+' .box_buttons').before('<div class="external_media_thumb" ><img src="'+link.src+'" id="e_m_'+data.id+'" /></div>');
                          show_people = false;
                          break;
                        case 'flash':
                          if (link.thumb) {
                            $('#box_'+data.id+' .box_buttons').before('<div class="external_media_thumb" ><img src="'+link.thumb+'" id="e_m_'+data.id+'" /><div class="video_icon"></div></div>');
                            show_people = false;
                          }
                          break;
                      }
                    }
                    // resizing image to 170x95 and centering
                    $('#e_m_'+data.id).load(function(e) {
                      var h = $(this).attr('height');
                      var w = $(this).attr('width');
                      if (h>0&&w>0) {
                        var adj_h = 170/w*h;
                        $(this).css('top', ((95-adj_h)/2)+'px' );
                      }
                      $(this).show();
                    });

                    if (show_people) {
                      // no media to show, create other people widget
                      var others = data.others;
                      var verb = data.verb;
                      $('#box_'+data.id+' .box_buttons').before(show_others(others, verb));
                    }
                    


                    max_displayed = (top*3+left)+1;
                    left++;
                  }
                }
        }
}


function create_verb(verb, internal)
{
        if (typeof profile_data.verbs[verb]=='undefined') {
                return false;
        }
        active_panel = verb;
        effective_height = 0;
        max_displayed = 0;
        var this_verb = profile_data.verbs[verb];
        $('#timeline_proto').fadeOut(200);
        $('.timeline_popular').fadeOut(200);
        $('.ajax-loader').fadeOut(200);
        $('#verb_proto').fadeIn(200);
        $('#verb_proto .verb_list').fadeIn(200);
        $('#verb_proto .verb_header_text').html(owner_with_s+" "+verb.toLowerCase()+" feed").fadeIn(200);
        $('#verb_proto .verb_item').remove();
        create_verb_items(verb);
        $('#verb_proto .verb_item:last').addClass('verb_item_last');
}

function create_verb_items(verb)
{
      var data = profile_data.verbs[verb].data;
      // check if we need to ajax in some more boxes
      if (max_displayed>data.length-3 && data.length<profile_data.verbs[verb].total && !data_ajax[verb]) {
        data_ajax[verb] = true;
        $.post('/get_verb/', {
          verb: verb,
          to: profile_data.verbs[verb].data[profile_data.verbs[verb].data.length-1].created_at,
          uid: uid,
          count: 10
          }, function(data) {
            for (var i=0;i<data.data.length;i++) {
              profile_data.verbs[verb].data.push(data.data[i]);
              profile_data.likes[data.data[i].id] = {
                likes: data.data[i].likes,
                voted: data.data[i].voted
              }
            }
            if (data.data.length>0) {
              data_ajax[verb] = false;
            }
            create_verb_items(verb);
        }, 'json');
      }
      for (var i=max_displayed;i<data.length;i++) {
              if (i>4 && $(window).height()+$(document).scrollTop() < effective_height) {
                // we have a scrollbar - can stop now
                break;
              }

              $('#item_proto').clone().attr('id', 'item_'+data[i].id)
                .find('.item_text').html(data[i].text).end()
                .find('.box_timestamp').html('<a href="http://twitter.com/'+screen_name+'/status/'+data[i].external_id+'" target="_blank">'+data[i].timestamp+'</a>').end()
                .find('.box_views').html(data[i].views+" views").end()
                .find('.box_like').attr('id','like_'+data[i].id).addClass((profile_data.likes[data[i].id].voted)?'like_voted':'nullClass').html(profile_data.likes[data[i].id].likes).end()
                .find('.delete_squib').data('id', data[i].id).data('type', 'verb').end()
                .find('.box_share').removeClass('hidden')
                  .find('.share_on_twitter').attr('href', 'http://twitter.com/home?status='+verb+' on Squibr (via @'+screen_name+') http://mo.nu/'+data[i].monurl).end()
                  .find('.share_on_facebook').data('u', "http://www.facebook.com/sharer.php?u=http://mo.nu/"+data[i].monurl).end()
                  .find('.permalink input').val('http://mo.nu/'+data[i].monurl).end()
                .end()
                .find('.box_comments').text((data[i].comments.length>0?data[i].comments.length+" ":"")+'Comment'+(data[i].comments.length==1?'':'s')).end()
                .appendTo('#verb_proto .verb_updates');
              max_displayed = i+1;
              effective_height = $('#verb_proto .verb_item:last').offset().top;
              
              create_comments(data[i].comments, 'item_'+data[i].id, true);
              
              var links = data[i].links;
              for (j in links) {
                switch(links[j].type) {
                  case 'image':
                    $('#item_'+data[i].id+' .box_buttons').before('<a class="external_media" href="'+links[j].url+'" target="_blank"><img src="'+links[j].src+'" /></a>');
                    break;
                  case 'flash':
                    $('#item_'+data[i].id+' .box_buttons').before('<div class="external_media" ><div id="verb_flash_'+data[i].id+'" ></div></div>');
                    swfobject.embedSWF(links[j].src, "verb_flash_"+data[i].id, "600", "450", "9.0.0", "/public/static/expressInstall.swf", false, {allowfullscreen:true, allowscriptaccess:'always',wmode:'opaque'});
                    break;
                }

              }
              $('#item_'+data[i].id+' .box_buttons').before('<div class="clearall"></div>');
              

      }
      $('#verb_proto .verb_item').removeClass('verb_item_last');
  
}

function resizeImage(image, width, height, maxWidth, maxHeight) {
        var ratio = 0;  // Used for aspect ratio
        // Check if the current width is different than the max
        if(width != maxWidth){
            ratio = maxWidth / width;   // get ratio for scaling image
            image.css("width", maxWidth); // Set new width
            image.css("height", (height * ratio));  // Scale height based on ratio
	    image.css("top", (0-((parseInt(image.css('height'))-maxHeight)/2))+"px"); // Center image
            height = height * ratio;    // Reset height to match scaled image
            width = maxWidth;    // Reset width to match scaled image
	}

        // Check if current height is smaller than max
        if(height < maxHeight){
            ratio = maxHeight / height; // get ratio for scaling image
            image.css("height", maxHeight);   // Set new height
            image.css("width", (width * ratio));    // Scale width based on ratio
	    image.css("top", "0px"); // Center image
	    image.css("left", (0-((parseInt(image.css('width'))-maxWidth)/2))+"px"); // Center image
            width = width * ratio;    // Reset width to match scaled image
        }
}

function set_profile_pic(image, invalidate)
{
    if (invalidate) {
      /* TODO: tell server to reload user details */
      $.get('/invalidate/'+x_uid, function(e) {
        
      });
    }
    if (image.indexOf('default_profile') == -1) {
      image = image.replace('_normal', '');
    }
    profile_pic = document.createElement('img');
    $(profile_pic).load(function(e) {
      var img = $('.user_pic > img');
      img.hide();
      img.attr('src', $(this).attr('src'));
      resizeImage(img, $(this).attr('width'), $(this).attr('height'), 280, 280);
      img.show();
      $(this).remove();
    });
    $(profile_pic).error(function(e) {
      // failed - this usually means the profile pic has been changed
      if (_twitter_user_profile_pic!=null) {
        // we already have a pic from twitter
        user_profile_pic = _twitter_user_profile_pic;
        _twitter_user_profile_pic = null;
        set_profile_pic(user_profile_pic, true);
      } else {
        user_profile_pic = null;
      }
      $(this).remove();
    });
    $(profile_pic).attr('src', image);
  
}

/**
 * show_others
 * Construct "also verbing" div from others array
 *
 * @param  others {array}   other people verbin
 * @param  verb   {string}  the verb
 */
function show_others (others, verb)
{
//  var others = profile_data.timeline[i].others;
  if (others.people.length>1) { // 1 means i am the only verber
    var others_div = '<div class="timeline_others"><div class="others_title">Other people '+verb.toLowerCase()+'...</div>';
    var shown=0;
    for (p in others.people) {
      var person = others.people[p];
      if (person.id != uid) {
        others_div += '<a class="other_box" href="/'+person.screen_name+'" title="Click to see what '+person.full_name+' is '+verb.toLowerCase()+'" ><img src="'+person.profile_pic+'" /></a>';
        if (shown>=3) {
          break;
        } else {
          shown++;
        }
      }
    }
    others_div += "</div>";
    return others_div;
  }
  return "";

}


function create_community_boxes(start_pos)
{
  if (typeof community_sampler == 'undefined' || community_sampler.people.length==0) {
    return false;
  }
  if (typeof start_pos == "undefined") {
    start_pos = max_displayed;
  }
  var top = Math.floor(start_pos/3);
  var left = start_pos%3;
  var box_width = 215;
  var box_height = 315;
  var offset_top = 271;
  data = community_sampler.people;
  for (var i=0;i<data.length;i++) {
    if (left>=3) {
            left -=3;
            top++;
            // we want at least 9 boxes and more if there's room
            // checking that the last row is below the fold
            if (i>8 && $(window).height()+$(document).scrollTop() < (offset_top+(top-1)*box_height)) {
              effective_height = offset_top+(top-1)*box_height;
              // we have a scrollbar - can stop now
              break;
            }
    }
    if (top>2) {
            $('#timeline_proto > .timeline_boxes').css('height', (top+1)*box_height+"px");
    }
    $('#cbox_proto').clone().attr('id', 'cbox_'+data[i].id).hide()
      .attr('href','/'+data[i].screen_name)
      .css({top:top*box_height+"px", left:left*box_width+"px"})
      .find('.cbox_profile_pic > img').attr('src', data[i].profile_pic).end()
      .find('.cbox_screen_name').html(data[i].screen_name).end()
      .find('.cbox_stats').html(data[i].stotal + " Squibs<br/> " + data[i].sumlikes + " loves").end()
      .find('.box_title_text').html("been " + data[i].verb).end()
      .find('.box_text').html(data[i].content).end()
      .appendTo($('#timeline_proto > .timeline_boxes')).delay(50*i).fadeIn(200);
    // only showing first link
    if (data[i].links) {
      link = data[i].links[0];
      switch(link.type) {
        case 'image':
          $('#cbox_'+data[i].id+' .box_text').after('<div class="external_media_thumb" ><img src="'+link.src+'" id="e_m_'+data[i].id+'" /></div>');
          break;
        case 'flash':
          if (link.thumb) {
            $('#cbox_'+data[i].id+' .box_text').after('<div class="external_media_thumb" ><img src="'+link.thumb+'" id="e_m_'+data[i].id+'" /><div class="video_icon"></div></div>');
          }
          break;
      }
    }
    // resizing image to 170x95 and centering
    $('#e_m_'+data[i].id).load(function(e) {
      var h = $(this).attr('height');
      var w = $(this).attr('width');
      if (h>0&&w>0) {
        var adj_h = 170/w*h;
        $(this).css('top', ((95-adj_h)/2)+'px' );
      }
      $(this).show();
    });


    start_pos = (top*3+left)+1;
    left++;
  }
}

function create_comments(comments, container, hidden)
{
  for (var c=0;c<comments.length;c++) {
    var comment = comments[c];
    create_one_comment(comment).appendTo($('#'+container+' .the_comments'));
    color_comments($('#'+container+' .the_comments'));
  }
  create_comment_input(container).removeClass(hidden?'':'hidden');
  
}
function create_one_comment(comment)
{
  var user_profile = comment.user_profile;
  if (user_profile==null) {
    user_profile = {name:false,profile_pic:"/public/images/v2/default-guest_pic.png"};
  }
  // Double ternary... yikes!
  // All this does is stick the name You if its you, Guest for guests, full name or screen name if its not you
  var display_name = (comment.foreign_id==my_details.foreign_id&&comment.foreign_id!=-1?'You':(user_profile.name?user_profile.name:comment.screen_name));
  var via = (comment.tweet_id>0?" <a href='http://twitter.com/"+comment.screen_name+"/status/"+comment.tweet_id+"' target='_blank'>via Twitter</a>":" via Squibr");
  var reply_span = (logged_in?'<span class="comment_reply anchor">Reply</span>':'');
  var delete_span = (is_owner?'<span class="delete_comment pointer">Delete</span>':'');
  return $('#comment_row_proto').clone().attr('id', 'comment_'+comment.id).css('margin-left', comment.level*20).data('level', comment.level)
  .find('.comment_pic > img').attr('src', user_profile.profile_pic).end()
  .find('.comment_title').text(display_name).end()
  .find('.comment_body').text(comment.text).end()
  .find('.comment_status').html(comment.created+via+reply_span+delete_span).end();
}
function color_comments(container)
{
  $(container).find('.one_comment:even').addClass('comment_bg').end().find('.one_comment:odd').removeClass('comment_bg').end();
}
function create_comment_input(container, add_class)
{
  return $('#comment_input_proto').clone().attr('id', 'comment_input_'+container)
    .addClass(add_class)
    .find('.comment_pic > img').attr('src', my_details.pic).end()
    .find('.comment_title').text(my_details.name_rel).end()
    .find('.comment_input_login').html(logged_in?'':'<span href="#" onclick="$(\'#login_link\').click()">Login</span> or <span href="#" onclick="$(\'.save_me_too\').eq(0).click()">register</span>').end()
    .appendTo($('#'+container));
}

String.prototype.ucFirst = function () {
    return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
};
if (typeof console == 'undefined') {
  console = {log:function(){}};
}
