var effective_height = 0;
var max_displayed = 0;
var active_panel = '_timeline';
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();
                //$('.modal-mask').fadeTo(250, 0.6);
                //$('.modal-settings').fadeIn(350);
        });
        $('.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 {
            create_timeline();
          }
          if (typeof community_sampler != 'undefined') {
            create_community_boxes();
          }
          
          $('#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).parent().parent().attr('id')+')').fadeOut(200);
        $('#timeline_proto').delay(200).fadeOut(600);
        $('.timeline_popular').delay(200).fadeOut(600);
        load_verb($(this).data('verb'));
});

$('.main_verb_link').live('click', function(e) {
        $('.timeline_box:not(#'+$(this).parent().parent().attr('id')+')').fadeOut(200);
        $('#timeline_proto').delay(200).fadeOut(600);
        $('.timeline_popular').delay(200).fadeOut(600);
        load_verb($(this).parent().parent().data('verb'));

});
$('.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) {
    delete_squib($(this).parent().data('id'), $(this).parent().data('type'));
    $(this).parent().html('Deleting...').removeClass('delete_red');
});
function delete_squib(squib, type)
{
    $.post('/_perform/delete', {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();
        }
      }
    });
}
$('.delete_no').live('click', function(e) {
    $(this).parent().html('Delete this Squib').removeClass('delete_red');
});
$('.delete_squib').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');
});
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') {
          $('.ajax-loader').delay(600).fadeIn(250);
          data_ajax[verb] = true;
          $.post('/get_verb/',
                 {
                    uid: uid,
                    verb: verb,
                    count:15
//                    to: profile_data.verbs[verb][profile_data.verbs[verb].length-1].created_at
                  },
                  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');
          //$.getJSON(site_base+'v2/get_verb/'+uid+'/'+verb+'?callback=?', function (data) {
          //        profile_data.verbs[verb] = data;
          //        create_verb(verb);
          //});
  } else {
          create_verb(verb);
          // initiate verb item rescan here
  }
}


//$('.verb_side_link').live('click', function(e) {
//        var verb = $(this).find('.verb_side_title').text();
//        if (typeof profile_data.verbs[verb] == 'undefined') {
//                $('.verb_list').fadeOut(200);
//                $('.verb_others').fadeOut(200);
//                $('#verb_proto .verb_header_text').fadeOut(200);
//                $('.ajax-loader').delay(400).fadeIn(250);
//                $.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++) {
                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 (profile_data.timeline[i].main_verb) {
                  // need to create a main box and update left and max_displayed accordingly
                  main_verb = profile_data.timeline[i].verb;
                  mvre = new RegExp("(!"+profile_data.timeline[i].o_verb+")", "gi");
                  $('#box_proto').clone().attr('id', 'box_'+profile_data.timeline[i].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+ " " + profile_data.timeline[i].verb.toLowerCase() + ((profile_data.timeline[i].count>1)?" feed ("+(profile_data.timeline[i].count-1)+" more)":"")).end()
                    .find('.box_title_number').html("").end()
                    .find('.box_text').html(profile_data.timeline[i].text.replace(mvre, '<span class="main_verb_link">$1</span>')).end()
                    .find('.box_timestamp').html('<a href="http://twitter.com/'+screen_name+'/status/'+profile_data.timeline[i].external_id+'" target="_blank">'+profile_data.timeline[i].timestamp+'</a>').end()
                    .find('.delete_squib').removeClass('hidden').data('id', profile_data.timeline[i].id).data('type','main').end()
                    .find('.box_views').html(profile_data.timeline[i].views+" views").end()
                    .find('.box_like').attr('id','like_'+profile_data.timeline[i].id).html(profile_data.likes[profile_data.timeline[i].id].likes).addClass((profile_data.likes[profile_data.timeline[i].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='+profile_data.timeline[i].verb+' on Squibr (via @'+screen_name+') http://mo.nu/'+profile_data.timeline[i].monurl).end()
                      .find('.share_on_facebook').data('u', "http://www.facebook.com/sharer.php?u=http://mo.nu/"+profile_data.timeline[i].monurl).end()
                      .find('.permalink input').val('http://mo.nu/'+profile_data.timeline[i].monurl).end()
                    .end()
                    .data('verb', profile_data.timeline[i].verb)
                    .prependTo($('#timeline_proto')).delay(50*i).fadeIn(200);
//                  max_displayed = i+3;
//                  left += 3;
                  links = profile_data.timeline[i].links;
                  for (j in links) {
                    switch(links[j].type) {
                      case 'image':
                        $('#box_'+profile_data.timeline[i].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_'+profile_data.timeline[i].id+' .timeline_main_padder').before('<div class="external_media e_m_large" ><div id="flash_'+profile_data.timeline[i].id+'" ></div></div>');
                        swfobject.embedSWF(links[j].src, "flash_"+profile_data.timeline[i].id, "600", "450", "9.0.0", "/public/static/expressInstall.swf", false, {allowfullscreen:true, allowscriptaccess:'always',wmode:'opaque'});
                        break;
                    }
                  }
                  var others = profile_data.timeline[i].others;
                  var verb = profile_data.timeline[i].verb;
                  $('#box_'+profile_data.timeline[i].id+' .box_buttons').before(show_others(others, verb));
                  
                } else {
                  if (profile_data.timeline[i].verb != main_verb) {
                    $('#box_proto').clone().attr('id', 'box_'+profile_data.timeline[i].id).hide()
                      .css({top:top*box_height+"px", left:left*box_width+"px"})
                      .find('.box_title_text').html(profile_data.timeline[i].verb).end()
                      .find('.box_title_number').html((profile_data.timeline[i].count-1>0)?" "+(profile_data.timeline[i].count-1)+" more":"").end()
                      .find('.box_text').html(profile_data.timeline[i].abbr).end()
                      .find('.box_timestamp').html('<a href="http://twitter.com/'+screen_name+'/status/'+profile_data.timeline[i].external_id+'" target="_blank">'+profile_data.timeline[i].timestamp+'</a>').end()
                      .find('.box_views').html(profile_data.timeline[i].views+" views").end()
                      .find('.box_like').attr('id','like_'+profile_data.timeline[i].id).html(profile_data.likes[profile_data.timeline[i].id].likes).addClass((profile_data.likes[profile_data.timeline[i].id].voted)?'like_voted':'nullClass').end()
                      .data('verb', profile_data.timeline[i].verb)
                      .appendTo($('#timeline_proto > .timeline_boxes')).delay(50*i).fadeIn(200);
                    // only showing first link
                    var show_people = true;
                    if (profile_data.timeline[i].links) {
                      link = profile_data.timeline[i].links[0];
                      switch(link.type) {
                        case 'image':
                          $('#box_'+profile_data.timeline[i].id+' .box_buttons').before('<div class="external_media_thumb" ><img src="'+link.src+'" id="e_m_'+profile_data.timeline[i].id+'" /></div>');
                          show_people = false;
                          break;
                        case 'flash':
                          if (link.thumb) {
                            $('#box_'+profile_data.timeline[i].id+' .box_buttons').before('<div class="external_media_thumb" ><img src="'+link.thumb+'" id="e_m_'+profile_data.timeline[i].id+'" /><div class="video_icon"></div></div>');
                            show_people = false;
                          }
                          break;
                      }
                    }
                    // resizing image to 170x95 and centering
                    $('#e_m_'+profile_data.timeline[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();
                    });

                    if (show_people) {
                      // no media to show, create other people widget
                      var others = profile_data.timeline[i].others;
                      var verb = profile_data.timeline[i].verb;
                      $('#box_'+profile_data.timeline[i].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 > .timeline_popular, #timeline_proto > .timeline_boxes').html('');
        $('#verb_proto').fadeIn(200);
        $('#verb_proto .verb_list').fadeIn(200);
        $('#verb_proto .verb_header_text').html(owner_with_s+" "+verb+" feed").fadeIn(200);
        $('#verb_proto .verb_item').remove();
        //var data = profile_data.verbs[verb].data;
        //for (var i=0;i<data.length;i++) {
        //        $('#item_proto').clone().attr('id', 'item'+data[i].tweet_id)
        //        .find('.item_text').html(data[i].text).end()
        //        .find('.box_like').html(1).end()
        //        .appendTo('#verb_proto .verb_updates');
        //}
        create_verb_items(verb);
        $('#verb_proto .verb_item:last').addClass('verb_item_last');
        //$('#verb_proto .verb_others').fadeIn(200);
        //var tl = profile_data.timeline
        //var v_len = (tl.length>9)?9:tl.length;
        //$('#verb_proto .verb_side_link').remove();
        //for (var i=0;i<v_len;i++) {
        //        if ($('#side_'+tl[i].verb).length==0 && tl[i].verb != verb) {
        //                $('#side_proto').clone().attr('id', 'side_'+tl[i].verb)
        //                .find('.verb_side_title').html(tl[i].verb).end()
        //                .find('.verb_side_total').html(tl[i].count).end()
        //                .appendTo('#verb_proto .verb_others');
        //                //if (tl[i].verb == verb) {
        //                //	$('#side_'+tl[i].verb).addClass('side_selected');
        //                //}
        //        }
        //}
}

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();
        }, 'json');
      }
      for (var i=max_displayed;i<data.length;i++) {
              if (i>8 && $(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()
                .appendTo('#verb_proto .verb_updates');
              max_displayed = i+1;
              effective_height = $('#verb_proto .verb_item:last').offset().top;
              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 load_media(element, url)
{
  $.post('/pheidippides.php', {url: url}, function(data) {
    switch(data.type) {
      case 'image':
        element.after('<a class="external_media" href="'+url+'" target="_blank"><img src="'+data.src+'" width="385" /></a>');
        break;
      case 'flash':
        break;
    }
  }, 'json');
  
}

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()
{
  if (typeof community_sampler == 'undefined' || community_sampler.people.length==0) {
    return false;
  }
  var top = Math.floor(max_displayed/3);
  var left = max_displayed%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();
    });


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



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