var ant_gyna = function () {

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

    var drugArray = Array();

    var instructionArray = Array();

    var forAll = function () {

        $('.dataTable').dataTable();

        $('body').on('change', '.updateElementSelect', function () {
            var id = $(this).attr("data-id");
            var colName = $(this).attr("data-colName");
            var tableName = $(this).attr("data-tableName");
            var value = $(this).val();
            var controllName = $('#controllName').val();
            var patientId = $('#patientId').val();
            var isSelect2 = $(this).attr("data-select2");
            if (isSelect2 == "yes") {
                var selectClass;
                if ($(this).attr('data-selectClass')) {
                    selectClass = $(this).attr('data-selectClass');
                } else {
                    selectClass = $("#dataClass").val();
                }
            }
            if (controllName == 111) {
                controllName = 'gyna';
            }
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=update', {
                id: id,
                value: value,
                tableName: tableName,
                colName: colName,
                patientId: patientId
            }, function (res) {
                if (isSelect2 == "yes" || id == "operationInstructions") {
                    // see how to change the value of updated option in the select
                    $('.' + selectClass).each(function () {
                        $(this).children('option[value = ' + id + ']').text(value);
                        if ($(this).val() == id) {
                            $(this).select2("val", id);
                        } else if ($(this).val() == -2) {
                            $(this).select2("val", '');
                        }
                    });
                }
                if (tableName == "diagnosis" || tableName == "diagnosisant" || tableName == "complaint" || tableName == "complaintant" || id == "operationInstructions") {
                    $('select').select2();
                }
            });
        });

        $('body').on('change', '.updatemyElement', function () {

            var id = $(this).attr("data-id");
            var paeid = $(this).attr("data-pid");
            var colName = $(this).attr("data-colName");
            var tableName = $(this).attr("data-tableName");
            var value = $(this).val();
            var controllName = $('#controllName').val();
            var patientId = $('#patientId').val();
            var vdateFlag = $(this).hasClass('calcWeeksF');
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=update', {
                pareid: paeid,
                id: id,
                value: value,
                tableName: tableName,
                colName: colName,
                patientId: patientId
            }, function (res) {
            });
        });

        $('body').on('change', '.updateElement', function () {

            var id = $(this).attr("data-id");
            var paeid = $(this).attr("data-pid");
            var colName = $(this).attr("data-colName");
            var tableName = $(this).attr("data-tableName");
            var value = $(this).val();
            var controllName = $('#controllName').val();
            var patientId = $('#patientId').val();
            var vdateFlag = $(this).hasClass('calcWeeksF');
            console.log('test');
            var dated;
            if ($(this).hasClass("datepicker")) {
                dated = 1;
            } else {
                dated = 0;
            }

            $.post(hosturl + '/controllers/' + controllName + '.php?ac=update', {
                pareid: paeid,
                id: id,
                value: value,
                tableName: tableName,
                colName: colName,
                patientId: patientId,
                dated: dated
            }, function (res) {
                console.log(res);
                if (controllName == 'followup' && colName == 'lmp') {
                    res = res.split(",");
                    $('#eed').val(res[0]);
                    $('#ivf').val(res[1]);
                    var tempvalue = value.split('-');
                    value = tempvalue[2] + '-' + tempvalue[1] + '-' + tempvalue[0];
                    var firstDate = new Date(value);
                    $('.calcWeeksF').each(function () {
                        var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds

                        var thisval = $(this).val();
                        var tempthisval = thisval.split('-');
                        thisval = tempthisval[2] + '-' + tempthisval[1] + '-' + tempthisval[0];
                        var secondDate = new Date(thisval);
                        var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
                        var diffInWeeks = Math.round(Math.abs(diffDays / 7));
                        $('#ga' + $(this).attr('data-id')).text(diffInWeeks);
                        if (secondDate < firstDate) {
                            $('#ga' + $(this).attr('data-id')).css('color', 'red');
                        } else {
                            $('#ga' + $(this).attr('data-id')).css('color', 'maroon');
                        }

                    });
                } else if (controllName == 'followup' && vdateFlag == true) {
                    var lmp = $('#lmp').val();
                    var tempvalue = lmp.split('-');
                    lmp = tempvalue[2] + '-' + tempvalue[1] + '-' + tempvalue[0];
                    var firstDate = new Date(lmp); // date of lmp

                    $('.calcWeeksF').each(function () {
                        var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds

                        var thisval = $(this).val();
                        var tempthisval = thisval.split('-');
                        thisval = tempthisval[2] + '-' + tempthisval[1] + '-' + tempthisval[0];
                        var secondDate = new Date(thisval);
                        var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
                        var diffInWeeks = Math.round(Math.abs(diffDays / 7));
                        $('#ga' + $(this).attr('data-id')).text(diffInWeeks);
                        if (secondDate < firstDate) {
                            $('#ga' + $(this).attr('data-id')).css('color', 'red');
                        } else {
                            $('#ga' + $(this).attr('data-id')).css('color', 'maroon');
                        }

                    });
                }


            });
        });

        jQuery.fn.forcepositiveNum = function () {

            return this.each(function () {
                $(this).keydown(function (e) {
                    var key = e.which || e.keyCode;
                    //alert(key);
                    if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
                            // numbers
                            key >= 48 && key <= 57 ||
                            // Numeric keypad
                            key >= 96 && key <= 105 ||
                            // comma, period and minus, . on keypad
                            //key == 190 || key == 188 || key == 109 || key == 110 ||
                            // Backspace and Tab and Enter
                            key == 8 || key == 9 || key == 13 ||
                            // Home and End
                            key == 35 || key == 36 ||
                            // left and right arrows
                            key == 37 || key == 39 ||
                            // Del and Ins
                            key == 46 || key == 45)
                        return true;
                    return false;
                });
            });
        }

        jQuery.fn.forcepositivefloat = function () {

            return this.each(function () {
                $(this).keydown(function (e) {
                    var key = e.which || e.keyCode;
                    //alert(key);
                    if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
                            // numbers
                            key >= 48 && key <= 57 ||
                            // Numeric keypad
                            key >= 96 && key <= 105 ||
                            // comma, period and minus, . on keypad
                            //key == 190 || key == 188 || key == 109 || key == 110 ||
                            // Backspace and Tab and Enter
                            key == 8 || key == 9 || key == 13 ||
                            // Home and End
                            key == 35 || key == 36 ||
                            // left and right arrows
                            key == 37 || key == 39 ||
                            //dot or point  .  on keyboard  for one time
                                    ((key == 110 || key == 190) && $(this).val().indexOf(".") < 0) ||
                                    // Del and Ins
                                    key == 46 || key == 45)
                        return true;
                    return false;
                });
            });
        }

        $(document).ready(function (e) {
            $(".positiveNo").forcepositiveNum();
            $(".positivefloat").forcepositivefloat();
            $("#patientvisitid").select2({
                minimumInputLength: 3
            });
        });

        $('body').on('click', '.delNew', function () {
            var itemid = $(this).attr('data-id');
            var urlgo = $(this).attr('data-link');
            var fngo = $(this).attr('data-fn');
            var tableName = $(this).attr('data-tableName');
            var dataFor = $(this).attr('data-for');
            var date = $(this).attr('data-date');
            var patientId = $('#patientId').val();
            var tr = $(this).parent().parent();
            bootbox.dialog({
                message: "Do you want to delete this item?",
                title: "Delete confirmation",
                buttons: {
                    danger: {
                        label: "Cancel",
                        className: "btn-primary"
                    },
                    main: {
                        label: "Delete",
                        className: "btn-danger",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/' + urlgo + '.php?ac=' + fngo, {
                                invId: itemid,
                                tableName: tableName,
                                dataFor: dataFor,
                                date: date,
                                patientId: patientId
                            }, function (res) {
                                if (res == 1) {
                                    tr.remove();
                                    var check_heigt_and_make_new_class = $(".check_heigt_and_make_new_class").height();
                                    if (check_heigt_and_make_new_class < 400) {
                                        $(".check_heigt_and_make_new_class").removeClass("overflow_scroll");
                                    }
                                } else {

                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
    };

    var patientDrug = function () {
        $('.all').on('click', '#addDrug', function () {
            if ($('#drugItr').val() == 0) {
                $("#addNewDrugRow").trigger('click');
            }

            // $("#addPatientDrugs").modal('show');
            $('#addPatientDrugs').modal({keyboard: true});
        });
        $('body').on('click', '#addNewDrugRow', function () {
            var itr = $('#drugItr').val();
            var presDate = $('#presDate').val();
            var patientId = $('#patientId').val();
            var newItr = Number(itr) + 1;
            var preFor = 0;
            var tableName = $(this).attr("data-tableName");
            var mainAntenatalId = $('#mainAntenatalId').val();
            var followid = $('#followId').val();
            $('#drugItr').val(newItr);
            if ($('#forHusband').is(':checked')) {
                preFor = 1;
            } else {
                preFor = 0;
            }

            
            $.post(hosturl + '/controllers/gyna.php?ac=drawRow', {
                type: "drug",
                itr: newItr,
                preFor: preFor,
                patientId: patientId,
                presDate: presDate,
                tableName: tableName,
                mainAntenatalId: mainAntenatalId,
                followid: followid
            }, function (res) {
                $('#drugContent').append(res);
            });
        });
        $('body').on('change', '#forHusband', function () {

            var preDate = $('#presDate').val();
            var patientId = $('#patientId').val();
            var mainAntenatalId = $('#mainAntenatalId').val();
            var followid = $('#followId').val();
            var preFor = 0;
            if ($(this).is(':checked')) {
                preFor = 1;
            } else {
                preFor = 0;
            }

            var controller = $(this).attr('data-controller');
            $.post(hosturl + '/controllers/' + controller + '.php?ac=showprescription', {
                preFor: preFor,
                patientId: patientId,
                preDate: preDate,
                type: "edit",
                mainAntenatalId: mainAntenatalId,
                followid: followid
            }, function (res) {
                $("#drugContent").html("");
                $("#drugContent").html(res);
            });
        });
        $('body').on('change', '#presDate', function () {
            var preDate = $(this).val();
            var patientId = $('#patientId').val();
            var mainAntenatalId = $('#mainAntenatalId').val();
            var followid = $('#followId').val();
            var preFor = 0;
            if ($('#forHusband').is(':checked')) {
                preFor = 1;
            } else {
                preFor = 0;
            }

            var controller = $(this).attr('data-controller');
            $.post(hosturl + '/controllers/' + controller + '.php?ac=showprescription', {
                preFor: preFor,
                patientId: patientId,
                preDate: preDate,
                type: "edit",
                mainAntenatalId: mainAntenatalId,
                followid: followid
            }, function (res) {
                $("#drugContent").html("");
                $("#drugContent").html(res);
            });
        });
        $('body').on('click', '.printPre', function () {
            var controller = $(this).attr('data-controller');
            var type = $(this).attr('data-type');
            var patientId = $('#patientId').val();
            var preFor = 0;
            var date = 0;
            var printDate = 0;
            var mainAntenatalId = $('#mainAntenatalId').val();
            var followid = $('#followId').val();
            if (type == 'add') {

                date = $('#presDate').val();
                printDate = $('#printDate').val();
                if ($('#forHusband').is(':checked')) {
                    preFor = 1;
                } else {
                    preFor = 0;
                }

                $.post(hosturl + '/controllers/' + controller + '.php?ac=printpre', {
                    preFor: preFor,
                    date: date,
                    patientId: patientId,
                    mainAntenatalId: mainAntenatalId,
                    followid: followid,
                    printDate: printDate
                }, function (res) {

                    $("#drugPrint").html(res);
                    //$.print("#drugPrint",{timeout: 75000});
                    $("#drugPrint").print({});
                    $("#drugPrint").html("");
                });
            } else {
                date = $(this).attr('data-date');
                preFor = $(this).attr('data-for');
                $.post(hosturl + '/controllers/' + controller + '.php?ac=printpre', {
                    preFor: preFor,
                    date: date,
                    patientId: patientId,
                    mainAntenatalId: mainAntenatalId,
                    followid: followid
                }, function (res) {
                    $("#drugPrintShow").html(res);
                    $.print("#drugPrintShow");
                    $("#drugPrintShow").html("");
                });
            }


            if ($('#preType').val() == 'edit') {
                $("#showDrugs").trigger('click');
            }
        });
        $('body').on('change', '.dcat', function () {
            var itr = $(this).attr('data-itr');
            var value = $(this).val();
            $.post(hosturl + '/controllers/gyna.php?ac=search', {value: value, type: "cat"}, function (res) {
                $('#dname' + itr).html(res);
                $('#dname' + itr).select2("val", "");
                $('#dtype' + itr).select2("val", "");
                $('#ddos' + itr).select2("val", "");
            });
        });
        $('body').on('change', '.dname', function () {
            var itr = $(this).attr('data-itr');
            var createNew = $(this).attr('data-createNew'); // 0 not yet , 1 created before
            if (createNew == 0) {
                if ($('#controllName').val() == 'followupcard') {
                    $(this).attr('data-createNew', 1);
                    var newItr = Number(itr) + 1;
                    $('#drugItr').val(newItr);
                    $.post(hosturl + '/controllers/followupcard.php?ac=drawRow', {itr: newItr}, function (res) {
                        $('#drugContent').append(res);
                    });
                } else {
                    $(this).attr('data-createNew', 1);
                    $("#addNewDrugRow").trigger('click');
                    $("#newDrug").trigger('click');
                }

            }
            var value = $(this).val();
            $.post(hosturl + '/controllers/gyna.php?ac=search', {value: value, type: "name_type"}, function (res) {
                $('#dtype' + itr).html(res);
                var firstType = $('#dtype' + itr + ' option:eq(1)').val();
                $('#dtype' + itr).select2("val", firstType);
                $('#dtype' + itr).change();
            });
            $.post(hosturl + '/controllers/gyna.php?ac=search', {value: value, type: "name_dos"}, function (res) {
                $('#ddos' + itr).html(res);
                var firstDos = $('#ddos' + itr + ' option:eq(1)').val();
                $('#ddos' + itr).select2("val", firstDos);
                $('#ddos' + itr).change();
            });
        });
        $('body').on('change', '.dtype', function () {
            var itr = $(this).attr('data-itr');
            var value = $(this).val();
            var drugId = $('#dname' + itr).val();
            if (!value) {
                $('#ddos' + itr).select2("val", "");
            } else {
                $.post(hosturl + '/controllers/gyna.php?ac=search', {
                    value: value,
                    type: "type",
                    drugId: drugId
                }, function (res) {

                    if (res == -1) {
                        $('#ddos' + itr).select2("val", "").trigger("change");
                    } else {
                        $('#ddos' + itr).select2("val", res).trigger("change");
                    }

                });
                $('#ddos' + itr).change();
            }

        });
        $('body').on('click', '.editPre', function () {
            var patientId = $('#patientId').val();
            var mainAntenatalId = $('#mainAntenatalId').val();
            var followid = $('#followId').val();
            var preDate = $(this).attr('data-date');
            var preFor = $(this).attr('data-for');
            var controller = $(this).attr('data-controller');
            $.post(hosturl + '/controllers/' + controller + '.php?ac=showprescription', {
                preFor: preFor,
                patientId: patientId,
                preDate: preDate,
                type: "edit",
                mainAntenatalId: mainAntenatalId,
                followid: followid
            }, function (res) {
                $("#drugContent").html("");
                $("#drugContent").html(res);
                $('#presDate').val(preDate);
                if (preFor == 1) {
                    $('#forHusband').attr('checked', 'checked');
                    $('#forHusband').parent().addClass('checked');
                } else if (preFor == 0) {
                    $('#forHusband').removeAttr('checked');
                    $('#forHusband').parent().removeClass('checked');
                }
                $('#preType').val('edit');
                //    $("#addPatientDrugs").modal('show');
                $('#addPatientDrugs').modal({keyboard: true});
            });
        });
        $('body').on('click', '#showDrugs', function () {
            var controller = $(this).attr('data-controller');
            var patientId = $('#patientId').val();
            var mainAntenatalId = $('#mainAntenatalId').val();
            var followid = $('#followId').val();
            var archive = $(this).attr('data-archive');
            $.post(hosturl + '/controllers/' + controller + '.php?ac=showprescription', {
                patientId: patientId,
                type: "show",
                mainAntenatalId: mainAntenatalId,
                followid: followid,
                archive: archive
            }, function (res) {
                $("#showPrescriptions").html("");
                $("#showPrescriptions").html(res);
                //   $("#showPatientDrugs").modal('show');
                $('#showPatientDrugs').modal({keyboard: true});
            });
        });
        $('body').on('click', '.closeDrug', function () {
            if ($('#preType').val() == 'edit') {
                $("#showDrugs").trigger('click');
            }
        });
        $('body').on('click', '#addNewDrugInTable', function () {
            $.post(hosturl + '/controllers/gyna.php?ac=getDrugModel', function (res) {
                $('#newDrugTableDiv').html('');
                $('#newDrugTableDiv').append(res);
                getdata();
                //   $('#addTableDrugs').modal('show');
                $('#addTableDrugs').modal({keyboard: true});
            });
        });
        $('body').on('click', '#saveDrugTable', function () {
            var cat = $('#drugcat').val();
            var name = $('#drugname').val();
            var type = $('#drugtype').val();
            var dos = $('#drugdos').val();
            $.post(hosturl + '/controllers/gyna.php?ac=saveDrugTable', $('#gynaDrugsTable').serialize(), function (res) {
                var result = res.split("-");
                if (result[0] == 1) {
                    $('.dcat').each(function () {
                        if ($(this).is("select"))    // check if  the input field is  a select
                        {
                            $(this).append('<option value="' + result[1] + '">' + cat + '</option>');
                        }
                    });
                    $('.dname').each(function () {
                        if ($(this).is("select"))    // check if  the input field is  a select
                        {
                            $(this).append('<option value="' + result[2] + '">' + name + '</option>');
                        }

                    });
                    $('.dtype').each(function () {
                        if ($(this).is("select"))    // check if  the input field is  a select
                        {
                            $(this).append('<option value="' + result[3] + '">' + type + '</option>');
                        }

                    });
                    $('.ddos').each(function () {
                        if ($(this).is("select"))    // check if  the input field is  a select
                        {
                            $(this).append('<option value="' + result[4] + '">' + dos + '</option>');
                        }

                    });
                    $('#addTableDrugs').modal('hide');
                    //$('#newDrugTableDiv').html('');
                } else {
                    alert('erorr !!!!!!!!!!!!!!!!!!!!!!!!!!!!');
                }

            });
        });
    };

    var getdata = function () {
        //happened in load the plugins
        //load all datalist
        var searchtxt = '';
        //name
        var listidn = 'namemedcine';
        $.post(hosturl + '/controllers/drugsex.php?ac=getthisserach', {
            listid: listidn,
            searchtxt: searchtxt
        }, function (data) {
            $('#' + listidn).html(data);
            //cat
            var listidc = 'groupmedcine';
            $.post(hosturl + '/controllers/drugsex.php?ac=getthisserach', {
                listid: listidc,
                searchtxt: searchtxt
            }, function (data) {
                $('#' + listidc).html(data);
                //dos
                var listidu = 'usemedcine';
                $.post(hosturl + '/controllers/drugsex.php?ac=getthisserach', {
                    listid: listidu,
                    searchtxt: searchtxt
                }, function (data) {
                    $('#' + listidu).html(data);
                    //type
                    var listidf = 'frommedcine';
                    $.post(hosturl + '/controllers/drugsex.php?ac=getthisserach', {
                        listid: listidf,
                        searchtxt: searchtxt
                    }, function (data) {
                        $('#' + listidf).html(data);
                    });
                });
            });
        });
    };

    var patientInv = function () {
        $('body').on('click', '#addInv', function () {
            var patientId = $('#patientId').val();
            $('#pId1').val(patientId);
            var mainAntenatalId = $('#mainAntenatalId').val();
            $('#mainId1').val(mainAntenatalId);
            //   $("#addPatientInvestigation").modal('show');
            $('#addPatientInvestigation').modal({keyboard: true});
        });
        $('body').on('click', '#showInv', function () {
            var controller = $(this).attr('data-controller');
            var archive = $(this).attr('data-archive');
            var patientId = $('#patientId').val();
            var mainAntenatalId = $('#mainAntenatalId').val();
            $.post(hosturl + '/controllers/' + controller + '.php?ac=showInvs', {
                patientId: patientId,
                mainAntenatalId: mainAntenatalId,
                archive: archive
            }, function (res) {
                $("#showInvs").html("");
                $("#showInvs").html(res);
                //    $("#showPatientInvestigation").modal('show');
                $('#showPatientInvestigation').modal({keyboard: true});
            });
        });
        $('body').on('click', '.printInvestigation', function () {
            var controller = $(this).attr('data-controller');
            var print = $(this).attr('data-print');
            $.post(hosturl + '/controllers/' + controller + '.php?ac=addinvestigation', $('#gynaInvest').serialize(), function (res) {
                if (print == 1) {
                    $("#inv_div").html(res);
                    $.print("#inv_div");
                }

                $("#inv_div").html("");
                $('.iiin').each(function () {
                    $(this).removeAttr('checked');
                    if ($(this).parent().attr("class") === 'checked') {
                        $(this).parent().attr("class", '')
                    }
                });
                $('#addPatientInvestigation').modal('hide');
            });
        });
//        $('body').on('change', '#allFavorite', function ()
//        {
//            if ($(this).is(":checked"))
//            {
//                $('.favorite').attr('checked', true);
//                $('.favorite').parent().addClass('checked');
//            }
//            else
//            {
//                $('.favorite').removeAttr('checked');
//                $('.favorite').parent().removeClass('checked');
//            }
//        });

//        $('body').on('change', '#allOthers', function ()
//        {
//            if ($(this).is(":checked"))
//            {
//                $('.others').attr('checked', true);
//                $('.others').parent().addClass('checked');
//            }
//            else
//            {
//                $('.others').removeAttr('checked');
//                $('.others').parent().removeClass('checked');
//            }
//        });

        $('body').on('change', '.checkGroup', function () {
            var groupClass = $(this).attr('data-gClass');
            if ($(this).is(":checked")) {
                $('.' + groupClass).attr('checked', true);
                $('.' + groupClass).parent().addClass('checked');
            } else {
                $('.' + groupClass).removeAttr('checked');
                $('.' + groupClass).parent().removeClass('checked');
            }
        });
        $('body').on('click', '.printInv', function () {
            var controller = $(this).attr('data-controller');
            var date = $(this).attr('data-date');
            var dataFor = $(this).attr('data-for');
            var patientId = $('#patientId').val();
            var mainAntenatalId = $('#mainAntenatalId').val();
            $.post(hosturl + '/controllers/' + controller + '.php?ac=printinv', {
                date: date,
                patientId: patientId,
                mainAntenatalId: mainAntenatalId,
                dataFor: dataFor
            }, function (res) {
                $("#inv_divShow").html(res);
                $.print("#inv_divShow");
                $("#inv_divShow").html("");
            });
        });
        $('body').on('change', '#forHusbandInv', function () {
            if ($(this).is(":checked")) {
                $('.husbandCheck').attr('checked', true);
                $('.husbandCheck').parent().addClass('checked');
            } else {
                $('.husbandCheck').removeAttr('checked');
                $('.husbandCheck').parent().removeClass('checked');
            }
        });
    };

    var patientUs = function () {
        $('body').on('click', '#addUS', function () {
            var ultrasoundForm = $('#ultrasoundForm').val();
            var controllName = $('#controllName').val();
            if (controllName == 'gyna') {
                if (ultrasoundForm == 0)    // simple form
                {
                    //     $("#SimplePatientUS").modal('show');
                    $('#SimplePatientUS').modal({keyboard: true});
                } else if (ultrasoundForm == 1)   // complete form
                {
                    //      $("#completePatientUS").modal('show');
                    $('#completePatientUS').modal({keyboard: true});
                }
            } else if (controllName == 'antenalvisit') {
                //     $("#antPatientUS").modal('show');
                $('#antPatientUS').modal({keyboard: true});
            }

        });

        $('body').on('click', '.addRowH', function () {
            var type = $(this).attr("data-type");
            var patientId = $('#patientId').val();
            var itr = $('#' + type + 'Itr').val();
            var newItr = Number(itr) + 1;
            $('#' + type + 'Itr').val(newItr);
            if (type == 'usantenatal') {
                var mainAntenatalId = $('#mainAntenatalId').val();
                $.post(hosturl + '/controllers/antenalvisit.php?ac=loadusrow', {
                    patientId: patientId,
                    itr: itr,
                    type: type,
                    mainAntenatalId: mainAntenatalId
                }, function (res) {
                    $('#' + type).prepend(res);
                });
            } else {
                $.post(hosturl + '/controllers/gyna.php?ac=loadusrow', {
                    patientId: patientId,
                    itr: itr,
                    type: type
                }, function (res) {
                    $('#' + type).prepend(res);
                });
            }

        });

        $('body').on('click', '.addLTovary', function () {
            var gynaUsId = $(this).attr("data-id");
            var type = $(this).attr("data-type");
            var id = $(this).attr("id");
            $('#Tovary').html("");
            $('#folliclesNumbers').val("");
            $('#lgynaUsId').val(gynaUsId);
            $('#currentBtnId').val(id);
            $.post(hosturl + '/controllers/gyna.php?ac=loadusrow', {
                patientId: gynaUsId,
                type: "ltovary",
                status: type
            }, function (res) {
                $('#Tovary').append(res);
                if (type == "show") {
                    $('.ff').hide();
                }
                if (type == "add") {
                    $('.ff').show();
                }
                //  $("#gynaLTovary").modal('show');
                $('#gynaLTovary').modal({keyboard: true});
            });
        });

        $('body').on('click', '.addRtovary', function () {
            var gynaUsId = $(this).attr("data-id");
            var type = $(this).attr("data-type");
            var id = $(this).attr("id");
            $('#rTovary').html("");
            $('#rgynaUsId').val(gynaUsId);
            $('#RfolliclesNumbers').val("");
            $('#currentBtnId').val(id);
            $.post(hosturl + '/controllers/gyna.php?ac=loadusrow', {
                patientId: gynaUsId,
                type: "rtovary",
                status: type
            }, function (res) {
                $('#rTovary').append(res);
                if (type == "show") {
                    $('.rr').hide();
                }
                if (type == "add") {
                    $('.rr').show();
                }
                //     $("#gynaRTovary").modal('show');
                $('#gynaRTovary').modal({keyboard: true});
            });
        });

        $('body').on('keyup', '#folliclesNumbers', function () {
            var no = $(this).val();
            $('#Tovary').html("");
            for (var $i = 1; $i <= Number(no); $i++) {
                var row = '<tr>'
                        + '<td>'
                        + '<input type="text" class="form-control" placeholder="Name" name="name' + $i + '" value="Follicle ' + $i + '">'
                        + '</td>  '
                        + '<td>'
                        + '<input type="text" class="form-control" placeholder="Length" name="length' + $i + '" value="">'
                        + '</td>'
                        + '<td>'
                        + ' <input type="text" class="form-control" placeholder="Width" name="width' + $i + '" value="">'
                        + '</td>'
                        + '<td>'
                        + '<input type="text" class="form-control" placeholder="Volume" name="volume' + $i + '" value="">'
                        + '  </td>'
                        + '</tr>';
                $('#Tovary').append(row);
            }

        });

        $('body').on('keyup', '#RfolliclesNumbers', function () {
            var no = $(this).val();
            $('#rTovary').html("");
            for (var $i = 1; $i <= Number(no); $i++) {
                var row = '<tr>'
                        + '<td>'
                        + '<input type="text" class="form-control" placeholder="Name" name="name' + $i + '" value="Follicle ' + $i + '">'
                        + '</td>  '
                        + '<td>'
                        + '<input type="text" class="form-control" placeholder="Length" name="length' + $i + '" value="">'
                        + '</td>'
                        + '<td>'
                        + ' <input type="text" class="form-control" placeholder="Width" name="width' + $i + '" value="">'
                        + '</td>'
                        + '<td>'
                        + '<input type="text" class="form-control" placeholder="Volume" name="volume' + $i + '" value="">'
                        + '  </td>'
                        + '</tr>';
                $('#rTovary').append(row);
            }

        });

        $('body').on('click', '.saveFocil', function () {
            var controller = $(this).attr('data-controller');
            var type = $(this).attr('data-type');
            var currentBtnId = $('#currentBtnId').val();
            $('#' + currentBtnId).attr('data-type', "show");
            $('#' + currentBtnId).html("Show");
            if (type == "left") {
                $.post(hosturl + '/controllers/' + controller + '.php?ac=savefocil', $('#focildata').serialize(), function (res) {
                    $('#gynaLTovary').modal('hide');
                });
            } else {
                $.post(hosturl + '/controllers/' + controller + '.php?ac=savefocil', $('#Rfocildata').serialize(), function (res) {
                    $('#gynaRTovary').modal('hide');
                });
            }

        });

        $('body').on('click', '.printUsRows', function () {
            var type = $(this).attr('data-type');
            var patientId = $('#patientId').val();
            var usRows = Array();
            $('.usPrint').each(function () {
                if ($(this).is(":checked") && $(this).is(":visible")) {
                    usRows.push($(this).val());
                }
            });
            var jsonString = JSON.stringify(usRows);
            $.post(hosturl + '/controllers/gyna.php?ac=printus', {
                type: type,
                patientId: patientId,
                jsonString: jsonString
            }, function (res) {
                $("#newDrugTableDiv").html("");
                $("#newDrugTableDiv").html(res);
                $.print("#newDrugTableDiv");
                $("#newDrugTableDiv").html("");
            });
        });
    };

    var addInvestigation = function () {
        $('body').on('click', '#invCat_add', function () {
            $.post(hosturl + '/controllers/addinvestigation.php?ac=addnewcat', function (res) {
                $('#invCat').append('<tr><td><input type="text" class="form-control updateElement invCatName" id="cat' + res + '" data-id="' + res + '" data-colName="name" data-tableName="investcats"/></td>'
                        + '<td><a class="btn green btn-xs showInv" data-id="' + res + '" style=" float: left;" href="#" ><i class="fa fa-pencil"></i>Show </a></td>'
                        + '<td><a class="btn grey-cascade btn-xs editCat" data-id="' + res + '" style=" float: left;" href="#" ><i class="fa fa-pencil"></i> </a></td>'
                        + '<td><a class="btn grey-cascade btn-xs deletemsgEX" data-id="' + res + '" style=" float: left;" href="#" data-link="addinvestigation" data-fn="del" data-tableName="investcats"><i class="fa fa-close"></i></a></td>'
                        + '</tr>');
                $('#cat' + res).focus();
            });
        });
        $('body').on('click', '#invest_add', function () {
            var catId = $('#catId').val();
            $.post(hosturl + '/controllers/addinvestigation.php?ac=addnewinv', {catId: catId}, function (res) {
                $('#invests').append('<tr><td><input type="text" class="form-control updateElement invName" id="inv' + res + '" data-id="' + res + '" data-colName="name" data-tableName="invests"/></td>'
                        + '<td><div class="md-checkbox">'
                        + '<input type="checkbox" id="checkbox' + res + '" data-id="' + res + '"  class="md-check addFavorite">'
                        + '<label for="checkbox' + res + '"><span></span><span class="check"></span><span class="box"></span> </label>'
                        + '</div></td>'
                        + '<td><a class="btn grey-cascade btn-xs editInv" data-id="' + res + '" style=" float: left;" href="#" ><i class="fa fa-pencil"></i> </a></td>'
                        + '<td><a class="btn grey-cascade btn-xs deletemsgEX" data-id="' + res + '" style=" float: left;" href="#" data-link="addinvestigation" data-fn="del" data-tableName="invests"><i class="fa fa-close"></i></a></td>'
                        + '</tr>');
                $('#inv' + res).focus();
            });
        });
        $('body').on('click', '.editCat', function () {
            var id = $(this).attr("data-id");
            $('#cat' + id).removeAttr('disabled');
            $('#cat' + id).focus();
        });
        $('body').on('click', '.editInv', function () {
            var id = $(this).attr("data-id");
            $('#inv' + id).removeAttr('disabled');
            $('#inv' + id).focus();
        });
        $('body').on('blur', '.invCatName', function () {
            $(this).attr("disabled", true);
        });
        $('body').on('blur', '.invName', function () {
            $(this).attr("disabled", true);
        });
        $('body').on('click', '.addFavorite', function () {
            var invId = $(this).attr("data-id");
            var check = $('#checkbox' + invId).is(":checked")
            var value = 0;
            if (check == true) {
                value = 1;
            }
            $.post(hosturl + '/controllers/addinvestigation.php?ac=addtofavorite', {
                invId: invId,
                value: value
            }, function (res) {
            });
        });
        $('body').on('click', '.showInv', function () {
            var catId = $(this).attr("data-id");
            $('#catId').val(catId);
            $.post(hosturl + '/controllers/addinvestigation.php?ac=getinvbycatid', {catId: catId}, function (res) {
                $('#showCatInv').html(res);
                //   $("#investsModel").modal('show');
                $('#investsModel').modal({keyboard: true});
            });
        });
    };

    var instruction = function () {
        $('body').on('click', '#printInstruction', function () {
            var patientId = $('#patientId').val();
            $('.inst').each(function () {
                if ($(this).parent().attr("class") === 'checked') {
                    instructionArray.push($(this).attr('data-intId'));
                }
            });
            var jsonString = JSON.stringify(instructionArray);
            $.post(hosturl + '/controllers/instruction.php?ac=getprint', {
                jsonString: jsonString,
                patientId: patientId
            }, function (res) {
                $('#instPrint').html("");
                $('#instPrint').html(res);
                $.print("#printIns");
                instructionArray = [];
            });
        });
        $('body').on('click', '.showInst', function () {
            var patientId = $('#patientId').val();
            var instructionId = $(this).attr('data-intId');
            var print = $(this).attr('data-print');
            $.post(hosturl + '/controllers/instruction.php?ac=getinstdetail', {
                instructionId: instructionId,
                patientId: patientId
            }, function (res) {
                $('#instPrint').html("");
                $('#instPrint').html(res);
                if (print == 'no') {
                    //      $("#instDetail").modal('show');
                    $('#instDetail').modal({keyboard: true});
                } else if (print == 'yes') {
                    $.print("#printIns");
                }
            });
        });
        $('body').on('click', '#printtt', function () {
            $.print("#printIns");
            $('#instPrint').html("");
            $("#instDetail").modal('hide');
        });
    };

    var menu = function () {
        $('body').on('click', '#arrang_main', function () {
            $.post(hosturl + '/controllers/_menu.php?ac=arrangemain', function (res) {
                $('#arrange_div').html("");
                $('#arrange_div').html(res);
                //    $("#arrangeMainModal").modal('show');
                $('#arrangeMainModal').modal({keyboard: true});
            });
        });
        $('body').on('click', '#arrang_sub', function () {
            var parent = $(this).attr('data-parent');
            $.post(hosturl + '/controllers/_menu.php?ac=arrangesub', {parent: parent}, function (res) {
                $('#arrange_div').html("");
                $('#arrange_div').html(res);
                //   $("#arrangeMainModal").modal('show');
                $('#arrangeMainModal').modal({keyboard: true});
            });
        });
        $('body').on('click', '#closemodel_arrange', function () {
            window.location = hosturl + "/controllers/_menu.php?ac=show";
        });
        $('body').on('change', '.displayOption', function () {
            if ($(this).val() == "image") {
                $('#iconDiv').hide();
                $('#imageDiv').show();
            } else if ($(this).val() == "icon") {
                $('#imageDiv').hide();
                $('#iconDiv').show();
            }
        });
        $('body').on('click', '#deleteBackground', function () {
            $('#backgroundImageValue').val(0);
            $('#backgroundImage').attr('src', '');
        });
    };

    var members = function () {
        $('body').on('change', '#role', function () {
            var roleId = $(this).val();
            $('#loginInfoDiv').show();
            $('#username').attr('required', true);
            $('#password').attr('required', true);
            $('#confirmpassword').attr('required', true);
            $('#special').select2('val', '');
            $('#position').select2('val', '');
            if (roleId == "") {
                $('#specialDiv').hide();
                $('#positionDiv').hide();
            } else {

                $.post(hosturl + '/controllers/_member.php?ac=getspecial', {roleId: roleId}, function (res) {
                    $('#special').html('');
                    $('#special').html(res);
                    $('#specialDiv').show();
                });
                $.post(hosturl + '/controllers/_member.php?ac=getposition', {roleId: roleId}, function (res) {
                    $('#position').html('');
                    $('#position').html(res);
                    $('#positionDiv').show();
                });
            }

        });
        $('body').on('change', '#position', function () {
            var position = $(this).val();
            if (position == 4 || position == 5) {
                $('#username').removeAttr('required');
                $('#password').removeAttr('required');
                $('#confirmpassword').removeAttr('required');
                $('#loginInfoDiv').hide();
            } else {
                $('#loginInfoDiv').show();
                $('#username').attr('required', true);
                $('#password').attr('required', true);
                $('#confirmpassword').attr('required', true);
            }

        });
        $('body').on('change', '#addV', function () {
            if ($(this).is(":checked")) {
                $('#vDiv').show();
            } else {
                $('#vDiv').hide();
            }
        });
    };

    var merge = function () {
        $('body').on('click', '#merge', function () {
            $('#talks-loading').show();
            var oldDbHost = $('#oldDbHost').val();
            var oldDbName = $('#oldDbName').val();
            var oldDbUser = $('#oldDbUser').val();
            var oldDbPass = $('#oldDbPass').val();
            $.post(hosturl + '/controllers/merge.php?ac=mergedb', {
                oldDbHost: oldDbHost,
                oldDbName: oldDbName,
                oldDbUser: oldDbUser,
                oldDbPass: oldDbPass
            }, function (res) {
                $('#mergeResult').html('');
                $('#mergeResult').html(res);
                $('#talks-loading').hide();
            });
        });
    };

    var minSelectInput = function () {
        $(document).ready(function (e) {
            $("#patientvisitid").select2({
                minimumInputLength: 3
            });
            $("#patientvisitidNo").select2({
                minimumInputLength: 1
            });
            $("#pName").select2({
                minimumInputLength: 3
            });
            $("#pNo").select2({
                minimumInputLength: 1
            });
        });
    };

    var visits = function () {
        $('body').on('click', '#addNewEndRecord', function () {
            var patientId = $('#patientId').val();
            $.post(hosturl + '/controllers/patients.php?ac=addendvisits', {patientId: patientId}, function (res) {
                res = Number(res);
                if ($('#showDoctor').val() == 1) {
                    $('#endReportsBody').prepend('<tr><td>'
                            + '<input type="text" class="form-control datepicker updateElementVisit" readonly="" data-colName="enddate" data-id="' + res + '"  data-tableName="endvisitreports" value="' + $('#today').val() + '"/>'
                            + '</td>'
                            + '<td>'
                            + '<textarea class="form-control updateElementVisit txtc" rows="2" data-id="' + res + '" data-colName="reason" data-tableName="endvisitreports" placeholder="Enter more text" data-toggle="popover" data-trigger="hover" data-placement="bottom" data-content=""></textarea>'
                            + '</td>'
                            + '<td>'
                            + '<textarea class="form-control updateElementVisit txtc" rows="2" data-id="' + res + '" data-colName="notes" data-tableName="endvisitreports" placeholder="Enter more text" data-toggle="popover" data-trigger="hover" data-placement="bottom" data-content=""></textarea>'
                            + '</td>'
                            + '<td>'
                            + $('#doctorName').val()
                            + '</td>'
                            + '</tr>'
                            );
                } else {


                    $('#endReportsBody').prepend('<tr><td>'
                            + '<input type="text" class="form-control datepicker updateElementVisit" readonly="" data-colName="enddate" data-id="' + res + '"  data-tableName="endvisitreports" value="' + $('#today').val() + '"/>'
                            + '</td>'
                            + '<td>'
                            + '<textarea class="form-control updateElementVisit txtc" rows="2" data-id="' + res + '" data-colName="reason" data-tableName="endvisitreports" placeholder="Enter more text" data-toggle="popover" data-trigger="hover" data-placement="bottom" data-content=""></textarea>'
                            + '</td>'
                            + '<td>'
                            + '<textarea class="form-control updateElementVisit txtc" rows="2" data-id="' + res + '" data-colName="notes" data-tableName="endvisitreports" placeholder="Enter more text" data-toggle="popover" data-trigger="hover" data-placement="bottom" data-content=""></textarea>'
                            + '</td>'
                            + '</tr>'
                            );
                }
                $(".datepicker").datepicker({
                    todayBtn: "linked",
                    autoclose: true,
                    todayHighlight: true,
                    format: 'yy/mm/dd',
                    isRTL: true
                });
            });
        });
        $('body').on('change', '.updateElementVisit', function () {
            var id = $(this).attr("data-id");
            var colName = $(this).attr("data-colName");
            var tableName = $(this).attr("data-tableName");
            var value = $(this).val();
            var dated;
            if ($(this).hasClass("datepicker")) {
                dated = 1;
            } else {
                dated = 0;
            }

            $.post(hosturl + '/controllers/patients.php?ac=endvisit', {
                id: id,
                value: value,
                tableName: tableName,
                colName: colName,
                dated: dated
            }, function (res) {
            });
        });
        $('body').on('click', '.emptyDeptVisit', function () {
            $('#talks-loading').show();
            var deptId = $(this).attr("data-id");
            $.post(hosturl + '/controllers/visits.php?ac=emptydeptvisit', {deptId: deptId}, function (res) {
                $('#talks-loading').hide();
            });
        });
        $('body').on('click', '.editVisit', function () {
            var visitId = $(this).attr("data-visitId");
            var row = $(this).parent().parent();
            $.post(hosturl + '/controllers/visits.php?ac=editvisit', {visitId: visitId}, function (res) {
                var obj = JSON.parse(res);
                var detection = '<div class="col-md-12">';
                if (obj.setting != 1) {
                    //detection += '<label for="form_control_1">نوع الكشف</label>';
                    //detection += '<div class="form-group  form-md-floating-label has-info" style="margin: 0 0 0 0;">';
                    detection += '<select  class="form-control newDetect " data-id="' + visitId + '"  data-getPrice="1"  placeholder="اختر نوع الكشف " id="newDetect' + visitId + '"   data-tableName="visits"  data-colName="detectionid">';
                } else {
                    detection += '<label for="form_control_1"> القسم</label>';
                    detection += '<div class="form-group  form-md-floating-label has-info" style="margin: 0 0 0 0;">';
                    detection += '<select  class="form-control newDetect " data-id="' + visitId + '"  data-getPrice="1"  placeholder="اختر القسم " id="newDetect' + visitId + '"   data-tableName="visits"  data-colName="detectionid">';
                }


                for (var j = 0; j < (obj.allDetections).length; j++) {
                    var sel = "";
                    if (((obj.allDetections)[j].id) == obj.detectionid) {
                        sel = "selected";
                    }
                    detection += '<option value=' + (obj.allDetections)[j].id + ' ' + sel + '> ' + (obj.allDetections)[j].title + '</option>';
                }

                if (obj.balancesetting == 1) {
                    if (obj.detectionid == -99) {
                        sel = "selected";
                    }
                    detection += '<option value=-99 ' + sel + '> دفع قسط</option>';
                }



                detection += '</select></div></div>';
                if (obj.setting != 1) {


                    row.find("td").eq(4).html('<div class="col-md-12">'
                            + '<div class="form-group form-md-line-input form-md-floating-label has-info" style="margin: 0 0 0 0;">'
                            + ' <input  class="form-control digitsOnly edited" style="border: 1px solid #000000;border-radius: 4px;"  type="text" id="newDetectVal' + visitId + '"   value="' + obj.detectionvalue + '">'
                            + '<label for="form_control_1"  class="txtr"> قيمة الكشف </label>'
                            + '</div></div>');
                } else {
                    row.find("td").eq(3).html(obj.husbandName);
                }
                row.find("td").eq(3).html(obj.husbandName);
                row.find("td").eq(5).html(detection);
//                row.find("td").eq(5).html('<div class="col-md-12">'
//                        + '<div class="form-group form-md-line-input form-md-floating-label has-info" style="margin: 0 0 0 0;">'
//                        + ' <input  class="form-control datepicker edited" style="border: 1px solid #000000;border-radius: 4px;"  type="text"   value="' + obj.visitdate + '" >'
//                        + '<label for="form_control_1"  class="txtr">تاريخ الزيارة  </label>'
//                        + '</div></div>');
                row.find("td").eq(7).html('<a class=" bg-green dltbtn  saveEditVisit" data-visitId="' + visitId + '">حفظ </a>');
                row.find("td").eq(8).html('<a class=" bg-red dltbtn  cancelEditVisit" data-visitId="' + visitId + '">إلغاء</a>');
                $('select').select2({
                    width: '270px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                    }
                });
                $(".datepicker").datepicker({
                    todayBtn: "linked",
                    autoclose: true,
                    todayHighlight: true,
                    format: 'yy/mm/dd',
                    isRTL: true
                });
            });
        });
        $('body').on('change', '.newDetect', function () {
            var visitId = $(this).attr("data-id");
            var getPrice = $(this).attr("data-getPrice");
            var value = $(this).val();
            if (getPrice == 1) {
                $.post(hosturl + '/controllers/visits.php?ac=getdtprice', {dtID: value}, function (data) {
                    $('#newDetectVal' + visitId).val(data);
                });
            }
        });
        $('body').on('click', '.saveEditVisit', function () {
            var visitId = $(this).attr("data-visitId");
            var newDetectId = $('#newDetect' + visitId).val();
            var newDetectVal = $('#newDetectVal' + visitId).val();
            var row = $(this).parent().parent();
            $.post(hosturl + '/controllers/visits.php?ac=updatevisit', {
                visitId: visitId,
                newDetectId: newDetectId,
                newDetectVal: newDetectVal
            }, function (res) {
                var obj = JSON.parse(res);
                row.find("td").eq(4).html(obj.address);
                row.find("td").eq(3).html(obj.husbandName);
                row.find("td").eq(5).html(obj.detectionType);
                row.find("td").eq(7).html('<a class=" bg-green dltbtn  editVisit" data-visitId="' + visitId + '">تعديل</a>');
                row.find("td").eq(8).html('<a class="deletemsgEX bg-red dltbtn"  data-today="0" id="deleterowtoday" data-id="' + visitId + '" data-link="visits" data-fn="del">حذف</a>');
            });
        });
        $('body').on('click', '.cancelEditVisit', function () {
            var visitId = $(this).attr("data-visitId");
            var row = $(this).parent().parent();
            $.post(hosturl + '/controllers/visits.php?ac=restorevisit', {visitId: visitId}, function (res) {
                var obj = JSON.parse(res);
                row.find("td").eq(4).html(obj.address);
                row.find("td").eq(3).html(obj.husbandName);
                row.find("td").eq(5).html(obj.detectionType);
                row.find("td").eq(7).html('<a class=" bg-green dltbtn  editVisit" data-visitId="' + visitId + '">تعديل</a>');
                row.find("td").eq(8).html('<a class="deletemsgEX bg-red dltbtn"  data-today="0" id="deleterowtoday" data-id="' + visitId + '" data-link="visits" data-fn="del">حذف</a>');
            });
        });
        //fatma
        $('body').on('click', '.payVisitClass', function () {
            if (!$(this).hasClass('processing')) {
                $(this).addClass('processing')
//                var thisBtn = $(this);
                var visitId = $(this).attr("data-visitId");
                var td = $(this).parent();
                $.post(hosturl + '/controllers/visits.php?ac=payvisit', {
                    visitId: visitId,
                }, function (res) {
                    if (res == 0)
                    {
                        td.html('تم الدفع');
                    } else if (res == 1) {
                        td.html('تم الدفع' + '- <a class=" bg-yellow-gold dltbtn">حجز بالتطبيق</a>');
                    }
//                    thisBtn.removeClass('processing');
                });
            }
        });
        //fatma
        $('body').on('change', '#visitdate', function () {
            $(this).val();
            //
            var today = new Date();
            var dd = today.getDate();
            var mm = today.getMonth() + 1; //January is 0!
            var yyyy = today.getFullYear();

            if (dd < 10) {
                dd = '0' + dd
            }

            if (mm < 10) {
                mm = '0' + mm
            }

            today = yyyy + '/' + mm + '/' + dd;
            if (today == $(this).val())
            {
                $('#payVisit').attr('checked', 'checked').uniform('refresh');
//                $.uniform.update('#payVisit');
//                $.uniform.update();
            } else {
                $('#payVisit').removeAttr('checked').uniform('refresh');
            }
        });


    };

    var followupcard = function () {
        $('body').on('click', '.deletefrow', function () {
            $(this).parent().parent().remove();
        });
        $('body').on('click', '#followDAdd', function () {
            var itr = $('#drugItr').val();
            var newItr = Number(itr) + 1;
            $('#drugItr').val(newItr);
            $.post(hosturl + '/controllers/followupcard.php?ac=drawRow', {itr: newItr}, function (res) {
                $('#drugContent').append(res);
            });
        });
        $('body').on('click', '.printCard', function () {
            var printCard = $(this).attr('data-print');
            var patientId = $('#patientId').val();
            $('#cardPrint').val(printCard);
            //$('#followardForm').submit();
            $.post(hosturl + '/controllers/followupcard.php?ac=printit', $('#followardForm').serialize(), function (res) {
                // alert(printCard);
                if (printCard == 'yes') {
                    $("#drugPrint").html(res);
                    $.print("#drugPrint");
                    $("#drugPrint").html("");
                    window.setTimeout(function () {
                        window.location = hosturl + "/controllers/patients.php?ac=showendvisits&patientid=" + patientId + "&comefrom=1";
                    }, 400);
                } else if (printCard == 'yesOnly') {
                    $("#drugPrint").html(res);
                    $.print("#drugPrint");
                    $("#drugPrint").html("");
                } else {
                    window.location = hosturl + "/controllers/patients.php?ac=showendvisits&patientid=" + patientId + "&comefrom=1";
                }
            });
        });
        $('body').on('click', '.delCard', function () {
            var id = $(this).attr("data-id");
            var colName = 'deleted';
            var tableName = 'followupcard';
            var value = 1;
            var controllName = $('#controllName').val();
            var tr = $(this).parent().parent();
            bootbox.dialog({
                message: "Do you want to delete this item?",
                title: "Delete confirmation",
                buttons: {
                    danger: {
                        label: "Cancel",
                        className: "btn-primary"
                    },
                    main: {
                        label: "Delete",
                        className: "btn-danger",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/' + controllName + '.php?ac=update', {
                                id: id,
                                value: value,
                                tableName: tableName,
                                colName: colName
                            }, function (res) {
                                if (res == 1) {
                                    tr.remove();
                                } else {
                                    alert("!!!!!!!!!!!!! some thing wrong here");
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $('body').on('click', '.cardDetails', function () {
            var id = $(this).attr("data-id");
            var patientId = $('#patientId').val();
            window.location = hosturl + "/controllers/followupcard.php?ac=addit&cardid=" + id + "&patientid=" + patientId;
        });
    };

    var fullReport = function () {
        $('body').on('change', '.fullDate', function () {
            var controllName = $('#controllName').val();
            var fromdate = $("#fromdateFull").val();
            var todate = $("#todateFull").val();
            var fullDept = $("#fullDept").val();
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=search', {
                fromdate: fromdate,
                todate: todate,
                fullDept: fullDept
            }, function (res) {
                console.log(res);
                $("#fullDiv").html("");
                $("#fullDiv").append(res);
            });
        });

        $('body').on('change', '.getTotalBalance', function () {
            var patientId = $(this).val();

            $.post(hosturl + '/controllers/visits.php?ac=gettotalbalance', {
                patientId: patientId
            }, function (res) {
                console.log(res);
                $("#balance").val(res);
            });
        });

        $('body').on('click', '#addBalance', function () {
            var newBalance = $('#newBalance').val();
            var patientId = $('#patientvisitid').val();

            $.post(hosturl + '/controllers/visits.php?ac=addbalance', {
                patientId: patientId, newBalance: newBalance
            }, function (res) {
                console.log(res);
                $("#balance").val(res);
                $("#newBalance").val(0);
            });
        });


        $('body').on('change', '.balanceSearch', function () {

            var fdate = $("#findate").val();
            var todate = $("#tofindate").val();
            var value = $("#patientName").val();
            var type = $("#type").val();
            var hvalue = $("#husband").val();
            if ($(this).attr('id') == "husband")
                value = '';
            $.post(hosturl + '/controllers/monitoring.php?ac=search', {type: type, fdate: fdate, todate: todate, value: value, hvalue: hvalue}, function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
            });

        });
    }

    var transfer = function () {
        $('body').on('click', '#printTransfer', function () {
            var hospitalName = $('#hospitalName').val();
            var instNotes = $('#instNotes').val();
            var patientId = $(this).attr('data-patientId');
            var realvalues = new Array();
            $('#operationInstructions :selected').each(function (i, selected) {
                realvalues[i] = $(selected).val();
            });
            $.ajax({
                url: hosturl + '/controllers/instruction.php?ac=printtransfer',
                data: {
                    value: JSON.stringify(realvalues),
                    hospitalName: hospitalName,
                    instNotes: instNotes,
                    patientId: patientId
                },
                type: 'POST',
                success: function (res) {
                    $("#printTtt").html(res);
                    $.print("#printTtt");
                    $("#printTtt").html("");
                }
            });
        });
        $('#hospitalName').select2({
            width: '170px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                return "<input class='form-control' id='newhospital' value='" + term + "' ><a href='#' id='addhospital'  class='btn btn-default'>Add</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addhospital', function () {
            var newitem = $('#newhospital').val();
            $.post(hosturl + '/controllers/instruction.php?ac=addnewhospital', {newitem: newitem}, function (data) {
                $('#hospitalName > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                $('#hospitalName').select2('val', Number(data)); // select the new term
                $('#hospitalName').select2('close'); // close the dropdown

            });
        });
        $('#hospitalName').on('change', function () {
            var thisvalue = $(this).val();
            if (thisvalue == '-2') {
                $('#hospitalName').select2('val', '');
                $.post(hosturl + '/controllers/instruction.php?ac=editselect', function (data) {
                    $("#alldatadiv").html(data);
                    //     $("#edit_model").modal('show');
                    $('#edit_model').modal({keyboard: true});
                });
            }

        });
        $('.delHospital').on('change', function () {
            var thisvalue = $(this).val();
            if (thisvalue == '-2') {
                $('#hospitalName').select2('val', '');
                $.post(hosturl + '/controllers/instruction.php?ac=editselect', function (data) {
                    $("#alldatadiv").html(data);
                    //     $("#edit_model").modal('show');
                    $('#edit_model').modal({keyboard: true});
                });
            }

        });
        $('body').on('click', '.delHospital', function () {
            var id = $(this).attr('data-id');
            var xx = $(this).parent().parent();
            $.post(hosturl + '/controllers/instruction.php?ac=delhospital', {id: id}, function (res) {
                xx.remove();
                $("#hospitalName option[value='" + id + "']").remove();
            });
        });
        // $('#usPrintAll').click(function (event)
        $('body').on('click', '#usPrintAll', function () {
            //on click
            if (this.checked) {
                // check select status
                $('.usPrint').each(function () { //loop through each checkbox
                    //this.checked = true;  //select all checkboxes with class "checkbox1"
                    $(this).attr('checked', 'checked');
                    $(this).parent().addClass('checked');
                });
            } else {
                $('.usPrint').each(function () { //loop through each checkbox
                    //this.checked = false; //deselect all checkboxes with class "checkbox1"
                    $(this).removeAttr('checked');
                    $(this).parent().removeClass('checked');
                });
            }
        });
        $("#addOpInst").live('change', function () {
            var newitem = $(this).val();
            $.post(hosturl + '/controllers/instruction.php?ac=addopinst', {newitem: newitem}, function (data) {
                $('select[id="operationInstructions"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                $('#operationInstructions option[value="' + Number(data) + '"]').attr('selected', true);
                $("#operationInstructions").select2();
            });
        });
        $('#operationInstructions').select2({
            width: '170px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                //return "<input class='form-control' id='newOpInst' value='" + term + "' ><a href='#' id='addOpInstNew' class='btn btn-default addnewselect'>Add</a>"
            }
        });
        /*.parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
         var newitem = $('#newOpInst').val();
         $.post(hosturl + '/controllers/instruction.php?ac=addopinst', {newitem: newitem}, function (data) {
         $('select[id="operationInstructions"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
         //$('<option value="' + Number(data) + '" >' + newitem + '</option>').appendTo('select[name="phregularity"]');
         $('#operationInstructions').select2('val', Number(data)); // select the new term
         $('#operationInstructions').select2('close'); // close the dropdown
         
         
         });
         });*/
        $('.transferInstructions').live('change', function () {

            var realvalues = new Array();
            var lastvalue;
            $('#operationInstructions :selected').each(function (i, selected) {
                realvalues[i] = $(selected).val();
                lastvalue = $(selected).val();
            });
            if (lastvalue == -2) {
                $("#operationInstructions option[value='-2']").prop("selected", false);
                $("#operationInstructions").select2();
                $.post(hosturl + '/controllers/instruction.php?ac=editopinst', {}, function (data) {
                    $("#alldatadiv").html(data);
                    //       $("#edit_model").modal('show');
                    $('#edit_model').modal({keyboard: true});
                });
                realvalues.pop();
            }
            if ($.inArray("-1", realvalues) != -1) {
                $("#operationInstructions option[value='-1']").prop("selected", false);
                $("#operationInstructions").select2();
                //    $("#add_Inst").modal('show');
                $('#add_Inst').modal({keyboard: true});
                realvalues.pop();
                $("#addOpInst").val('');
            }
        });
        $(".delrow").live('click', function () {
            var itemid = $(this).attr('data-id');
            var urlgo = $(this).attr('data-link');
            var fngo = $(this).attr('data-fn');
            var tableName = $(this).attr('data-tableName');
            var selectname = $("#selectname").val();
            var tr = $(this).parent().parent();
            bootbox.dialog({
                message: "Do you want to delete this item?",
                title: "Delete confirmation",
                buttons: {
                    danger: {
                        label: "Cancel",
                        className: "btn-primary"
                    },
                    main: {
                        label: "Delete",
                        className: "btn-danger",
                        callback: function () {
                            $.post(hosturl + '/controllers/' + urlgo + '.php?ac=' + fngo, {
                                id: itemid,
                                tableName: tableName
                            }, function (res) {
                                if (res == 1) {

                                    $("." + selectname + " option[value='" + itemid + "']").remove();
                                    tr.remove();
                                } else {
                                    alert("!!!!!!!!!!!!! some thing wrong here");
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
    }

    var monitoring = function () {

        $('#procedure').select2({
            //  width: '170px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                $id = $(this).attr('data-id');
                var selectTableName = $(this).attr('select-tablename');
                var selectColName = $(this).attr('select-colname');
                var parentTableName = $(this).attr('data-tablename');
                var parentColName = $(this).attr('data-colname');
                return "<input class='form-control' id='newItem' value='" + term + "' data-id='" + $id + "'>\n\
<a href='#' id='addNewItemBtn' data-id=" + $id + "  \n\
select-tablename=" + selectTableName + "  select-colname=" + selectColName + " data-tablename=" + parentTableName + " data-colname=" + parentColName + " \n\
class='btn btn-default addnewselect'>Add</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
            var selectid = $(this).attr('data-id');
            var newitem = $('#newItem').val();
            var selectTableName = $(this).attr('select-tablename');
            var selectColName = $(this).attr('select-colname');
            var parentTableName = $(this).attr('data-tablename');
            var parentColName = $(this).attr('data-colname');
            $.post(hosturl + '/controllers/monitoring.php?ac=addNewItem', {newitem: newitem, selectTableName: selectTableName,
                selectColName: selectColName, parentColName: parentColName, parentTableName: parentTableName, id: selectid, inline: 1, parent: 1}, function (data) {

                $('select[name="procedure"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                $('#procedure').select2('val', Number(data)); // select the new term
                $('#procedure').select2('close'); // close the dropdown


            });
        });
        $('#ejac').select2({
            //  width: '170px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                $id = $(this).attr('data-id');
                var selectTableName = $(this).attr('select-tablename');
                var selectColName = $(this).attr('select-colname');
                var parentTableName = $(this).attr('data-tablename');
                var parentColName = $(this).attr('data-colname');
                return "<input class='form-control' id='newItem' value='" + term + "' data-id='" + $id + "'>\n\
<a href='#' id='addNewItemBtn' data-id=" + $id + "  \n\
select-tablename=" + selectTableName + "  select-colname=" + selectColName + " data-tablename=" + parentTableName + " data-colname=" + parentColName + " \n\
class='btn btn-default addnewselect'>Add</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
            var selectid = $(this).attr('data-id');
            var newitem = $('#newItem').val();
            var selectTableName = $(this).attr('select-tablename');
            var selectColName = $(this).attr('select-colname');
            var parentTableName = $(this).attr('data-tablename');
            var parentColName = $(this).attr('data-colname');
            $.post(hosturl + '/controllers/monitoring.php?ac=addNewItem', {newitem: newitem, selectTableName: selectTableName,
                selectColName: selectColName, parentColName: parentColName, parentTableName: parentTableName, id: selectid, inline: 1, parent: 1}, function (data) {

                $('select[name="ejac"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                $('#ejac').select2('val', Number(data)); // select the new term
                $('#ejac').select2('close'); // close the dropdown


            });
        });
        $('#pesa').select2({
            //  width: '170px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                $id = $(this).attr('data-id');
                var selectTableName = $(this).attr('select-tablename');
                var selectColName = $(this).attr('select-colname');
                var parentTableName = $(this).attr('data-tablename');
                var parentColName = $(this).attr('data-colname');
                return "<input class='form-control' id='newItem' value='" + term + "' data-id='" + $id + "'>\n\
<a href='#' id='addNewItemBtn' data-id=" + $id + "  \n\
select-tablename=" + selectTableName + "  select-colname=" + selectColName + " data-tablename=" + parentTableName + " data-colname=" + parentColName + " \n\
class='btn btn-default addnewselect'>Add</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
            var selectid = $(this).attr('data-id');
            var newitem = $('#newItem').val();
            var selectTableName = $(this).attr('select-tablename');
            var selectColName = $(this).attr('select-colname');
            var parentTableName = $(this).attr('data-tablename');
            var parentColName = $(this).attr('data-colname');
            $.post(hosturl + '/controllers/monitoring.php?ac=addNewItem', {newitem: newitem, selectTableName: selectTableName,
                selectColName: selectColName, parentColName: parentColName, parentTableName: parentTableName, id: selectid, inline: 1, parent: 1}, function (data) {

                $('select[name="pesa"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                $('#pesa').select2('val', Number(data)); // select the new term
                $('#pesa').select2('close'); // close the dropdown


            });
        });
        $('#tese').select2({
            //  width: '170px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                $id = $(this).attr('data-id');
                var selectTableName = $(this).attr('select-tablename');
                var selectColName = $(this).attr('select-colname');
                var parentTableName = $(this).attr('data-tablename');
                var parentColName = $(this).attr('data-colname');
                return "<input class='form-control' id='newItem' value='" + term + "' data-id='" + $id + "'>\n\
<a href='#' id='addNewItemBtn' data-id=" + $id + "  \n\
select-tablename=" + selectTableName + "  select-colname=" + selectColName + " data-tablename=" + parentTableName + " data-colname=" + parentColName + " \n\
class='btn btn-default addnewselect'>Add</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
            var selectid = $(this).attr('data-id');
            var newitem = $('#newItem').val();
            var selectTableName = $(this).attr('select-tablename');
            var selectColName = $(this).attr('select-colname');
            var parentTableName = $(this).attr('data-tablename');
            var parentColName = $(this).attr('data-colname');
            $.post(hosturl + '/controllers/monitoring.php?ac=addNewItem', {newitem: newitem, selectTableName: selectTableName,
                selectColName: selectColName, parentColName: parentColName, parentTableName: parentTableName, id: selectid, inline: 1, parent: 1}, function (data) {

                $('select[name="tese"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                $('#tese').select2('val', Number(data)); // select the new term
                $('#tese').select2('close'); // close the dropdown


            });
        });
        $('#sryo').select2({
            //  width: '170px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                $id = $(this).attr('data-id');
                var selectTableName = $(this).attr('select-tablename');
                var selectColName = $(this).attr('select-colname');
                var parentTableName = $(this).attr('data-tablename');
                var parentColName = $(this).attr('data-colname');
                return "<input class='form-control' id='newItem' value='" + term + "' data-id='" + $id + "'>\n\
<a href='#' id='addNewItemBtn' data-id=" + $id + "  \n\
select-tablename=" + selectTableName + "  select-colname=" + selectColName + " data-tablename=" + parentTableName + " data-colname=" + parentColName + " \n\
class='btn btn-default addnewselect'>Add</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
            var selectid = $(this).attr('data-id');
            var newitem = $('#newItem').val();
            var selectTableName = $(this).attr('select-tablename');
            var selectColName = $(this).attr('select-colname');
            var parentTableName = $(this).attr('data-tablename');
            var parentColName = $(this).attr('data-colname');
            $.post(hosturl + '/controllers/monitoring.php?ac=addNewItem', {newitem: newitem, selectTableName: selectTableName,
                selectColName: selectColName, parentColName: parentColName, parentTableName: parentTableName, id: selectid, inline: 1, parent: 1}, function (data) {

                $('select[name="sryo"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                $('#sryo').select2('val', Number(data)); // select the new term
                $('#sryo').select2('close'); // close the dropdown


            });
        });
        $('#protocol').select2({
            //  width: '170px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                $id = $(this).attr('data-id');
                var selectTableName = $(this).attr('select-tablename');
                var selectColName = $(this).attr('select-colname');
                var parentTableName = $(this).attr('data-tablename');
                var parentColName = $(this).attr('data-colname');
                return "<input class='form-control' id='newItem' value='" + term + "' data-id='" + $id + "'>\n\
<a href='#' id='addNewItemBtn' data-id=" + $id + "  \n\
select-tablename=" + selectTableName + "  select-colname=" + selectColName + " data-tablename=" + parentTableName + " data-colname=" + parentColName + " \n\
class='btn btn-default addnewselect'>Add</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
            var selectid = $(this).attr('data-id');
            var newitem = $('#newItem').val();
            var selectTableName = $(this).attr('select-tablename');
            var selectColName = $(this).attr('select-colname');
            var parentTableName = $(this).attr('data-tablename');
            var parentColName = $(this).attr('data-colname');
            $.post(hosturl + '/controllers/monitoring.php?ac=addNewItem', {newitem: newitem, selectTableName: selectTableName,
                selectColName: selectColName, parentColName: parentColName, parentTableName: parentTableName, id: selectid, inline: 1, parent: 1}, function (data) {

                $('select[name="protocol"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                $('#protocol').select2('val', Number(data)); // select the new term
                $('#protocol').select2('close'); // close the dropdown


            });
        });
        $('#hmg').select2({
            //  width: '170px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                $id = $(this).attr('data-id');
                var selectTableName = $(this).attr('select-tablename');
                var selectColName = $(this).attr('select-colname');
                var parentTableName = $(this).attr('data-tablename');
                var parentColName = $(this).attr('data-colname');
                return "<input class='form-control' id='newItem' value='" + term + "' data-id='" + $id + "'>\n\
<a href='#' id='addNewItemBtn' data-id=" + $id + "  \n\
select-tablename=" + selectTableName + "  select-colname=" + selectColName + " data-tablename=" + parentTableName + " data-colname=" + parentColName + " \n\
class='btn btn-default addnewselect'>Add</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
            var selectid = $(this).attr('data-id');
            var newitem = $('#newItem').val();
            var selectTableName = $(this).attr('select-tablename');
            var selectColName = $(this).attr('select-colname');
            var parentTableName = $(this).attr('data-tablename');
            var parentColName = $(this).attr('data-colname');
            $.post(hosturl + '/controllers/monitoring.php?ac=addNewItem', {newitem: newitem, selectTableName: selectTableName,
                selectColName: selectColName, parentColName: parentColName, parentTableName: parentTableName, id: selectid, inline: 1, parent: 1}, function (data) {

                $('select[name="hmg"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                $('#hmg').select2('val', Number(data)); // select the new term
                $('#hmg').select2('close'); // close the dropdown


            });
        });
        $('#agonist').select2({
            //  width: '170px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                $id = $(this).attr('data-id');
                var selectTableName = $(this).attr('select-tablename');
                var selectColName = $(this).attr('select-colname');
                var parentTableName = $(this).attr('data-tablename');
                var parentColName = $(this).attr('data-colname');
                return "<input class='form-control' id='newItem' value='" + term + "' data-id='" + $id + "'>\n\
<a href='#' id='addNewItemBtn' data-id=" + $id + "  \n\
select-tablename=" + selectTableName + "  select-colname=" + selectColName + " data-tablename=" + parentTableName + " data-colname=" + parentColName + " \n\
class='btn btn-default addnewselect'>Add</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
            var selectid = $(this).attr('data-id');
            var newitem = $('#newItem').val();
            var selectTableName = $(this).attr('select-tablename');
            var selectColName = $(this).attr('select-colname');
            var parentTableName = $(this).attr('data-tablename');
            var parentColName = $(this).attr('data-colname');
            $.post(hosturl + '/controllers/monitoring.php?ac=addNewItem', {newitem: newitem, selectTableName: selectTableName,
                selectColName: selectColName, parentColName: parentColName, parentTableName: parentTableName, id: selectid, inline: 1, parent: 1}, function (data) {

                $('select[name="agonist"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                $('#agonist').select2('val', Number(data)); // select the new term
                $('#agonist').select2('close'); // close the dropdown


            });
        });


        $('#hcg').select2({
            //  width: '170px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                $id = $(this).attr('data-id');
                var selectTableName = $(this).attr('select-tablename');
                var selectColName = $(this).attr('select-colname');
                var parentTableName = $(this).attr('data-tablename');
                var parentColName = $(this).attr('data-colname');
                return "<input class='form-control' id='newItem' value='" + term + "' data-id='" + $id + "'>\n\
<a href='#' id='addNewItemBtn' data-id=" + $id + "  \n\
select-tablename=" + selectTableName + "  select-colname=" + selectColName + " data-tablename=" + parentTableName + " data-colname=" + parentColName + " \n\
class='btn btn-default addnewselect'>Add</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
            var selectid = $(this).attr('data-id');
            var newitem = $('#newItem').val();
            var selectTableName = $(this).attr('select-tablename');
            var selectColName = $(this).attr('select-colname');
            var parentTableName = $(this).attr('data-tablename');
            var parentColName = $(this).attr('data-colname');
            $.post(hosturl + '/controllers/monitoring.php?ac=addNewItem', {newitem: newitem, selectTableName: selectTableName,
                selectColName: selectColName, parentColName: parentColName, parentTableName: parentTableName, id: selectid, inline: 1, parent: 1}, function (data) {

                $('select[name="hcg"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                $('#hcg').select2('val', Number(data)); // select the new term
                $('#hcg').select2('close'); // close the dropdown


            });
        });



        $('.deleteoption').on('change', function () {
            var thisvalue = $(this).val();
            var selectTableName = $(this).attr('select-tablename');
            var selectId = $(this).attr('id'); // the value of attr id of the select

            if (thisvalue == '-2') {
                $(this).select2('val', '');
                $.post(hosturl + '/controllers/monitoring.php?ac=editselect', {selectTableName: selectTableName, selectId: selectId}, function (data) {
                    $("#alldatadiv").html('');
                    $("#alldatadiv").html(data);
                    //     $("#edit_model").modal('show');
                    $('#edit_model').modal({keyboard: true});
                });
            }

        });
        $('body').on('click', '.delItem', function () {
            var id = $(this).attr('data-id');
            var selectTableName = $(this).attr('select-tablename');
            var selectId = $(this).attr('select-selectId');
            var xx = $(this).parent().parent();
            $.post(hosturl + '/controllers/monitoring.php?ac=update', {id: id, value: 1, tableName: selectTableName,
                colName: 'deleted'}, function (res) {
                xx.remove();
                $("#" + selectId + " option[value='" + id + "']").remove();
            });
        });
        // var ids = ["procedure", "ejac", "pesa", "tese", "sryo", "protocol", "hmg", "agonist"];

        $(document).ready(function (e) {
            $('.visitdateAll').trigger('change');
        });



        $('body').on('click', '#monitorAadd', function () {

            var monitorSheetId = $('#monitorSheetId').val();
            $.post(hosturl + '/controllers/monitoring.php?ac=addNewVisit', {monitorSheetId: monitorSheetId}, function (res) {
                console.log(res);
                if (res != -1)
                {
                    $('#monitorAaddDiv').prepend(res);
                    $('.visitdateAll').trigger('change');
                }
            });
        });


        $('body').on('change', '.visitdate', function () {
            var id = $(this).attr('data-id');
            var startDate = new Date($('#startDate').val());

            if (startDate > new Date($(this).val()))
            {
                $("#visitdate" + Number(id)).css("background-color", "red");
                $("#visitdateCycle" + Number(id)).css("background-color", "red");
                $("#visitdateCycle" + Number(id)).html("!");
            } else {
                $.post(hosturl + '/controllers/monitoring.php?ac=getCycleDay', {id: id}, function (res) {
                    var obj = JSON.parse(res);
                    $("#visitdateCycle" + Number(obj.id)).css("background-color", "white");
                    $("#visitdate" + Number(obj.id)).css("background-color", "white");
                    $("#visitdateCycle" + Number(obj.id)).html('');
                    $("#visitdateCycle" + Number(obj.id)).html(obj.cycleDay);
                });
            }





        });


        $('body').on('change', '.visitdateAll', function () {
            var startDate = new Date($(this).val());

            $('.visitdate').each(function () {
                var id = $(this).attr('data-id');
                if (startDate > new Date($(this).val()))
                {
                    $("#visitdate" + Number(id)).css("background-color", "red");
                    $("#visitdateCycle" + Number(id)).css("background-color", "red");
                    $("#visitdateCycle" + Number(id)).html("!");
                } else {
                    $.post(hosturl + '/controllers/monitoring.php?ac=getCycleDay', {id: id}, function (res) {
                        var obj = JSON.parse(res);
                        $("#visitdateCycle" + Number(obj.id)).css("background-color", "white");
                        $("#visitdate" + Number(obj.id)).css("background-color", "white");
                        $("#visitdateCycle" + Number(obj.id)).html('');
                        $("#visitdateCycle" + Number(obj.id)).html(obj.cycleDay);
                    });
                }
            });
        });


        $('body').on('click', '#remarkSheet', function () {
            var monitorSheetId = $('#monitorSheetId').val();
            $.post(hosturl + '/controllers/monitoring.php?ac=remarkSheet', {monitorSheetId: monitorSheetId}, function (res) {
                var obj = JSON.parse(res);
                console.log(obj);
                if (res != -1)
                {
                    //         $("#remarkModel").modal('show');
                    $('#remarkModel').modal({keyboard: true});
                }
            });
        });


        $('body').on('click', '#trigMonitorSheet', function () {
            var monitorSheetId = $('#monitorSheetId').val();
            var patientId = $('#patientId').val();
            $.post(hosturl + '/controllers/monitoring.php?ac=trigSheet', {monitorSheetId: monitorSheetId}, function (res) {
                if (res != -1)
                {
                    window.location = hosturl + "/controllers/monitoring.php?ac=trials&patientid=" + patientId;
                }
            });

        });
    };

    var addpresenthistory = function () {
        $('body').on('click', '#question_add', function () {
            $.post(hosturl + '/controllers/addpresenthistory.php?ac=Addnew', {questionId: 0}, function (res) {
                $('#question').append('<tr><td><input type="text" class="form-control updateElement invCatName" id="cat' + res + '" data-id="' + res + '" data-colName="name" data-tableName="presenthistoryquestions"/></td>'
                        + '<td><a class="btn green btn-xs showInv" data-id="' + res + '" style=" float: left;" href="#" ><i class="fa fa-pencil"></i>Show </a></td>'
                        + '<td><a class="btn grey-cascade btn-xs editCat" data-id="' + res + '" style=" float: left;" href="#" ><i class="fa fa-pencil"></i> </a></td>'
                        + '<td><a class="btn grey-cascade btn-xs deletemsgEX" data-id="' + res + '" style=" float: left;" href="#" data-link="addpresenthistory" data-fn="del" data-tableName="presenthistoryquestions"><i class="fa fa-close"></i></a></td>'
                        + '</tr>');
                $('#cat' + res).focus();
            });
        });
        $('body').on('click', '#answer_add', function () {
            var questionId = $('#questionId').val();
            $.post(hosturl + '/controllers/addpresenthistory.php?ac=Addnew', {questionId: questionId}, function (res) {
                $('#showAnswers').append('<tr><td><input type="text" class="form-control updateElement invName" id="inv' + res + '" data-id="' + res + '" data-colName="name" data-tableName="presenthistoryanswers"/></td>'
                        + '<td><div class="md-checkbox">'
                        + '<input type="checkbox" id="checkbox' + res + '" data-id="' + res + '"  class="md-check addFavorite">'
                        + '<label for="checkbox' + res + '"><span></span><span class="check"></span><span class="box"></span> </label>'
                        + '</div></td>'
                        + '<td><a class="btn grey-cascade btn-xs editInv" data-id="' + res + '" style=" float: left;" href="#" ><i class="fa fa-pencil"></i> </a></td>'
                        + '<td><a class="btn grey-cascade btn-xs deletemsgEX" data-id="' + res + '" style=" float: left;" href="#" data-link="addpresenthistory" data-fn="del" data-tableName="presenthistoryanswers"><i class="fa fa-close"></i></a></td>'
                        + '</tr>');
                $('#inv' + res).focus();
            });
        });
        $('body').on('click', '.editCat', function () {
            var id = $(this).attr("data-id");
            $('#cat' + id).removeAttr('disabled');
            $('#cat' + id).focus();
        });
        $('body').on('click', '.editInv', function () {
            var id = $(this).attr("data-id");
            $('#inv' + id).removeAttr('disabled');
            $('#inv' + id).focus();
        });
        $('body').on('blur', '.invCatName', function () {
            $(this).attr("disabled", true);
        });
        $('body').on('blur', '.invName', function () {
            $(this).attr("disabled", true);
        });
        $('body').on('click', '.addFavorite', function () {
            var answerId = $(this).attr("data-id");
            var check = $('#checkbox' + answerId).is(":checked")
            var value = 0;
            if (check == true) {
                value = 1;
            }
            $.post(hosturl + '/controllers/addpresenthistory.php?ac=addtofavorite', {
                answerId: answerId,
                value: value
            }, function (res) {
            });
        });
        $('body').on('click', '.showInv', function () {
            var questionId = $(this).attr("data-id");
            $('#questionId').val(questionId);
            $.post(hosturl + '/controllers/addpresenthistory.php?ac=getbyquesid', {questionId: questionId}, function (res) {
                $('#showAnswers').html(res);
                //      $("#answersModel").modal('show');
                $('#answersModel').modal({keyboard: true});
            });
        });
    };

    var patientPH = function () {
        $('body').on('click', '#addph', function () {
            var controller = $(this).attr('data-controller');
            var patientId = $('#patientId').val();

            $.post(hosturl + '/controllers/' + controller + '.php?ac=addphmodel', function (res) {
                $("#modalShow").html("");
                $("#modalShow").html(res);
                //      $("#addPatientPH").modal('show');
                $('#addPatientPH').modal({keyboard: true});
                $('#pIdph').val(patientId);
            });


        });

        $('body').on('click', '#showph', function () {
            var controller = $(this).attr('data-controller');
            var archive = $(this).attr('data-archive');
            var patientId = $('#patientId').val();
            $.post(hosturl + '/controllers/' + controller + '.php?ac=showphs', {
                patientId: patientId,
                archive: archive
            }, function (res) {
                $("#showPHDiv").html("");
                $("#showPHDiv").html(res);
                //  $("#showPatientPH").modal('show');
                $('#showPatientPH').modal({keyboard: true});
            });
        });

        $('body').on('click', '.printph', function () {
            var controller = $(this).attr('data-controller');
            var print = $(this).attr('data-print');
            $.post(hosturl + '/controllers/' + controller + '.php?ac=addph', $('#phform').serialize(), function (res) {
                if (print == 1) {
                    $("#inv_div").html(res);
                    $.print("#inv_div");
                }

                $("#inv_div").html("");
                $('.iiin').each(function () {
                    $(this).removeAttr('checked');
                    if ($(this).parent().attr("class") === 'checked') {
                        $(this).parent().attr("class", '')
                    }
                });
                $('#addPatientPH').modal('hide');
            });
        });

        $('body').on('change', '.checkGroup', function () {
            var groupClass = $(this).attr('data-gClass');
            if ($(this).is(":checked")) {
                $('.' + groupClass).attr('checked', true);
                $('.' + groupClass).parent().addClass('checked');
            } else {
                $('.' + groupClass).removeAttr('checked');
                $('.' + groupClass).parent().removeClass('checked');
            }
        });

        $('body').on('change', '.checkParent', function () {
            var parent = $(this).attr('data-parent');

            if ($(this).is(":checked")) {
                $('#catId' + parent).attr('checked', true);
                $('#catId' + parent).parent().addClass('checked');
            }
        });


        $('body').on('click', '.printphShow', function () {
            var controller = $(this).attr('data-controller');
            var date = $(this).attr('data-date');
            var patientId = $('#patientId').val();

            $.post(hosturl + '/controllers/' + controller + '.php?ac=printPh', {
                date: date,
                patientId: patientId,
            }, function (res) {
                $("#PH_divShow").html(res);
                $.print("#PH_divShow");
                $("#PH_divShow").html("");
            });
        });
    };

    var setting = function () {
        $('body').on('change', '#past', function () {
            if ($(this).is(":checked")) {
                $('#medical').attr('checked', true);
                $('#medical').parent().addClass('checked');

                $('#surgical').attr('checked', true);
                $('#surgical').parent().addClass('checked');

                $('#gynecological').attr('checked', true);
                $('#gynecological').parent().addClass('checked');

                $('#art').attr('checked', true);
                $('#art').parent().addClass('checked');
            } else {
                $('#medical').removeAttr('checked');
                $('#medical').parent().removeClass('checked');

                $('#surgical').removeAttr('checked');
                $('#surgical').parent().removeClass('checked');

                $('#gynecological').removeAttr('checked');
                $('#gynecological').parent().removeClass('checked');

                $('#art').removeAttr('checked');
                $('#art').parent().removeClass('checked');
            }
        });

        $('body').on('change', '#medical , #surgical, #gynecological ,#art', function () {
            if (!$('#medical').is(":checked") && !$('#surgical').is(":checked") && !$('#gynecological').is(":checked") && !$('#art').is(":checked")) {
                $('#past').removeAttr('checked');
                $('#past').parent().removeClass('checked');
            }
        });
    };

    var patientInfertility = function () {



        $('body').on('click', '#addInf', function () {

            var controller = $('#controllName').val();
            var patientId = $('#patientId').val();

            $.post(hosturl + '/controllers/' + controller + '.php?ac=getInfdata', {patientId: patientId}, function (data) {
                $('#infertilityModal').html('');
                $('#infertilityModal').html(data);
                $('#infertilityModal').modal({keyboard: true});

                $('.datepicker').datepicker();
                //here will open from
                $("#type").select2({
                    placeholder: "Select",
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        return "<input class='form-control' id='newTerm_type' value='" + term + "'><a href='#' id='addNew_type' class='btn blue custombtnstyle'>إضافة جديد</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNew_type', function () {
                    /* add the new term */
                    var doctorname = $('#newTerm_type').val();
                    var hosturl = $('#hosturl').val();

                    $.post(hosturl + "/controllers/gyna.php?ac=addnewrecord", {
                        colname: 'type',
                        doctorname: doctorname,
                        inline: patientId
                    }, function (data) {
                        $('#type > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + doctorname + '</option>');

                        $('#type').select2('val', Number(data)); // select the new term
                        $("#type").select2('close'); // close the dropdown
                    });
                });

            });
        });

        $('body').on('change', '.editModelSel', function () {

            var selectId = $(this).attr('id');
            var value = $(this).val();
            var colname = $(this).attr('data-colName');

            if (value == 0) {
                $.post(hosturl + '/controllers/gyna.php?ac=getalldata', {colname: colname, selectId: selectId}, function (data) {
                    $("#" + selectId).select2("val", "");
                    $('#editModal').html(data);
                    $('#editModal').modal('show');
                });
            }
        });

        $('body').on('click', '#addPlan', function () {

            var controller = $('#controllName').val();
            var patientId = $('#patientId').val();
            var itr = Number($('#planItr').val())
            var newItr = itr + 1;
            $('#planItr').val(newItr)


            $.post(hosturl + '/controllers/' + controller + '.php?ac=addnewplan', {newItr: newItr, patientId: patientId}, function (data) {
                $('#planTable').append(data);
            });
        });



    };

    $('body').on('keyup', '.searchPat', function () {
        var search = $('#statusNo').val();
        var controllName = $("#controllName").val();
        $.post(hosturl + '/controllers/visits.php?ac=searchpatient', {search: search}, function (res) {
            console.log(res);
            if (controllName == 'financialreport') {
                $('#patientName').select2("val", res).trigger("change");
            } else {
//                $('#patientvisitid').select2("val", res).trigger("change");
            }

        });
    });

    return {
        //main function to initiate the module
        init: function () {
            forAll();
            patientDrug();
            patientInv();
            patientUs();
            patientPH();
            if ($('#controllName').val() == "addinvestigation")
            {
                addInvestigation();
            }
            if ($('#controllName').val() == "addpresenthistory")
            {
                addpresenthistory();
            }
            setting();
            instruction();
            menu();
            members();
            getdata();
            merge();
            minSelectInput();
            visits();
            followupcard();
            fullReport();
            transfer();
            patientInfertility();
            if ($('#controllName').val() == "monitoring")
            {
                monitoring();
            }
        }

    };
}();
