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');
                        }

                    });
                }


            });
        });

        $('body').on('change', '.updateElementCheck', 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 ischecked = $(this).is(':checked');

            if (!ischecked) {
                value = 0;
            }

            $.post(hosturl + '/controllers/' + controllName + '.php?ac=updateajax', {
                id: id, patientId: patientId,
                value: value,
                tableName: tableName,
                colName: colName
            }, function (res) {
                console.log(res);

                if (tableName == 'op_4d_list' && (colName == 't1' || colName == 't2')) {
                    $('#search4DV').trigger("click");
                }
            });

        });


        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
            });

            $(".select2h").select2();

            if ($('#controllname').val() == 'operations') {
                $('#searchOpV').trigger("click");
            }

            if ($('#cardStatusNo').val() > 0) {
                var statusNo = $('#cardStatusNo').val();
                //      $('#statusNoRemote').val(statusNo);
                $('#patientvisitidNo').val(statusNo);

                //   $('.searchPatRemote ').trigger('keyup');
                $('#patientvisitidNo ').trigger('change');
            }

        });
        $('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');
        });


        $('.show_period_his').live('click', function () {
            var period = $(this).attr('data-no');
            if (period == 0) {
                $('.vi_all').show();
            } else {
                $('.vi_all').hide();
                $('.period_for_' + period).show();
            }

            //       $('#select_filter_visit').val(period);
        });


        if ($('#indexLoad').val() == 1) {
            var period = $('#select_filter_period').val();
            var branch = $('#select_filter_branch').val();

            onlyShow(branch, period);
        }


        $('.show_branch_his').live('click', function () {
            var branch = $(this).attr('data-no');
            var period = 0;

            $('#select_filter_period').val(period);
            $('#select_filter_branch').val(branch);

            onlyShow(branch, period);
        });

        $('.show_period_his').live('click', function () {
            var period = $(this).attr('data-no');
            var branch = $('#select_filter_branch').val();

            $('#select_filter_period').val(period);
            $('#select_filter_branch').val(branch);

            onlyShow(branch, period);
        });



        function onlyShow(branch, period) {

            if (branch == 0 && period == 0) {
                $('.vi_all').show();
                numSpan('vi_all');

            } else if (period == 0 && branch > 0) {
                $('.vi_all').hide();
                numSpan('branch_for_' + branch);
                $('.branch_for_' + branch).show();

            } else if (branch == 0 && period > 0) {
                $('.vi_all').hide();
                numSpan('period_for_' + period);
                $('.period_for_' + period).show();

            } else if (branch > 0 && period > 0) {
                $('.vi_all').hide();
                numSpan('common_' + branch + '_' + period);
                $('.common_' + branch + '_' + period).show();
            }
        }


        function numSpan($className) {
            var i = 1;
            $('.' + $className).each(function () {
                $(this).find('.numSpan').html(i);
                i++;
            });
        }

        $('.timepicker-10').timepicker({
            autoclose: true,
            minuteStep: 10,
            showSeconds: false,
            showMeridian: false,
            //   defaultTime: null
        });

        $('.dnameSelect').select2({
//   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                // var itr = $(this).attr("data-itr");
                return "<input class='form-control' id='newdnameSelectTerm' value='" + term + "'><a href='#' id='addNewdnameSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewdnameSelect', function () {
            /* add the new term */
            var dnameSelect = $('#newdnameSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/patienthistory.php?ac=addRow", {value: dnameSelect, table: 'drugname'}, function (data) {

                $('.dnameSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + dnameSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.dnameSelect').select2('close'); // close the dropdown
            });
        });

        $('.dtypeSelect').select2({
//   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                // var itr = $(this).attr("data-itr");
                return "<input class='form-control' id='newdtypeSelectTerm' value='" + term + "'><a href='#' id='addNewdtypeSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewdtypeSelect', function () {
            /* add the new term */
            var dtypeSelect = $('#newdtypeSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/patienthistory.php?ac=addRow", {value: dtypeSelect, table: 'drugtype'}, function (data) {

                $('.dtypeSelect > .deleteoptincompo').before('<option value="' + dtypeSelect + '" >' + dtypeSelect + '</option>');
                $('#' + thisId + '').select2('val', dtypeSelect).trigger("change"); // select the new term
                $('.dtypeSelect').select2('close'); // close the dropdown
            });
        });


        $(".ddosSelect").select2({
//   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                // var itr = $(this).attr("data-itr");
                return "<input class='form-control' id='newddosSelectTerm' value='" + term + "'><a href='#' id='addNewddosSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewddosSelect', function () {
            /* add the new term */
            var ddosSelect = $('#newddosSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/patienthistory.php?ac=addRow", {value: ddosSelect, table: 'drugDos'}, function (data) {

                $('.ddosSelect > .deleteoptincompo').before('<option value="' + ddosSelect + '" >' + ddosSelect + '</option>');
                $('#' + thisId + '').select2('val', ddosSelect).trigger("change"); // select the new term
                $('.ddosSelect').select2('close'); // close the dropdown
            });
        });

    };
    var patientDrug = function () {

        $('.all').on('click', '#addDrugModal', function () {

            var controller = $(this).attr('data-controller');
            var patientId = $('#patientId').val();
            var mainAntenatalId = $('#mainAntenatalId').val();
            var followid = $('#followId').val();
            var preDate = $(this).attr('data-date');
            $.post(hosturl + '/controllers/' + controller + '.php?ac=loadDrugModal', {
                patientId: patientId,
                mainAntenatalId: mainAntenatalId,
                followid: followid
            }, function (res) {

                $("#gynaDrugs").html('');
                $("#gynaDrugs").html(res);
                $('.select2me').select2();
                if ($('#drugItr').val() == 0) {
                    $("#addNewDrugRow").trigger('click');
                }

                $('#addPatientDrugs').modal({keyboard: true});
            });
        });

        $('.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();
            var old = $(this).attr('data-old');
            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,
                    old: old,
                    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,
                    old: old,
                    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');
            var old = $(this).attr('data-old');

            $.post(hosturl + '/controllers/' + controller + '.php?ac=showprescription', {
                preFor: preFor,
                patientId: patientId,
                preDate: preDate,
                type: "edit",
                old: old,
                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');
            var old = $(this).attr('data-old');
            $.post(hosturl + '/controllers/' + controller + '.php?ac=showprescription', {
                patientId: patientId,
                old: old,
                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();
            var old = $(this).attr('data-old');

            $.post(hosturl + '/controllers/' + controller + '.php?ac=showInvs', {
                patientId: patientId,
                mainAntenatalId: mainAntenatalId,
                old: old,
                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', '.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();
            var old = $(this).attr('data-old');

            $.post(hosturl + '/controllers/' + controller + '.php?ac=printinv', {
                date: date,
                patientId: patientId,
                mainAntenatalId: mainAntenatalId,
                old: old,
                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();
            $('#visitaddsubmit').hide();
            $('.editVisit').hide();
            $('.deletevisit').hide();
            row.css('background-color', '#f36a5a');
            $('#patientEditDiv').show();
            $.post(hosturl + '/controllers/visits.php?ac=editvisit', {visitId: visitId}, function (res) {
                if (Number(res) == -1) {
                    $('#visitaddsubmit').show();
                    $('#invType').attr("disabled", false);
                    reloadVisits();
                } else {
                    var obj = JSON.parse(res);
                    $('#patientvisitid').select2("val", obj.patientid);
                    $('#visitdate').val(obj.visitdate);
                    if (obj.detectionid > 0) {
                        $('#detectionid').select2("val", obj.detectionid);
                    }

                    if (obj.visit_period > 0) {
                        $('#visit_period').select2("val", obj.visit_period).trigger('change');
                    }

                    $('#totaldetectionvalue').val(obj.totaldetectionvalue);
                    $('#discount').val(obj.discount);
                    $('#detectionvalue_visa').val(obj.detectionvalue_visa);
                    $('#detectionvalue_cash').val(obj.detectionvalue_cash);
                    $('#restdetectionvalue').val(obj.restdetectionvalue);
                    $('#notes').val(obj.notes);
                    $('#approx_time').val(obj.approx_time);
                    if (obj.payedflag == 1) {
                        $('#payVisit').attr('checked', 'checked');
                        $('#payVisit').parent().addClass('checked');
                    }

                    if (obj.urgent == 1) {
                        $('#urgent').attr('checked', 'checked');
                        $('#urgent').parent().addClass('checked');
                    }

                    if (obj.patient_edit == 1) {
                        $('#patient_edit').attr('checked', 'checked');
                        $('#patient_edit').parent().addClass('checked');
                    }

                }

                $('#saveEditVisit').attr("data-visitId", visitId);
                $('#mVisitId').val(visitId);
                $('#editView').val(1);
                $('#saveEditVisit').show();
                $('#cancelEditVisit').show();
            });
        });
        $('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 cash = $('#detectionvalue_cash').val();
            var printserial = $('#printserial').val();
            $.post(hosturl + '/controllers/visits.php?ac=updatevisit', $("#myvisitform").serialize(), function (data) {
                $('#patientEditDiv').hide();

                if (cash > 0 && printserial == 1) {
                    $.post(hosturl + '/controllers/visits.php?ac=printvisitrecept', {
                        visitId: Number(data)
                    }, function (res) {
//                                console.log(res1);
                        $("#printRDiv").html(res);
                        $.print("#printRDiv");
                        $("#printRDiv").html("");
                    });
                }


                var date_from = $('#date_from').val();
                var date_to = $('#date_to').val();
                var patientId = $('#patientIdRemote').val();
                $.post(hosturl + '/controllers/visits.php?ac=reloadVisits', {date_from: date_from, date_to: date_to, patientId: patientId}, function (res) {
                    $('#visitNew').html(res);
                    $('#visitaddsubmit').show();
                    $('#saveEditVisit').hide();
                    $('#cancelEditVisit').hide();
                    $('#mVisitId').val(0);
                    $('#editView').val(0);
                    $("#patientvisitid").select2("val", "");
                    $("#detectionid").select2("val", "");
                    $('#visit_period').select2().trigger('change');
                    $("#detectionvalue_cash").val(0);
                    $("#detectionvalue_visa").val(0);
                    $("#restdetectionvalue").val(0);
                    $("#totaldetectionvalue").val(0);
                    $("#discount").val(0);
                    $('#notes').val('');
                    $('#urgent').removeAttr('checked');
                    $('#urgent').parent().removeClass('checked');
                    $('#patient_edit').removeAttr('checked');
                    $('#patient_edit').parent().removeClass('checked');
                });
            });
        });
        $('body').on('click', '.cancelEditVisit', function () {
            $('#patientEditDiv').hide();
            var date_from = $('#date_from').val();
            var date_to = $('#date_to').val();
            var patientId = $('#patientIdRemote').val();
            $.post(hosturl + '/controllers/visits.php?ac=reloadVisits', {date_from: date_from, date_to: date_to, patientId: patientId}, function (res) {
                $('#visitNew').html(res);
                $('#visitaddsubmit').show();
                $('#saveEditVisit').hide();
                $('#cancelEditVisit').hide();
                $('#mVisitId').val(0);
                $('#editView').val(0);
                $("#patientvisitid").select2("val", "");
                $("#detectionid").select2("val", "");
                $('#visit_period').select2().trigger('change');
                $("#detectionvalue_cash").val(0);
                $("#detectionvalue_visa").val(0);
                $("#restdetectionvalue").val(0);
                $("#totaldetectionvalue").val(0);
                $("#discount").val(0);
                $('#notes').val('');
                $('#urgent').removeAttr('checked');
                $('#urgent').parent().removeClass('checked');
                $('#patient_edit').removeAttr('checked');
                $('#patient_edit').parent().removeClass('checked');
            });
        });
        //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');
            }
        });
        //######################  heba : visit visa , cash , discount paying ##############

        $('#visit_period').on('change', function () {
            var value = $('#visit_period').val();
            if (value == '-2') {
                $.post(hosturl + '/controllers/visits.php?ac=visitPeriodEdit', function (data) {
                    $('#visit_period').select2("val", "");
                    $("#editModalDiv").html(data);
                    $("#edit_model").modal('show');
                });
            }

        });
        $('body').on('keyup change', '.detectionvalue', function () {
            var total = Number($('#totaldetectionvalue').val());
            var paid_cash = Number($('#detectionvalue_cash').val());
            var paid_visa = Number($('#detectionvalue_visa').val());
            var rest = Number($('#restdetectionvalue').val());
            var discount = 0;
            var discountType = $('input[name="discountType"]:checked').val();
            if (discountType == 1) {
                var discountRatio = Number($('#discount').val());
                discount = total * (discountRatio / 100);
            } else {
                discount = Number($('#discount').val());
            }

            var paid = paid_cash + paid_visa;
            total = total - discount;
            if (paid > total) {
                switch ($(this).attr('id')) {

                    case 'totaldetectionvalue':
                        $('#detectionvalue_cash').val(total);
                        $('#detectionvalue_visa').val(0);
                        break;
                    case 'detectionvalue_cash':
                        $('#detectionvalue_visa').val(total - paid_cash);
                        break;
                    case 'detectionvalue_visa':
                        $('#detectionvalue_cash').val(total - paid_visa);
                        break;
                }

            }

            if (paid_cash > total) {
                $('#detectionvalue_cash').val(total);
                $('#detectionvalue_visa').val(0);
            }

            if (paid_visa > total) {
                $('#detectionvalue_cash').val(0);
                $('#detectionvalue_visa').val(total);
            }

            paid_cash = Number($('#detectionvalue_cash').val());
            paid_visa = Number($('#detectionvalue_visa').val());
            paid = paid_cash + paid_visa;
            $('#restdetectionvalue').val(total - paid);
        });
        $('.newitemP').live('change', function (e) {
            var value = $(this).val();
            var id = $(this).attr("data-id");
            var colName = $(this).attr("data-colName");
            var tableName = $(this).attr("data-tableName");
            if (id > 0) {
                $.post(hosturl + '/controllers/visits.php?ac=updateAjax', {
                    tableName: tableName, colName: colName, id: id, value: value}, function (data) {
                    if (colName == "name") {
                        $('.' + tableName + '  option[value="' + id + '"]').text(value);
                    }
                });
            }
        });
        $('.deleteModalP').live('click', function () {
            var id = $(this).attr('data-id');
            var tableName = $(this).attr("data-tableName");
            var tr = $(this).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/visits.php?ac=updateAjax', {
                                tableName: tableName, colName: 'deleted', id: id, value: 1}, function (data) {
                                if (data == 1)
                                {
                                    tr.parent().remove();
                                    $('.' + tableName + ' option[value="' + id + '"]').remove();
                                } else
                                {
                                    alert("!!!!!!!!!!!!! some thing wrong here");
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $("#addnewPeriod").live('click', function () {
            var tableName = 'visit_periods';
            var colName = 'name';
            $.post(hosturl + "/controllers/visits.php?ac=addNewRow",
                    {tableName: tableName, colName: colName}, function (data) {

                var dataid = Number(data);
                if (dataid > 0) {

                    $('.' + tableName + ' > .deleteoptincompo').before('<option value="' + dataid + '" ></option>');
                    $("#editTableP").prepend('<tr>'
                            + '<td>'
                            + '<input type="text" class="form-control newitemP"     '
                            + 'data-id="' + dataid + '"  data-tableName="visit_periods"   '
                            + 'data-colName="name"   value="">    '
                            + '</td>'
                            + '<td>'
                            + '<input type="text" class="form-control newitemP"     '
                            + 'data-id="' + dataid + '"  data-tableName="visit_periods"   '
                            + 'data-colName="timing"   value="">    '
                            + '</td>'
                            + '<td>'
                            + '<input type="text" class="form-control newitemP positiveNo"     '
                            + 'data-id="' + dataid + '"  data-tableName="visit_periods"   '
                            + 'data-colName="max_no"   value="">    '
                            + '</td>'
                            + '<td>'
                            + '<a href="#" class="btn btn-xs red fleft deleteModalP wds100"       '
                            + ' data-id="' + dataid + '"   data-tableName="visit_periods"  >    '
                            + '<i class="fa fa-times" ></i>     </a>   '
                            + '</td>'
                            + ' </tr>'
                            );
                    $(".positiveNo").forcepositiveNum();
                }
            });
        });
        $('body').on('change', '#visit_period', function () {
            var periodId = $(this).val();
            var visitdate = $('#visitdate').val();
            if (periodId > 0) {
                $.post(hosturl + "/controllers/visits.php?ac=patPerPeriod",
                        {periodId: periodId, visitdate: visitdate}, function (data) {
                    $('#periodPatCount').val(data);
                });
            } else {
                $('#periodPatCount').val('');
            }
        });
        function reloadVisits()
        {
            var date_from = $('#date_from').val();
            var date_to = $('#date_to').val();
            var patientId = $('#patientIdRemote').val();
            var cardStatusNo = $('#cardStatusNo').val();
            $.post(hosturl + '/controllers/visits.php?ac=reloadVisits',
                    {date_from: date_from, date_to: date_to, patientId: patientId, cardStatusNo: cardStatusNo}, function (res) {
                $('#visitNew').html(res);
                $('#mVisitId').val(0);
            });
        }

        $('.deletevisitAjax').live('click', function () {
//check for edit

            var itemid = $(this).attr('data-id');
            //here will delete by ajax

            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/visits.php?ac=del', {id: itemid}, function (res) {
                                if (Number(res) == 1) {
                                    reloadVisits();
                                } else if (Number(res) == -1) {
                                    alert(' لابد من حذف مرتجعات العملاء المرتبطة بالزيارة أولا ');
                                } else {
                                    alert('خطأ  . لم يتم الحذف  !!!!!!!!!!!!!!!!');
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });


        $('.updatevisitAjax').live('click', function () {
//check for edit

            var itemid = $(this).attr('data-id');
            var date = $(this).attr('data-date');
            var tr = $(this).parent().parent();
            //here will delete by ajax


            if (date == 1) {
                var message = 'Do you want to update this item?';
                var label = 'Update';
                var title = 'Update confirmation';
                var className = 'bg-green';
            } else {
                var message = 'Do you want to delete this item?';
                var label = 'Delete';
                var title = 'Delete confirmation';
                var className = 'btn-danger';
            }

            bootbox.dialog({
                message: message,
                title: title,
                buttons: {
                    danger: {
                        label: "Cancel",
                        className: "btn-primary"
                    },
                    main: {
                        label: label,
                        className: className,
                        callback: function () {
                            $.post(hosturl + '/controllers/visits.php?ac=updateWaiting', {id: itemid, date: date}, function (res) {
                                if (Number(res) == 1) {
                                    tr.remove();
                                    reloadVisits();
                                } else {
                                    alert('خطأ  . لم يتم الحذف  !!!!!!!!!!!!!!!!');
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $(document).ready(function (e) {
            if ($('#addVisitControl').val() == 1)
            {
                $('#visit_period').select2().trigger('change');
                reloadVisits();
            }

            if ($('#visitPeriod').val() == 1) {
                $('#visit_period').select2().trigger('change');
            }
        });
        $("#showList").live('click', function () {
            $.post(hosturl + '/controllers/visits.php?ac=waitingList', function (data) {
                $("#waitingListDiv").html(data);
                $("#waitingListModel").modal('show');
            });
        });

        $('body').on('click', '.payVisitVal', function () {
            var visitId = $(this).attr('data-visitId');
            var patientId = $('#patientvisitid').val();
            var paid_cash = Number($('#payVal_cash' + visitId).val());
            var paid_visa = Number($('#payVal_visa' + visitId).val());
            var dept = Number($(this).attr('data-dept'));
            var paid = paid_cash + paid_visa;
            var restDiscount = Number($('#restDiscount' + visitId).val());
            var restNotes = $('#restNotes' + visitId).val();
            var deptRest = dept - restDiscount;
            if (paid > deptRest)
            {
                $('#res' + visitId).html(' المبلغ المراد دفعه أكبر من المبلغ المتبقى ');
            } else {
                $.post(hosturl + '/controllers/visits.php?ac=payval',
                        {
                            visitId: visitId, paid_cash: paid_cash, paid_visa: paid_visa
                            , patientId: patientId, restDiscount: restDiscount, restNotes: restNotes
                        }, function (res) {

                    if (paid_cash > 0) {
                        $('#printingDiv').html("");
                        $('#printingDiv').html(res);
                        $.print("#printingDiv");
                        $('#printingDiv').html("");
                    }

                    reloadVisits();
                    getLastVisit(patientId);
                    getRestDetectionVlues(patientId);
                });
            }
        });

        function getLastVisit(patientId)
        {
            $.post(hosturl + '/controllers/visits.php?ac=getlatestvisits', {
                patientId: patientId
            }, function (res) {
                if (res != -1) {
                    $('#lastVisitDetails').html('');
                    $('#lastVisitDetails').html(res);
                }
            });
        }

        function getRestDetectionVlues(patientId)
        {
            $.post(hosturl + '/controllers/visits.php?ac=getrestvalues', {patientId: patientId}, function (data) {

                if (Number(data) == -1) {
                    $('#restDiv').html('');
                } else {
                    $('#restDiv').html(data);
                    alert(' ملحوظة : يوجد مبالغ مستحقة  على المريض ');
                }
            });
        }

        $('body').on('click', '.refund', function () {
            var visitId = $(this).attr('data-visitId');
            var patientId = $('#patientvisitid').val();
            var refund_cash = Number($('#refundVal_cash' + visitId).val());
            var refund_visa = Number($('#refundVal_visa' + visitId).val());
            var notes = $('#notes' + visitId).val();
            var paid = Number($(this).attr('data-paid'));
            if (paid < (refund_cash + refund_visa))
            {
                $('#refund' + visitId).html(' المبلغ المراد إعادته  أكبر من المبلغ المدفوع بالزيارة  ');
            } else {
                bootbox.dialog({
                    message: "هل أنت متأكد من إعادة المبلغ ؟",
                    title: "تأكيد الإعادة  ",
                    buttons: {
                        danger: {
                            label: "إلغاء ",
                            className: "btn-primary"
                        },
                        main: {
                            label: "نعم ",
                            className: "btn-danger",
                            callback: function () {
                                //do something else
                                $.post(hosturl + '/controllers/visits.php?ac=refund', {visitId: visitId, refund_cash: refund_cash, refund_visa: refund_visa, patientId: patientId, notes: notes}, function (res) {
                                    if (Number(res) != -1) {

                                        if (refund_cash > 0) {
                                            $('#printingDiv').html("");
                                            $('#printingDiv').html(res);
                                            $.print("#printingDiv");
                                            $('#printingDiv').html("");
                                        }
                                        getLastVisit(patientId);
                                        getRest(patientId);
                                        reloadVisits();
                                    } else {
                                        $('#refund' + visitId).html(' حدث خطأ . حاول مرة أخرى   ');
                                    }
                                });
                            }
                        }
                    }
                }).find('.modal-content').addClass('modal-sm');
            }
        });
        $('body').on('click', '.editRefundVisit', function () {
            var visitId = $(this).attr("data-visitId");
            var row = $(this).parent().parent();
            $.post(hosturl + '/controllers/visits.php?ac=editrefundvisit', {visitId: visitId}, function (res) {
                var obj = JSON.parse(res);
                var newRow = ' ';
                newRow += '<td>' + row.find("td").eq(0).html() + '</td>'
                newRow += '<td>' + row.find("td").eq(1).html() + '</td>'
                newRow += '<td>' + row.find("td").eq(2).html() + '</td>'
                newRow += '<td>' + row.find("td").eq(3).html() + '</td>'


                newRow += '<td><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 positiveNo   edited" id="updatedCash' + visitId + '"  style="border: 1px solid #000000;border-radius: 4px;"  type="text"   value="' + obj.detectionvalue_cash + '" >'
                        + '<label for="form_control_1"  class="txtr">كاش</label>'
                        + '</div></div></td>';
                newRow += '<td><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  positiveNo  edited" id="updatedVisa' + visitId + '"  style="border: 1px solid #000000;border-radius: 4px;"  type="text"   value="' + obj.detectionvalue_visa + '" >'
                        + '<label for="form_control_1"  class="txtr">فيزا</label>'
                        + '</div></div></td>';
                newRow += '<td><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" id="updatedDate' + visitId + '"  style="border: 1px solid #000000;border-radius: 4px;"  type="text"   value="' + obj.visitdate + '" >'
                        + '<label for="form_control_1"  class="txtr">تاريخ الزيارة  </label>'
                        + '</div></div></td>';
                newRow += '<td colspan="2"><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  edited" id="updatedNotes' + visitId + '"   style="border: 1px solid #000000;border-radius: 4px;"  type="text"   value="' + obj.notes + '" >'
                        + '<label for="form_control_1"  class="txtr">ملاحظات</label>'
                        + '</div></div></td>';
                newRow += '<td><a class=" bg-green dltbtn  saveEditFVisit" data-visitId="' + visitId + '">حفظ </a></td>'
                newRow += '<td><a class=" bg-red dltbtn  cancelEditFVisit" data-visitId="' + visitId + '">إلغاء</a></td>'

                row.html(newRow);
                $(".datepicker").datepicker({
                    todayBtn: "linked",
                    autoclose: true,
                    todayHighlight: true,
                    format: 'yy/mm/dd',
                    isRTL: true
                });
                $(".positiveNo").forcepositiveNum();
            });
        });
        $('body').on('click', '.editPayValVisit', function () {
            var visitId = $(this).attr("data-visitId");
            var row = $(this).parent().parent();
            $.post(hosturl + '/controllers/visits.php?ac=editpayvalvisit', {visitId: visitId}, function (res) {
                var obj = JSON.parse(res);
                var newRow = ' ';
                newRow += '<td>' + row.find("td").eq(0).html() + '</td>'
                newRow += '<td>' + row.find("td").eq(1).html() + '</td>'
                newRow += '<td>' + row.find("td").eq(2).html() + '</td>'
                newRow += '<td>' + row.find("td").eq(3).html() + '</td>'


                newRow += '<td><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 positiveNo   edited" id="updatedPCash' + visitId + '"  style="border: 1px solid #000000;border-radius: 4px;"  type="text"   value="' + obj.detectionvalue_cash + '" >'
                        + '<label for="form_control_1"  class="txtr">كاش</label>'
                        + '</div></div></td>';
                newRow += '<td><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  positiveNo  edited" id="updatedPVisa' + visitId + '"  style="border: 1px solid #000000;border-radius: 4px;"  type="text"   value="' + obj.detectionvalue_visa + '" >'
                        + '<label for="form_control_1"  class="txtr">فيزا</label>'
                        + '</div></div></td>';
                newRow += '<td><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  positiveNo  edited" id="updatedPDiscount' + visitId + '"  style="border: 1px solid #000000;border-radius: 4px;"  type="text"   value="' + obj.discount + '" >'
                        + '<label for="form_control_1"  class="txtr">خصم</label>'
                        + '</div></div></td>';
                newRow += '<td><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" id="updatedPDate' + visitId + '"  style="border: 1px solid #000000;border-radius: 4px;"  type="text"   value="' + obj.visitdate + '" >'
                        + '<label for="form_control_1"  class="txtr">تاريخ الزيارة  </label>'
                        + '</div></div></td>';
                newRow += '<td><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  edited" id="updatedPNotes' + visitId + '"   style="border: 1px solid #000000;border-radius: 4px;"  type="text"   value="' + obj.notes + '" >'
                        + '<label for="form_control_1"  class="txtr">ملاحظات</label>'
                        + '</div></div></td>';
                newRow += '<td><a class=" bg-green dltbtn  saveEditPVisit" data-visitId="' + visitId + '">حفظ </a></td>'
                newRow += '<td><a class=" bg-red dltbtn  cancelEditFVisit" data-visitId="' + visitId + '">إلغاء</a></td>'

                row.html(newRow);
                $(".datepicker").datepicker({
                    todayBtn: "linked",
                    autoclose: true,
                    todayHighlight: true,
                    format: 'yy/mm/dd',
                    isRTL: true
                });
                $(".positiveNo").forcepositiveNum();
            });
        });
        $('body').on('click', '.cancelEditFVisit', function () {
            reloadVisits();
        });
        $('body').on('click', '.saveEditFVisit', function () {

            var visitId = $(this).attr("data-visitId");
            var printserial = $('#printserial').val();

            $.post(hosturl + '/controllers/visits.php?ac=updatefundvisit', {
                detectionvalue_cash: Number($('#updatedCash' + visitId).val()),
                detectionvalue_visa: Number($('#updatedVisa' + visitId).val()),
                visitdate: $('#updatedDate' + visitId).val(),
                visitId: visitId,
                notes: $('#updatedNotes' + visitId).val()
            }, function (data) {
                if (Number(data) == -3) {
                    alert(' المبلغ المراد إعادته  أكبر من المبلغ المدفوع بالزيارة  ');
                } else if (Number(data) == 1) {
                    reloadVisits();
                    if (Number($('#updatedCash' + visitId).val()) > 0 && printserial == 1) {
                        $.post(hosturl + '/controllers/visits.php?ac=printvisitrecept', {
                            visitId: visitId
                        }, function (res) {
                            console.log(res);
                            $("#printRDiv").html(res);
                            $.print("#printRDiv");
                            $("#printRDiv").html("");
                        });
                    }
                } else {
                    alert(' حدث خطأ . حاول مرة أخرى   ');
                }
            });
        });
        $('body').on('click', '.saveEditPVisit', function () {

            var visitId = $(this).attr("data-visitId");
            var printserial = $('#printserial').val();

            $.post(hosturl + '/controllers/visits.php?ac=updatepayvalvisit', {
                detectionvalue_cash: Number($('#updatedPCash' + visitId).val()),
                detectionvalue_visa: Number($('#updatedPVisa' + visitId).val()),
                discount: Number($('#updatedPDiscount' + visitId).val()),
                visitdate: $('#updatedPDate' + visitId).val(),
                visitId: visitId,
                notes: $('#updatedPNotes' + visitId).val()
            }, function (data) {
                if (Number(data) == -3) {
                    alert(' المبلغ  المدفوع   أكبر من المبلغ  المتبقى    ');
                } else if (Number(data) == 1) {
                    reloadVisits();
                    if (Number($('#updatedPCash' + visitId).val()) > 0 && printserial == 1) {
                        $.post(hosturl + '/controllers/visits.php?ac=printvisitrecept', {
                            visitId: visitId
                        }, function (res) {
                            console.log(res);
                            $("#printRDiv").html(res);
                            $.print("#printRDiv");
                            $("#printRDiv").html("");
                        });
                    }
                } else {
                    alert(' حدث خطأ . حاول مرة أخرى   ');
                }
            });
        });

        $('body').on('click', '.printVisitRecept', function () {

            var visitId = $(this).attr('data-visitId');

            $.post(hosturl + '/controllers/visits.php?ac=printvisitrecept', {
                visitId: visitId
            }, function (res) {
                console.log(res);
                $("#printRDiv").html(res);
                $.print("#printRDiv");
                $("#printRDiv").html("");
            });
        });
    };
    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 = $('#startDate').val();
            var endDate = $(this).val();
            if (new Date(startDate) > new Date(endDate)) {
                $("#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, endDate: endDate, startDate: startDate}, 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 = $(this).val();
            $('.visitdate').each(function () {
                var id = $(this).attr('data-id');
                var endDate = $(this).val();
                if (new Date(startDate) > new Date(endDate)) {
                    $("#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, endDate: endDate, startDate: startDate}, 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("");
            });
        });
        $('body').on('click', '#addPrevMarr', function () {
            var marrFor = $(this).attr('data-for');
            var patientId = $(this).attr('data-patientId');
            $.post(hosturl + '/controllers/patients.php?ac=addprevmarr', {marrFor: marrFor, patientId: patientId}, function (res) {
                $("#prevMarrContainer" + marrFor).append(res);
            });
        });
    };
    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');
                $('#art').trigger('change');
            } 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');
                $('#art').trigger('change');
            }
        });
        $('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');
            }
        });
        //#################################################

        $('body').on('change', '#art', function () {
            if ($(this).is(":checked")) {
                $('#art_internal').attr('checked', true);
                $('#art_internal').parent().addClass('checked');
                $('#art_external').attr('checked', true);
                $('#art_external').parent().addClass('checked');
            } else {
                $('#art_internal').removeAttr('checked');
                $('#art_internal').parent().removeClass('checked');
                $('#art_external').removeAttr('checked');
                $('#art_external').parent().removeClass('checked');
            }
        });
        $('body').on('change', '#art_internal , #art_external', function () {
            if (!$('#art_external').is(":checked") && !$('#art_internal').is(":checked")) {
                $('#art').removeAttr('checked');
                $('#art').parent().removeClass('checked');
                $('#art').trigger('change');
            }
        });
    };
    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");
            }

        });
    });

    var formatResultName = function (data) {
        return data.name;
    }

    function formatSelectionName(data) {
        return data.name;
    }

    $("#patientIdRemote , #patientvisitidW").select2({
        placeholder: "اختر ",
        minimumInputLength: 3,
        width: '100%',
        allowClear: true,
        quietMillis: 100,
        ajax: {
            url: hosturl + '/controllers/visits.php?ac=getnames',
            dataType: 'json',
            data: function (term, page) {

                return {
                    term: term, //search term
                    page_limit: 10 // page size
                };
            },
            results: function (data) {
                //     alert(data);
                return {results: data};
            }
        },
        formatResult: formatResultName,
        formatSelection: formatSelectionName,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {
                id: item[0],
                name: item[1]
            };
            callback(data);
        }
    });

    $('.searchPatRemote').live('keyup', function (e) {
        var statusNo = $('#statusNoRemote').val();

        if (statusNo != '') {
            $.post(hosturl + '/controllers/visits.php?ac=getnameswithstatus', {statusNo: statusNo}, function (res) {
                var obj = JSON.parse(res);
                $('#patientIdRemote').val(null).empty();
                var option = new Option(obj.name, obj.id, true, true);
                $("#patientIdRemote").append(option);
                $('#patientIdRemote').select2("val", obj.id).trigger("change").trigger('select2:select');
                //   $("#select2-chosen-1").html(obj.name);

                if (controllname == 'operations') {
                    $("#select2-chosen-2").html(obj.name);
                } else {
                    $("#select2-chosen-1").html(obj.name);
                }
            });
        } else {
            $('#patientIdRemote').val(null).empty().trigger("change");
        }
    });

    $('.searchPatVisit').live('keyup', function (e) {
        var statusNo = $('#statusNoVisit').val();
        var controllname = $('#controllname').val();

        if (statusNo != '') {
            $.post(hosturl + '/controllers/visits.php?ac=getnameswithstatus', {statusNo: statusNo}, function (res) {
                var obj = JSON.parse(res);
                $('#patientvisitidW').val(null).empty();
                var option = new Option(obj.name, obj.id, true, true);
                $("#patientvisitidW").append(option);
                $('#patientvisitidW').select2("val", obj.id).trigger("change").trigger('select2:select');
                $("#select2-chosen-1").html(obj.name);
            });
        } else {
            $('#patientvisitidW').val(null).empty().trigger("change");
        }
    });

    $('body').on('change', '#operationW , #placeW , #four_dW', function () {
        var celtable = $(this).attr("data-celtable");
        var selid = $(this).attr('id');
        var value = $(this).val();
        var newterm = $(this).attr('data-new');

        if ($.inArray('-1', value) > -1 || value == -1) {
            $("#" + selid + " option[value='-1']").prop("selected", false);
            $.post(hosturl + '/controllers/infertilitysheet.php?ac=getselectajax', {
                newterm: newterm, celtable: celtable}, function (data) {
                $('#' + selid + ' > .adddataselect').before('<option value="' + Number(data) + '" >' + newterm + '</option>');
                $('#' + selid + ' option[value="' + Number(data) + '"]').attr('selected', true);
                $("#" + selid + " option[value='']").prop("selected", false);
                $('#' + selid).trigger('change');
            });
        } else if (value == -2 || $.inArray('-2', value) > -1) {
            $.post(hosturl + '/controllers/operations.php?ac=getdataselect', {celtable: celtable}, function (result) {
                $("#" + selid + " option[value='-2']").prop("selected", false);
                $('#' + selid).trigger('change');

                $("#allgetdataselect").html(result);
                $("#getdataselect").modal('show');

            });
        }
    });

    $("#operationW").select2({
        allowClear: true,
        formatNoMatches: function (term) {
            $(this).attr("data-new", term);
            return "Not Found";
        }
    });

    $("#four_dW").select2({
        allowClear: true,
        formatNoMatches: function (term) {
            $(this).attr("data-new", term);
            return "Not Found";
        }
    });


    $("#addnewOperattion").live('click', function () {
        var tableName = $(this).attr("data-celtable");
        var colName = 'title';


        $.post(hosturl + "/controllers/visits.php?ac=addNewRow",
                {tableName: tableName, colName: colName}, function (data) {

            var dataid = Number(data);
            if (dataid > 0) {
                $('#' + tableName + 'W > .deleteselect').before('<option value="' + Number(data) + '" ></option>');

                $("#editTableO").prepend('<tr>'
                        + '<td>'
                        + '<input type="text" class="form-control"  name="title"    '
                        + 'data-id="' + dataid + '"   data-table="' + tableName + '"    value="">    '
                        + '</td>'
                        + '<td>'
                        + '<a href="#" class="btn btn-xs red fleft deleteselect wds100"       '
                        + ' data-id="' + dataid + '"   data-table="' + tableName + '"  >    '
                        + '<i class="fa fa-times" ></i>     </a>   '
                        + '</td>'
                        + ' </tr>'
                        );
            }
        });
    });


    $("#placeW").select2({
        allowClear: true,
        formatNoMatches: function (term) {
            return "<input class='form-control' id='newTermPlaceW'  "
                    + " value='" + term + "'><a href='#' id='addNewPlaceW'  "
                    + " class='btn blue custombtnstyle'>إضافة جديد</a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNewPlaceW', function () {
        /* add the new term */
        var new_name = $('#newTermPlaceW').val();
        $.post(hosturl + "/controllers/operations.php?ac=addnewrecord", {
            selectId: 'place',
            new_name: new_name
        }, function (data) {
            $('#placeW > .deleteselect').before('<option value="' + Number(data) + '" >' + new_name + '</option>');
            $('#placeW').select2('val', Number(data)); // select the new term
            //    $('#placeW option[value="' + Number(data) + '"]').attr('selected', true);
            $("#placeW").select2('close'); // close the dropdown

        });
    });

    $('body').on('click', '#saveNewOpV', function () {
        var patientid = $('#patientvisitidW').val();

        $('#saveNewOpV').attr('disabled', true);

        if (patientid > 0) {
            $("#operationW option[value='']").prop("selected", false);
            $.post(hosturl + '/controllers/operations.php?ac=addInList', $("#myvisitform").serialize(), function (data) {
                console.log(data);

                if (data && Number(data) != -1) {

                    var shortCutFunction = 'success';
                    var msg = 'تم الإضافة ........';
                    var title = 'Success';

                    toastr.options = {
                        closeButton: $('#closeButton').prop('checked'),
                        debug: $('#debugInfo').prop('checked'),
                        positionClass: $('#positionGroup input:checked').val() || 'toast-top-left',
                        onclick: null
                    };
                    var $toast = toastr[shortCutFunction](msg, title);

                    $("#operationW , #placeW").select2("val", "");
                    $("#statusNoVisit").val('').trigger("keyup");
                    $("#notes").val('');
                }

                searchOpVisits();
                $('#saveNewOpV').attr('disabled', false);
            });
        } else {
            $('#saveNewOpV').attr('disabled', false);
        }
    });

    $('body').on('click', '#searchOpV', function () {
        searchOpVisits();
    });

    function searchOpVisits() {
        var date_from = $('#date_from').val();
        var date_to = $('#date_to').val();
        var patientId = $('#patientIdRemote').val();

        $.post(hosturl + '/controllers/operations.php?ac=reloadOpVisits',
                {date_from: date_from, date_to: date_to, patientId: patientId}, function (data) {
            $('#visitNew').html(data);
            $('#mVisitId').val(0);
        });
    }

    $('body').on('click', '.editOpVisit', function () {
        var visitId = $(this).attr("data-visitId");
        var row = $(this).parent().parent();
        $('#saveNewOpV').hide();
        $('.editOpVisit').hide();
        row.css('background-color', '#f36a5a');

        $.post(hosturl + '/controllers/operations.php?ac=editvisit', {visitId: visitId}, function (res) {
            if (Number(res) == -1) {
                $('#saveNewOpV').show();
                searchOpVisits();
            } else {
                var obj = JSON.parse(res);
                $('#statusNoVisit').val(obj.statusno).trigger('keyup');
                $('#opdate').val(obj.opdate);
                $('#notes').val(obj.notes);
                if (obj.operation != '' && obj.operation != null) {
                    var operation = obj.operation.split(",");
                    if (operation.length > 0) {
                        $('#operationW').select2('val', operation);
                    }
                }
                if (obj.place > 0) {
                    $('#placeW').select2("val", obj.place);
                }
            }

            $('#saveEditOpV').attr("data-visitId", visitId);
            $('#mVisitId').val(visitId);
            $('#editView').val(1);
            $('#saveEditOpV').show();
            $('#cancelEditOpV').show();
        });
    });

    $('body').on('click', '#saveEditOpV', function () {
        $.post(hosturl + '/controllers/operations.php?ac=updatevisit', $("#myvisitform").serialize(), function (data) {
            $('#saveEditOpV').attr("data-visitId", 0);
            $('#saveNewOpV').show();
            $('#saveEditOpV').hide();
            $('#cancelEditOpV').hide();
            $('#mVisitId').val(0);
            $('#editView').val(0);
            $("#operationW , #placeW").select2("val", "");
            $("#statusNoVisit").val('').trigger("keyup");
            $("#notes").val('');
            searchOpVisits();
        });
    });

    $('body').on('click', '#cancelEditOpV', function () {
        searchOpVisits();
        $('#saveEditOpV').attr("data-visitId", 0);
        $('#saveNewOpV').show();
        $('#saveEditOpV').hide();
        $('#cancelEditOpV').hide();
        $('#mVisitId').val(0);
        $('#editView').val(0);
        $("#operationW , #placeW").select2("val", "");
        $("#statusNoVisit").val('').trigger("keyup");
        $("#notes").val('');
    });

    $('.deleteOpVisitAjax').live('click', function () {
//check for edit

        var itemid = $(this).attr('data-id');
        var link = $(this).attr('data-link');
        //here will delete by ajax

        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/operations.php?ac=del', {id: itemid, link: link}, function (res) {
                            if (Number(res) == 1) {
                                if (link == 'op_wait_list') {
                                    searchOpVisits();
                                } else if (link == 'op_4d_list') {
                                    search4DVisits();
                                }

                            } else {
                                alert('خطأ  . لم يتم الحذف  !!!!!!!!!!!!!!!!');
                            }
                        });
                    }
                }
            }
        }).find('.modal-content').addClass('modal-sm');
    });

//##################################################################

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

        var patientid = $('#patientvisitidW').val();

        $('#saveNew4DV').attr('disabled', true);

        if (patientid > 0) {
            $("#operationW option[value='']").prop("selected", false);
            $.post(hosturl + '/controllers/operations.php?ac=add4DList', $("#myvisitform").serialize(), function (data) {
                console.log(data);

                if (data && Number(data) != -1) {

                    var shortCutFunction = 'success';
                    var msg = 'تم الإضافة ........';
                    var title = 'Success';

                    toastr.options = {
                        closeButton: $('#closeButton').prop('checked'),
                        debug: $('#debugInfo').prop('checked'),
                        positionClass: $('#positionGroup input:checked').val() || 'toast-top-left',
                        onclick: null
                    };
                    var $toast = toastr[shortCutFunction](msg, title);

                    $("#four_dW , #placeW").select2("val", "");
                    $("#statusNoVisit").val('').trigger("keyup");
                    $("#notes").val('');
                } else if (Number(data) == -2) {
                    alert('No open ANC Sheet for this patient .');
                }

                search4DVisits();
                $('#saveNew4DV').attr('disabled', false);
            });
        } else {
            $('#saveNew4DV').attr('disabled', false);
        }
    });

    $('body').on('click', '#search4DV', function () {
        search4DVisits();
    });

    function search4DVisits() {
        var date_from = $('#date_from').val();
        var date_to = $('#date_to').val();
        var patientId = $('#patientIdRemote').val();

        $.post(hosturl + '/controllers/operations.php?ac=reload4DVisits',
                {date_from: date_from, date_to: date_to, patientId: patientId}, function (data) {
            $('#visitNew').html(data);
            $('#mVisitId').val(0);
        });
    }

    $('body').on('click', '.edit4DVisit', function () {
        var visitId = $(this).attr("data-visitId");
        var row = $(this).parent().parent();
        $('#saveNew4DV').hide();
        $('.edit4DVisit').hide();
        row.css('background-color', '#f36a5a');

        $.post(hosturl + '/controllers/operations.php?ac=editvisit4d', {visitId: visitId}, function (res) {
            if (Number(res) == -1) {
                $('#saveNew4DV').show();
                search4DVisits();
            } else {
                var obj = JSON.parse(res);
                $('#statusNoVisit').val(obj.statusno).trigger('keyup');
                $('#opdate').val(obj.opdate);
                $('#notes').val(obj.notes);
                if (obj.four_d != '' && obj.four_d != null) {
                    var four_d = obj.four_d.split(",");
                    if (four_d.length > 0) {
                        $('#four_dW').select2('val', four_d);
                    }
                }
                if (obj.place > 0) {
                    $('#placeW').select2("val", obj.place);
                }
            }

            $('#saveEdit4DV').attr("data-visitId", visitId);
            $('#mVisitId').val(visitId);
            $('#editView').val(1);
            $('#saveEdit4DV').show();
            $('#cancelEdit4DV').show();
        });
    });

    $('body').on('click', '#saveEdit4DV', function () {
        $.post(hosturl + '/controllers/operations.php?ac=updatevisit4d', $("#myvisitform").serialize(), function (data) {
            $('#saveEdit4DV').attr("data-visitId", 0);
            $('#saveNew4DV').show();
            $('#saveEdit4DV').hide();
            $('#cancelEdit4DV').hide();
            $('#mVisitId').val(0);
            $('#editView').val(0);
            $("#four_dW , #placeW").select2("val", "");
            $("#statusNoVisit").val('').trigger("keyup");
            $("#notes").val('');
            search4DVisits();
        });
    });

    $('body').on('click', '#cancelEdit4DV', function () {
        search4DVisits();
        $('#saveEdit4DV').attr("data-visitId", 0);
        $('#saveNew4DV').show();
        $('#saveEdit4DV').hide();
        $('#cancelEdit4DV').hide();
        $('#mVisitId').val(0);
        $('#editView').val(0);
        $("#four_dW , #placeW").select2("val", "");
        $("#statusNoVisit").val('').trigger("keyup");
        $("#notes").val('');
    });

    $('body').on('click', '.sendToVisits', function () {
        var visitId = $(this).attr("data-visitId");
        var btn = $(this);
        btn.hide();

        $.post(hosturl + '/controllers/operations.php?ac=sendToVisits', {visitId: visitId}, function (res) {
            if (res == 1) {
                var shortCutFunction = 'success';
                var msg = 'تم الإضافة ........';
                var title = 'Success';
            } else {
                var shortCutFunction = 'error';
                var msg = 'Try again .. something wrong happened';
                var title = 'Error';

            }
            toastr.options = {
                closeButton: $('#closeButton').prop('checked'),
                debug: $('#debugInfo').prop('checked'),
                positionClass: $('#positionGroup input:checked').val() || 'toast-top-right',
                onclick: null
            };
            var $toast = toastr[shortCutFunction](msg, title);

            btn.show();
        });
    });

    //##################################################################
    $('body').on('click', '#deviceAdd', function () {
        $.post(hosturl + '/controllers/adddevices.php?ac=addnewdevice', function (res) {

            $('#devicesContainer').append(res);
        });
    });

    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();
            }
        }

    };
}();
