//var fb_url = $('#firebaseurl').val();
//console.log(fb_url);
//var ref = new Firebase(fb_url);
//var ref = new Firebase("https://ursugar-6ce9a.firebaseio.com/");
//var ref = new Firebase("https://ursugartest.firebaseio.com/");
var ref = new Firebase($('#HFirebaseID').val());
var rref = new Firebase($('#HFirebaseID').val());
//var ref = '';
var messagesRef = ref.child("ChatMessages");
var UserRef = ref.child("Users");
let firebaseChatList = [];
let patientList  = [];
var AllMessages = new Array();
var AllPatients = new Array();
var KeyArray = new Array();
var KeyForDelete;
var ReplytoPatientID;
var DoctorId = $('#myHiddenVar').val();

var RDRref = rref.child("ref_doctor_list/" + DoctorId + "/chat_list");

var DRref = ref.child("doctor_list/" + DoctorId + "/chat_list");

var Chatref = "";

$(document).ready(function () {
    if ($.trim($('#payment_msg').val()).length > 0) {
        if ($('#payment_msg').val() == "Success") {
            toastr.success("Payment successful!!!");
            location.replace('/Message');
        }
        else {
            toastr.warning("Payment Failure. Please try again after some time.");
            location.replace('/Message');
        }
    }    
    GetChatConfiguration("1");


    if($('#Sendradio').val()==1){
        $('#divMsgTitle').show();
        $('#divMsgType').show();
        $('#divMsgBody').show();
        $('#divMsgUrl').show();
        $('#divImage').show();
        $('#divArticlefileUpload').show();
        $('#divChatStatus').show();

        $('#divMsgTemplate').hide();
        $('#divMessagePreview').hide();
    }
    else if($('#Sendradio').val()==2){
        $('#divMsgTemplate').show();
        $('#divMessagePreview').hide();

        $('#divMsgTitle').hide();
        $('#divMsgType').hide();
        $('#divMsgBody').hide();
        $('#divMsgUrl').hide();
        $('#divImage').hide();
        $('#divArticlefileUpload').hide();
        $('#divChatStatus').hide();
    }
    else if($('#Sendradio').val()==3){
        $('#divMsgTitle').hide();
        $('#divMsgType').show();
        $('#divMsgBody').show();
        $('#divMsgUrl').show();
        $('#divImage').show();
        $('#divArticlefileUpload').show();
        $('#divChatStatus').show();

        $('#divMsgTemplate').hide();
        $('#divMessagePreview').hide();
    }

    LoadBranch();

    
});

$('#Sendradio').change(function(){
    if($('#Sendradio').val()==1){
        $('#divMsgTitle').show();
        $('#divMsgType').show();
        $('#divMsgBody').show();
        $('#divMsgUrl').show();
        $('#divImage').show();
        $('#divArticlefileUpload').show();
        $('#divChatStatus').show();

        $('#divMsgTemplate').hide();
        $('#divMessagePreview').hide();
    }
    else if($('#Sendradio').val()==2){
        $('#divMsgTemplate').show();
        $('#divMessagePreview').hide();

        $('#divMsgTitle').hide();
        $('#divMsgType').hide();
        $('#divMsgBody').hide();
        $('#divMsgUrl').hide();
        $('#divImage').hide();
        $('#divArticlefileUpload').hide();
        $('#divChatStatus').hide();

        $('#selTemplate').empty();
        var default_opt = '<option value="0">--Choose Template--</option>';
       
        $('#selTemplate').append(default_opt);
    }
    else if($('#Sendradio').val()==3){
        //$('#divMsgTitle').hide();
        //$('#divMsgType').show();
        //$('#divMsgBody').show();
        //$('#divMsgUrl').show();
        //$('#divImage').show();
        //$('#divArticlefileUpload').show();
        //$('#divChatStatus').show();

        //$('#divMsgTemplate').hide();
        //$('#divMessagePreview').hide();
        $('#divMsgTemplate').show();
        $('#divMessagePreview').hide();

        $('#divMsgTitle').hide();
        $('#divMsgType').hide();
        $('#divMsgBody').hide();
        $('#divMsgUrl').hide();
        $('#divImage').hide();
        $('#divArticlefileUpload').hide();
        $('#divChatStatus').hide();


        var doctorData = {
            Dml_Indicator: 'TL'        
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Message/Broadcast_Patients_list',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(doctorData),
            success: function (data) {
                debugger;
                $('#selTemplate').empty();
                var data1 = JSON.parse(data);
                if(data1.msg=="Success"){
                    var data1=data1.data;                
                    if (jQuery.isEmptyObject((data1))) {
                        toastr.warning('No Details Found');
                    }
                    else {
                        if (data1.Table.length > 0) {
                            var SubDepartment;
                            var default_opt = '<option value="0">--Choose Template--</option>';
                            $.each(data1.Table, function (i, emp) {
                                SubDepartment = SubDepartment + '<option value="' + emp.Id + '">' + emp.TemplateName + '</option>';
                            });

                            $('#selTemplate').append(default_opt + SubDepartment);
                        }
                    }
                }
            }
        });

    }
})

function LoadBranch() {
    debugger;
    $('#SelBranch').empty();
    var subdepartment = {
        Dml_Indicator: "LBRAN"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#SelBranch').append(SubDepartment);
                        $('#SelBranch').change();

                        $('#SelCreditBranch').append(SubDepartment);
                    }
                    else {
                        $('#SelBranch').append(default_opt + SubDepartment);

                        $('#SelCreditBranch').append(default_opt + SubDepartment);
                    }

                    if ($('#hiddenRole_id').val() != 2) {
                        $('#SelBranch').val($('#HospitalBranchID').val());
                        $('#SelBranch').attr('disabled', true); 
                        
                        $('#SelCreditBranch').val($('#HospitalBranchID').val());
                        $('#SelCreditBranch').attr('disabled', true); 
                      
                    }
                    
                }
            }
            else {
                console.log(data1);
            }

            LoadCreditType();
           
        }
    });
}

$("#patsearch1").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#userul li").filter(function() {
        $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
});

function listenChat(e) {
    var pid = $(e).attr("data-id");
    var p_name = $(e).attr("data-name");
    if($('#selpatlist').val() == "4")
    {
        RDRref.child(pid).once("value", function (snap) {
            console.log(snap.val());
            if (snap.val() != null) {
                var roomid = snap.val().roomid;
                $("#chat_input").attr("data-patient", pid);
                openchat(roomid, e);
                if(snap.val().message && snap.val().message.unread !== 0) {
                    RDRref.child(pid).child("message/unread").set(0);
                }
            } 
            else {
                var roomid = rref.child("ref_chat_room/").push().key();
                var pdoc = {
                    id: pid,
                    name: p_name,
                    roomid: roomid,
                    url: ""
                }
                var ddoc = {
                    id: DoctorId,
                    name: $('#txtDusername').html(),
                    roomid: roomid,
                    url: ""
                }
                var PRref = rref.child("referral_list/" + pid + "/chat_list");
                RDRref.child(pid).set(pdoc);
                rref.child("ref_chat_room").child(roomid).set({
                    referalcodeId: pid,
                    doctorId:DoctorId
                })
                PRref.child(DoctorId).set(ddoc);
                $("#chat_input").attr("data-patient", pid);
                openchat(roomid, e);
            }
        })

    }
    else
    {
        DRref.child(pid).once("value", function (snap) {
            console.log(snap.val())
            if (snap.val() != null) {
                var roomid = snap.val().roomid;
                $("#chat_input").attr("data-patient", pid);
                openchat(roomid, e);
                if(snap.val().message && snap.val().message.unread !== 0) {
                    DRref.child(pid).child("message/unread").set(0);
                }
            } else {
                var roomid = ref.child("chat_room/").push().key();
                var pdoc = {
                    id: pid,
                    name: p_name,
                    roomid: roomid,
                    url: ""
                }
                var ddoc = {
                    id: DoctorId,
                    name: $('#txtDusername').html(),
                    roomid: roomid,
                    url: ""
                }
                var PRref = ref.child("patient_list/" + pid + "/chat_list");
                DRref.child(pid).set(pdoc);
                ref.child("chat_room").child(roomid).set({
                    patientId: pid,
                    doctorId:DoctorId
                })
                PRref.child(DoctorId).set(ddoc);
                $("#chat_input").attr("data-patient", pid);
                openchat(roomid, e);
            }
        })
    }
}
var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
};
function openchat(roomid, e) {
    if($('#selpatlist').val() == "4")
    {
        $(".user_item").css("background", "white")
        $(e).css("background", "#f0f0f0")
        $("#chat_name").html($(e).attr('data-name').replace(/_s_/, ' '));
        var p_name = $(e).attr("data-name");
        var patientsrc = $(e).attr('data-img');
        var pid = $(e).attr("data-id");
        $('#selpatname').html(p_name);
        $('#selpatid').html(pid);
        $('#selphone').html($(e).attr("data-phone"));
        $('#patimage').html('<img height="50" onerror=changedefault(this) class=chat-image chat-image-default src=' + patientsrc + ' alt="logo" />');
        $("#chat_img").attr("src", patientsrc);
        $("#chat_img").css("display", "block");
        Chatref = rref.child("ref_chat_room/" + roomid + "/messages");
        $("#chat_wapper").css("display", "block");
        rref.child("ref_chat_room/" + roomid + "/messages");
        if (Chatref != "") { Chatref.off() }
        var chat_wrapper = $('.chat_input_wrapper').css('width').replace("px", "");
        $("#chat_input").css("width", chat_wrapper - 100 + "px");
        enterevent();
        Chatref.on("value", function (docs) {
            $("#message_list").empty();
            docs.forEach(function (doc) {
                var data = doc.val();
                var msg = data.msg;
                var time = gettime(data.ts);
                if (msg == "b_f_d")
                {
                    msg = data.blog["msgtitle"];
                    time = Date(data.ts).split(" ")[4];
                }           
                var type = data.type;
                var docimg = $("#ProfilePhotoTop").attr("src");           
                if (type == "rc") {
                    $("#message_list").append("<div class='chat-message padding'><div class='chat-message chat-message-recipient'><img onerror='changedefault(this)' class='chat-image chat-image-default' src=" + patientsrc + " /><div class='chat-message-wrapper'><div class='chat-message-content'><p>" + msg + "</p></div><div class='chat-details'>" + time + "</div></div></div>")
                } else {
                    $("#message_list").append("<div class='chat-message padding'><div class='chat-message chat-message-sender'><img  onerror='changedefault(this)' class='chat-image chat-image-default' src=" + docimg + " /><div class='chat-message-wrapper'><div class='chat-message-content'><p>" + msg + "</p></div><div class='chat-details' style='text-align:right'>" + time + "</div></div></div>")
                }
            });
            var $target = $('.inbox-body');
            //usmsgscroller();
        })
    }
    else
    {
        $(".user_item").css("background", "white")
        $(e).css("background", "#f0f0f0")
        $("#chat_name").html($(e).attr('data-name').replace(/_s_/, ' '));
        var p_name = $(e).attr("data-name");
        var patientsrc = $(e).attr('data-img');
        var pid = $(e).attr("data-id");
        $('#selpatname').html(p_name);
        $('#selpatid').html(pid);
        $('#selphone').html($(e).attr("data-phone"));
        $('#patimage').html('<img height="50" onerror=changedefault(this) class=chat-image chat-image-default src=' + patientsrc + ' alt="logo" />');
        $("#chat_img").attr("src", patientsrc);
        $("#chat_img").css("display", "block");
        Chatref = ref.child("chat_room/" + roomid + "/messages");
        $("#chat_wapper").css("display", "block");
        ref.child("chat_room/" + roomid + "/messages");
        if (Chatref != "") { Chatref.off() }
        var chat_wrapper = $('.chat_input_wrapper').css('width').replace("px", "");
        $("#chat_input").css("width", chat_wrapper - 100 + "px");
        enterevent();
        Chatref.on("value", function (docs) {
            $("#message_list").empty();
            docs.forEach(function (doc) {
                var data = doc.val();
                var msg = data.msg;
                var time = gettime(data.ts);
                if (msg == "b_f_d")
                {
                    msg = data.blog["msgtitle"];
                    time = Date(data.ts).split(" ")[4];
                }           
                var type = data.type;
                var docimg = $("#ProfilePhotoTop").attr("src");           
                if (type == "p") {
                    $("#message_list").append("<div class='chat-message padding'><div class='chat-message chat-message-recipient'><img onerror='changedefault(this)' class='chat-image chat-image-default' src=" + patientsrc + " /><div class='chat-message-wrapper'><div class='chat-message-content'><p>" + msg + "</p></div><div class='chat-details'>" + time + "</div></div></div>")
                } else {
                    $("#message_list").append("<div class='chat-message padding'><div class='chat-message chat-message-sender'><img  onerror='changedefault(this)' class='chat-image chat-image-default' src=" + docimg + " /><div class='chat-message-wrapper'><div class='chat-message-content'><p>" + msg + "</p></div><div class='chat-details' style='text-align:right'>" + time + "</div></div></div>")
                }
            });
            var $target = $('.inbox-body');
            usmsgscroller();
            //message_list
            //$target.animate({ scrollTop: $target.height() }, 1000);
        })
    }
}
function usmsgscroller() {
    console.log($('#message_list').innerHeight())
    $('.inbox-body').scrollTop($('#message_list')[0].scrollHeight);
    listenChat();
}

function gettime(ts) {
    var ts = new Date(ts);
    var hour = ts.getHours();
    var min = ts.getMinutes();
    var am = "AM"
    if (hour > 11) {
        am = "PM"
        if (hour > 12) {
            hour = hour - 12;
        }
    }
    if (hour < 10) {
        hour = "0" + hour
    }
    if (min < 10) {
        min = "0" + min
    }
    var time = hour + ":" + min + " " + am;
    return time;
}

function enterevent() {
    var input = document.getElementById("chat_input");
    input.addEventListener("keyup", function (event) {
        if (event.keyCode === 13) {
            event.preventDefault();
            sendChatMessage();
        }
    });
}
function sendChatMessage() {
    debugger;
    var msg = $("#chat_input").val().trim();
    if (msg == "") return;
    console.log(Chatref);
    if($('#selpatlist').val() == "4")
    {
        Chatref.push().set({
            msg: msg,
            ts: new Date().getTime(),
            type: "rd",
            product_code: $('#HProductCode').val()
        }) 
    }
    else
    {
        Chatref.push().set({
            msg: msg,
            ts: new Date().getTime(),
            type: "d",
            product_code: $('#HProductCode').val()
        })
    }
     $("#chat_input").val("");
}
function listenChatList() {
    if($('#selpatlist').val() == "4")
    {
        RDRref.on("value", function (docs) {
            firebaseChatList = [];
            docs.forEach(function (doc) {
                let { message } = doc.val();
                if(message) {
                    let chat = doc.val();
                    chat.ts = message.ts;
                    chat.unread = message.unread;
                    chat.msg = message.msg;
                    firebaseChatList.push(chat);
                }
            })
            initLeftMenu();
        });
    }
    else
    {
        DRref.on("value", function (docs) {
            firebaseChatList = [];
            docs.forEach(function (doc) {
                let { message } = doc.val();
                if(message) {
                    let chat = doc.val();
                    console.log("1000000000");
                    console.log(message);
                    chat.ts = message.ts;
                    chat.unread = message.unread;
                    chat.msg = message.msg;
                    firebaseChatList.push(chat);
                }
            })
            initLeftMenu();
        });
    }
}

$('#selpatlist').change(function(){
    $('#loaderimg').show();
    GetChatConfiguration($('#selpatlist').val());
});

function GetChatConfiguration(val) {
    var indicator_id;
    if(val == "1")
    {
        if($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5")
        {
            indicator_id = "PL";
        }
        else
        {
            indicator_id = "PLA";
        }
    }
    else if(val == "2") 
    {
        if($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5")
        {
            indicator_id = "VP";
        }
        else
        {
            indicator_id = "VPA";
        }
    }
    else  if(val == "3") 
    {
        if($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5")
        {
            indicator_id = "WP";
        }
        else
        {
            indicator_id = "WPA";
        }
    }
    else if(val == "4")
    {
        if($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5")
        {
            indicator_id = "RHL";
        }
        else
        {
            indicator_id = "RHL";
        }
    }
    var DoctorId = $('#myHiddenVar').val();
    var Configur = {
        doctor_id: DoctorId,
        indicator_id: indicator_id,
        product_code: $('#HProductCode').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Message/patient_list',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Configur),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if(data1.msg=="Success"){
                var data1=data1.patient_list;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    patientList = data1;
                    listenChatList();
                    $('#loaderimg').hide();
                }
            }
            else{
                console.log(data1);
            }
        }
    });
    $('#loaderimg').hide();
}

function initLeftMenu() {
    $('#userul').empty();
    let activeChat = [];
    let chat = [];
    let list = [];

    if($('#selpatlist').val() == "4")
    {
        patientList.forEach(item => {
            let {referral_code_id} = item;
            firebaseChatList.forEach(chat  => {
                let { id, ts, msg, unread} = chat;
                if(chat.id === referral_code_id) {
                    item.ts = ts;
                    item.unread = unread;
                    item.msg = msg;
                }
            })
            if(item.ts) {
                activeChat.push(item);
            }else {
                chat.push(item);
            }
        })
        activeChat.sort((a,b) =>  b.unread - a.uread);
        activeChat.sort((a,b) =>  b.ts - a.ts);
        activeChat.forEach(item => {
            list.push(item);
        })

        chat.forEach(item => {
            list.push(item);
        })

        for (var i = 0; i < list.length; i++) {
            var patient = list[i];
            var pid = patient.referral_code_id;
            var photo = "";
            var url = $('#patphotopath').val();
            var photoSrc = "";
            if (photo != "") {
                photoSrc = url + photo;
            } else {
                photoSrc = "/Content/img/profile_icon.png";
            }
            var phone_num = "-";
            var message = patient.msg;
            var badge = patient.unread;
            message = message ?  message : "";
            badge = badge ?  badge : 0;
            var name = patient.referral_hospital;
            if (name.trim() == "") {
                name = "Unknown";
            }
            var id = 'patient_chat' + pid;
            //var pname = name.replace(/ /, '_s_');
            var pname = name;
            var badgeDiv = '';
            if(badge !== 0) {
                badgeDiv = '<div class="user_item-badge">'+badge+'</div>'
            }
            var content = '<li> <a data-name=' + pname + ' data-phone=' + phone_num + ' onerror="changedefault(this)"    id=' + id + ' data-img=' + photoSrc + ' class="user_item" data-id=' + pid + ' onclick="listenChat(this)"> <img onerror=changedefault(this) src="' + photoSrc + '" class="img-circle img-responsive img-msgs" alt="" style="border-radius:50%;height:35px;width:35px!important;margin-right:10px"><div class="user_item-content"> <div class="user_item-name">  ' + name + '</div><div class="user_item-message">'+ message +'</div></div> '+badgeDiv+' </a>  </li>';
            $('#userul').append(content);
        }
        var chat_id = getUrlParameter('chat_id');
        var dom = document.getElementById('patient_chat' + chat_id);
        if (chat_id != undefined && dom != null) {
            listenChat(dom)
        }
    }
    else
    {
        patientList.forEach(item => {
            let {patient_id} = item;
            firebaseChatList.forEach(chat  => {
                let { id, ts, msg, unread} = chat;
                if(chat.id === patient_id) {
                    item.ts = ts;
                    item.unread = unread;
                    item.msg = msg;
                }
            })
            if(item.ts) {
                activeChat.push(item);
            }else {
                chat.push(item);
            }
        })
        activeChat.sort((a,b) =>  b.unread - a.uread);
        activeChat.sort((a,b) =>  b.ts - a.ts);
        activeChat.forEach(item => {
            list.push(item);
        })

        chat.forEach(item => {
            list.push(item);
        })

        for (var i = 0; i < list.length; i++) {
            var patient = list[i];
            var pid = patient.patient_id;
            var photo = patient.photo;
            var url = $('#patphotopath').val();
            var photoSrc = "";
            if (photo != "") {
                photoSrc = url + photo;
            } else {
                photoSrc = "/Content/img/profile_icon.png";
            }
            var phone_num;
            if(patient.phone_number_1 == "" || patient.phone_number_1 == null) phone_num = "-";
            else phone_num = patient.phone_number_1;
            var message = patient.msg;
            var badge = patient.unread;
            message = message ?  message : "";
            badge = badge ?  badge : 0;
            var name = patient.patient_name;
            if (name.trim() == "") {
                name = patient.phone_number_1;
            }
            var id = 'patient_chat' + pid;
            var pname = name.replace(/ /, '_s_');
            var badgeDiv = '';
            if(badge !== 0) {
                badgeDiv = '<div class="user_item-badge">'+badge+'</div>'
            }
            var content = '<li> <a data-name=' + pname + ' data-phone=' + phone_num + ' onerror="changedefault(this)"    id=' + id + ' data-img=' + photoSrc + ' class="user_item" data-id=' + pid + ' onclick="listenChat(this)"> <img onerror=changedefault(this) src="' + photoSrc + '" class="img-circle img-responsive img-msgs" alt="" style="border-radius:50%;height:35px;width:35px!important;margin-right:10px"><div class="user_item-content"> <div class="user_item-name">  ' + name + '</div><div class="user_item-message">'+ message +'</div></div> '+badgeDiv+' </a>  </li>';
            $('#userul').append(content);
        }
        var chat_id = getUrlParameter('chat_id');
        var dom = document.getElementById('patient_chat' + chat_id);
        if (chat_id != undefined && dom != null) {
            listenChat(dom)
        }
    }
   
}

function changedefault(e) {
    var photoSrc = "/Content/img/profile_icon.png";
    $(e).attr("src", photoSrc)
}
UserRef.on("child_added", function (snapshot) {
    snapshot.forEach(function (child) {
        //
    });
});

UserRef.on("value", function (snapshot) {
    snapshot.forEach(function (child) {

    });
});

messagesRef.limitToFirst(1).on("child_added", function (snapshot) {
    //    GetChatConfiguration();
});
messagesRef.on('child_removed', function (oldChildSnapshot) {
    //  retriveMessages = true;
});
function redirectToChat(patientId) {
    window.location = '/PatientChat?patientId=' + patientId;
}
function GetMessages() {
    var DoctorId = $('#myHiddenVar').val();
    messagesRef.orderByChild('DoctorId').startAt(DoctorId).endAt(DoctorId).on("value", function (snapshot) {
        AllMessages = new Array();
        snapshot.forEach(function (child) {
            AllMessages.push(child.val())
            var newUserData = {
                "PatientId": child.val().PatientId,
                "DoctorId": child.val().DoctorId,
                "Key": child.key(),
                "Message": child.val().Message
            };
            KeyArray.push(newUserData);
        });
        $("#contentNonRead").empty();
        $('#contentstarred').empty();
        $('#content').empty();
        var displayedMessages = new Array();
        var ages = AllMessages.map(function (obj) { return obj.PatientId });
        ages = ages.filter(function (v, i) { return ages.indexOf(v) == i; });
        for (var i = 0; i < ages.length; i++) {
            var filtered = AllMessages.filter(function (x) { return x.PatientId == ages[i] && x.Message.indexOf(x.PatientId) > -1; });
            displayedMessages.push(filtered[filtered.length - 1]);
        }
        $('#userul').empty();
        $('#userul').append('<li> <h4>Buddy online</h4> </li>');
        for (var i = 0; i < displayedMessages.length; i++) {
            var PatientName = AllPatients.filter(function (x) { return x.Patient_id == displayedMessages[i].PatientId; });
            if (PatientName.length > 0 && PatientName[0].ChatStatus == 1) {

                loadData(PatientName[0].Patient_first_Name, PatientName[0].patient_photo, displayedMessages[i])
            }
            if (PatientName.length > 0) {
                loadPatientData(PatientName[0].Patient_first_Name, PatientName[0].patient_photo);
            }
        }
    });
}

function loadPatientData(Patient_Name, patient_photo) {
    var image = patient_photo;
    var photoSrc;
    var PatientPhoto = $('#patphotopath').val();
    if ($.trim(image) == "" || image == null) {
        photoSrc = "/Content/img/profile_icon.png";
    }
    else {
        photoSrc = PatientPhoto + image;
    }
    var content = '<li> <a href="#"> <img onerror=changedefault(this) src="' + photoSrc + '" class="img-circle img-responsive img-msgs" alt="" style="border-radius:50%; max-width:100%; width:100%;"><i class=" fa fa-circle text-white f9"></i>' + Patient_Name + ' </a>  </li>';
    $('#userul').append(content);
}
function loadData(Patient_Name, patient_photo, displayedMessages) {
    var Message = displayedMessages.Message.replace(displayedMessages.PatientId, '');
    var image = patient_photo;
    var PatientId = displayedMessages.PatientId;
    var DoctorRead = displayedMessages.DoctorRead;
    var DoctorId = displayedMessages.DoctorId;
    var IsStarred = displayedMessages.IsStarred;
    var starColor = "gold";
    if (IsStarred == 0) {
        starColor = "gray";
    }

    var photoSrc;
    var PatientPhoto = $('#patphotopath').val();
    if ($.trim(image) == "" || image == null) {
        photoSrc = "/Content/img/profile_icon.png";

    }
    else {

        photoSrc = PatientPhoto + image;

    }
    var content = '<div class="search-boxa"><div class="box mobile-top"><div class="box-header with-border">';
    content = content + '<table class="message-user"><tbody><tr><td onclick="StarTheMessage(this,\'' + Message + '\',\'' + PatientId + '\',\'' + DoctorId + '\')" class="starred"><i class="fa fa-star ' + starColor + '" aria-hidden="true"></i></td><td class="profile-icon"><img onerror=changedefault(this) src=' + photoSrc + ' class="img-circle img-responsive img-msgs" alt="" style="border-radius:50%; max-width:100%; width:100%;"></td>';
    content = content + '<td><div class="name-ar"><a onclick="return redirectToChat(\'' + PatientId + '\')" href="#"><i class=" fa fa-circle text-danger"></i>' + Patient_Name + ',</a></div><div class="place-m">Chennai</div></td></tr></tbody></table></div>';
    content = content + '<div class="box-body"><p>' + Message + '</p></div></div><div class="box-footer message-box-f"><div class="search-boxb"><a onclick="return Reply(\'' + PatientId + '\');" href="#" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#replay-p" data-backdrop="static" data-keyboard="true"><i class="fa fa-reply" aria-hidden="true"></i> Reply </a><a onclick="return Delete(\'' + Message + '\',\'' + PatientId + '\',\'' + DoctorId + '\');" href="#" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#delete-p" data-backdrop="static" data-keyboard="true"><i class="fa fa-trash-o" aria-hidden="true"></i> Delete </a></div></div></div>';

    if (DoctorRead == 0) {
        $('#contentNonRead').append(content);
    }

    if (IsStarred == 1) {
        $('#contentstarred').append(content);
    }
    $('#content').append(content);
    $('#starredCount')[0].innerText = AllMessages.filter(function (x) { return x.IsStarred == 1; }).length;
    $('#UnreadCount')[0].innerText = AllMessages.filter(function (x) { return x.DoctorRead == 0; }).length;
    $('#allCount')[0].innerText = AllMessages.filter(function (x) { return x.Message.indexOf(DoctorId) == -1; }).length;

}
function StarTheMessage(obj, Message, PatientId, DoctorId) {
    var starred = 0;
    if (obj.children['0'].className.indexOf("gray") > -1) {
        starred = 1;
    }
    Message = PatientId + Message;
    var filtered = KeyArray.filter(function (x) { return x.PatientId == PatientId && x.DoctorId == DoctorId && x.Message == Message; });
    ref.child('/ChatMessages/' + filtered[0].Key).update({ IsStarred: starred });
}
function Delete(Message, PatientId, DoctorId) {
    Message = PatientId + Message;
    var filtered = KeyArray.filter(function (x) { return x.PatientId == PatientId && x.DoctorId == DoctorId && x.Message == Message; });
    KeyForDelete = filtered[0].Key;

}
function Reply(PatientId) {
    ReplytoPatientID = PatientId;
}
function ConfirmDelete() {
    messagesRef.child(KeyForDelete).remove();
    KeyForDelete = "";
    document.getElementById('closeDelete').click();

    AllMessages = new Array();
    KeyArray = new Array()
    KeyForDelete = "";
    GetMessages();
}
function CancelDelete() {
    KeyForDelete = "";
    document.getElementById('closeDelete').click();
}

function replyMessage() {

    messagesRef.push({
        DoctorId: $('#myHiddenVar').val(),
        PatientId: ReplytoPatientID,
        Message: $('#myHiddenVar').val() + ' ' + $('#comment').val(),
        TimeStamp: Date.now(),
        PatientRead: 0,
        DoctorRead: 1,
        IsStarred: 0
    }, function (error) {
        if (error) {
            console.log("Error adding new message:", error);
        }
    });
    document.getElementById('close').click();
    $('#comment').val("");
}


//buy sms code started


function doctor_id() {
    var doc_id = '';
    if ($('#hiddenRole_id').val() == 1 || $('#hiddenRole_id').val() == 5) { doc_id = $('#HiddenDoctorID').val(); }
    else { doc_id = $('#SelDoctorapp').val(); }
    return doc_id;
}


function doctorlist() {
    var DoctorData = {
        Dml_Indicator: "DL",
        user_role: $('#hiddenRole_id').val(),
        doctor_id: $('#HiddenDoctorID').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Prescription_Settings/casesheet_configurations',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data1 = JSON.parse(data);
            if(data1.msg=="Success"){
                var data1=data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var b = data1.Table;
                    var tr = '';
                    var SelRole = '';
                    $('#SelDoctorapp').empty();
                    var default_opt = '<option value="">--Select Doctor--</option>';
                    $.each(b, function (i, emp) {
                        SelRole = SelRole + '<option value="' + emp.doctor_id + '">' + emp.doctor_name + '</option>';
                    });
                    $('#SelDoctorapp').html(default_opt + SelRole);
                }
            }
            else{
                console.log(data1);
            }

        }
    });
}


$('#smsid').click(function () {
    $('#loaderimg').show();
    $('#smsTime').val("");
    campaign_load();
});



//function open_buy_sms_overlay() {
//    var RepData = {
//        indicator_id: 'AD',
//        doctor_id: $('#HiddenDoctorID').val()
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/DrBroadcastChat/sms_details_charge',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(RepData),
//        success: function (data) {
//            debugger;
//            var data1 = JSON.parse(data);
//            if(data1.msg=="Success"){
//                var data1=data1.data;
//                $('#sms_buy_table').empty();
//                $('#Bsms').modal('toggle');
//                table_buysms_binding(data1);
//            }
//            else{
//                console.log(data1);
//            }
//        }
//    });
//}


//function table_buysms_binding(data1) {
//    debugger;
//    var a = data1['Table'];
//    var b = data1['Table1'];
//    //$('#drbalanceamt').html('1200');
//    $('#adminsmscost').html(a[0].sms_cost);
//    $('#adminnotcost').html(a[0].notification_cost);
//    $('#adminlinkcost').html(a[0].sms_cost_with_link);

//    if (jQuery.isEmptyObject((b)) || b.length == "0") {
//        tr = $('<table class="table table-bordered" id="sms_buy_tab" />');
//        tr.append("<thead><tr><th>S No</th><th>Payment Id</th><th>Credits(Rs)</th><th>Buy Date</th></tr></thead><tbody>");
//        tr.append("</tbody>");
//        $.when($('#sms_buy_table').append(tr)).then($('#sms_buy_tab').DataTable({
//            "columnDefs": [{
//                "orderable": false,
//            }]
//        }));
//    }
//    else if (b.length > 0) {
//        $('#sms_buy_table').empty();
//        var j = 0;
//        tr = $('<table class="table table-bordered" id="sms_buy_tab" />');
//        tr.append("<thead><tr><th>S No</th><th>Payment Id</th><th>Credits(Rs)</th><th>Buy Date</th></tr></thead><tbody>");
//        $.each(b, function (i, emp) {
//            j++;
//            row_data = "<tr><td>" + j + "</td><td>" + emp.admin_payment_id + "</td><td>" + emp.credit + "</td><td>" + (emp.created_on).split('T')[0] + "</td></tr>";
//            tr.append(row_data);
//        });
//        tr.append("</tbody>");
//        $.when($('#sms_buy_table').append(tr)).then($('#sms_buy_tab').DataTable({
//            "columnDefs": [{
//                "orderable": false,
//            }]
//        }));
//    }
//}


//added by nandhini

$('#btnBuyCredit').click(function () {
    debugger;
    if ($('#SelCreditBranch').val() == "" || $('#SelCreditBranch').val() == null || $('SelCreditBranch').val()==0) {
        $('#PSelCreditBranch').show();
        $('#PSelCreditBranch').fadeOut(8000);
        $('#PSelCreditBranch').html('Select Branch Name');
        $('#SelCreditBranch').focus();
        $('#SelCreditBranch').val('');
        return false;
    }

    if ($('#selCreditType').val() == "" || $('#selCreditType').val() == null || $('selCreditType').val()==0) {
        $('#PselCreditType').show();
        $('#PselCreditType').fadeOut(8000);
        $('#PselCreditType').html('Select Credit Type');
        $('#selCreditType').focus();
        $('#selCreditType').val('');
        return false;
    }

    if ($.trim($('#creditamt').val()).length <= 0) {
        $('#Pcreditamt').show();
        $('#Pcreditamt').fadeOut(8000);
        $('#Pcreditamt').html('Enter the credit amount');
        $('#creditamt').focus();
        $('#creditamt').val('');
        return false;
    }
   
        var broadcastdata = {
            indicator_id: 'I',
            credit_amount: $('#creditamt').val(),
            credit_type: $('#selCreditType').val(),
            branch_id : $('#SelCreditBranch').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/DrBroadcastChat/Buy_Broadcast_Credit',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(broadcastdata),
            success: function (data) {
                var data1 = JSON.parse(data);
                if(data1.msg=="Success"){
                    var data1=data1.data;                 
                  
                    if(data1.Table.length>0) {
                        $('#amtvalue').val($('#creditamt').val());
                        var paymentid = '', invoiceid = '', amount = $('#creditamt').val();
                       
                        paymentid= data1.Table[0].payment_id;
                        invoiceid= data1.Table[0].invoice_no;

                        location.href = '/Controllers/dataFrom.htm?indicator_id1=SP&payment_id=' + paymentid + '&amt=' + amount + '&invoice_id=' + invoiceid;
                    }
                }
                else{
                    console.log(data1);
                }
            }
        });
   
});




$('#closeid,#closeid1').click(function () {
    campaign_load();
});



function campaign_load() {
    var RepData = {
        indicator_id: 'LC',
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DrBroadcastChat/sms_details_charge',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RepData),
        success: function (data) {
            var data2=JSON.parse(data);
            var data1=data2.data;
            if (jQuery.isEmptyObject((data1))) {
            }
            else {
                //var data1 = ;
                var tr = '';
                var SelRole = '';
                $('#smscampaign').empty();
                var SelRole = '<option value="">--Select--</option>';
                var j = 0, bal = '0';
                if (data1['Table'].length > 0) {
                    for (var i = 0; i < data1['Table'].length; i++) {
                        j++;
                        SelRole = SelRole + '<option value="' + data1['Table'][i].campaign_id + '">' + data1['Table'][i].name + '</option>';
                        bal = data1['Table'][i].bal_amount;

                    }
                    if(bal==null)
                    {
                        bal='0';
                    }
                    $('#smsbal').html(parseFloat(bal).toFixed(2));
                    //$('#smscampaign').append(default_opt + SelRole);
                    $('#smscampaign').append(SelRole);
                    if (data1['Table'].length == 1) {
                        $('#smscampaign').val();
                    }
                }
            }
            buy_sms_details_table();
        }
    });
}

function buy_sms_details_table() {
    var RepData = {
        indicator_id: 'LC',
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DrBroadcastChat/sms_details_charge',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RepData),
        success: function (data) {
            debugger;
            $('#loaderimg').hide();
            $('#sms_table_list').empty();
            if (jQuery.isEmptyObject((data)) || data.length == "0") {
                tr = $('<table class="table m22" id="smslist" />');
                tr.append("<thead><tr><th>S No</th><th>Message Title</th><th>Message Body</th><th>Send Via</th><th>Frequency<th>Campaign Name</th></th><th>Status</th><th>Action</th></tr></thead><tbody>");
                tr.append("</tbody>");
            }
            else if (data.length > 0) {
                var j = 0;
                var data1 = JSON.parse(data);
                var data2=data1.data;
                var b = data2.Table1;
                tr = $('<table class="table" id="smslist" />');
                tr.append("<thead><tr><th>S No</th><th>Message Title</th><th>Message Body</th><th>Send Via</th><th>Frequency<th>Campaign Name</th></th><th>Status</th><th>Action</th></tr></thead><tbody>");
                $.each(b, function (i, emp) {
                    j++;
                    var send_via = '', Frequency = '', status = "";
                    if (emp.send_to == "1") send_via = "SMS";
                    else if (emp.send_to == "2") send_via = "URSUGAR App";
                    else if (emp.send_to == "3") send_via = "SMS & URSUGAR";
                    if (emp.trigger_type == "1") Frequency = "Daily";
                    else if (emp.trigger_type == "2") Frequency = "Weekly";
                    else if (emp.trigger_type == "3") Frequency = "Monthly";
                    else if (emp.trigger_type == "4") Frequency = "When Occurs";
                    else if (emp.trigger_type == "5") Frequency = "One Time";
                    if (emp.trigger_status == "1") {
                        status = "Active";
                        row_data = "<tr><td>" + j + "</td><td><a href='#' onclick = send_campaign_details(" + emp.broadcast_chat_doctor_id + "); data-target='#daily-appt'>" + emp.message_title + "</a></td><td>" + emp.message_body + "</td><td>" + send_via + "</td><td>" + Frequency + "</td><td>" + emp.name + "</td><td>" + status + "</td><td><span class='btn btn-primaryuse btn-xs' data-toggle='popover' title='Edit SMS Details' onclick=edit_sms(" + emp.broadcast_chat_doctor_id + ")><i class='fa fa-pencil-square-o' aria-hidden='true'></i> </span>&nbsp;<span class='btn btn-warning btn-xs us-msg-stop-btn' data-toggle='popover' title='Stop Sending SMS' onclick=delete_sms(" + emp.broadcast_chat_doctor_id + ")>Stop</span>&nbsp; <button class='btn btn-danger btn-xs' data-toggle='popover' onclick='SMSCampdelete("+emp.broadcast_chat_doctor_id+")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                    }
                    else if (emp.trigger_status == "2") {
                        status = "Non Active";
                        row_data = "<tr><td>" + j + "</td><td><a href='#' onclick = send_campaign_details(" + emp.broadcast_chat_doctor_id + "); data-target='#daily-appt'>" + emp.message_title + "</a></td><td>" + emp.message_body + "</td><td>" + send_via + "</td><td>" + Frequency + "</td><td>" + emp.name + "</td><td>" + status + "</td><td><span class='btn btn-primaryuse btn-xs' data-toggle='popover' title='Edit SMS Details' onclick=edit_sms(" + emp.broadcast_chat_doctor_id + ")><i class='fa fa-pencil-square-o' aria-hidden='true'></i> </span>&nbsp;<span class='btn btn-warning btn-xs us-msg-active-btn' data-toggle='popover' title='Activate Sending SMS' onclick=activate_sms(" + emp.broadcast_chat_doctor_id + ")>Activate</span>&nbsp;<button class='btn btn-danger btn-xs' data-toggle='popover' onclick='SMSCampdelete("+emp.broadcast_chat_doctor_id+")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                    }
                    tr.append(row_data);
                });
                tr.append("</tbody>");
                $.when($('#sms_table_list').append(tr)).then($('#smslist').DataTable({
                    "columnDefs": [{
                        "orderable": false,
                    }]
                }));
            }
        }
    });

}


var freq_type = '';

$('#smsfreq').change(function () {
    freq_change();
});

function freq_change() {
    freq_type = $('#smsfreq').val();
    $('#us_msg_Ifdays,#us_msg_Ifdate,#us_msg_Iftime').hide();
    if (freq_type == "1") $('#us_msg_Iftime').show();
    else if (freq_type == "2") $('#us_msg_Ifdays,#us_msg_Iftime').show();
    else if (freq_type == "3") $('#us_msg_Ifdate,#us_msg_Iftime').show();
    else if (freq_type == "4") $('#us_msg_Ifdate,#us_msg_Iftime').show();
    else if (freq_type == "5") $('#us_msg_Ifdate,#us_msg_Iftime').show();
}

$('#smsexecute').click(function () {
    if ($.trim($('#smsbal').html()).length == "" || parseInt($.trim($('#smsbal').html())) < parseInt(100)) {
        toastr.warning("Insufficient balance");
        return false;
    }
    if ($.trim($('#smsmsgtitle').val()).length == "") {
        $('#Psmsmsgtitle').show();
        $('#Psmsmsgtitle').fadeOut(8000);
        $('#Psmsmsgtitle').html('Please Enter the SMS title');
        $('#smsmsgtitle').focus();
        $('#smsmsgtitle').val('');
        return false;
    }
    if ($.trim($('#smsmsgtype').val()).length == "") {
        $('#Psmsmsgtype').show();
        $('#Psmsmsgtype').fadeOut(8000);
        $('#Psmsmsgtype').html('Please select the SMS type');
        $('#smsmsgtype').focus();
        $('#smsmsgtype').val('');
        return false;
    }
    if ($.trim($('#smsbody').val()).length == "") {
        $('#Psmsbody').show();
        $('#Psmsbody').fadeOut(8000);
        $('#Psmsbody').html('Please Enter the Message Body');
        $('#smsbody').focus();
        $('#smsbody').val('');
        return false;
    }
    if ($.trim($('#Sendradio1').val()).length == "") {
        $('#PSendradio1').show();
        $('#PSendradio1').fadeOut(8000);
        $('#PSendradio1').html('Please select the Send Message Type');
        $('#Sendradio1').focus();
        $('#Sendradio1').val('');
        return false;
    }
    if ($.trim($('#smsfreq').val()) == "") {
        $('#Psmsfreq').show();
        $('#Psmsfreq').fadeOut(8000);
        $('#Psmsfreq').html('Please select the Frequency');
        $('#smsfreq').focus();
        $('#smsfreq').val('');
        return false;
    }
    if ($.trim($('#smsTime').val()) == "") {
        $('#PsmsTime').show();
        $('#PsmsTime').fadeOut(8000);
        $('#PsmsTime').html('Please select Time');
        $('#smsTime').focus();
        $('#smsTime').val('');
        return false;
    }
    if ($.trim($('#smscampaign').val()) == "") {
        $('#Psmscampaign').show();
        $('#Psmscampaign').fadeOut(8000);
        $('#Psmscampaign').html('Please select the campaign');
        $('#smscampaign').focus();
        $('#smscampaign').val('');
        return false;
    }
    if ($.trim($('#creditamt,#smsmsgtype,#smsbody,#Sendradio1,#smsfreq,#smsbal').val()).length > 0) {
        exceute_campaign();
    }
});


function exceute_campaign() {
    $('#loaderimg').show();
    var select = '';
    var indicator = '';

    if ($('#smsexecute').html() == "Update Campaign") {
        indicator = "US";
    }
    else {
        indicator = "IS";
    }

    select = $('#smsSelDay').select2('val');


    var RepData = {
        indicator_id: indicator,
        sms_title: $('#smsmsgtitle').val(),
        sms_type: $('#smsmsgtype').val(),
        sms_body: $('#smsbody').val(),
        link: $('#smsmsgurl').val(),
        sent_to: $('#Sendradio1').val(),
        frequency: $('#smsfreq').val(),
        sms_time: $('#smsTime').val(),
        sms_date: $('#smsDate').val(),
        sms_days: JSON.stringify(select),
        sms_campaign: $('#smscampaign').val(),
        broadcast_chat_doctor_id: $('#broadcastid').val(),
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DrBroadcastChat/sms_details_charge',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RepData),
        success: function (data) {
            buy_sms_details_table();
            $('#smsmsgtitle').val('');
            $('#smsmsgtype').val('')
            $('#smsbody').val('');
            $('#smsmsgurl').val('');
            $('#smscampaign').val('');
            $('#smsfreq').val('');
            $('#smsTime').val('');
            $('#Sendradio1').val('');
            $("#radioBtn > a.active").removeClass("active").addClass("not-active");
            freq_change();
            if ($('#smsexecute').html() == "Update Campaign") {
                $('#smsexecute').html('Execute Campaign');
            }
        }
    });
}


function edit_sms(id) {
    $('#loaderimg').show();
    var RepData = {
        indicator_id: 'ES',
        broadcast_chat_doctor_id: id,
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DrBroadcastChat/sms_details_charge',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RepData),
        success: function (data) {
            $('#loaderimg').hide();
            $("#radioBtn > a.active").removeClass("active").addClass("not-active");
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                var select = '';
                var data1 = JSON.parse(data);
                if (data1.data['Table'].length > 0) {
                    $.each(data1.data['Table'][0], function (i, emp) {
                        if (emp.trigger_type == "1") $('#us_msg_Iftime').show();
                        else if (emp.trigger_type == "2") $('#us_msg_Ifdays,#us_msg_Iftime').show();
                        else if (emp.trigger_type == "3") $('#us_msg_Ifdate,#us_msg_Iftime').show();
                        else if (emp.trigger_type == "4") $('#us_msg_Ifdate,#us_msg_Iftime').show();
                        else if (emp.trigger_type == "5") $('#us_msg_Ifdate,#us_msg_Iftime').show();
                        $('#smsmsgtitle').val(emp.message_title);
                        $('a[data-toggle=smsmsgtype][data-title="' + emp.message_type + '"]').removeClass('not-active');
                        $('a[data-toggle=smsmsgtype][data-title="' + emp.message_type + '"]').addClass('active');
                        $('#smsmsgtype').val(emp.message_type);
                        $('#smsbody').val(emp.message_body);
                        $('#smsmsgurl').val(emp.link);
                        $('#smsfreq').val(emp.trigger_type);
                        $('a[data-toggle=Sendradio1][data-title="' + emp.send_to + '"]').removeClass('not-active');
                        $('a[data-toggle=Sendradio1][data-title="' + emp.send_to + '"]').addClass('active');
                        $('#Sendradio1').val(emp.send_to);
                        $('#smsTime').val(emp.send_time);
                        $('#smsDate').val(emp.send_date);
                        var dat = JSON.parse(emp.days);
                        $('#smsSelDay').trigger('change.select2');
                        $('#smscampaign').val(emp.campaign_id);
                        $('#broadcastid').val(emp.broadcast_chat_doctor_id);
                        $('#smsexecute').html("Update Campaign");
                    });
                }
            }
        }
    });
}

function delete_sms(id) {
    $('#loaderimg').show();
    var RepData = {
        indicator_id: 'DS',
        broadcast_chat_doctor_id: id,
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DrBroadcastChat/sms_details_charge',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RepData),
        success: function (data) {
            buy_sms_details_table();
        }
    });
}

function SMSCampdelete(id) {
    $('#loaderimg').show();
    var RepData = {
        indicator_id: 'SMSCDL',
        broadcast_chat_doctor_id: id,
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DrBroadcastChat/sms_details_charge',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RepData),
        success: function (data) {
            buy_sms_details_table();
        }
    });
}



function activate_sms(id) {
    $('#loaderimg').show();
    var RepData = {
        indicator_id: 'AS',
        broadcast_chat_doctor_id: id,
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DrBroadcastChat/sms_details_charge',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RepData),
        success: function (data) {
            buy_sms_details_table();
        }
    });
}



function send_campaign_details(id) {
    var RepData = {
        indicator_id: 'CSD',
        broadcast_chat_doctor_id: id,
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DrBroadcastChat/sms_details_charge',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RepData),
        success: function (data) {
            var data1 = JSON.parse(data);
            $('#send_camp_details').empty();
            $('#daily-appt').modal('toggle');
            if (jQuery.isEmptyObject((data1['Table'])) || data1['Table'].length == 0) {
                tr = $('<table class="table table-bordered" id="send_camp_table" />');
                tr.append("<thead><tr><th>S No</th><th>Campaign Name</th><th>Sent Date</th><th>No of SMS</th><th>Action</th></tr></thead><tbody>");
                tr.append("</tbody>");
                $.when($('#send_camp_details').append(tr)).then($('#send_camp_table').DataTable({
                    "columnDefs": [{
                        "orderable": false,
                    }]
                }));
            }
            else if (data1['Table'].length > 0) {
                var j = 0;
                tr = $('<table class="table table-bordered" id="send_camp_table" />');
                tr.append("<thead><tr><th>S No</th><th>Campaign Name</th><th>Sent Date</th><th>No of SMS</th><th>Action</th></tr></thead><tbody>");
                $.each(data1['Table'], function (i, emp) {
                    j++;
                    row_data = "<tr><td>" + j + "</td><td>" + emp.name + "</td><td>" + (emp.sent_on).split('T')[0] + "</td><td>" + emp.total_sms + "</td><td><a href='' class='pop-msg-download'><i class='fa fa-download' aria-hidden='true' id='download_sms' onclick = download_camp_details(this) data-id=" + emp.broadcast_id + " data-name=" + emp.sent_on + "></i></a></tr>";
                    tr.append(row_data);
                });
                tr.append("</tbody>");
                $.when($('#send_camp_details').append(tr)).then($('#send_camp_table').DataTable({
                    "columnDefs": [{
                        "orderable": false,
                    }]
                }));
            }
        }
    });
}


function download_camp_details(e) {
    $('#loaderimg').show();
    var id = e.getAttribute("data-id")
    var dat = e.getAttribute("data-name")
    var RepData = {
        indicator_id: 'DCS',
        broadcast_chat_doctor_id: id,
        sms_date: dat,
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DrBroadcastChat/download_sms_details',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RepData),
        success: function (data) {
            var data1 = JSON.parse(data);
            if(data1.msg=="Success"){
                var data1=data1.data;
                var d = new Date();
                var time = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + "H:" + d.getMinutes() + "M:" + d.getSeconds() + "S";
                JSONToCSVConvertor(data1['Table'], time, true);
                $('#loaderimg').hide();
            }
            else{
                console.log(data1);
            }
        }
    });
}

function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

    var CSV = '';

    CSV += '\r';

    if (ShowLabel) {
        var row = "";

        for (var index in arrData[0]) {

            row += index + ',';
        }

        row = row.slice(0, -1);

        CSV += row + '\r\n';
    }

    for (var i = 0; i < arrData.length; i++) {
        var row = "";

        for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '",';
        }

        row.slice(0, row.length - 1);

        CSV += row + '\r\n';
    }

    if (CSV == '') {
        toastr.warning("Invalid Data");
        return;
    }

    var fileName = "SMSReport_";
    fileName += ReportTitle.replace(/ /g, "_");

    var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);


    var link = document.createElement("a");
    link.href = uri;

    link.style = "visibility:hidden";
    link.download = fileName + ".csv";

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}



//buy sms code ended
//banner module started

$('#bnrmod').click(function () {
    banner_list();
});

$('#fbannerimage').change(function () {
    bannerimageupload();
});

function bannerimageupload() {
    $('.load-position').show();
    var uploadpath = $('#fbannerimage').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (window.FormData !== undefined) {
        var fileUpload = $("#fbannerimage").get(0);
        var files = fileUpload.files;
        var fileData = new FormData();
        for (var i = 0; i < files.length; i++) {
            fileData.append(files[i].name, files[i]);
        }
        fileData.append('username', 'Manas');
        $.ajax({
            url: '/Message/UploadBannerImage',
            type: "POST",
            contentType: false,
            processData: false,
            data: fileData,
            success: function (result) {
                $.each(result, function (i, emp) {
                    $('#fbannerimagelog').empty();
                    var d, n, drloimage;
                    d = new Date();
                    n = d.getTime();
                    drloimage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/Banner/' + emp + '?' + n;
                    $('#fbannerimagelog').append('<a href=" ' + drloimage + '" target="_blank">Preview</a>');
                    $('#fbannerimage_val').val(emp);
                    $('.load-position').hide();
                });
            }
        });
    }
}


$('#bannersubmit').click(function () {
    if ($.trim($('#bannertitle').val()).length == "") {
        $('#Pbannertitle').show();
        $('#Pbannertitle').fadeOut(8000);
        $('#Pbannertitle').html('Please Enter Banner Title');
        $('#bannertitle').focus();
        $('#bannertitle').val('');
        return false;
    }
    if ($.trim($('#fbannerimage').val()).length == "") {
        $('#Pfbannerimage').show();
        $('#Pfbannerimage').fadeOut(8000);
        $('#Pfbannerimage').html('Please Upload Banner Image');
        $('#fbannerimage').focus();
        $('#fbannerimage').val('');
        return false;
    }
    if($('#bannertitle,#fbannerimage_val').val().length > 0)
    {
        var d, n;
        d = new Date();
        n = d.getTime();
        var pdoc = {
            banner_id: $('#HospitalId').val() + '_' + n,
            type: "1",
            active: true,
            title: $('#bannertitle').val(),
            image: $('#hdnfilepath1').val() + $('#HospitalId').val() + '/Banner/' + $('#fbannerimage_val').val(),
            created_on: n,
            created_by: $('#HiddenDoctorID').val(),
        }
        var PRref = ref.child("banners/" + $('#HospitalId').val() + '_' + n);
        bannerRef.child($('#HospitalId').val() + '_' + n).set(pdoc);
        banner_list();
        $('#bannertitle,#fbannerimage_val').val('');
    }
});

function banner_list()
{
    $('#test_table_banner').empty();
    var tr = '', status = '';
    bannerRef.on("value", function (docs) {
        docs.forEach(function (doc) {
            debugger;
            var data = doc.val();
            var Cdate = "";
            //if (data.created_on==null || data.created_on=="")
            //{
            //    Cdate = "-";
            //}
            //else {
            //    Cdate = data.created_on
            //}
            var date = new Date(data.created_on);
            var currentDayOfMonth = date.getDate();
            var currentMonth = date.getMonth();
            var currentYear = date.getFullYear();
            date = currentDayOfMonth + '-' + (currentMonth + 1) + '-' + currentYear;

            if (date == "NaN-NaN-NaN") {
                date="";
            }
            if (data.active == true) {
                status = "Active";
                tr = tr + '<tr><td>' + data.title + '</td><td><a href=" ' + data.image + '" target="_blank">Preview</a></td><td>' + status + '</td><td>' + date + '</td><td><a class="delete btn btn-default btn-rounded btn-sm" href="javascript:void(0);" onclick=banner_del("' + data.banner_id + '")><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>';
            }
            else {
                status = "Non Active";
                tr = tr + '<tr><td>' + data.title + '</td><td><a href=" ' + data.image + '" target="_blank">Preview</a></td><td>' + status + '</td><td>' + date + '</td><td>-</td></tr>';
            }            
        })
        $('#test_table_banner').html(tr);
    })
}

function banner_del(id)
{
    var pdoc = 
        {
            active: false,
            banner_id: id
        }
    bannerRef.child(id).update(pdoc);
    banner_list();
}


//banner module ended
//start broadcast patients list
$('#selBroadcastSendPatientType').change(function(){

    $('#divPatientsList').hide();
    $('#TotalPatientsCount').html('');

    $('#divSelBMIType').hide();  

    if($('#selBroadcastSendPatientType').val()==null || $('#selBroadcastSendPatientType').val()=='' || $('#selBroadcastSendPatientType').val()==0){
        $('#PselType').show();
        $('#PselType').fadeOut(8000);
        $('#PselType').html('Please Select Type');
        $('#selBroadcastSendPatientType').focus();
        $('#selBroadcastSendPatientType').val('');
        return false;
    }

    if($('#selBroadcastSendPatientType').val() == 2){
        $('#divSelBMIType').show();
    }  
});



$('#btnProceed').click(function () {
    debugger;

    if ($('#SelBranch').val() == "" || $('#SelBranch').val() == null || $('SelBranch').val()==0) {
        $('#PSelBranch').show();
        $('#PSelBranch').fadeOut(8000);
        $('#PSelBranch').html('Select Branch Name');
        $('#SelBranch').focus();
        $('#SelBranch').val('');
        return false;
    }

    if ($('#communicationFrequency').val() == "" || $('#communicationFrequency').val() == null || $('communicationFrequency').val()==0) {
        $('#PcommunicationFrequency').show();
        $('#PcommunicationFrequency').fadeOut(8000);
        $('#PcommunicationFrequency').html('Select Frequency');
        $('#communicationFrequency').focus();
        $('#communicationFrequency').val('');
        return false;
    }

    if ($.trim($('#Sendradio').val()).length == "") {
        $('#PSendradio').show();
        $('#PSendradio').fadeOut(8000);
        $('#PSendradio').html('Please select the Sent Type');
        $('#Sendradio').focus();
        $('#Sendradio').val('');
        return false;
    }

    if(($('#Sendradio').val()==1 || $('#Sendradio').val()=="1")){   // mobile app push notification
        if ($.trim($('#msgtitle').val()).length == "") {
            $('#Pmsgtitle').show();
            $('#Pmsgtitle').fadeOut(8000);
            $('#Pmsgtitle').html('Please Enter Message Title');
            $('#msgtitle').focus();
            $('#msgtitle').val('');
            return false;
        }
        if ($.trim($('#msgtype').val()).length == "") {
            $('#Pmsgtype').show();
            $('#Pmsgtype').fadeOut(8000);
            $('#Pmsgtype').html('Please select the Message Type');
            $('#msgtype').focus();
            $('#msgtype').val('');
            return false;
        }
        if ($.trim($('#msgbody').val()).length == "") {
            $('#Pmsgbody').show();
            $('#Pmsgbody').fadeOut(8000);
            $('#Pmsgbody').html('Please Enter the Message Body');
            $('#msgbody').focus();
            $('#msgbody').val('');
            return false;
        }

        if (url != "") {
            var url = document.getElementById("msgurl").value;
            var regexp = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
            if (url != "") {
                if (!regexp.test(url)) {
                    toastr.warning("Please enter the Valid URL.");
                    return false;
                } else {
              
                }
            }
        }

        if ($.trim($('#enableChatBtn').val()).length == "") {
            $('#PenableChatBtn').show();
            $('#PenableChatBtn').fadeOut(8000);
            $('#PenableChatBtn').html('Please select the chat status');
            $('#enableChatBtn').focus();
            $('#enableChatBtn').val('');
            return false;
        }
    }
    else if(($('#Sendradio').val()==2 || $('#Sendradio').val()=="2") || ($('#Sendradio').val()==3 || $('#Sendradio').val()=="3")){   // sms 

        if ($.trim($('#selTemplate').val()).length == "") {
            $('#PselTemplate').show();
            $('#PselTemplate').fadeOut(8000);
            $('#PselTemplate').html('Please Select Template');
            $('#selTemplate').focus();
            $('#selTemplate').val('');
            return false;
        }
    }
    //else if(($('#Sendradio').val()==3 || $('#Sendradio').val()=="3")){   // whatsapp
       
    //    if ($.trim($('#msgtype').val()).length == "") {
    //        $('#Pmsgtype').show();
    //        $('#Pmsgtype').fadeOut(8000);
    //        $('#Pmsgtype').html('Please select the Message Type');
    //        $('#msgtype').focus();
    //        $('#msgtype').val('');
    //        return false;
    //    }
    //    if ($.trim($('#msgbody').val()).length == "") {
    //        $('#Pmsgbody').show();
    //        $('#Pmsgbody').fadeOut(8000);
    //        $('#Pmsgbody').html('Please Enter the Message Body');
    //        $('#msgbody').focus();
    //        $('#msgbody').val('');
    //        return false;
    //    }

    //    if (url != "") {
    //        var url = document.getElementById("msgurl").value;
    //        var regexp = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
    //        if (url != "") {
    //            if (!regexp.test(url)) {
    //                toastr.warning("Please enter the Valid URL.");
    //                return false;
    //            } else {
              
    //            }
    //        }
    //    }

    //    if ($.trim($('#enableChatBtn').val()).length == "") {
    //        $('#PenableChatBtn').show();
    //        $('#PenableChatBtn').fadeOut(8000);
    //        $('#PenableChatBtn').html('Please select the chat status');
    //        $('#enableChatBtn').focus();
    //        $('#enableChatBtn').val('');
    //        return false;
    //    }
    //}      

    if ($('#fromDate').val() == null || $('#fromDate').val() == '') {
        $('#PfromDate').show();
        $('#PfromDate').fadeOut(8000);
        $('#PfromDate').html('Please Select From Date');
        $('#fromDate').focus();
        $('#fromDate').val('');
        return false;
    }

    if ($('#toDate').val() == null || $('#toDate').val() == '') {
        $('#PtoDate').show();
        $('#PtoDate').fadeOut(8000);
        $('#PtoDate').html('Please Select To Date');
        $('#toDate').focus();
        $('#toDate').val('');
        return false;
    }

    if($('#selPatientType').val() == null || $('#selPatientType').val() == '' || $('#selPatientType').val() == 0){
        $('#PselPatientType').show();
        $('#PselPatientType').fadeOut(8000);
        $('#PselPatientType').html('Please Select Patient Type');
        $('#selPatientType').focus();
        $('#selPatientType').val('');
        return false;
    }
       

    if ($('#selBroadcastSendPatientType').val() == null || $('#selBroadcastSendPatientType').val() == '' || $('#selBroadcastSendPatientType').val() == 0) {
        $('#PselType').show();
        $('#PselType').fadeOut(8000);
        $('#PselType').html('Please Select Type');
        $('#selBroadcastSendPatientType').focus();
        $('#selBroadcastSendPatientType').val('');
        return false;
    }

    if ($('#selBroadcastSendPatientType').val() == 2) {
        if ($('#selBMIType').val() == null || $('#selBMIType').val() == '' || $('#selBMIType').val() == 0) {
            $('#PselBMIType').show();
            $('#PselBMIType').fadeOut(8000);
            $('#PselBMIType').html('Please Select BMI Type');
            $('#selBMIType').focus();
            $('#selBMIType').val('');
            return false;
        }
    }
              

    $('.load-position').show();
    if ($('#selBroadcastSendPatientType').val()==8 || $('#selBroadcastSendPatientType').val() == 2) {
        LoadPatientsList(1);
    }
    else {

        var dml_indicator; var condition;var visit_type='';

        dml_indicator = $('#selBroadcastSendPatientType').val() == 1 ? 'MC' : $('#selBroadcastSendPatientType').val() == 6 ? 'MD' : 'MP';

        visit_type = $('#selPatientType').val();

        var doctorData = {
            Dml_Indicator: dml_indicator,
            condition: condition,
            visit_type: visit_type
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Message/Broadcast_Patients_list',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(doctorData),
            success: function (data) {
                debugger;
                var data1 = JSON.parse(data);
                if(data1.msg=="Success"){
                    var data1=data1.data;
                    $('.load-position').hide();
                    if (jQuery.isEmptyObject((data1))) {
                        toastr.warning('No Details Found');
                    }
                    else {
                        if (data1.Table.length > 0) {
                            var tr = '';
                            var type_heading = '';
                            $('#master_Lists').empty();

                            $('#sendBulksms').modal('toggle');
                            var thead = '';
                            var tbodyStart = "<tbody>";
                            var tbodyEnd = "</tbody>";
                            var j = 0;
                            for (var i = 0; i < data1.Table.length; i++) {

                                if ($('#selBroadcastSendPatientType').val() == 1) {

                                    type_heading = 'Co morbid conditions List';
                                    thead = "<thead><tr><th>Co morbid conditions</th></tr></thead>";
                                    tr = tr + '<tr><td><div class="col-md-12" style="padding-left:0px!important;padding-right:0px!important;padding-top:10px;"><input type="checkbox" id="ComorbidCheck_' + (i + 1) + '" name="ComorbidCheck_' + (i + 1) + '" value="' + data1.Table[i].id + '">&nbsp;&nbsp;<label for="' + data1.Table[i].type + '"> ' + data1.Table[i].type + '</label></div></td></tr>';
                                }
                                else if ($('#selBroadcastSendPatientType').val() == 6) {

                                    type_heading = 'Diagnosis List';
                                    thead = "<thead><tr><th>Diagnosis</th></tr></thead>";
                                    tr = tr + '<tr><td><div class="col-md-12" style="padding-left:0px!important;padding-right:0px!important;padding-top:10px;"><input type="checkbox" id="DiagnosisCheck_' + (i + 1) + '" name="DiagnosisCheck_' + (i + 1) + '" value="' + data1.Table[i].diagnosis + '">&nbsp;&nbsp;<label for="' + data1.Table[i].diagnosis + '"> ' + data1.Table[i].diagnosis + '</label></div></td></tr>';
                                }
                                else if ($('#selBroadcastSendPatientType').val() == 7) {
                                    type_heading = 'Procedure List';
                                    thead = "<thead><tr><th>Procedure</th></tr></thead>";
                                    tr = tr + '<tr><td><div class="col-md-12" style="padding-left:0px!important;padding-right:0px!important;padding-top:10px;"><input type="checkbox" id="ProcedureCheck_' + (i + 1) + '" name="ProcedureCheck_' + (i + 1) + '" value="' + data1.Table[i].procedure_template + '">&nbsp;&nbsp;<label for="' + data1.Table[i].procedure_template + '"> ' + data1.Table[i].procedure_template + '</label></div></td></tr>';
                                }
                                j++;
                            }
                            $('#totalMasterListCount').val(j);
                            $('#TypeHeader').html(type_heading);
                            $('#master_Lists').empty();
                            $('#master_Lists').append(thead + tbodyStart + tr + tbodyEnd);

                            $("#master_Lists").dataTable().fnDestroy();
                            $('#master_Lists').DataTable({
                                "lengthChange": false,
                                "info": false,
                                "pageLength": 1000,
                                "bPaginate": false,
                                "ordering": false
                            });
                        }
                        else {
                            toastr.warning('No Details Found');
                        }
                    }
                }
                else{
                    console.log(data1);
                }
            }
        });
    }
});

$('#btnMasterSubmit').click(function () {
    debugger;
    LoadPatientsList(0);

});

var patientsListJson = '';
function LoadPatientsList(val) {
    debugger;
    var dml_indicator;
    var type_id = '';
    var type_name = '';
    var from_date = '';
    var to_date = '';var visit_type='';

    var totalMasterListCount = $('#totalMasterListCount').val();

    if ($('#selBroadcastSendPatientType').val() == 8)
    {
        dml_indicator = 'ALL';
    }
    if($('#selBroadcastSendPatientType').val() == 1){
        dml_indicator = ($('#selPatientType').val()==1) ? 'CS' : "CIS";
        for(var i = 0; i < totalMasterListCount; i++){
            if($('#ComorbidCheck_'+(i+1)).prop('checked')==true) {
                type_id= type_id + $('#ComorbidCheck_'+(i+1)).val() + ',';
            }
        }
        type_id= $.trim(type_id); 
        type_id = "1"
    }
    else if($('#selBroadcastSendPatientType').val() == 2){
        dml_indicator = ($('#selPatientType').val()==1) ? 'BS' : "BIS";
        type_id = $('#selBMIType').val();
    }        
    else if($('#selBroadcastSendPatientType').val() == 6){
        dml_indicator = ($('#selPatientType').val()==1) ? 'DS' : "DIS";
        for(var i = 0; i < totalMasterListCount; i++){
            if($('#DiagnosisCheck_'+(i+1)).prop('checked')==true) {
                type_name= type_name + $('#DiagnosisCheck_'+(i+1)).val() + ',';
            }
        }
        type_name= $.trim(type_name);
           
    }
    else if($('#selBroadcastSendPatientType').val() == 7){

        dml_indicator = ($('#selPatientType').val()==1) ? 'PS' : "PIS";
        for(var i = 0; i < totalMasterListCount; i++){
            if($('#ProcedureCheck_'+(i+1)).prop('checked')==true) {
                type_name= type_name + $('#ProcedureCheck_'+(i+1)).val() + ',';
            }
        }
        type_name= $.trim(type_name);
    } 

    var doctorData = {
        Dml_Indicator: dml_indicator,
        type_id: type_id,
        type_name: type_name,
        from_date: from_date,
        to_date: to_date,
        branch_id: $('#SelBranch').val(),
        visit_type: visit_type,
        //doctor_id : $('#SelDoctorMultiple').val().toString()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Message/Broadcast_Patients_list',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(doctorData),
        success: function (data) {
            var data1 = JSON.parse(data);
            if(data1.msg=="Success"){
                var data1=data1.data;
                $('.load-position').hide();
                if (val == 0) {
                    $('#sendBulksms').modal('toggle');
                }
                if (jQuery.isEmptyObject((data1))) {
                    $('#divPatientsList').hide();
                    $('#TotalPatientsCount').html('');
                }
                else {
                    patientsListJson = data1;
                    if (data1.Table.length > 0) {
                        var tr = '';
                        var totalcount = '';
                        $('#tbodyPatientsList').empty();


                        for (var i = 0; i < data1.Table.length; i++) {
                            tr = tr + '<tr><td class="msgSelCheckbox"><input type="checkbox" id="selectRowCheck" name="selectRowCheck" onchange=changeSelectAll();></td><td>' + (i + 1) + '</td><td>' + data1.Table[i].patient_id + '</td><td>' + data1.Table[i].first_name + '</td><td>' + data1.Table[i].age + '</td><td>' + data1.Table[i].phone_number + '</td><td style="display:none">' + data1.Table[i].patient_token + '</td></tr>';

                        }

                        $('#tbodyPatientsList').html(tr);
                    }
                    $("#tablePatientsList").DataTable();
                    if (data1.Table1.length > 0) {
                        var count = data1.Table1[0].total_count;
                        $('#divPatientsList').show();
                        $('#TotalPatientsCount').html(count + ' patients selected');
                        $('#checkSelectAll').prop("checked", true);
                        $('#checkSelectAll').change();
                    }
                    if(data1.Table1[0].total_count==0)
                    {
                        toastr.warning('No Details Found');
                    }
                }
            
            }
            else{
                console.log(data1);
            }
        }
    });
}

function changeSelectAll() {
    if ($('#checkSelectAll').prop('checked') == true) {
        $('#checkSelectAll').prop('checked', false);
    } else {
        $('#checkSelectAll').prop('checked', true);
    }
}

$('#checkSelectAll').change(function (e) {
    debugger;
    $('input[name=selectRowCheck]').prop('checked', $('#checkSelectAll').prop("checked"));

});
$('#addbroadcast').click(function () {
    debugger;
    Loadbroadcast();
});

//end broadcast patients list
$('#btnsubmit').click(function () {
    debugger;
    if ($.trim($('#broadcast_type').val()) == "") {
        $('#Pbroadcast_type').show();
        $('#Pbroadcast_type').fadeOut(8000);
        $('#Pbroadcast_type').html('Enter Broadcast');
        $('#broadcast_type').focus();
        return false;
    }
    var indicator_id = ''

    if ($('#btnsubmit').html() == 'Submit') {
        indicator_id = 'I'        
    }
    else {
        indicator_id = 'U'      
    }
    var broadcast = {
        Dml_Indicator: indicator_id,
        broadcast_id: $('#Htxtbroadcastid').val(),
        broadcast_type: $('#broadcast_type').val(),
        is_active:'1',
        created_by: $('#hiddenUser_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Message/Broadcast_type',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(broadcast),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    if (data1.Table[0].msg == 'already')
                    {
                        toastr.warning('Name Already Exists');                      
                    }
                   else if (data1.Table[0].msg == "Success")
                    {                                               
                            toastr.success("Successfully Added");                                                  
                    }
                    else if(data1.Table[0].msg == "Update")
                    {
                        toastr.success("Successfully Updated"); 
                        $('#btnsubmit').html('Submit');
                    }
                    else
                    {     
                        toastr.warning("Somthing Went Wrong");
                        return false;
                    }
                    
                }
            }
            else {
                console.log(data1);
            }
            $('#broadcast_type').val('');
            Loadbroadcast()
        }      
    });

});

function Loadbroadcast(){
    debugger;
    var broadcast = {
        Dml_Indicator: 'L'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Message/Broadcast_type',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(broadcast),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                debugger;
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    $('#broadcast_table_list tbody').empty();
                    $('#broadcast_table_list').dataTable().fnClearTable();
                    $('#broadcast_table_list').dataTable().fnDestroy();

                    var j = 0, b = '', tr = '', edit = '', del = '', other_info = '';

                    b = data1.Table;
                    $.each(b, function (i, emp) {
                        j++

                        edit = '<a data-toggle="tooltip" title="Edit" class="btn btn-edit btn-xs" data-id="SM_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="c_details_form"  href="javascript:void(0);" onclick=broadcastedit(this,"' + emp.broadcast_id + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        del = ' <a  data-toggle="tooltip" title="Delete"  id="broadcastdel_' + emp.broadcast_id + '" class="btn deleteicon-btn btn-xs"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form"  href="javascript:void(0);" onclick=broadcastdel(this,"' + emp.broadcast_id + '","D")><i class="fa fa-trash" aria-hidden="true"></i></a>';                       
                        other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + '</div></div>';
                       
                       
                        tr = tr + '<tr' + j + '"></td><td>' + j + '</td><td>' + emp.broadcast_type + '</td><td>' + other_info + '</td></tr>';

                    });
                    $('#broadcast_body').html(tr);
                    datatable('broadcast_table_list', 'broadcast_form', 'Legal');
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function broadcastedit(event, id){
    debugger;
    var broadcast = {
        Dml_Indicator: 'E',
        broadcast_id : id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Message/Broadcast_type',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(broadcast),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var emp = data1.data.Table;
            $("#broadcast_type").val(emp[0].broadcast_type);
            $("#Htxtbroadcastid").val(emp[0].broadcast_id);            
            $('#btnsubmit').html('Update');
        }
    })
}

function broadcastdel(event, Id, indicatorid) {
    debugger;

    var status = "";
    if (indicatorid == 'D') {
        status = "Are you sure, Do you want to Delete?";
    }
    toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", status,
     {
         closeButton: true,
         progressBar: true,
         allowHtml: true,
         timeOut: 20000000,

         onShown: function (toast) {
             $("#confirmationRevertYes").click(function () {
                 var Delete = {
                     Dml_Indicator: indicatorid,
                     broadcast_id: Id
                 }

                 $.ajax({
                     async: true,
                     type: 'POST',
                     url: '/Message/Broadcast_type',
                     contentType: 'application/json; charset=UTF-8',
                     data: JSON.stringify(Delete),
                     success: function (data) {
                         debugger;
                         var data1 = JSON.parse(data);
                         if (data1.msg == "Success") {
                             if (data1.data.Table[0].msg == 'Deleted') {
                                 toastr.success("Deleted Successfully");                                
                             }
                             else {
                                 toastr.warning("Somthing Went Wrong");
                                 return false;
                             }
                         }
                         else {
                             toastr.warning("Somthing Went Wrong");
                             return false;
                         }
                         Loadbroadcast()
                     }
                 });
             });
         }
     })
};

$('#addcredit').click(function () {
    debugger;
    broadcast_type()
    Loadcredit()
});

function broadcast_type(br_type){
    debugger;
    $('#txtbroadcasttype').empty();
    var subdepartment = {
        Dml_Indicator: "LB"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Message/Broadcast_type',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.broadcast_type + '">' + emp.broadcast_type + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#txtbroadcasttype').append(SubDepartment);
                        $('#txtbroadcasttype').change();
                    }
                    else {
                        $('#txtbroadcasttype').append(default_opt + SubDepartment);
                    }

                    if ($('#hiddenRole_id').val() != 2) {
                        $('#txtbroadcasttype').val($('#HospitalBranchID').val());
                        $('#txtbroadcasttype').attr('disabled', true);                      
                      
                    }
                    if (br_type != 0 && br_type != undefined) {
                        $('#txtbroadcasttype').val(br_type);

                    }
                    
                }
            }
            else {
                console.log(data1);
            }

        }
    });
}
$('#btnsubmitcredit').click(function () {
    debugger;
    if ($.trim($('#txtbroadcasttype').val()) == "") {
        $('#Ptxtbroadcasttype').show();
        $('#Ptxtbroadcasttype').fadeOut(8000);
        $('#Ptxtbroadcasttype').html('Enter Broadcast');
        $('#txtbroadcasttype').focus();
        return false;
    }
    if ($.trim($('#creditvalue').val()) == "") {
        $('#Pcreditvalue').show();
        $('#Pcreditvalue').fadeOut(8000);
        $('#Pcreditvalue').html('Enter Credit Value');
        $('#creditvalue').focus();
        return false;
    }
    if ($.trim($('#lowestcredit').val()) == "" || $('#creditvalue').val() < $('#lowestcredit').val()) {
        $('#Plowestcredit').show();
        $('#Plowestcredit').fadeOut(8000);
        $('#Plowestcredit').html('Enter Lowest Credit Value');
        $('#lowestcredit').focus();
        return false;
    }
    var indicator_id = ''

    if ($('#btnsubmitcredit').html() == 'Submit') {
        indicator_id = 'I'        
    }
    else {
        indicator_id = 'U'      
    }
    var broadcast = {
        Dml_Indicator: indicator_id,
        credit_id: $('#Htxtcreditid').val(),
        broadcast_type: $('#txtbroadcasttype').val(),
        credit_value: $('#creditvalue').val(),
        lowest_credit_value: $('#lowestcredit').val(),
        is_active:'1',
        created_by: $('#hiddenUser_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Message/Broadcast_credit',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(broadcast),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    if (data1.Table[0].msg == 'already')
                    {
                        toastr.warning('Name Already Exists');                      
                    }
                   else if (data1.Table[0].msg == "Success")
                    {                                               
                        toastr.success("Successfully Added");                                                  
                    }
                    else if(data1.Table[0].msg == "Update")
                    {
                        toastr.success("Successfully Updated"); 
                        $('#btnsubmitcredit').html('Submit');
                    }
                    else
                    {     
                        toastr.warning("Somthing Went Wrong");
                        return false;
                    }
                    
                }
            }
            else {
                console.log(data1);
            }
            $('#txtbroadcasttype').val(0);
            $('#creditvalue').val('');
            $('#lowestcredit').val('');     
            Loadcredit()
        }      
    });

});
function Loadcredit(){
    debugger;
    var broadcast = {
        Dml_Indicator: 'LC'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Message/Broadcast_credit',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(broadcast),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                debugger;
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    $('#credit_table_list tbody').empty();
                    $('#credit_table_list').dataTable().fnClearTable();
                    $('#credit_table_list').dataTable().fnDestroy();

                    var j = 0, b = '', tr = '', edit = '', del = '', other_info = '';

                    b = data1.Table;
                    $.each(b, function (i, emp) {
                        j++

                        edit = '<a data-toggle="tooltip" title="Edit" class="btn btn-edit btn-xs" data-id="SM_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="c_details_form"  href="javascript:void(0);" onclick=creditedit(this,"' + emp.credit_id + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        del = ' <a  data-toggle="tooltip" title="Delete"  id="creditdel_' + emp.credit_id + '" class="btn deleteicon-btn btn-xs"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form"  href="javascript:void(0);" onclick=creditdel(this,"' + emp.credit_id + '","D")><i class="fa fa-trash" aria-hidden="true"></i></a>';                       
                        other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + '</div></div>';
                       
                       
                        tr = tr + '<tr' + j + '"></td><td>' + j + '</td><td>' + emp.broadcast_type + '</td><td>' + emp.credit_value + '</td><td>' + emp.lowest_credit_value + '</td><td>' + other_info + '</td></tr>';

                    });
                    $('#credit_body').html(tr);
                    datatable('credit_table_list', 'credit_form', 'Legal');

                   
                }
            }
            else {
                console.log(data);
            }
        }
    });
}
function creditedit(event, id){
    debugger;
    var broadcast = {
        Dml_Indicator: 'EC',
        credit_id : id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Message/Broadcast_credit',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(broadcast),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var emp = data1.data.Table;
            broadcast_type(emp[0].broadcast_type)
            //$("#broadcast_type").val(emp[0].broadcast_type);
            $("#Htxtcreditid").val(emp[0].credit_id); 
            $("#creditvalue").val(emp[0].credit_value);
            $("#lowestcredit").val(emp[0].lowest_credit_value);
            $('#btnsubmitcredit').html('Update');
        }
    })
}

function creditdel(event, Id, indicatorid) {
    debugger;

    var status = "";
    if (indicatorid == 'D') {
        status = "Are you sure, Do you want to Delete?";
    }
    toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", status,
     {
         closeButton: true,
         progressBar: true,
         allowHtml: true,
         timeOut: 20000000,

         onShown: function (toast) {
             $("#confirmationRevertYes").click(function () {
                 var Delete = {
                     Dml_Indicator: indicatorid,
                     credit_id: Id
                 }

                 $.ajax({
                     async: true,
                     type: 'POST',
                     url: '/Message/Broadcast_credit',
                     contentType: 'application/json; charset=UTF-8',
                     data: JSON.stringify(Delete),
                     success: function (data) {
                         debugger;
                         var data1 = JSON.parse(data);
                         if (data1.msg == "Success") {
                             if (data1.data.Table[0].msg == 'Deleted') {
                                 toastr.success("Deleted Successfully");                                
                             }
                             else {
                                 toastr.warning("Somthing Went Wrong");
                                 return false;
                             }
                         }
                         else {
                             toastr.warning("Somthing Went Wrong");
                             return false;
                         }
                         Loadcredit()
                     }
                 });
             });
         }
     })
};



function LoadCreditType(){

    var broadcast = {
        Dml_Indicator: 'LC'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Message/Broadcast_credit',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(broadcast),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                debugger;
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    var  b = '';
                    b = data1.Table;                 

                    //added by nandhini for credit dropdown in buy credit pop up
                    if(b.length>0){
                        var credittype;
                        var default_opt = '<option value="0">--Select--</option>';
                        $.each(b, function (i, emp) {
                            credittype = credittype + '<option value="' + emp.credit_id + '">' + emp.broadcast_type + '</option>';
                        });

                        $('#selCreditType').append(credittype);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}



$('#communicationFrequency').change(function () {
    freq_change();
});

function freq_change() {
    freq_type = $('#communicationFrequency').val();
    $('#divcommunicationfreq_days,#divcommunicationfreq_date,#divcommunicationfreq_time').hide();
    if (freq_type == "1") $('#divcommunicationfreq_time').show();
    else if (freq_type == "2") $('#divcommunicationfreq_days,#divcommunicationfreq_time').show();
    else if (freq_type == "3") $('#divcommunicationfreq_date,#divcommunicationfreq_time').show();
    else if (freq_type == "4") $('#divcommunicationfreq_date,#divcommunicationfreq_time').show();
    else if (freq_type == "5") $('#divcommunicationfreq_date,#divcommunicationfreq_time').show();
}


//$('#SelBranch').change(function(){


//    var doctorData = {
//        Dml_Indicator: 'TL'        
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/Message/Broadcast_Patients_list',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(doctorData),
//        success: function (data) {
//            debugger;
//            $('#selTemplate').empty();
//            var data1 = JSON.parse(data);
//            if(data1.msg=="Success"){
//                var data1=data1.data;                
//                if (jQuery.isEmptyObject((data1))) {
//                    toastr.warning('No Details Found');
//                }
//                else {
//                    if (data1.Table.length > 0) {
//                        var SubDepartment;
//                        var default_opt = '<option value="0">--Choose Template--</option>';
//                        $.each(data1.Table, function (i, emp) {
//                            SubDepartment = SubDepartment + '<option value="' + emp.Id + '">' + emp.TemplateName + '</option>';
//                        });

//                        $('#selTemplate').append(SubDepartment);
//                    }
//                }
//            }
//        }
//    });


//});