if( typeof(LargeTicker) == 'undefined'){ LargeTicker = {}; }

bu.popup.to_hide(['#ad_unit_300_250']);

LargeTicker.init = function(){
  Sharer.ref_override = 'r__view';
  LargeTicker.channel = new api.Channel( LargeTicker.new_channel_data );
  var group_submitter_app = group_submitter.make({'channel':LargeTicker.channel, 'ref_override':'r__view'});
  var group_submitter_widget = group_submitter_app.views.standard({'on_done_sharing':bu.popup.close});
  $('#group_submitter_holder').html(group_submitter_widget).append(DIV({'style':'clear:both;'}));
  bu.hinted({hint:translate('enter_your_email')}, $('#username_for_fanning'));
  api.Channel.channels[ LargeTicker.channel.channel_id ] = LargeTicker.channel;

  LargeTicker.channel_template_instance = new api.Channel.Template();
  LargeTicker._ticker_size = 'small';

  if( window.location.href.indexOf('map=2') > 0 ){
    var iid = window.location.href.match(/iid=(\d*)/);
    if( iid != null ){
      iid = iid[1];
    }
    LargeTicker.initial_view('grid', iid);
  }else{
    LargeTicker.initial_view('slideticker');
  }

  //api.User.templates.render_channel_list( LargeTicker.channel['owner_user_id'], "120", "400", "channel_list_holder" );

  api.Review.Template.update_rate_outside = LargeTicker.update_channel_data;
  LargeTicker.review_template_instance = new api.Review.Template(LargeTicker.li_nxuid);
  var reviewsDiv = LargeTicker.review_template_instance.render_review_section(LargeTicker.channel.reviews,
                                                                              LargeTicker.channel.total_review_count,
                                                                              LargeTicker.channel.channel_id);
  $("#ticker_reviews_body").append( reviewsDiv );
  LargeTicker.init_channel_label();
  ChannelBrowser.init();

  if( LargeTicker.channel.privacy === "invite" ){ $('#embed_code').hide(); }
  $(window).bind("resize", LargeTicker.on_resize);

  if( AppBase.user && LargeTicker.viewer_is_invited && LargeTicker.viewer_can_fan ){
    AppBase.ual('largeticker_overlay_add_friend_show');
    bu.popup(DIV({'class':'slide_message'},
      DIV({'class':'overlay_mugshot'},LargeTicker.owner.render_mugshot({'frame':true})),
      P({},translate('would_you_like_to_befriend', LargeTicker.owner.display_name)),
      BUTTON({'class':'big_yellow_button', 'onclick':LargeTicker.on_click_add_friend_from_tutorial}, translate('Yes')),
      A({onclick:function(){LargeTicker.on_click_no_thanks_from_tutorial('add_friend');}}, translate('no_thanks')),
      DIV({'style':'clear:both'})
    ), {'dim':true, 'width':'400'});
  }
};

LargeTicker.on_click_add_friend_from_tutorial = function(){
  AppBase.ual('largeticker_overlay_add_friend_accept');
  bu.popup(DIV({'class':'slide_message'},
    H1({'class':'overlay_feedback'}, translate('Thanks!')),
    DIV({'style':'clear:both'})
  ), {'autoclose':false});
  api.User.fan( {'puid':LargeTicker.owner.puid} );
  window.location.reload();
};

LargeTicker.on_click_no_thanks_from_tutorial = function( context ){
  if( context === 'add_friend' ){
    AppBase.ual('largeticker_overlay_add_friend_no_thanks');
  }
  bu.popup.close();
};


LargeTicker.close_sharer_and_thank = function(){
  bu.popup(DIV({'id':'email_sharing_thanks'}, translate('thanks_for_sharing_by_email')));
  setTimeout(bu.popup.close, 3000);
};

/**
 * POPUP LINKS
 */
LargeTicker.popup_sharer = function(){

  Sharer.initialize({
    'channel' : LargeTicker.new_channel_data,
    'pxcid' : LargeTicker.pxcid,
    'pcid' : LargeTicker.pcid,
    'to_share' : LargeTicker.channel,
    'on_finished' : LargeTicker.close_sharer_and_thank,
    'do_forward_to_live' : false
  });

  AppBase.ual('popup_sharer');
  bu.popup($('#send_container'), {
    'dim':true,
    'top':'center',
    'padding':'10px',
    'closable' : true,
    'width':370
  });
};

LargeTicker.popup_embed_code = function(){
  AppBase.ual('popup_embed_code');
  bu.popup($('#embed_code'), {
    'dim':true,
    'top':'center',
    'padding':'10px',
    'on_popup':function(){
      $('#embedCode').focus().select();
    },
    'closable' : true,
    'width':438
  });
};

LargeTicker.popup_share_link = function(){
  AppBase.ual('popup_share_link');
  bu.popup($('#share_link'), {
    'dim':true,
    'top':'center',
    'padding':'10px',
    'on_popup':function(){
      $('#url').focus().select();
    },
    'closable' : true,
    'width':438
  });
};

LargeTicker.popup_group_submitter = function(){
  AppBase.ual('popup_group_submitter');
  bu.popup($('#group_submitter_container'), {
    'dim':true,
    'top':'center',
    'padding':'10px',
    'closable' : true,
    'width':675
  });
};

LargeTicker.close_sharer_overlay = function(){
  $('#hidden_space').html($('#send_container'));
  bu.popup.close();
};


/**
 * Initial Ticker Rendering - separated from change_view to log initial display
 * @param view_type determines how pictures are shown in the ticker
 * @param iid (optional) initial item id, only considered for grid view. Stored in LargeTicker NS
 */
LargeTicker.initial_view = function( view_type, iid ){
  if( view_type == 'grid' ){
    AppBase.js_ual_log( 'initial_ticker_grid' );
  }else if( view_type == 'slideticker' ){
    AppBase.js_ual_log( 'initial_ticker_slideticker' );
  }
  LargeTicker._iid = iid;
  LargeTicker.change_view( view_type, true );
};

/**
 * Ticker Rendering
 * Change the view of the ticker and render the ticker.
 * @param new_view determines how pictures are shown in the ticker
 * @param iid (optional) initial item id, only considered for grid view
 * @param initial indicates whether we respect the iid and leave the logging ti initial_view
 */
LargeTicker.change_view = function( new_view, initial ){
  initial = lu.defaulted( initial, false );

  if( !initial && new_view == 'grid' ){
    AppBase.js_ual_log( 'transition_ticker_grid' );
  }else if( !initial && new_view == 'slideticker' ){
    AppBase.js_ual_log( 'transition_ticker_slideticker' );
  }
  LargeTicker._ticker_view = new_view;
  if( LargeTicker.channel.type === 'G' ){
    if( new_view === 'grid' ){
      $('a.gallery_view_button').unbind('click').addClass('disabled_link');
      $('a.original_view_button').bind('click', function(){ LargeTicker.change_view('slideticker'); }).removeClass('disabled_link');
      $('.original_toggle_pointer').removeClass('view_toggle_pointer_on').addClass('view_toggle_pointer_off');
      $('.grid_toggle_pointer').removeClass('view_toggle_pointer_off').addClass('view_toggle_pointer_on');
      $('#showcase_fullscreen .gallery_view_button').hide();
      $('#showcase_fullscreen .original_view_button').show();
    }else{
      $('a.original_view_button').unbind('click').addClass('disabled_link');
      $('a.gallery_view_button').bind('click', function(){LargeTicker.change_view('grid');}).removeClass('disabled_link');
      $('.original_toggle_pointer').removeClass('view_toggle_pointer_off').addClass('view_toggle_pointer_on');
      $('.grid_toggle_pointer').removeClass('view_toggle_pointer_on').addClass('view_toggle_pointer_off');
      $('#showcase_fullscreen .gallery_view_button').show();
      $('#showcase_fullscreen .original_view_button').hide();
    }
  }
  LargeTicker.render_ticker();
};

/**
 * Change the size of the ticker and render the ticker.
 */
LargeTicker.change_size = function( new_size ){
  if( new_size == 'fullscreen' ){
    AppBase.js_ual_log( 'ticker_fullscreen' );
  }else if( new_size == 'small' ){
    AppBase.js_ual_log( 'ticker_small' );
  }

  LargeTicker._ticker_size = new_size;
  LargeTicker.render_ticker();
};

/**
 * Close the fullscreen view. Safe to call anytime.
 */
LargeTicker.close_full_screen = function(){
  bu.popup.close();
  LargeTicker.change_size('small');
};


/**
 * Redraw the ticker
 */
LargeTicker.render_ticker = function(){
  var target_id;
  var dimensions = bu.window_dimensions();
  var popup_width = parseInt(dimensions.x - (dimensions.x / 10), 10);
  var flashVars = {};
  var adsense_channel = LargeTicker.adsense_channel;
  $('#ticker_holder, #ticker_holder_fullscreen').empty();

  if( LargeTicker._ticker_size == 'small'){
    LargeTicker.channel_template_instance._slideticker_size_factor = 1.35;
    target_id = 'ticker_holder';
    $('#showcase, #top_banner_ad, #ad_unit_300_250, #ticker_related_body').show();
    $('#showcase_fullscreen').hide();
  }else{
    target_id = 'ticker_holder_fullscreen';
    $('#showcase_fullscreen').show().css({'width':popup_width+"px"});
    $('#showcase, #top_banner_ad, #ad_unit_300_250, #ticker_related_body').hide();
    var std_w = LargeTicker.channel_template_instance._ticker_std_width;
    var std_h = LargeTicker.channel_template_instance._ticker_std_height;
    var ticker_width = popup_width;
    var ticker_height = parseInt(dimensions.y - 50, 10);
    var scaler = Math.min(ticker_width/std_w, ticker_height/std_h);
    adsense_channel = undefined; // No ads on large view
    if( LargeTicker.channel.privacy == 'public' && !(LargeTicker.channel.count <= 4 && LargeTicker._ticker_view == 'grid') ){
      flashVars['shareInterface'] = 'true';
      flashVars['shareInterfaceCallback'] = 'LargeTicker.share_clicked';
    }
    LargeTicker.channel_template_instance._slideticker_size_factor = scaler;
  }

  var map;
  if( LargeTicker.channel.privacy != 'public' ){
    map = "030100100";
  }else{
    map = "130100100";
  }

  LargeTicker.channel_template_instance._render_slideticker( LargeTicker.channel,
                                                             LargeTicker._ticker_view,
                                                             LargeTicker._iid,
                                                             adsense_channel,
                                                             {
                                                               'target_id':target_id,
                                                               'flashVars':flashVars,
                                                               'map':map
                                                             });
  if( LargeTicker._ticker_size == 'fullscreen'){
    bu.popup($("#showcase_fullscreen"), {
               'width':popup_width,
               'background-color':'black',
               'dim':true,
               'on_close':function(){LargeTicker.change_size('small');}
    });
  }
};

LargeTicker.share_clicked = function( target ){

  if( target == 'email' ){
    LargeTicker.close_full_screen();
    LargeTicker.popup_sharer();
  }else if( target == "embed" ){
    LargeTicker.close_full_screen();
    LargeTicker.popup_embed_code();
  }else if( target == "share" ){
    LargeTicker.close_full_screen();
    LargeTicker.popup_group_submitter();
  }else if( target == "link" ){
    LargeTicker.close_full_screen();
    LargeTicker.popup_share_link();
  }else if( target == "make" ){
    LargeTicker.close_full_screen();
    AppBase.js_ual_log( 'arrange_button' );
    window.location = '/arrange';
  }else if(target == "play"){
    if( LargeTicker._ticker_view == 'grid' ){
      LargeTicker.render_ticker();
    }
  }

};


LargeTicker.update_channel_data = function( new_rating ){
  $('#ticker_rating').empty().append(LargeTicker.render_stars_div(parseInt(parseInt(new_rating, 10)/20, 10), 10));
  if( parseInt(new_rating, 10) === 0 ){
    $('.api_review_rating_dependent').hide();
  }else{
    $('.api_review_rating_dependent').show();
  }
};


LargeTicker.init_channel_label = function(){
  $('#ticker_imagecount').text(translate('pictures_total',LargeTicker.channel.count));
  $('#ticker_date').text(AppBase.datestring(LargeTicker.channel.time));
  $('#ticker_rating').empty().append(LargeTicker.render_stars_div(parseInt(LargeTicker.channel.ratings['average']/20, 10)));
};


LargeTicker.render_stars_div = function( star_count ){
  starsDiv = SPAN({},'');
  if (star_count !== 0) {
    for (var i=0; i < Number(star_count); i++) {
      starsDiv.appendChild(SPAN({},
        IMG({'src':Serdes.make_static_url('/images/slidecom/staron_small.gif'), 'width':'11', 'height':'10'})
      ));
    }
    for (;i<5;i++) {
      starsDiv.appendChild(SPAN({},
        IMG({'src':Serdes.make_static_url('/images/slidecom/staroff_small.gif'), 'width':'11', 'height':'10'}
      )));
    }
  }else{
    starsDiv.style.height = '12px';
  }
  return starsDiv;
};

LargeTicker.fan_user = function( options ){
  options = lu.defaulted(options, {});
  options.on_fan = lu.defaulted(options.on_fan, function(){});
  options.on_fan_failure = lu.defaulted(options.on_fan_failure, function(){});
  api.User.fan({
    'puid' : LargeTicker.channel.owner_puid,
    'on_fan' : options.on_fan,
    'on_fan_failure' : options.on_fan_failure,
    'ref_override' : 'r__view'
  });
  return false;
};

LargeTicker.on_fan_while_logged_in = function( response ){
  if( response && response['error'] ){
    alert( translate('blocked_fan_deny'));
  }else{
    getObject('fan_while_logged_in_block').innerHTML = '<div class="fan_added">'+translate('fan_added')+'</div>';
  }
};

LargeTicker.affecting_field_for_fanning = function( event ){
  if( event.keyCode === 13 ){
    LargeTicker.fan_user_while_logged_out();
  }
  return false;
};

LargeTicker.fan_user_while_logged_out = function(){
  $('#username_for_fanning')[0].scrutenize();
  if( $('#username_for_fanning').val() ){
    LargeTicker.fan_user_while_logged_out.display('loading');
    LargeTicker.fan_user_while_logged_out.sign_in();
  }else{
    LargeTicker.fan_user_while_logged_out.inform('enter_username','username');
  }
  $('#username_for_fanning')[0].scrutenize(false);
};
LargeTicker.fan_user_while_logged_out.sign_in = function(){
  var options = {
    'username' : $('#username_for_fanning').val(),
    'password' : $('#password_for_fanning').val(),
    'on_success' : LargeTicker.fan_user_while_logged_out.sign_in.on_success,
    'on_failure' : LargeTicker.fan_user_while_logged_out.sign_in.on_failure,
    'do_signup' : true
  };
  AppBase.manual_login(options);
};
LargeTicker.fan_user_while_logged_out.sign_in.on_failure = function( result ){
  if( result === 'EMAIL_ALREADY_USED' ){
    $('#password_for_fanning').val('');
    LargeTicker.fan_user_while_logged_out.inform('wrong_password', 'username');
  }else if( result === 'PASSWORD_REQUIRED' ){
    LargeTicker.fan_user_while_logged_out.display('password');
  }else if( result === 'SIGNIN_BAD_COMBINATION' ){
    LargeTicker.fan_user_while_logged_out.inform('invalid_username', 'username');
  }else{
    LargeTicker.fan_user_while_logged_out.display('error');
  }
};
LargeTicker.fan_user_while_logged_out.sign_in.on_success = function( result ){
  LargeTicker.fan_user({
    'on_fan' : LargeTicker.fan_user_while_logged_out.on_fan,
    'on_fan_failure' : LargeTicker.fan_user_while_logged_out.on_fan_failure
  });
};
LargeTicker.fan_user_while_logged_out.on_fan = function( response ){
  LargeTicker.fan_user_while_logged_out.display('thanks');
};
LargeTicker.fan_user_while_logged_out.on_fan_failure = function( response ){
  if( response.error === 'cant_fan' ){
    LargeTicker.fan_user_while_logged_out.display('cant_fan');
  }else{
    alert('unknown_error_while_fanning');
  }
};

LargeTicker.fan_user_while_logged_out.display = function( focus ){
  $('#invalid_username_for_fanning_block, #loading_for_fanning_block, #username_for_fanning_block, #enter_username_for_fanning_block, #password_for_fanning_block, #error_for_fanning_block, #wrong_password_for_fanning_block').hide();
  var visible_block = $('#'+focus+'_for_fanning_block').show();
  visible_block.find('input:first').focus().val('');
};

LargeTicker.fan_user_while_logged_out.inform = function( focus, next_focus ){
  LargeTicker.fan_user_while_logged_out.display(focus);
  setTimeout(function(){LargeTicker.fan_user_while_logged_out.display(next_focus);}, 1500);
};


LargeTicker.reported_inappropriate = function(){
  $('#lt_report_link').empty();
  $('#lt_report_link')[0].appendChild(SPAN({'style':'color:white;'},translate('reported_thanks')));
};

/**
 * Called when browser window is resized, will redraw the ticker if we are in fullscreen mode and the window size has
 * changed more than 10 pixels
 */
LargeTicker.on_resize = function(e){
  var dim = bu.window_dimensions();
  var min_delta = 10;
  var changed_enough = Math.abs(dim.y - LargeTicker._on_resize_old_y ) > min_delta;
  changed_enough = changed_enough || Math.abs(dim.x - LargeTicker._on_resize_old_x ) > min_delta;

  if( changed_enough && LargeTicker._ticker_size == 'fullscreen'){
    LargeTicker._on_resize_old_x = dim.x;
    LargeTicker._on_resize_old_y = dim.y;
    LargeTicker.render_ticker();
  }
};
LargeTicker._on_resize_old_x = 0;
LargeTicker._on_resize_old_y = 0;

var displayReportPopup = function(location, id, offsetX, offsetY) {
	var frm = makeEditPopup(location, "This material is Inappropriate", null, offsetX, offsetY);

	frm.style.textAlign = "left";
	frm.style.fontSize = "8pt";
	frm.style.color = "black";

	createText(frm, "We promise to review each and every submission within 24-48 hours. Flagging tells us this is:");
	var why = createElement(frm, "p");
	why.style.fontWeight = "bold";
	why.style.fontSize = "9pt";
	why.style.margin = "5px 15px 5px 15px";
	createText(why, "-Sexually explicit");
	createElement(why, "br");
	createText(why, "-Violates our ");
	createLink(why, "/static/terms", "Terms of Use", "_blank");
	createText(frm, "If you are the copyright owner of this material and believe it has been uploaded without your permission, please follow ");
	var copyright = createElement(frm, "a");
	copyright.href = "/static/copyright";
	copyright.target = "_blank";
	copyright.innerHTML = " these directions";
	createText(frm, " to submit a copyright infringement notice.");

	var flagButton = createInput(editDiv, 'submit');
	flagButton.value = "Flag as Inappropriate";
	flagButton.onclick = function() {
		dismissEditPopup();
		asyncAction('channelajax',
			{ xaction: 'flagforreview',
			cid : id},
			function(theResponse){
				if (theResponse == 'PASS') {
					ShowUpdate(location, 10, 10, "Flagged");
				} else {
					alert(theResponse);
				}
			} );
		return false;
		};
	flagButton.focus();
	return false;
};


/**
 * Browse the Large Ticker owner's channels with this.
 */
ChannelBrowser = {};

ChannelBrowser.init = function(){
  api.Channel.fetch( LargeTicker.puid, 0, 'profile', ChannelBrowser._init_profile_channels, {'limit':12});
};

/**
 * UI software interface function -- Set the specified filter value and update channel listing and filter UI
 */
ChannelBrowser.filter_set = function(new_filter_val){
  if( new_filter_val == ChannelBrowser.current_filter_value ){ return false; }

  $('.chan_browser_ctl').hide();
  ChannelBrowser.current_filter_value = new_filter_val;
  $('ul#filters li').removeClass('filter_selected');
  $('#channels').empty();
  // Do an initial loading of the filter if needed
  if( ChannelBrowser.profileChannels[new_filter_val].length === 0 ){
    $('#related_channels_loading').show();
    ChannelBrowser.fetch_profile_channels( ChannelBrowser.on_filter_set );
  }else{ // Load filter channels from cache, increasing cache size in set_channel_thumb_page if needed
    ChannelBrowser.set_channel_thumb_page(0);
    $('li#'+ChannelBrowser.current_filter_value).addClass('filter_selected');
  }
  return true;
};

ChannelBrowser.on_filter_set = function( channels, users, filter_val, page_num){

  if( channels.length === 0 ){
    $("#related_channels_info").empty().text(translate(filter_val+"_none_found")).show();
    setTimeout("ChannelBrowser.filter_set('profile');$('#related_channels_info').hide();",3000);
    $("li#"+filter_val).unbind('click').css({'color':'#CCCCCC','cursor':'default'});
    $("li#"+filter_val)[0].onclick="return false";
    return;
  }

  if( ChannelBrowser.current_filter_value == filter_val && page_num == ChannelBrowser.curPageNum){
    ChannelBrowser.set_channel_thumb_page(0, filter_val);
  }

  if( ChannelBrowser.current_filter_value == filter_val ){
    $('li#'+ChannelBrowser.current_filter_value).addClass('filter_selected');
  }
};

/**
 * UI software interface function -- use this to page through the current filter's channel listing
 * You can directly request pages, but you must progressively initialize the filter. Call 0, 1, 2, 3, 4
 * before calling 5, because we need to initialize our cache with PSID-sequenced requests.
 *
 * You can switch from one filter to another arbitrarily, and request arbitrary pages after the
 * cache is initialized, but at first you MUST request pages in order.
 *
 * We load two sets at a time, showing one and then retrieving the second from the cache on request. This
 * triggers a new pair to be loaded, and we request a new pair of channels whenever we are showing
 * the last channel in the cache.
 */
ChannelBrowser.set_channel_thumb_page = function(pageNum){
  ChannelBrowser.curPageNum = pageNum;
  var filter_value = ChannelBrowser.current_filter_value;
  // Update UI
  $('.chan_browser_ctl').hide();
  $('#channels_next').unbind('click').click(function(){ChannelBrowser.set_channel_thumb_page(pageNum+1, filter_value);return false;});
  $('#channels_previous').unbind('click').click(function(){ChannelBrowser.set_channel_thumb_page(pageNum-1, filter_value);return false;});
  var pcs = ChannelBrowser.profileChannels[filter_value];
  var pcl = pcs.length;
  if( pageNum < 0 || pageNum >= pcl){
    throw "setting illegal page number";
  }

  if( pcl >= pageNum+2){
    $('#channels_next').show();
  }else{
    $('#channels_next').hide();
  }
  if( pageNum !== 0 ){
    $('#channels_previous').show();
  }else{
    $('#channels_previous').hide();
  }
  if( pcl >= pageNum+2 && pageNum !== 0){
    $('#chan_browser_pn_divider').show();
  }
  if( pageNum+1 == pcl && ChannelBrowser.profileChannelsPSIDS[filter_value] !== ""){
    $('#chan_browser_pn_divider').show();
    ChannelBrowser.fetch_profile_channels();
    $('#channels_next_fake').show();
  }

  // Update UI
  var newChannels = pcs[ pageNum ];
  ChannelBrowser.render_channel_thumbs( newChannels );
};


/**
 * Special api.Channel.fetch handler for the first request, in which we automatically draw the thumb page
 */
ChannelBrowser._init_profile_channels = function( channels, users, li_nxuid, psid, orig_tab){
  ChannelBrowser._on_fetch_profile_channels( channels, users, li_nxuid, psid, 0, 'profile');
  ChannelBrowser.set_channel_thumb_page(0, 'profile');
};

/**
 * updates the cache with the next set of channels of the current filter. safe to call after buffer is full.
 */
ChannelBrowser.fetch_profile_channels = function(on_fetch){
  var filter_val = ChannelBrowser.current_filter_value;
  var page_num = ChannelBrowser.curPageNum;

  if( typeof( on_fetch ) == "undefined" ){ on_fetch = function(){}; }

  api.Channel.fetch( LargeTicker.puid,
                     ChannelBrowser.profileChannelsPSIDS[filter_val],
                     filter_val,
                     function(channels, users, li_nxuid, psid){
                       ChannelBrowser._on_fetch_profile_channels(channels,
                                                                 users,
                                                                 li_nxuid,
                                                                 psid,
                                                                 page_num,
                                                                 filter_val);
                       on_fetch(channels, users, filter_val, page_num);
                     },
                     {'limit':12}
                   );
};

/**
 * Workhorse - adds a set of channels (and request metadata) to the cache and updates UI with new navigation options
 */
ChannelBrowser._on_fetch_profile_channels = function( channels, users, li_nxuid, psid, old_idx, old_filter_val){
  var pcs = ChannelBrowser.profileChannels[ChannelBrowser.current_filter_value];
  var curIdx = ChannelBrowser.profileChannels[ChannelBrowser.current_filter_value].length;
  var lenlim = Math.max(channels.length, 6);

  if( ChannelBrowser.current_filter_value != old_filter_val || old_idx != ChannelBrowser.curPageNum ){
    return false;
  }

  if( ChannelBrowser.current_filter_value == old_filter_val && old_idx == ChannelBrowser.curPageNum && channels.length > 0){
    $('#channels_next_fake').hide();
    $('#channels_next').show(); // We don't show the next link until channels are cached.
  }
  ChannelBrowser.profileChannelsPSIDS[old_filter_val] = psid;
  $('#related_channels_loading').hide();
  if( lenlim > 6 ){
    pcs[curIdx] = channels.slice(0,6);
    pcs[curIdx+1] = channels.slice(6,13);
  }else{
    pcs[curIdx] = channels;
  }
};


/**
 * This function renders channels to the canvas. If you want to do a live feed, request live channels from cmds/profile and hit this
 * repeatedly.
 */
ChannelBrowser.render_channel_thumbs = function( channels){
  $("#channels").empty();
  for( var i = 0; i < channels.length; i++ ){
    $('#channels').append( LargeTicker.channel_template_instance.render_channel_thumb( channels[i],channels[i].link,true,channels[i].pcid == LargeTicker.pcid ));
  }
};

/**
 * Dictionary of categories, each containing arrays of lt-owning user's profile channels.
 */
ChannelBrowser.profileChannels = {
  'profile':[],
  'profile_G':[],
  'profile_Q':[],
  'profile_C':[],
  'profile_P':[]
};

/**
 * Dictionary of categories and their most recent lookup psids. "" means we are done, 0 means we have not started
 */
ChannelBrowser.profileChannelsPSIDS = {
  'profile':0,
  'profile_G':0,
  'profile_Q':0,
  'profile_C':0,
  'profile_P':0
};

ChannelBrowser.current_filter_value = "profile";
ChannelBrowser.curPageNum = 0;
