	$(document).ready(function(){
		// username array
		var user_arr = new Array();
		user_arr.push($('#info-id-accountlogin-name').text());
		// realname array
		var realname_arr = new Array();
		realname_arr.push('Tôi');
		// avatar array
		var user_avatar = new Array();
		user_avatar.push($('.headerTinymanPhoto').attr('src'));
		
		loadlistFriends();
		
		function loadlistFriends() {
			$.ajax({
				type: "POST",
				url: "getlistfriendsacc",
				dataType: "json",
				success: function(response){
					if(response != "null") {
						$.each(response, function(entryIndex, entry){
							user_arr.push(entry['id']);
							realname_arr.push(entry['realname']);
							user_avatar.push(entry['avatar']);
						});
					}
				}
			});
		}			
		
		// Autoload msg khi scroll top
		function scrollTopEvent(){
			$(".chatbox-content").unbind("scroll");
			$(".chatbox-content").scroll(function(){
				if ($(this).scrollTop() == 0){
					var receiver = $(this).attr("id");
					var offset = $(this).children(".chatbox-msg-header").attr("new");
					if (offset != "root"){
						$(this).children(".chatbox-msg-header").remove();
						loadMessage(replaceToOriginal(receiver.substring(6, receiver.length)), offset);
					}
				}
			});
		}
		
		function loadMessage(to, offset){
			var rows = "";
			$.ajax({
				type: "POST",
				url: "getChatMsg",
				data: "receiver=" + to + "&offset=" + offset,
				beforeSend: function(){
					$("#window" + replaceSpace(to)).children(".chatbox-msg-header").html('<img src="images/loading-small.gif">');
				},
				success: function(res){
					var data = $.parseJSON(res);
					rows += data[0].id; // Header
					for(var i = 1; i < data.length; i++){
						rows += '<div class="chatbox-msg"><b>' + getRealName(data[i].sender) + '</b> ' + data[i].content + '<br><span class="system-time">' + data[i].date + '</span><hr class="hr-chat-content"></div>';
					}
					$("#window" + replaceSpace(to)).prepend(rows);
					$("#window" + replaceSpace(to)).animate({ scrollTop: $("#window" + replaceSpace(to)).height() }, 1);
				}
			});
		}
		
		// Ẩn hiện khung friend list
		$(document).on("click", ".chatbox-friend-list-title", function(){
			if ($(this).next().is(":hidden")){
				$(".chatbox-friend-list-label").text("Danh Sách Bạn Bè");
				$(this).next().show();
			} else {
				countOnlineUser();
				$(this).next().hide();
			}
		});
		
		// Đếm user đang online
		function countOnlineUser(){
			var total = 0;
			$(".chatbox-friend-list-friend-status-icon").each(function(){
				if ($.trim($(this).html()) != "") total++;
			});
			$(".chatbox-friend-list-label").html("<img src='images/online.png'/> Đang Online (" + total + ")");
		}
		
		// Ẩn hiện  khung chat riêng
		$(document).on("click", ".chatbox-title", function(){
			if ($(this).next(".chatbox-content").is(":hidden")){
				$(this).closest(".chatbox-window").css("height", "300px");
				$(this).next(".chatbox-content").show();
				var temp = $(this).next(".chatbox-content");
				temp.animate({ scrollTop: temp.height() + 99999 }, 1);
			} else {
				$(this).next(".chatbox-content").hide();
				$(this).closest(".chatbox-window").css("height", "27px");
			}
		});
		
		// Tắt khung chat riêng
		$(document).on("click", ".chatbox-close-button", function(){
			$(this).closest(".chatbox-window").remove();
			fixedChatWinPos();
		});
		
		// Set focus text area
		$(document).on("click", ".chatbox-window", function(){
			$(this).last().find(".chat-editor").focus();
		});
		
		// Login box
		$(".username-label").click(function(){
			if ($(".login-box").is(":hidden")){
				$(".login-box").slideDown(300);
				$("#username").focus();
			} else {
				$(".login-box").slideUp();
			}
		});
		
		// Mo khung chat rieng
		var chosenElem = null;
		$(document).on("dblclick", ".chatbox-friend-list-friend", function(){
			chosenElem = $(this);
			var receiver = $(this).attr("user");
			var con = true;
			$(".chat-editor").each(function(){
				if ($(this).attr("receiver") == receiver) {
					$(this).focus();
					con = false;
					return false;
				}
			});
			if (con)
				openChatWin($('#info-id-accountlogin-name').text(), receiver, "");
		});
		
		function openChatWin(from, to, content){
			$.ajax({
				type: "POST",
				url: "emoticon.jsp",
				success: function(res){	
					var html = '<div class="chatbox-window"><div class="chatbox-title"><div class="chatbox-username"><span id="stt_icon_' + replaceSpace(to) + '"></span> ' + getRealName(to);
					html += '</div><div class="chatbox-close"><span title="Thoát" class="chatbox-close-button">X</span></div></div><div class="chatbox-content" id="window' + replaceSpace(to) + '"><div class="chatbox-msg">' + content;
					html += '</div></div><div class="chatbox-posting"><hr class="hr-chat-separation">';
					html += '<textarea spellcheck="false" class="chat-editor" receiver="' + to + '" sender="' + from + '" autofocus></textarea>';
					html += res + '</div></div>';
					$(document.body).append(html);
					loadMessage(to, 0);
					scrollTopEvent();
					if ($.trim($(chosenElem).children(".chatbox-friend-list-friend-status-icon").html()) != "")
						$("#stt_icon_" + replaceSpace(to)).empty().html('<img class="online-icon" src="images/online.png"/>');
					fixedChatWinPos();
				}
			});
		}
		
		function replaceSpace(content){
			content = content.replace(".", "--");
			return content.replace("@", "-");
		}
		
		function replaceToOriginal(content){
			content = content.replace("--", ".");
			return content.replace("-", "@");
		}
		
		// Get họ tên
		function getRealName(user){
			var rname = "";
			for (var i = 0; i < user_arr.length; i++){
				if (user_arr[i] == user){
					rname = realname_arr[i];
					break;
				}
			}
			return rname;
		}
		
		// Bảng emoticon
		$(document).on("click", ".chat-emoticonx-toggle", function(e){
			if ($(".chat-emoticonx-table").is(":hidden")){
				e.stopPropagation();
				$(this).next().fadeIn(100);
				bindEmoticonEvent();
			}
		});
		
		function bindEmoticonEvent(){
			// Unbind events
			$("body").click(function(e){
				if (e.target.className !== "chat-emoticonx-table") {
					$(".chat-emoticonx-table").fadeOut(100);
					$("body").unbind("click");
					$(".chat-emoticonx-table").unbind("click");
				}
			});
		}
		
		// Append emoticon
		$(document).on("click", ".chat-emox-elems", function(){
			$(this).closest(".chat-emoticonx-table").prev().prev().insertAtCursor($(this).attr("emo"));
			$("body").unbind("click");
			$(".chat-emoticonx-table").unbind("click");
			$(this).closest(".chat-emoticonx-table").fadeOut(100);
		});
		
		// Fix cửa sổ chat
		function fixedChatWinPos(){
			var temp = 230;
			$(".chatbox-window").each(function() {
				$(this).css("margin-right", temp);
				temp += 260;
			});
		}
		
		fixedChatWinPos();
	});