<?php use_helper('tvtl'); ?>
<div id="activeBlog">
  <div class="doc">
    <h2>
   
      <div style="float:left">Chat room</div> 
      
    </h2>
    <div class="content">
      <div id="content"></div>
	  <span id="status" style="display:none">Connecting...</span>
			<?php $u= $sf_user->getUserFullname();
			
			if ($chat == 1)
			{
			?>
            <input type="text" id="input" disabled="disabled" style="width:518px" />
			<?php
			}
			else
			{
				echo $msg;
			}
			?>
    </div>
  </div>
</div>









        <style>
        * { font-family:tahoma; font-size:12px; padding:0px; margin:0px; }
        p { line-height:18px; }
        div content { width:175px; margin-left:auto; margin-right:auto;}
        #content { padding:5px; background:#FFF; border-radius:5px; overflow-y: scroll;
                   border:1px solid #CCC; margin-top:10px; height: 410px;; }
        #input { border-radius:2px; border:1px solid #ccc;
                 margin-top:10px; padding:5px; width:170px;  }
        #status { width:88px; display:block; float:left; margin-top:15px; }
        </style>

        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type="text/javascript">
var connection;
$.noConflict(); 
jQuery(document).ready(function($) {
$(function () {
    "use strict";
    var content = $('#content');
    var input = $('#input');
    var status = $('#status');
    var myColor = false;
    var myName = false;
    window.WebSocket = window.WebSocket || window.MozWebSocket;
    if (!window.WebSocket) {
        content.html($('<p>', { text: 'Trình duyệt của bạn không hỗ trợ web socket'} ));
                                  
        input.hide();
        $('span').hide();
        return;
    }
 
    // open connection
    connection = new WebSocket('ws://54.254.150.10:8000');
    connection.onopen = function () 
	{
    	<?php 
		if ($chat == 1)
		{
		?>
    	connection.send(JSON.stringify({type:'init', bl_id:'<?php echo $blogId;?>', username: '<?php echo $u;?>', userId:'<?php echo $userId;?>'}));   
		status.text('');
		<?php
		}
		else
		{
		?>
		connection.send(JSON.stringify({type:'his', bl_id:'<?php echo $blogId;?>'}));   
		<?php
		}
		?>
    };
    connection.onerror = function (error) {
        // just in there were some problems with conenction...
        content.html($('<p>', { text: 'Kết nối không ổn định, nhấn F5 để thử lại '} ));
                                    
    };
    // most important part - incoming messages
    connection.onmessage = function (message) {
        // try to parse JSON message. Because we know that the server always returns
        // JSON this should work without any problem but we should make sure that
        // the massage is not chunked or otherwise damaged.
        try {
            var json = JSON.parse(message.data);
        } catch (e) {   
            return;
        }

        // NOTE: if you're not sure about the JSON structure
        // check the server source code above
        if (json.type === 'color') { // first response from the server with user's color
            myColor = json.data;
            status.text(myName + ': ').css('color', myColor);
            input.removeAttr('disabled').focus();
            // from now user can start sending messages
        } else if (json.type === 'history') { // entire message history
            // insert every single message to the chat window
            for (var i=0; i < json.data.length; i++) {
                addMessage(json.data[i].author, json.data[i].text,
                           json.data[i].color, new Date(json.data[i].time),json.data[i].index,json.data[i].id,json.data[i].pos, json.data[i].type);
            }
        } else if (json.type === 'message') { // it's a single message
            input.removeAttr('disabled'); // let the user write another message
            addMessage(json.data.author, json.data.text,
                       json.data.color, new Date(json.data.time),json.data.index, json.data.id, json.data.pos, json.data.type);
        } else {
           
        }
    };

    /**
     * Send mesage when user presses Enter key
     */
    input.keydown(function(e) {
        if (e.keyCode === 13) {
            var msg = $(this).val();
            if (!msg) {
                return;
            }
            //connection.send(msg);
			connection.send(JSON.stringify({type:'msg', msg:msg}));   
            $(this).val('');
            input.attr('disabled', 'disabled');
            if (myName === false) {
                myName = msg;
            }
        }
    });
 

    setInterval(function() {
        if (connection.readyState !== 1) {
            status.text('Error');
            input.attr('disabled', 'disabled').val('Mất kết nối, nhấn F5 để thử lại');
        }
    }, 3000);
	
    /**
     * Add message to the chat window
     */
    function addMessage(author, message, color, dt, index, id,pos, type) {
		if (type == "delete")
		{
		$("#msg_"+message).hide();
		}
		if (type == "msg")
		
		{ 
			<?php
			if ($admin==1)
			{
			?>
			if (id != <?php echo $userId;?>)
			{
			content.prepend('<div id="msg_'+pos+'" style="font-size:10px;">' + message + '<br /><span style=\"cursor:pointer\" title=\"Xóa tin này\" onClick=\"delete_msg(\''+pos+'\');\">xóa</span>|<span title=\"Loại khỏi chat room\"  style=\"cursor:pointer\" onClick=\"remove_user(\''+index+'\',\''+author+'\',\''+id+'\');\">Loại</span></span><br /><span style="font-size:8px;color:' + color + '">' + author  
				 + " - " + (dt.getHours() < 10 ? '0' + dt.getHours() : dt.getHours()) + ':'
				 + (dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes()) + ':'
				 + (dt.getSeconds() < 10 ? '0' + dt.getSeconds() : dt.getSeconds())
				 + '<br /></div>');
			}
			else
			{
				content.prepend('<div id="msg_'+pos+'" style="font-size:10px;">' + message + '<br /><span style=\"cursor:pointer\" title=\"Xóa tin này\" onClick=\"delete_msg(\''+pos+'\');\">xóa</span>|<span title=\"Loại khỏi chat room\"  style=\"cursor:pointer\" onClick=\"remove_user(\''+index+'\',\''+author+'\',\''+id+'\');\"></span></span><br /><span style="font-size:8px;color:' + color + '">' + author  
				 + " - " + (dt.getHours() < 10 ? '0' + dt.getHours() : dt.getHours()) + ':'
				 + (dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes()) + ':'
				 + (dt.getSeconds() < 10 ? '0' + dt.getSeconds() : dt.getSeconds())
				 + '<br /></div>');
			}
			<?php
			}
			else
			{
			?>
			content.prepend('<div id="msg_'+pos+'" style="font-size:10px;">' + message + '</span><br /><span style="font-size:8px;color:' + color + '">' + author   
				 + " - " + (dt.getHours() < 10 ? '0' + dt.getHours() : dt.getHours()) + ':'
				 + (dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes()) + ':'
				 + (dt.getSeconds() < 10 ? '0' + dt.getSeconds() : dt.getSeconds())
				 + '<br /></div>');
			<?php
			}
			?>
		}
    }
	
});

});
function remove_user(id, name, u_id)
	{
		var r=confirm("Bạn có muốn loại "+name+" ra khỏi phòng chat?")
		if (r==true)
		  {
		  connection.send(JSON.stringify({type:'remove', ind:id,name:name,userId:u_id}));   
		  }
		
		   
	}
function delete_msg(pos)
	{
		var r=confirm("Bạn có muốn xóa tin này?")
		if (r==true)
		  {
		  connection.send(JSON.stringify({type:'delete', pos:pos}));   
		  }
		
		   
	}
</script>