// Fluids JS //

$(document).ready(function () {
    ShowFluids();
    $('#txtLogdate').datepicker({
        autoclose: true,
        todayHighlight: true,
        format: "dd/mm/yyyy"
        //endDate: new Date()
    });

    $('#txtLogtime').timepicker({
        showInputs: false
    });

    $('#txtLogdate_input').datepicker({
        autoclose: true,
        todayHighlight: true,
        format: "dd/mm/yyyy"
        //endDate: new Date()
    });

    $('#txtLogtime_input').timepicker({
        showInputs: false
    });
});




function ShowFluids() {
    var Fluidsdata = {

        Dml_Indicator: "S",
        ip_visit_report_id: $("#IPVisitReport_Id").val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: 'Fluids_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Fluidsdata),
        success: function (data) {
            debugger;
            $('#overall_input').val('')
            $('#overall_output').val('')
            $('#overall_fluids').val('')
            if (jQuery.isEmptyObject((data))) {

                tr = $('<table id="example1" class="table table-responsive table-bordered table-striped dataTable tablecolumnsticky" />');

                tr.append("<thead><tr><th>Fluids Name</th><th>IV Fluids</th><th>Blood Products</th><th>Oral</th><th>TPN / FJ</th><th>Input Total</th><th>Input Date</th><th>Notes</th><th>Urine</th><th>Drain</th><th>Vomit</th><th>RTA</th><th>Output Total</th><th>Fluid Balance</th><th>Output Date</th><th>Created By</th><th>Actions</th></tr></thead><tbody>");
                $('#tblFluids').html(tr);
            }
            else
            {
                var data2 = JSON.parse(data);
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    $('#overall_input').val(data1[0].Input_total)
                    $('#overall_output').val(data1[0].Output_total)
                    $('#overall_fluids').val(data1[0].fluid_balance)

                    tr = $('<table id="example1" class="table table-responsive table-bordered table-striped dataTable tablecolumnsticky" />');

                    tr.append("<thead><tr><th>Fluids Name</th><th>IV Fluids</th><th>Blood Products</th><th>Oral</th><th>TPN / FJ</th><th>Input Total</th><th>Input Date</th><th>Notes</th><th>Urine</th><th>Drain</th><th>Wammit</th><th>RTA</th><th>Output Total</th><th>Fluid Balance</th><th>Output Date</th><th>Created By</th><th>Actions</th></tr></thead><tbody>");

                    $.each(data1, function (i, emp) {


                        view = "<a href=# title='Edit' class='edit_icon'onclick=loadFluids('" + emp.IP_visit_number + "');><i class='fa fa-pencil'></i></a>";
                        Del = "<a href=# title='Delete' class='delete_icon' onclick=DeledeFluids('" + emp.IP_visit_number + "');><i class='fa fa-trash-o'></i></a>";
                        other_info = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu info-dropdown-new"><div class="disp_if mb-10"><li>' + view + '</li><li>' + Del + '</li></div></ul></div>';

                        row_data = "<tr><td>" + emp.fluid_name + " </td><td>" + emp.IP_IVFluids + " </td><td> " + emp.IP_BloodProducts + "</td><td> " + emp.IP_Oral + "</td><td>" + emp.IP_TPN_FJ + "</td><td>" + emp.IP_InputTotal + "</td><td>" + emp.ipfluids_datetime_input + "</td><td>" + emp.notes + " </td><td>" + emp.IP_Urine + "</td><td>" + emp.IP_Drain + "</td><td>" + emp.IP_Wammit + "</td><td>" + emp.IP_RTA + "</td><td>" + emp.IP_OutputTotal + "</td><td>" + emp.IP_FluidBalance + "</td><td>" + emp.ipfluids_datetime + "</td><td>" + emp.CreatedBy + "</td><td>" + other_info + "</td></tr>";
                        tr.append(row_data);
                    });
                    tr.append("</tbody></table>");
                    $('#tblFluids').html(tr);
                }
                else {
                    console.log(data);
                }
            }
           
        },
        error: function (data) {
            toastr.warning('some issue');
        }
    });
}

$('#btnFluidsAdd').click(function () {
    debugger;
    if ($("#IPDischarge_Id").val() != "2") {


        if ($.trim($("#txtFluidBalance").val()) == "") {

            toastr.warning('Enter IV Fluids Values...',
                 {
                  //closeButton: false,
                   progressBar: true,
                   allowHtml: true,
                   timeOut: 0,
                });
            return false;
        }

        //if ($.trim($("#txtLogdate_input").val()) == "") {
        //    $('#PtxtLogdate_input').show();
        //    $('#PtxtLogdate_input').fadeOut(8000);
        //    $('#PtxtLogdate_input').html('Select Input Date');
        //    $('#txtLogdate_input').val('');
        //    $('#txtLogdate_input').focus();
        //    return false;
        //}

        //if ($.trim($("#txtLogdate").val()) == "") {
        //    $('#PtxtLogdate').show();
        //    $('#PtxtLogdate').fadeOut(8000);
        //    $('#PtxtLogdate').html('Select Output Date');
        //    $('#txtLogdate').val('');
        //    $('#txtLogdate').focus();
        //    return false;
        //}

        var LDT = $('#txtLogdate').val();
        if (LDT == '') {
            LDT = '';
        }
        else {
            var a = LDT.split('/');
            LDT = a[2] + '-' + a[1] + '-' + a[0];
        }

        var time = $("#txtLogtime").val();
        var hours = Number(time.match(/^(\d+)/)[1]);
        var minutes = Number(time.match(/:(\d+)/)[1]);
        var AMPM = time.match(/\s(.*)$/)[1];
        if (AMPM == "PM" && hours < 12) hours = hours + 12;
        if (AMPM == "AM" && hours == 12) hours = hours - 12;
        var sHours = hours.toString();
        var sMinutes = minutes.toString();
        if (hours < 10) sHours = "0" + sHours;
        if (minutes < 10) sMinutes = "0" + sMinutes;
        var LTM = sHours + ":" + sMinutes;
      
        if (LDT == "") {
            var ipfluids_datetime = ""
        }
        else {
            var ipfluids_datetime =  LDT + " " + LTM;
        }
        

        var LDTI = $('#txtLogdate_input').val();
        if (LDTI == '') {
            LDTI = '';
        }
        else {
            var ai = LDTI.split('/');
            LDTI = ai[2] + '-' + ai[1] + '-' + ai[0];
        }

        var timeinput = $("#txtLogtime_input").val();
        var hoursinput = Number(timeinput.match(/^(\d+)/)[1]);
        var minutesinput = Number(timeinput.match(/:(\d+)/)[1]);
        var AMPMI = timeinput.match(/\s(.*)$/)[1];
        if (AMPMI == "PM" && hoursinput < 12) hoursinput = hoursinput + 12;
        if (AMPMI == "AM" && hoursinput == 12) hoursinput = hoursinput - 12;
        var sHoursinput = hoursinput.toString();
        var sMinutesinput = minutesinput.toString();
        if (hoursinput < 10) sHoursinput = "0" + sHoursinput;
        if (minutesinput < 10) sMinutesinput = "0" + sMinutesinput;
        var LTMI = sHoursinput + ":" + sMinutesinput;


        if (LDTI == "") {
            var ipfluids_datetime_input = ""
        }
        else {
            var ipfluids_datetime_input =  LDTI + " " + LTMI;
        }


        var Fluidsdata = {
            IP_visit_number: $('#HFluids').val(),
            IP_IVFluids: $('#txtIVFluids').val(),
            IP_BloodProducts: $('#txtBloodProducts').val(),
            IP_Oral: $('#txtOral').val(),
            IP_TPN_FJ: $('#txtTPN').val(),
            IP_InputTotal: $('#txtInputTotal').val(),
            IP_Urine: $('#txtUrine').val(),
            IP_Drain: $('#txtDrain').val(),
            IP_Wammit: $('#txtWammit').val(),
            IP_RTA: $('#txtRTA').val(),
            IP_OutputTotal: $('#txtOutputTotal').val(),
            IP_FluidBalance: $('#txtFluidBalance').val(),
            Dml_Indicator: "I",
            ipfluids_datetime: ipfluids_datetime,
            ipfluids_datetime_input: ipfluids_datetime_input,
            ip_visit_report_id: $("#IPVisitReport_Id").val(),
            fluid_name: $("#fluids_name").val(),
            notes: $("#notes").val()
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: 'Fluids_Ins_Upd_sel',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Fluidsdata),
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data);
                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    if ($('#HFluids').val()=="") {
                        toastr.success('IV Fluids Inserted Successfully.');
                    }
                    else
                    {
                        toastr.success('IV Fluids Updated Successfully.');
                    }

                    clearFluids();
                    ShowFluids();
                }
                else {
                    console.log(data);
                }
            },
            error: function (data) {
            }
        });

    }

});

function clearFluids() {

    $('#HFluids').val(""),
    $('#txtIVFluids').val(""),
    $('#txtBloodProducts').val(""),
    $('#txtOral').val(""),
    $('#txtTPN').val(""),
    $('#txtInputTotal').val(""),
    $('#txtUrine').val(""),
    $('#txtDrain').val(""),
    $('#txtWammit').val(""),
    $('#txtRTA').val(""),
    $('#txtOutputTotal').val(""),
    $('#txtFluidBalance').val("")
}

function loadFluids(val) {

    if ($("#IPDischarge_Id").val() != "2")
    {
        var Vitalsdata = {
            IP_visit_number: val,
            Dml_Indicator: "ID"
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: 'Fluids_Ins_Upd_sel',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Vitalsdata),
            success: function (data) {
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {
                }
                else {

                    if (data2.msg == "Success") {
                        var data1 = data2.data;

                        $.each(data1, function (i, emp) {

                            $('#HFluids').val(emp.IP_visit_number),
                            $('#txtIVFluids').val(emp.IP_IVFluids),
                            $('#txtBloodProducts').val(emp.IP_BloodProducts),
                            $('#txtOral').val(emp.IP_Oral),
                            $('#txtTPN').val(emp.IP_TPN_FJ),
                            $('#txtInputTotal').val(emp.IP_InputTotal),
                            $('#txtUrine').val(emp.IP_Urine),
                            $('#txtDrain').val(emp.IP_Drain),
                            $('#txtWammit').val(emp.IP_Wammit),
                            $('#txtRTA').val(emp.IP_RTA),
                            $('#txtOutputTotal').val(emp.IP_OutputTotal),
                            $('#txtFluidBalance').val(emp.IP_FluidBalance),
                            $("#txtLogdate").val(emp.Fluid_date),
                            $("#txtLogtime").val(emp.Fluid_time),
                            $("#txtLogdate_input").val(emp.Fluid_date_input),
                          $("#txtLogtime_input").val(emp.Fluid_time_input),
                             $("#fluids_name").val(emp.fluid_name),
                             $("#notes").val(emp.notes)
                        });
                    }
                    else {
                        console.log(data);
                    }

                   
                }
            }
        });
    }
    
}

function DeledeFluids(val) {
    if ($("#IPDischarge_Id").val() != "2")
    {

        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>", 'Are You sure You want delete IV Fluids..?',
      {
          closeButton: true,
          progressBar: true,
          allowHtml: true,
          timeOut: 0,

          onShown: function (toast) {
              $("#confirmationRevertYes").click(function () {

                  var Fluidsdata = {
                      IP_visit_number: val,
                      Dml_Indicator: "DEL"
                  }

                  $.ajax({
                      async: true,
                      type: 'POST',
                      url: 'Fluids_Ins_Upd_sel',
                      contentType: 'application/json; charset=UTF-8',
                      data: JSON.stringify(Fluidsdata),
                      success: function (data) {

                          toastr.success('IV Fluids Deleted Successfully...',
                                       {
                                           //closeButton: false,
                                           progressBar: true,
                                           allowHtml: true,
                                           timeOut: 0,
                                       });
                          ShowFluids();
                      }
                  });
              });
          }
      });
    }
    
}


$(document).on('input', '#Total', function () {

    var Cal_InTotal = 0;
    var Cal_OutTotal = 0;

    $("#Total .InTotal").each(function () {
        var Get_Invalue = $(this).val();
        if ($.isNumeric(Get_Invalue)) {
            Cal_InTotal += parseFloat(Get_Invalue);
        }


        $('#txtInputTotal').val(Cal_InTotal);
    });

    $("#Total .OutTotal").each(function () {
        var Get_Outvalue = $(this).val();
        if ($.isNumeric(Get_Outvalue)) {
            Cal_OutTotal += parseFloat(Get_Outvalue);
        }


        $('#txtOutputTotal').val(Cal_OutTotal);
    });

    var FBalance = ($('#txtInputTotal').val() - $('#txtOutputTotal').val());

    $('#txtFluidBalance').val(FBalance);

});