$(document).ready(function () {
  //  $("body").removeClass("sidebar-collapse");
    //var ref = new Firebase("https://ursugar-6ce9a.firebaseio.com/");
    var ref = '';
    var messagesRef = ref.child("ChatMessages");
    var INDoctorId = $('#myHiddenVar').val();

    var $Message = $("#Chatmsg");
    var $submit = $("#submit");
    var $messageList = $("#PatientMessageList");
    var Configuration = {
        doctor_id: INDoctorId,
    }
    var url = location.href;
    var arr = url.split('=');
    var INPatientId = arr[1];
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Message/GetPatientdetails',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Configuration),
        success: function (data) {
            var newArray = data.filter(function (el) {
                return el.Patient_id == INPatientId;
            });
            $('#PatientName')[0].innerText = newArray[0].Patient_first_Name;

        }
    });
    function addMessage(DoctorId, PatientId, Message, isDoctorRead,KeyForUpdate) {
        var el = "";
        if (INDoctorId == DoctorId && INPatientId == PatientId) {
            if (isDoctorRead = 0) {
                ref.child('/ChatMessages/' + KeyForUpdate).update({ DoctorRead: 1 });
            }
            if (Message.indexOf(DoctorId) > -1) {
                el = '<li class="replies"><img width="50" height="50" src="~../../Content/img/user2-160x160.jpg" alt="" /><p>' + Message.replace(DoctorId, '') + '</p></li>';
            }
            else if (Message.indexOf(PatientId) > -1) {
                el = '<li class="sent"><img width="50" height="50" src="~../../Content/img/male.png" alt="" /><p>' + Message.replace(PatientId, '') + '</p></li>';
            }
        }
        $messageList.append(el);
    }
    messagesRef.on("child_added", function (snapshot) {
        var message = snapshot.val();
            addMessage(message.DoctorId, message.PatientId, message.Message, message.DoctorRead,snapshot.key());
    });
    $submit.click(function () {

        if ($Message.val().length > 0) {
            sendMessage();
        }
    });
    $Message.keypress(function (e) {
        if (e.keyCode == 13 && $Message.val().length > 0) {
            sendMessage();
        }
    });
    function sendMessage() {

        messagesRef.push({
            DoctorId: INDoctorId,
            PatientId: INPatientId,
            Message: INDoctorId + ' ' + $Message.val(),
            TimeStamp: Date.now(),
            PatientRead: 0,
            DoctorRead: 1,
            IsStarred: 0
        }, function (error) {
            if (error) {
                console.log("Error adding new message:", error);
            }
        });
        $Message.val("");
    }

});