function roomRand(returnit){var room="";var uv="1234567890abcdefghijklmnopqrstuvwxyz";for(var i=0;i<5;i++){room+=uv.charAt(Math.floor(Math.random()*33));}
$("#room-name").val(room);return room;}
function roomGo()
{if($('#room-name').length>0)
{if($("#room-name").val()==lang_chat_input_default||$("#room-name").val()==lang_choose_roomname||$("#room-name").val()=='')
{roomRand();}
$("#room-name").val($("#room-name").val().toLowerCase().replace(/([^a-z0-9_-])/g,""));if($("#room-name").val()==lang_chat_input_default||$("#room-name").val()==lang_choose_roomname||$("#room-name").val()=='')
{roomRand();}
var room=$("#room-name").val();}
else
{var room=roomRand(true);}
var room=base_url+room;self.location=room;}
function f(o){if(document.getElementById("room-name").value==lang_chat_input_default||document.getElementById("room-name").value==lang_choose_roomname||document.getElementById("room-name").value=='')
{o.value='';}
o.value=o.value.toLowerCase().replace(/([^a-z0-9_-])/g,"");}

$(document).ready(function()
{
	if($('#statuses').length > 0)
	{
		status_updates();
		TC.load_bit({'friends/people_you_follow_online': '#live_chat_rooms'}, on_bit_load);
		window.setTimeout(function()
		{
			TC.load_bit({"rooms/popular_chats" : "#popular_chat_rooms"}, on_bit_load);
		}, 0);
	}
	
	if($('#tags').length > 0)
	{
		TC.call("bit/activity/people_online", function(result)
		{
			if(typeof result.html !='undefined')
			{
				$('#people_list').html('');
				
				result.html = result.html.replace(/<img/gi, "<brokenimg");
				
				var div = $("<div></div>");
				div.html(result.html);
				$('#people_list').html(div.html());
			}
			else
			{
				$('#people_list').html(TC.bit_error_html());
			}
			
			adjust_people_pagination();
			
			$('.people_pagination .previous').click(function()
			{
				adjust_people_pagination(-1);
			});
			
			$('.people_pagination .next').click(function()
			{
				adjust_people_pagination(1);
			});
			
		});
		
		tags();
	}
});

var people_page = 1;
function adjust_people_pagination(dir)
{
	var users_per_page = 10;
	var total_users = $('#people .user').length;
	var total_pages = Math.ceil(total_users / users_per_page);
	
	var old_page = people_page;
		
	if(dir == 1)
	{
		people_page++;
	}
	else if(dir == -1)
	{
		people_page--;
	}
	
	if(people_page <= 1) { people_page = 1; }
	if(people_page > total_pages) { people_page = total_pages; }
	
	$('.people_pagination .page').html(people_page);
	$('.people_pagination .total_pages').html(total_pages);
	
	if(people_page > 1)
	{
		$('.people_pagination .previous').removeClass('disabled');
	}
	else
	{
		$('.people_pagination .previous').addClass('disabled');
	}
	
	if(people_page >= total_pages)
	{
		$('.people_pagination .next').addClass('disabled');
	}
	else
	{
		$('.people_pagination .next').removeClass('disabled');
	}
	
	st = (people_page - 1) * users_per_page;
	
	
	var users = $('#people .user');
	users.addClass('hidden');
	
	for(var i=0; i < users.length; i++)
	{
		if(i >= st && i < (st+users_per_page))
		{
			var user = $($('#people .user').get(i));
			
			user.removeClass('hidden');
			user.html(user.html().replace(/<brokenimg/gi, "<img"));
		}
	}
}

var rooms_by_tag_xhr;

function search_for_tag()
{
	var tag = $('#search_tags').val();
	$('#categories li').removeClass('active');
	$('#rooms_by_tag').html(TC.loading_bit_html());
	
	$('#room_search_copy').html('')
	
	var data = {tag: tag};	
	
	var cache = $.param(data);
	
	
	if(typeof tag_cache[cache] != 'undefined')
	{
		insert_tags(cache, tag_cache[cache]);
		return false;
	}
	
	
	if(typeof rooms_by_tag_xhr != 'undefined' && typeof rooms_by_tag_xhr.abort == 'function')
	{
		rooms_by_tag_xhr.abort();
	}

	rooms_by_tag_xhr = TC.call("tags/rooms", data, function(result) { insert_tags(cache, result); window.setTimeout(function() { $('#search_tags').trigger('keyup');  }, 0);});	
	return false;
}


var allow_category_change = false;
function tags()
{
	$('#categories li').click(function()
	{
		if($(this).hasClass('active') || !allow_category_change)
		{
			return;
		}
		
		$('#categories li').removeClass('active');
		$(this).addClass('active');
		
		$('#search_tags').val('').trigger('blur');
		
		refresh_tags();
	});
	
	$('#room_tabs li').click(function()
	{	
		$('#room_tabs li').removeClass('active');
		$(this).addClass('active');
		
		refresh_tags();
	});
	
	
	$('.room_pagination .previous').click(function() { adjust_tags_page(-1); });
	$('.room_pagination .next').click(function() { adjust_tags_page(1); });
	
	$('#search_tags').defaultValue($('#search_tags').val());
	$('#search_tags').keyup(function()
	{
		var search = $.trim($(this).val().toLowerCase());
		if(search.length == 0 || search == "")
		{
			if($('#room_search_copy .user').length > 0)
			{
				var html = $('#room_search_copy').html();
				$('#room_search_copy').html('');
				$('#rooms_by_tag').html(html);
				$('.hl').removeClass('hl');
			}
			
		}
		else
		{
			$('.hl').removeClass('hl');
		
			if($('#room_search_copy .user').length == 0)
			{
				$('#room_search_copy').html($('#rooms_by_tag').html());
			}
			
			
			$('#rooms_by_tag').html($('#room_search_copy').html());
			$('#rooms_by_tag .user').each(function()
			{
				var name = $(this).attr('rel');
				var match = false;

				if(name.substr(0, search.length).toLowerCase() == search)
				{
					$(this).find('.name').addClass('hl');
					match = true;
				}
				else
				{
				/*	$(this).find('.pics img').each(function()
					{
						if($(this).attr('rel').substr(0, search.length) == search)
						{
							$(this).addClass('hl');
							match = true;
						}
					});*/
					
					$(this).find('.tags li').each(function()
					{	
						if($(this).html().substr(0, 1) != '#') { return; }			
						if($(this).html().substr(1, search.length).toLowerCase() == search)
						{
							$(this).addClass('hl');
							
							var el = $(this).clone(true, true);
							$(this).parents('.tags').prepend(el);
							
							$(this).remove();
							
							match = true;
						}
					});
				}
				
				if(!match)
				{
					$(this).remove();
				}
			});
		}
		
		adjust_tags_page();
	});
	
	$('#search_tags').blur(function()
	{
		if($('#room_search_copy .user').length > 0 && ($(this).val() == '' || $(this).val() == $(this).defaultValue()))
		{
			var html = $('#room_search_copy').html();
			$('#room_search_copy').html('');
			$('#rooms_by_tag').html(html);
			$('.hl').removeClass('hl');
		}
	});
}

var tag_cache = {};
function refresh_tags()
{
	var data = {};
	data.category = $('#categories li.active').attr('rel');
		
	var cache = $.param(data);
	
	
	if(typeof tag_cache[cache] != 'undefined')
	{
		insert_tags(cache, tag_cache[cache]);
		return;
	}
	
	//allow_category_change = false;
	$('#rooms_by_tag').html(TC.loading_bit_html());	
	
	$(document).bind("tinychat.ajax.error", function(e, ajaxerror)
	{
		//allow_category_change = true;
	});
	
	
	if(typeof rooms_by_tag_xhr != 'undefined' && typeof rooms_by_tag_xhr.abort == 'function')
	{
		rooms_by_tag_xhr.abort();
	}

	rooms_by_tag_xhr = TC.call("categories/rooms", data, function(result) { allow_category_change = true; insert_tags(cache, result); });
}

function adjust_tags_page(dir)
{
	total_users = $('#rooms_by_tag .user').length;
	total_pages = Math.ceil(total_users / users_per_page);
		
	if(dir == 1)
	{
		page++;
	}
	else if(dir == -1)
	{
		page--;
	}
	
	if(page <= 1) { page = 1; }
	if(page > total_pages) { page = total_pages; }
	
	$('.room_pagination .page').html(page);
	$('.room_pagination .total_pages').html(total_pages);
	
	if(page > 1)
	{
		$('.room_pagination .previous').css('visibility', 'visible');
	}
	else
	{
		$('.room_pagination .previous').css('visibility', 'hidden');
	}
	
	if(page < total_pages)
	{
		$('.room_pagination .next').css('visibility', 'visible');
	}
	else
	{
		$('.room_pagination .next').css('visibility', 'hidden');
	}
	
	st = (page - 1) * users_per_page;
	
	
	var users = $('#rooms_by_tag .user');
	users.addClass('hidden');
	
	for(var i=0; i < users.length; i++)
	{
		if(i >= st && i < (st+users_per_page))
		{
			var user = $($('#rooms_by_tag .user').get(i));
			user.removeClass('hidden');
			user.html(user.html().replace(/<brokenimg/gi, "<img"));		}
	}
	
	$('#rooms_by_tag .tags li').each(function()
	{
		var tag = $(this).text().substring(1);
		if(tag == '..')
		{
			return;
		}
		
		$(this).click(function()
		{
			$('#search_tags').val(tag).trigger('keyup');
			search_for_tag();
			
		}).css('cursor', 'pointer');
	});
}

var total_users = 0;
var users_per_page = 8;
var page = 1;
var total_pages = 1;
function insert_tags(key, result)
{
	if(typeof result.html != 'undefined')
	{
		$('#rooms_by_tag').html('');
		
		result.html = result.html.replace(/<img/gi, "<brokenimg");
		
		var div = $("<div></div>");
		div.html(result.html);
		

		$('#rooms_by_tag').html(div.html());
		
		tag_cache[key] = result;
		
		page = 1;
		
		adjust_tags_page();
		
	}
}

function on_popular_load(result)
{
	allow_category_change = true;
	if(typeof result.html != 'undefined')
	{
		insert_tags("category=popular", result);
	}
	on_bit_load();
}

var removed_bits = null;
function on_bit_load()
{
	if(!removed_bits)
	{
		removed_bits = $("<div></div>");
	}
	
	
	if($('#tags').length > 0)
	{	
		allow_category_change = true;
		$('#categories li').removeClass('active');
		$('#categories li[rel=popular]').addClass('active');
		adjust_tags_page();
	}
	else
	{
		if($('#left_block .user:visible').length > 10)
		{
			while(($('#left_block .user').length) > 10)
			{
				if($('#live_chats .user').length > 5)
				{
					var el = $('#live_chats .user:last-child');
					el.data('target', '#live_chats');
					removed_bits.append(el.clone(true, true));
					
					el.remove();
				}
				else
				{
					var el = $('#popular_chat_rooms .user:last-child');
					el.data('target', '#popular_chat_rooms');
					removed_bits.append(el.clone(true, true));
					
					el.remove();
				}
				
				$('#left_block .view_more').click(function()
				{
					load_hidden_bits();
				});
			
				adjust_block_height();
			}	
		}
		
		adjust_block_height();
	}
}

function adjust_block_height()
{
	
	if($('#live_chats .bit_missing').length > 0)
	{
		$('#live_chats').hide();
	}
	
	window.setTimeout(function()
	{
		var columns = $('#left_block,#right_block');
		columns.css('height', 'auto');
		var tallestcolumn = 0;
		columns.each(function()
		{
			currentHeight = $(this).height();
			if(currentHeight > tallestcolumn)
			{
				tallestcolumn  = currentHeight;
			}
		});
		columns.height(tallestcolumn);
	}, 0);

}

var allow_new_status = true;
function status_updates()
{
	$('#status_selectors li[rel=messages]').click(function()
	{
		$('#status_selectors li').removeClass('active');
		$(this).addClass('active');
		timeline({private: 1});
	});
	
	$('#status_selectors li[rel=activity]').click(function()
	{
		$('#status_selectors li').removeClass('active');
		$(this).addClass('active');
		timeline();
	});
	
	timeline();

	$('#new_options').hide();
	$('#new_status').focus(function()
	{
		if($('#new_options:hidden').length > 0)
		{
			$('#new_options').slideDown('fast', function()
			{
				adjust_block_height();
			});
		}
	});
	
	$('#new_status').keyup(function()
	{
		var characters_left = 180 - $('#new_status').val().length;
		$('#character_limit').html(characters_left);
		
		if(characters_left < 0)
		{
			$('#character_limit').css('color', 'red');
			$('#option_buttons button').attr('disabled', true).addClass('disabled');
		}
		else
		{
			$('#character_limit').css('color', '#444');
			$('#option_buttons button').attr('disabled', false).removeClass('disabled');
		}
		
		if($('#new_status').val().substring(0, 1) == "@" && allow_new_status)
		{
			$('#send_message').show();
		}
		else
		{
			$('#send_message').hide();
		}
	});
	
	$('#new_status').trigger('keyup');
	
	$('#option_buttons button').click(function()
	{
		if(!allow_new_status)
		{
			return;
		}
		
		var characters_left = 180 - $('#new_status').val().length;
		
		if(characters_left < 0)
		{
			return false;
		}
		
		var text = $('#send_status').html();
		
		var message =  $.trim($('#new_status').val());
		
		if($('#new_status').val().substring(0, 1) == "@")
		{
			var tmp = $('#new_status').val().split(" ");
			delete tmp[0];
			
			tmp = $.trim(tmp.join(" "));
			if(tmp == "")
			{
				return;
			}
		}
		
		if(message.length > 180 || message == "")
		{
			return;
		}
		
		var private = 0;
		
		if($(this).attr('id') == 'send_message')
		{
			private = 1;
		}
		
		$('#send_message').hide();
		$('#send_status').addClass('loading').html('').append($("<img src='"+img_url+"ajax-loader.gif' alt='' />"));
		
		TC.call("objects/add", { text: message, private: private }, function(result)
		{
			allow_new_status = false;
			window.setTimeout(function()
			{
				$('#send_status').removeClass('loading').html(text);
				$('#send_message').show();
				allow_new_status = true;
			}, 10000);
			
			if(typeof result != 'undefined' && typeof result.html != 'undefined')
			{
				$('#new_status').val('');
				$('#new_status').blur();
				$('#statuses').prepend(result.html);
				
				on_status_load();
				
				$('#new_options').slideUp('fast', function()
				{
					adjust_block_height();
				});
				
			}
			else if(typeof result.error !='undefined' && result.error.message != 'undefined')
			{
				TC.warn(result.error.message);
			}
		});
	});
	
	
	var times_scrolled=0;
	if(enable_endless_scrolling)
	{
		$(document).endlessScroll({
			bottomPixels: 450,
			fireDelay: 100,
			callback: function(p)
			{
				if(!enable_endless_scrolling || getting_more_timeline)
				{
					return;
				}
				
				more_timeline();
				times_scrolled++;
			},
			ceaseFire: function()
			{
				
				$('#live_chats .user').show();
				$('#popular_chat_rooms .user').show();
				if(times_scrolled >= 2 && enable_endless_scrolling)
				{
					enable_endless_scrolling = false;
					$('#status_updates .view_more').show().click(function()
					{
						$('#status_updates .view_more').each(function()
						{
							$(this).data('label', $(this).html());
							$(this).html($("<img src='"+img_url+"ajax-loader.gif' alt='' />"));
						});
						
						more_timeline();
					});
				}
			}
		});
		
		
	}
	
	
	window.setInterval(refresh_timeline, (30 * 1000));
	
	
	new function($) {
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery);
	
}

function load_hidden_bits()
{
	if(typeof removed_bits != 'undefined')
	{
		$(removed_bits).find(".user").each(function()
		{
			if($(this).data('target') != '')
			{
				$($(this).data('target')).append($(this).clone(true, true));
				$(this).remove();
				$('#left_block .view_more').remove();
				adjust_block_height();
			}
		});
	}
}

var enable_endless_scrolling = true;
var getting_more_timeline = false;
function more_timeline()
{
		var id = $('#statuses .entry:last-child').attr('rel');
		if(typeof id == 'undefined' || parseInt(id) <= 0)
		{
			return;
		}
		
		delete timeline_data.after_id;
		timeline_data.before_id = id;
		timeline_data.json = true;
		
		getting_more_timeline = true;
		TC.call("bit/activity/timeline?" + $.param(timeline_data), {}, function(result)
		{
			if($("#statuses .blank_response").length > 0)
			{
				$('#status_updates .view_more').remove();
				return;
			}
		
			$('#statuses .bit_missing').remove();
			if(typeof result.html != 'undefined')
			{
				enable_endless_scrolling = true;
				$('#statuses').append(result.html);
			}
			else if(typeof result.count != 'undefined' && result.count == 0)
			{
				enable_endless_scrolling = false;
				$('#statuses .bumper').remove();
				$('#status_updates .view_more').hide();
				$('#statuses').append("<div class='bumper'></div>");
			}
			else
			{
				enable_endless_scrolling = false;
				$('#statuses').append(TC.bit_error_html());
			}
			
			on_status_load();
			adjust_block_height();
			getting_more_timeline = false;
		});
}


function refresh_timeline()
{
		var id = $('#statuses .entry:first-child').attr('rel');
		if(typeof id == 'undefined' || parseInt(id) <= 0)
		{
			return;
		}
		
		delete timeline_data.before_id;
		
		timeline_data.after_id = id;
		timeline_data.json = true;
		
		TC.call("bit/activity/timeline?" + $.param(timeline_data), {}, function(result)
		{
			$('#statuses .bit_missing').remove();
			
			if(typeof result.html != 'undefined')
			{
				enable_endless_scrolling = true;
				$('#statuses').prepend(result.html);
			}
						
			on_status_load();
			adjust_block_height();
		});
}

function timeline(data)
{
	$('#statuses').html(TC.loading_bit_html());
	
	timeline_data = $.extend({}, data);
	TC.call("bit/activity/timeline?" + $.param(timeline_data), {}, function(result)
	{
		$('#statuses').html('');
		if(typeof result.html != 'undefined')
		{
			enable_endless_scrolling = true;
			$('#statuses').append(result.html);
		}
		else if(typeof result.count != 'undefined' && result.count == 0)
		{
			$('#statuses').append(TC.bit_error_html());
			enable_endless_scrolling = false;
			$('#statuses .bumper').remove();
			$('#statuses').append("<div class='bumper'></div>");
		}
		else
		{
			enable_endless_scrolling = false;
			$('#statuses').append(TC.bit_error_html());
		}
		
		adjust_block_height();
		on_status_load();
	});
	
}


function on_status_load()
{
	$('#statuses .entry .reply').click(function()
	{
		var text = "@" + $(this).parents('.entry').find('.name a').text() + " ";
		$('#new_status').val(text).focus().trigger('keyup');
		$('#new_status').setCursorPosition($('#new_status').val().length);
	});
	
	if($("#statuses .blank_response").length > 0)
	{
		$('#status_updates .view_more').remove();
	}
	
	$('#status_updates .view_more').each(function()
	{
		if($(this).data('label'))
		{
			$(this).html($(this).data('label'));
		}
	});
	
	adjust_block_height();
}

var timeline_data = {};


function delete_entry(id)
{
	TC.call("objects/remove", {id: id}, function(result)
	{
		if(result.ok == true)
		{
			$('#object_'+id).fadeOut();
			adjust_block_height();
		}
	});
}
