//$(document).ready(function () {
   
//});

// Load branch
//function LoadBranch() {
//    $('#SelBranch').empty();
//    $('#tblCodeTemplates').empty();
//    var codeData = {
//        Dml_Indicator: "BL",
//        hospital_id: $('#SelectedHospitalID').val(),
//        branch_id: 0
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/Hospitalsetup/Code_Templates_Sel',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(codeData),
//        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, function (i, emp) {
//                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
//                    });
//                    if (data1.length == 1) {
//                        $('#SelBranch').append(SubDepartment);
//                        LoadCodeTemplatesList();
//                    }
//                    else {
//                        $('#SelBranch').append(default_opt + SubDepartment);
//                    }
//                    if ($('#hiddenRole_id').val() == 1) {
//                        $('#SelBranch').val($('#HospitalBranchID').val());
//                        $('#SelBranch').attr('disabled', true);
//                        LoadCodeTemplatesList();
//                    }                   
//                }
//            }
//            else {
//                console.log(data1);
//            }            
//        }
//    });
//}

function LoadBranch() {
    debugger;
    
    $('#SelBranch').empty();
    $('#tblCodeTemplates').empty();

    //Only KinderSurge
    //var dml = ''
    //if (parseInt($('#hiddenRole_id').val()) == 1) {
    //    dml = 'DLBRAN'
    //}
    //else {
    //    dml = 'LBRAN'
    //}



    var subdepartment = {
        Dml_Indicator: "LBRAN",
        //Dml_Indicator: dml,
        name: $('#HiddenDoctorID').val()
    }
    $.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) {
            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);
                        LoadCodeTemplatesList();
                    }
                    else {
                        $('#SelBranch').append(default_opt + SubDepartment);
                    }

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

        }
    });
}

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

    if ($('#SelBranch').val() == "" || $('#SelBranch').val() == null || $('#SelBranch').val() == 0) {
        $('#tblCodeTemplates').empty();
        return false;
    }
    LoadCodeTemplatesList();
});

function LoadCodeTemplatesList(event, hospital_id) {

    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");


    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {

         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {
                     return;
                 }
                 else {
                     $('#code_templates').modal()
    $('#SelectedHospitalID').val(hospital_id);
    var codeData = {
        Dml_Indicator: "HS",
        hospital_id: hospital_id
        //branch_id: $('#SelBranch').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Code_Templates_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(codeData),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            $('#tblCodeTemplates').empty();

            //$('#SelBranch').prop('disabled', true);
            $('#SelBranch').closest('.col-md-3').hide();

            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    if (data1.length > 0) {
                        var tr = "";
                        for (var i = 0; i < data1.length; i++) {
                            tr = tr + '<tr><td style="display:none" id="formid_' + (i + 1) + '">' + data1[i].form_id + '</td><td class="pt-20" id="formname_' + (i + 1) + '">' + data1[i].form_name + '</td><td><div class="form-group"><input type="text" class="form-control  prefixformid_' + data1[i].form_id + ' " id="prefix_' + (i + 1) + '" placeholder="Prefix" autocomplete="off" value="' + data1[i].prefix + '"><p id="Pprefix_' + data1[i].form_id + '" style="color:red"></p></div></td>'
                                + '<td><div class="form-group"><input type="text" class="form-control" id="suffix_' + (i + 1) + '" placeholder="Suffix" autocomplete="off" value="' + ((data1[i].suffix == null || data1[i].suffix=="") ? "" : data1[i].suffix) + '"></div></td>'
                                + '<td><div class="form-group"><input type="text" class="form-control" id="no_of_digits_' + (i + 1) + '" placeholder="No.of.digits" autocomplete="off" value="' + data1[i].no_of_digits + '" onkeyup=checkDigitsValue("' + (i + 1) + '")><p id="Pno_of_digits_' + (i + 1) + '" style="color:red"></p></div></td>'
                                + '<td><div class="form-group"><input type="number" maxlength="5" class="form-control" id="startvalue_' + (i + 1) + '" placeholder="Start Value" autocomplete="off" value="' + data1[i].start_value + '" onkeyup=checkStartValue("' + (i + 1) + '")><p id="Pstartvalue_' + (i + 1) + '" style="color:red"></p></div></td>'
                                + '<td class="codetemp-year"><input type="checkbox" id="ckhyearwise_' + (i + 1) + '" onchange=ChangeYearWise(' + (i + 1) + ');>'
                                + '<div class="form-group" id="divradio_' + (i + 1) + '" style="display:none;"><select class="form-control" id="year_type_' + (i + 1) + '"><option value="0">-Select-</option><option value="1">Date Month Year</option><option value="2">Month Year</option><option value="3">Year</option><option value="4">Financial Year</option></select><p id="Pyeartype_' + (i + 1) + '" style="color:red"></p><div>'
                                //+ '<div class="form-group cust_codetemplates_radio" id="divradio_' + (i + 1) + '" style="display:none;"><input type="radio" class="code-rdo" id="datemonthyear_' + (i + 1) + '" name="year_type_' + (i + 1) + '" value="1"><label for="datemonthyear_' + (i + 1) + '" class="mr-10"> DateMonthYear</label><input type="radio" class="code-rdo" id="monthyear_' + (i + 1) + '" name="year_type_' + (i + 1) + '" value="2"><label for="monthyear_' + (i + 1) + '" class="mr-10">MonthYear</label><input type="radio" class="code-rdo" id="year_' + (i + 1) + '" name="year_type_' + (i + 1) + '" value="3"><label for="year_' + (i + 1) + '" class="mr-10">Year</label><input type="radio" class="code-rdo" id="financialyear_' + (i + 1) + '" name="year_type_' + (i + 1) + '" value="4"><label for="financialyear_' + (i + 1) + '" class="mr-10">FinancialYear</label></div> '
                                + '</td>'
                                + '</tr>'
                        }

                        $('#tblCodeTemplates').append(tr);

                        //setting checkbox value
                        for (var j = 0; j < data1.length; j++) {
                            $("#ckhyearwise_" + (j + 1)).prop('checked', ((data1[j].is_year_wise == "1" || data1[j].is_year_wise == 1) ? true : false));

                            if (data1[j].is_year_wise == "1" || data1[j].is_year_wise == 1) {
                                $('#divradio_' + (j + 1)).show();
                                if (data1[j].year_type != "" && data1[j].year_type != null) {
                                    $('#year_type_' + (j + 1)).val(data1[j].year_type);
                                    //$('input[name="year_type_' + (j + 1) + '"][value="' + data1[j].year_type + '"]').attr('checked', true);
                                }
                            }
                            else {
                                $('#divradio_' + (j + 1)).hide();
                            }
                        }
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    })
                 }
             }
         }
     });
}


function ChangeYearWise(idVal) {
    if ($("#ckhyearwise_" + idVal).prop('checked') == 1) {
        $('#divradio_' + idVal).show();
        $('#Pyeartype_' + idVal).show();
        $('#Pyeartype_' + idVal).fadeOut(8000);
        $('#Pyeartype_' + idVal).html('Please select any one format');
    }
    else {
        $('#divradio_' + idVal).hide();
        $('#Pyeartype_' + idVal).hide();
        //$('input[name="year_type_' + idVal + '"]').attr('checked', false);
    }
}

function checkDigitsValue(incVal) {
    var value = $("#no_of_digits_" + incVal).val();
    var preg_check = /[^0-9]/ig;
    if (value <= 0 || value > 6 || preg_check.test(value)) {
        $('#Pno_of_digits_' + incVal).show();
        $('#Pno_of_digits_' + incVal).fadeOut(8000);
        $('#Pno_of_digits_' + incVal).html('Invalid Digits. Digits must be less than or equal to 6');
        $('#no_of_digits_' + incVal).val('');
        $('#no_of_digits_' + incVal).focus();
        return false;
    }
}

function checkStartValue(incVal) {
    var noofdigits = $("#no_of_digits_" + incVal).val();
    var value = $("#startvalue_" + incVal).val();    
    if (value.length>noofdigits) {
        $('#Pstartvalue_' + incVal).show();
        $('#Pstartvalue_' + incVal).fadeOut(8000);
        $('#Pstartvalue_' + incVal).html('Invalid Start Value');
        $('#startvalue_' + incVal).val('');
        $('#startvalue_' + incVal).focus();
        return false;
    }
}

$('#btnSaveCodeTemplate').click(function () {

    var selectedHospitalID = $('#SelectedHospitalID').val();

    if ($("#tblCodeTemplates tr").length <= 0) {
        toastr.warning("There is no records available");
        return false;
    }
        
    debugger;
    if ($("#tblCodeTemplates tr").length > 0) {
        var totalRowsCount = $("#tblCodeTemplates tr").length;

        debugger;
        for (var i = 0; i < totalRowsCount; i++) {
            if ($("#ckhyearwise_" + (i + 1)).prop('checked') == 1 && $('#year_type_' + (i + 1)).val()<=0) {
                $('#Pyeartype_' + (i + 1)).show();
                $('#Pyeartype_' + (i + 1)).fadeOut(8000);
                $('#Pyeartype_' + (i + 1)).get(0).scrollIntoView();
                $('#Pyeartype_' + (i + 1)).focus();
                $('#Pyeartype_' + (i + 1)).html('Please select any one format');
                return false;
            }
        }
    }

    // Check patient id prefix already exists or not
    var patientform_id = "", patientPrefix = "";
    if ($("#tblCodeTemplates tr").length > 0) {
        var totalRowsCount = $("#tblCodeTemplates tr").length;

        for (var i = 0; i < totalRowsCount; i++) {
            if ($("#formid_" + (i + 1)).html() == "31") {
                patientform_id = $("#formid_" + (i + 1)).html();
                
                patientPrefix = $("#prefix_" + (i + 1)).val();
            }
        }
    }
    debugger;
    if (patientform_id != null && patientform_id != "") {
        var codeData = {
            Dml_Indicator: "SC",
            hospital_id: $('#SelectedHospitalID').val(),
            branch_id: $('#SelBranch').val(),
            form_id: patientform_id,
            prefix: patientPrefix
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Hospitalsetup/Code_Templates_Sel',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(codeData),
            success: function (data) {
                debugger;
                var data1 = JSON.parse(data);               
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    console.log(data1);
                    if (data1[0].totalcount > 0) {
                        $('#Pprefix_31').show();                        
                        $('#Pprefix_31').html('This patient id prefix already exists. Try another prefix.');
                        $(".prefixformid_31").get(0).scrollIntoView();
                        $(".prefixformid_31").focus();
                        $('#Pprefix_31').fadeOut(8000);
                        return false;
                    }
                    else {
                        //check user id prefix already exists or not

                        if ($("#tblCodeTemplates tr").length > 0) {
                            var totalRowsCount = $("#tblCodeTemplates tr").length;

                            for (var i = 0; i < totalRowsCount; i++) {
                                if ($("#formid_" + (i + 1)).html() == "121") {
                                    patientform_id = $("#formid_" + (i + 1)).html();
                                    patientPrefix = $("#prefix_" + (i + 1)).val();
                                }
                            }
                        }
                        if (patientform_id != null && patientform_id != "") {
                            var codeData = {
                                Dml_Indicator: "SC",
                                hospital_id: $('#SelectedHospitalID').val(),
                                branch_id: $('#SelBranch').val(),
                                form_id: patientform_id,
                                prefix: patientPrefix
                            }
                            $.ajax({
                                async: true,
                                type: 'POST',
                                url: '/Hospitalsetup/Code_Templates_Sel',
                                contentType: 'application/json; charset=UTF-8',
                                data: JSON.stringify(codeData),
                                success: function (data) {
                                    var data1 = JSON.parse(data);
                                    if (data1.msg == "Success") {
                                        var data1 = data1.data;
                                        console.log(data1);
                                        if (data1[0].totalcount > 0) {
                                            $('#Pprefix_121').show();
                                            $('#Pprefix_121').html('This user id prefix already exists. Try another prefix.');
                                            $(".prefixformid_121").get(0).scrollIntoView();
                                            $(".prefixformid_121").focus();
                                            $('#Pprefix_121').fadeOut(8000);
                                            return false;
                                        }
                                        else {
                                            SaveCodeTemplates();
                                        }
                                    }
                                    else {
                                        console.log(data1);
                                    }
                                }
                            });
                        }
                        else {
                            SaveCodeTemplates();
                        }
                        
                    }
                }
                else {
                    console.log(data1);
                }
            }
        });
    }
    else {
        SaveCodeTemplates();
    }
     

});


function SaveCodeTemplates() {
    var templatesArray = new Array();
    if ($("#tblCodeTemplates tr").length > 0) {
        var totalRowsCount = $("#tblCodeTemplates tr").length;

        for (var i = 0; i < totalRowsCount; i++) {
            var template = {};

            template.hospital_id = $('#SelectedHospitalID').val();
            //template.branch_id = $('#SelBranch').val(),
            template.branch_id = ($('#SelBranch').val() !== null) ? $('#SelBranch').val() : 0;
            template.Dml_Indicator = 'I',
             template.form_id = $("#formid_" + (i + 1)).html(),
             template.type_name = $("#formname_" + (i + 1)).html(),
             template.prefix = $("#prefix_" + (i + 1)).val(),
             template.suffix = $("#suffix_" + (i + 1)).val(),
            template.no_of_digits = $("#no_of_digits_" + (i + 1)).val(),
            template.start_value = $("#startvalue_" + (i + 1)).val(),
            template.is_year_wise = ($("#ckhyearwise_" + (i + 1)).prop('checked')) ? 1 : 0,
            //template.year_type = $('input[name="year_type_'+ (i + 1)+'"]:checked').val(),
            template.year_type = $('#year_type_' + (i + 1)).val(),

            templatesArray.push(template);
        }
    }

    console.log(templatesArray);

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Code_Templates_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(templatesArray),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                toastr.success('Saved Successfully');
            }
            else {
                console.log(data1);
            }
        }
    });
}



