<script type="text/javascript">
    var started_session = false;

    $(document).ready(function () {

        $('.datatables').DataTable();
        setInterval(function(){
            ajax_load_received_msg();
        },2000);
        
         setInterval(function(){
            refresh_online_users();
        },60000);
        
        refresh_online_users();
    });

    var refresh_chat_handler = function (customerID) {
        var n = 0;
        var refresher = function () {
             var isEnd = !$('#chatting_msg_box_' + customerID).length || $('#chatting_msg_box_' + customerID).attr("data-end") =="true" ;
            if(!isEnd){
                notify("Session started", 'Tekun ...', 'success');
                setTimeout(refresher, 2000);
            }
        };
        refresher();
    };


    function chatting_send_msg(me) {
        customerId = $(me).attr("data-customerID");
        sesionId = $(me).attr("data-sessionID");
        msg = $("#chatting_msg_box_" +customerId ).val();
        if($.trim(msg) !==""){
            $.ajax({
            type: "POST",
            data: {
                customerID:customerId,
                sesionID: sesionId,
                message: msg
            },
            url: "<?php echo base_url() ?>admin/admin_send_msg",
            success: function (data) {
                var result = isjson(data);
                if (result && result.status == "success") {
                    format_and_display('s', $(me).attr("data-customerID"));
                }else{
                    notify('Serveur encounter some issues','Message not sent', 'error');
                }
            }});
        }
        
//        msg = $("#chatting_msg_box").val();
//        receiver = $("#chatting_msg_box").attr("data-receiver");
//        ajax_chatting_send_msg (msg,receiver);
//        $("#chatting_msg_box").val("");
//        temp = '<div class="direct-chat-msg right">\
//                  <div class="direct-chat-info clearfix">\
//                    <span class="direct-chat-name pull-right">Sarah Bullock</span>\
//                    <span class="direct-chat-timestamp pull-left">23 Jan 2:05 pm</span>\
//                  </div>\
//                  <img alt="(-_-)" src="../dist/img/user3-128x128.jpg" class="direct-chat-img">\
//                  <div class="direct-chat-text">\
//                   ' + msg + '\
//                  </div>\
//                </div>\
//                ';
//        $("#chatting_msg_contenair").append(temp);

    }

    function refresh_online_users() {
        var oTable = $("#datatable_unattend").dataTable();
        oTable.fnClearTable();
        var oTableAll = $("#datatable_all").dataTable();
        oTableAll.fnClearTable();
        
        $.ajax({
            type: "POST",
            data: {
                option: 'all'
            },
            url: "<?php echo base_url() ?>admin/get_chat_users",
            success: function (data) {
                var result = isjson(data);
                if (result && result.status == "success") {
                    var n = result.records.length, i = 0, k=0;
                    for (i = 0; i < n; i++) {
                        if(result.records[i].status == 0){
                            var c = oTable.fnAddData([
                            '<td><div class="text-center width-100">' + (k + 1) + '</div></td>',
                            '<td><div class="user_name"><a data-ip="' + result.records[i].ip + '" data-sessionID="' + result.records[i].sessionID + '" data-customerID="' + result.records[i].fldid + '" href="javascript:" onclick="open_chat(this)" ><img id="customer_profife_pic_'+ result.records[i].fldid +'" class="direct-chat-img" src="<?php echo base_url(); ?>dist/img/profile/' + result.records[i].profile_picture + '" alt="(-_-)"><span>' + result.records[i].username + '</span></a></div></td>',
                            '<td>' + result.records[i].question + '</td>',
                            '<td><div class="text-center width-100"><span id="datatable_sesion_status_' + result.records[i].sessionID + '">' + result.records[i].sessionStatus + '</span></div></td>',
                            '<td><div class="text-center width-100">' + result.records[i].startTime + '</div></td>',
                            '<td></td>',
                            '<td></td>'
                        ]); 
                        }
                        var a = oTableAll.fnAddData([
                            '<td><div class="text-center width-100">' + (i + 1) + '</div></td>',
                            '<td><div class="user_name"><a data-ip="' + result.records[i].ip + '" data-sessionID="' + result.records[i].sessionID + '" data-customerID="' + result.records[i].fldid + '" href="javascript:" onclick="open_chat(this)" ><img id="customer_profife_pic_'+ result.records[i].fldid +'" class="direct-chat-img" src="<?php echo base_url(); ?>dist/img/profile/' + result.records[i].profile_picture + '" alt="(-_-)"><span>' + result.records[i].username + '</span></a></div></td>',
                            '<td>' + result.records[i].question + '</td>',
                            '<td><div class="text-center width-100"><span id="datatable_sesion_status_' + result.records[i].sessionID + '">' + result.records[i].sessionStatus + '</span></div></td>',
                            '<td><div class="text-center width-100">' + result.records[i].startTime + '</div></td>',
                            '<td></td>',
                            '<td></td>'
                        ]);
                    }
                }
            }});
    }

    function end_interval_var(ID) {

    }

    function add_chat_box(me) {
        var tr = $(me).parents("tr"),
                question = $(tr).find("td:eq(2)").text(),
                startTimme = $(tr).find("td:eq(4)").text(),
                customerID = $(tr).find("td:eq(1) a").attr('data-customerID'),
                sessionID = $(tr).find("td:eq(1) a").attr('data-sessionID'),
                customerName = $(tr).find("td:eq(1) span").text(),
                img = $(tr).find("td:eq(1) img").attr("src"),
                ipadr = $(tr).find("td:eq(1) a").attr('data-ip');
        if ($('#direct_chat_contenair_' + customerID).length) {
            $('#direct_chat_contenair_' + customerID).remove();
        }

//        var temp = '<div class="chat-box">\
//                    <div id="direct_chat_contenair_' + customerID + '" class="box box-primary direct-chat direct-chat-danger">\
//                        <div class="box-header with-border">\
//                            <h3 class="box-title">Direct Chat</h3>\
//                            <div class="box-tools pull-right">\
//                                <button data-widget="collapse" class="btn btn-box-tool"><i class="fa fa-minus"></i></button>\
//                                <button data-toggle="tooltip" title="End session"  onclick="end_chatting_session(this)" data-sessionID="' + sessionID + '" data-customerID="' + customerID + '" class="btn btn-box-tool"><i class="fa fa-stop"></i></button>\
//                                <button data-widget="remove" class="btn btn-box-tool"><i class="fa fa-times"></i></button>\
//                            </div>\
//                        </div>\
//                        <div class="box-body">\
//                            <div id="chatting_msg_contenair_' + customerID + '" class="direct-chat-messages">\
//                                <div class="direct-chat-msg">\
//                                    <div class="direct-chat-info clearfix">\
//                                        <span id="customer_name_' + customerID + '" class="direct-chat-name pull-left">' + customerName + '</span>\
//                                        <span class="direct-chat-timestamp pull-right">' + startTimme + '</span>\
//                                    </div>\
//                                    <img id="customer_profife_pic_' + customerID + '" alt="(-_-)" src="' + img + '" class="direct-chat-img">\
//                                    <div class="direct-chat-text">' + question + ' \
//                                    </div>\
//                                </div>\
//                            </div>\
//                            <div class="direct-chat-contacts">\
//                                <ul class="contacts-list">\
//                                    <li>\
//                                        <a href="#">\
//                                            <img src="../dist/img/user1-128x128.jpg" class="contacts-list-img">\
//                                            <div class="contacts-list-info">\
//                                                <span class="contacts-list-name">\
//                                                    Count Dracula\
//                                                    <small class="contacts-list-date pull-right">2/28/2015</small>\
//                                                </span>\
//                                                <span class="contacts-list-msg">How have you been? I was...</span>\
//                                            </div>\
//                                        </a>\
//                                    </li>\
//                                </ul>\
//                            </div>\
//                        </div>\
//                        <div class="box-footer">\
//                                <div class="input-group">\
//                                    <input data-customerID="' + customerID + '" data-sessionID="' + sessionID + '" disabled id="chatting_msg_box_' + customerID + '" type="text" class="form-control" placeholder="Type Message ..." name="message">\
//                                    <span class="input-group-btn">\
//                                        <button data-customerID="' + customerID + '" data-sessionID="' + sessionID + '" onclick="chatting_send_msg(this)" class="btn btn-danger btn-flat" type="button">Send</button>\
//                                    </span>\
//                                </div>\
//                        </div>\
//                    </div></div>';
 var temp = '<div class="chat-box">\
                    <div id="direct_chat_contenair_' + customerID + '" class="box box-primary direct-chat direct-chat-danger">\
                        <div class="box-header with-border">\
                            <h3 class="box-title">Direct Chat</h3>\
                            <div class="box-tools pull-right">\
                                <button data-widget="collapse" class="btn btn-box-tool"><i class="fa fa-minus"></i></button>\
                                <button data-widget="chat-pane-toggle" title="" data-toggle="tooltip" class="btn btn-box-tool" data-original-title="Contacts"><i class="fa fa-comments"></i></button>\
                                <button data-toggle="tooltip" title="End session"  onclick="end_chatting_session(this)" data-sessionID="' + sessionID + '" data-customerID="' + customerID + '" class="btn btn-box-tool"><i class="fa fa-times"></i></button>\
                                <button  data-widget="remove" id="btn_end_chatting_session_' + customerID + '" class="btn btn-box-tool hide"><i class="fa fa-times"></i></button>\
                            </div>\
                        </div>\
                        <div class="box-body">\
                            <div id="chatting_msg_contenair_' + customerID + '" class="direct-chat-messages">\
                            </div>\
                            <div class="direct-chat-contacts">\
                                <ul class="contacts-list">\
                                    <li>\
                                        <a href="#">\
                                            <img src="' + img + '" class="contacts-list-img">\
                                            <div class="contacts-list-info">\
                                                <span class="contacts-list-name">\
                                                    <small class="contacts-list-date pull-right">'+ date_format('now')  +'</small>\
                                                </span>\
                                                <span class="contacts-list-msg"> Name: '+ customerName +'</span><br/>\
                                                     <span class="contacts-list-msg">IP : '+ ipadr +'</span><br/>\
                                                <span class="contacts-list-msg"> Start Time : '+ startTimme +'</span><br/>\
                                                     <span class="contacts-list-msg">Question : '+ question +'</span><br/>\
                                            </div>\
                                        </a>\
                                    </li>\
                                </ul>\
                            </div>\
                        </div>\
                        <div class="box-footer">\
                                <div class="input-group">\
                                    <input data-customerID="' + customerID + '" data-sessionID="' + sessionID + '" disabled id="chatting_msg_box_' + customerID + '" type="text" class="form-control" placeholder="Type Message ..." name="message">\
                                    <span class="input-group-btn">\
                                        <button data-customerID="' + customerID + '" data-sessionID="' + sessionID + '" onclick="chatting_send_msg(this)" class="btn btn-danger btn-flat" type="button">Send</button>\
                                    </span>\
                                </div>\
                        </div>\
                    </div></div>';
        $("#chatting_chat_box").append(temp).removeClass("hide");
        $('#chatting_msg_box_' + customerID).keydown(function (e) {
            if (e.keyCode == 13) {
                chatting_send_msg(this);
                return false;
            }
        });
        update_sesion_admin(sessionID, customerID);
    }

    function end_chatting_session(me) {
        var customerID = $(me).attr("data-customerID");
        var sessionID = $(me).attr("data-sessionID");
        
        $("#btn_end_chatting_session_" + customerID).trigger("click");
        $.ajax({
            type: "POST",
            data: {
                session: sessionID
            },
            url: "<?php echo base_url() ?>admin/end_chatting_session",
            success: function (data) {
                var result = isjson(data);
                if (result && result.status == "success") {
                    notify("Session ended", 'Tekun ...', 'success');
                    
//                    $('#chatting_msg_box_' + customerID).attr("disabled", "disabled");
//                    $('#chatting_msg_box_' + customerID).attr("data-end", "true");
//                    $("#datatable_sesion_status_" + sessionID).text("Close ...");
                }
            }});
    }

    function format_and_display(option, handler) {
        if (option == "s") {
            var msg = '<div class="direct-chat-msg right">\
                        <div class="direct-chat-info clearfix">\
                            <span class="direct-chat-name pull-right">Me</span>\
                            <span class="direct-chat-timestamp pull-left">'+ date_format('now')  +'</span>\
                        </div>\
                        <img alt="(-_-)" src="' + $("#user_login_profile_pic").attr("src") + '" class="direct-chat-img">\
                        <div class="direct-chat-text">\
                            ' + $("#chatting_msg_box_" + handler).val() + '\
                        </div>\
                    </div>';
            $('#chatting_msg_contenair_' + handler).append(msg);
            $("#chatting_msg_box_" + handler).val("");
            var d = $('#chatting_msg_contenair_' + handler);
            d.scrollTop(d.prop("scrollHeight"));
        } else {
            var msg = '<div class="direct-chat-msg">\
                            <div class="direct-chat-info clearfix">\
                                <span class="direct-chat-name pull-left">' + $("#customer_name_" + handler.customerID).text() + '</span>\
                                <span class="direct-chat-timestamp pull-right">' + handler.msgTime + '</span>\
                            </div>\
                            <img alt="(-_-)" src="' + $("#customer_profife_pic_" + handler.customerID).attr('src') + '" class="direct-chat-img">\
                            <div class="direct-chat-text">\
                             <span id="_message_'+ handler.messageID +'">' + handler.message + '</span> \
                            </div>\
                        </div>';
            $('#chatting_msg_contenair_' + handler.customerID).append(msg);
            var d = $('#chatting_msg_contenair_' + handler.customerID);
            d.scrollTop(d.prop("scrollHeight"));
            set_msg_to_read(handler.messageID);
        }
        
      
    }

    function ajax_load_received_msg() {
        $.ajax({
            type: "POST",
            data: {
            },
            url: "<?php echo base_url() ?>admin/get_msg_receive_for_admin",
            success: function (data) {
                var result = isjson(data);
                if (result && result.status == "success") {
                    var n = result.records.length, i = 0;
                    for (i = 0; i < n; i++) {
                        format_and_display('r', result.records[i]);
                    }
                }
            }});
    }
    
    function set_msg_to_read(msgID){
        if(!$("#_message_"+msgID).length){
            return 0;
        }
        $.ajax({
            type: "POST",
            data: {
                msgID:msgID
            },
            url: "<?php echo base_url() ?>admin/set_msg_to_read",
            success: function (data) {
               
            }});
    }

    function open_chat(me) {
        add_chat_box(me);
//        $.ajax({
//            type: "POST",
//            data: {
//                option: 'all'
//            },
//            url: "<?php echo base_url() ?>admin/get_chat_users",
//            success: function (data) {
//                var result = isjson(data);
//                if (result && result.status == "success") {
//                    var n = result.records.length, i = 0;
//                   
//                }
//            }});
    }

    function update_sesion_admin(session, customerID) {
        $.ajax({
            type: "POST",
            data: {
                "session": session
            },
            url: "<?php echo base_url() ?>admin/update_sesion_admin",
            success: function (data) {
                var result = isjson(data);
                if (result && result.status == "success") {
                    $('#chatting_msg_box_' + customerID).removeAttr("disabled");
                    notify("Session started", 'Tekun ...', 'success');
                    $("#datatable_sesion_status_" + session).text("Attending ...");

                } else {
                    notify("Fail to start session", 'Tekun ...', 'error');
                }
            }}
        );
    }


</script>
<style>
    .chatbox{
        position:fixed;
        bottom:0px;
        float:right;
        right: 10px;
        z-index: 10000;
    }
    .chatbox .chat-box{
        position: relative !important;
        width: 400px !important;
        float: right;
        margin-left:10px !important;
    }
    td {
        vertical-align: middle !important;
    }
    .user_name{
        margin:auto;
    }

    .user_name span{
        position: relative;
        top:10px;
        padding-left: 5px;
    }
</style>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <h1>
            <?php echo $this->lang->line('module'); ?>
        </h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-home"></i> <?php echo $this->lang->line('home'); ?></a></li>
            <li><a href="#"><?php echo $this->lang->line('module'); ?></a></li>
            <li class="active"><?php echo $this->lang->line('livehelp'); ?></li>
        </ol>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-md-12">
                <!-- Horizontal Form -->
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title"><?php echo $this->lang->line('livehelp'); ?></h3>
                        <button onclick="refresh_online_users()" class="btn btn-primary pull-right" type="button"><i class="fa fa-refresh"></i></button>
                    </div><!-- /.box-header -->

                    <!-- Custom Tabs -->
                    <div class="nav-tabs-custom">
                        <ul class="nav nav-tabs">
                            <li class="active"><a aria-expanded="true" href="#tab_unattend" data-toggle="tab"><?php echo $this->lang->line('unattended'); ?></a></li>
                            <li class=""><a aria-expanded="false" href="#tab_alluser" data-toggle="tab"><?php echo $this->lang->line('allusers'); ?></a></li>
                        </ul>
                        <div class="tab-content">
                            <div class="tab-pane active" id="tab_unattend">
                                <table id="datatable_unattend" class="table table-bordered table-striped datatables">
                                    <thead>
                                        <tr>
                                            <th class="text-center"><?php echo $this->lang->line('no'); ?></th>
                                            <th><?php echo $this->lang->line('username'); ?></th>
                                            <th><?php echo $this->lang->line('question'); ?></th>
                                            <th class="text-center"><?php echo $this->lang->line('status'); ?></th>
                                            <th class="text-center"><?php echo $this->lang->line('starttime'); ?></th>
                                            <th class="text-center"><?php echo $this->lang->line('waitingtime'); ?></th>
                                            <th class="text-center"><?php echo $this->lang->line('chattime'); ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>
                            <div class="tab-pane" id="tab_alluser">
                                <table id="datatable_all" class="table table-bordered table-striped datatables">
                                    <thead>
                                        <tr>
                                            <th class="text-center"><?php echo $this->lang->line('no'); ?></th>
                                            <th class="text-center"><?php echo $this->lang->line('username'); ?></th>
                                            <th><?php echo $this->lang->line('question'); ?></th>
                                            <th class="text-center"><?php echo $this->lang->line('status'); ?></th>
                                            <th class="text-center"><?php echo $this->lang->line('starttime'); ?></th>
                                            <th class="text-center"><?php echo $this->lang->line('waitingtime'); ?></th>
                                            <th class="text-center"><?php echo $this->lang->line('chattime'); ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>

                        </div>
                    </div>

                </div>
            </div>
        </div>
    </section><!-- /.content -->
</div><!-- /.content-wrapper -->
