	$(document).ready(function(){
		// Web socket
		var ws = "null";
		// 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") {
						var html = '';
						if (response.length == 0) {
							html = '<div class="chatbox-friend-list-friend-empty">Danh sách bạn còn trống</div>';
						} else
						$.each(response, function(entryIndex, entry){
							html += dragfriendslistacc(entry['id'], entry['realname'], entry['avatar']);
							user_arr.push(entry['id']);
							realname_arr.push(entry['realname']);
							user_avatar.push(entry['avatar']);
						});
						
						$('.chatbox-friend-list-content').html(html);
						// load completed open socket
						ws = new WebSocket("ws://" + document.location.host + "/Chat");
						connectToWebsocket();
					}
				}
			});
		}
		
		function dragfriendslistacc(id, name, avatar) {
			var html = '<div user="' + id + '" class="chatbox-friend-list-friend"><div class="chatbox-friend-list-friend-avatar"><img class="bdrad" src="' + avatar + '"/></div><div class="chatbox-friend-list-friend-name">' + name + '</div><div class="chatbox-friend-list-friend-status-icon"></div></div>';
			return html;
		}
		
		// Post private comment
		$(document).on("keypress", ".chat-editor", function(e){
			if (((e.which == 13) || (e.keyCode == 13)) && e.shiftKey){
				// Không làm gì hết
			} else if ((e.which == 13) || (e.keyCode == 13)){
				var content = $(this).val();
				if ($.trim(content) != ""){
					content = content.replace(/\n\r?/g, '<br>');			
					sendMessage("chat\0" + $(this).attr("receiver") + "\0" + content);
					$(this).val("");
					return false;
				} else {
					return false;
				}
			} else if (ws == "null"){
				alert("Vui lòng đăng nhập");
				return false;
			}
		});		
		
		// Thuộc về socket
		function connectToWebsocket(){
			ws.onmessage = function(data) {
				analyseData(data.data);
				 
			};
			 
			ws.onopen = function(){
//				 sendMessage("Tôi muốn kết nối");
			};
			 
			ws.onclose = function() {
				$(".chatbox-friend-list-title").css("background-color", "gray");
				$(".chatbox-friend-list-label").empty().text("Mất Kết Nối Đến Máy Chủ");
				$(".chatbox-friend-list-content").empty().hide();
			};
		}
		
		function analyseData(data){
			var array = data.split("\0");
			var com = array[0];
			var form = array[1];
			var to = array[2];
			var content = array[3];
			var time = array[4];
			var username = $('#info-id-accountlogin-name').text();
			
			if (com == "pri") {	
				if (form == username){ // He thong tra da nhan dc tin nhan
					$("#window" + replaceSpace(to)).append(appendPrivateMsg("<b>" + getRealName(username) + "</b> " + content + "<br><span class='system-time'>" + time + "</span>"));
					$("#window" + replaceSpace(to)).scrollTop($("#window" + replaceSpace(to)).scrollTop() + 99999);
				} else searchChatWin(form, "<b>" + getRealName(form) + "</b> " + content + "<br><span class='system-time'>" + time + "</span>");
				// Âm thanh
				ringChat();
			} else if (com == "online"){
				setOnlineUserList(to);
			} else if (com == "pub"){
				setOnlineUser(form, to);
			}
		}
		
		// Check online user
		function setOnlineUserList(list){
			var onlineList = list.split(",");
			$(".chatbox-friend-list-friend").each(function(){
				for (var i = 0; i < onlineList.length; i++){
					if ($(this).attr("user") == onlineList[i]){
						$(this).children(".chatbox-friend-list-friend-status-icon").empty().html('<img src="images/online2.png"/>');
						break;
					}
				}
			});
		}
		
		// Set online user
		function setOnlineUser(status, user){
			if (status == "online"){
				// Khung chat riêng
				$("#stt_icon_" + replaceSpace(user)).empty().html('<img class="online-icon" src="images/online.png"/>');
				// Danh sách online
				$(".chatbox-friend-list-friend").each(function(){
						if ($(this).attr("user") == user){
							$(this).children(".chatbox-friend-list-friend-status-icon").empty().html('<img src="images/online2.png"/>');
							result = true;
							return false;
						}
				});
			} else {
				// Khung chat riêng
				$("#stt_icon_" + replaceSpace(user)).empty();
				// Danh sách online
				$(".chatbox-friend-list-friend").each(function(){
					if ($(this).attr("user") == user){
						$(this).children(".chatbox-friend-list-friend-status-icon").empty();
						result = true;
						return false;
					}
				});
			}
			
			// Set số lượng online
			if ($(".chatbox-friend-list-content").is(":hidden")) countOnlineUser();
		}
		
		// Kiem tra cua so chat nay da ton tai chua
		function searchChatWin(receiver, content){
			var con = true;
			$(".chat-editor").each(function(){
				if ($(this).attr("receiver") == receiver) {
					$("#window" + replaceSpace(receiver)).append(appendPrivateMsg(content));
					$("#window" + replaceSpace(receiver)).scrollTop($("#window" + replaceSpace(receiver)).scrollTop() + 500);
					$("#window" + replaceSpace(receiver)).find(".chatbox-msg").last().hide().css("background-color", "#FFF8C6").fadeIn(1000, function(){$(this).css("background-color", "");});
					con = false;
					return false;
				}
			});
			if (con) {
				openChatWin($('#info-id-accountlogin-name').text(), receiver, content);
			}
		}

		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) + '"><img class="online-icon" src="images/online.png"/></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) + '">';
					html += '</div><div class="chatbox-posting"><hr class="hr-chat-separation">';
					html += '<textarea spellcheck="false" class="chat-editor" receiver="' + to + '" sender="' + from + '"></textarea>';
					html += res + '</div></div>';
					$(document.body).append(html);
					loadMessage(to, 0);
				}
			});
		}
		
		function appendPrivateMsg(content){
			var html = '<div class="chatbox-msg">' + content + '<hr class="hr-chat-content"></div>';
			return html;
		}
		
		function sendMessage(msg) {
		     ws.send(msg);
		}
		
		// Load tin nhắn cũ
		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);
					$("#window" + replaceSpace(to)).find(".chatbox-msg").last().hide().css("background-color", "#FFF8C6").fadeIn(1000, function(){$(this).css("background-color", "");});
					scrollTopEvent();
					fixedChatWinPos();
				}
			});
		}
		
		// 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);
					}
				}
			});
		}
		
		// Đếm số 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 + ")");
		}
		
		// Remove space for DOM ID
		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áo có tin nhắn mới
		function ringChat(){
			if (!$("#chat-ring-notification").is(":hidden")){
				$("#chat-ring-notification").empty().html('<audio hidden="true" autoplay="autoplay" src="sound/chat-ring.mp3"></audio>');
				$("#chat-ring-notification").fadeOut(0).delay(1500).fadeIn(0);
			}
		}
		
		function fixedChatWinPos(){		
			var temp = 230;
			$(".chatbox-window").each(function() {
				$(this).css("margin-right", temp);
				temp += 260;
			});
		}	
		
	});