var ant_gyna = function () {
    var hosturl = $('#hosturl').val();
    var drugArray = Array();
    var instructionArray = Array();


    var forAll = function () {

        $('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) {
                //alert(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', 'black');
                        }

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

                    });
                }


            });
        });


        jQuery.fn.forcepositiveNum = function () {

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

                    return false;
                });
            });
        }

        jQuery.fn.forcepositivefloat = function () {

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

                    return false;
                });
            });
        }


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

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

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

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

            $("#addPatientDrugs").modal('show');
        });

        $('body').on('click', '#addNewDrugRow', function () {
            var itr = $('#drugItr').val();
            var presDate = $('#presDate').val();
            var patientId = $('#patientId').val();
            var newItr = Number(itr) + 1;
            var preFor = 0;
            var tableName = $(this).attr("data-tableName");
            var mainAntenatalId = $('#mainAntenatalId').val();
            var followid = $('#followId').val();

            $('#drugItr').val(newItr);

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


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


        $('body').on('change', '#forHusband', function () {

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

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

            $.post(hosturl + '/controllers/' + controller + '.php?ac=showprescription', {
                preFor: preFor,
                patientId: patientId,
                preDate: preDate,
                type: "edit",
                mainAntenatalId: mainAntenatalId,
                followid: followid
            }, function (res) {
                $("#drugContent").html("");
                $("#drugContent").html(res);
            });


        });

        $('body').on('change', '#presDate', function () {
            var preDate = $(this).val();
            var patientId = $('#patientId').val();
            var mainAntenatalId = $('#mainAntenatalId').val();
            var followid = $('#followId').val();
            var preFor = 0;

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

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

            $.post(hosturl + '/controllers/' + controller + '.php?ac=showprescription', {
                preFor: preFor,
                patientId: patientId,
                preDate: preDate,
                type: "edit",
                mainAntenatalId: mainAntenatalId,
                followid: followid
            }, function (res) {
                $("#drugContent").html("");
                $("#drugContent").html(res);
            });
        });

        $('body').on('click', '.printPre', function () {
            var controller = $(this).attr('data-controller');
            var type = $(this).attr('data-type');
            var patientId = $('#patientId').val();
            var preFor = 0;
            var date = 0;
            var printDate = 0;

            var mainAntenatalId = $('#mainAntenatalId').val();
            var followid = $('#followId').val();
            if (type == 'add') {

                date = $('#presDate').val();
                printDate = $('#printDate').val();


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

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

                    $("#drugPrint").html(res);
                    //$.print("#drugPrint",{timeout: 75000});
                    $("#drugPrint").print({});
                    $("#drugPrint").html("");
                });
            } else {
                date = $(this).attr('data-date');
                preFor = $(this).attr('data-for');

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


            if ($('#preType').val() == 'edit') {
                $("#showDrugs").trigger('click');
            }
        });


        $('body').on('change', '.dcat', function () {
            var itr = $(this).attr('data-itr');
            var value = $(this).val();
            $.post(hosturl + '/controllers/gyna.php?ac=search', {value: value, type: "cat"}, function (res) {
                $('#dname' + itr).html(res);
                $('#dname' + itr).select2("val", "");
                $('#dtype' + itr).select2("val", "");
                $('#ddos' + itr).select2("val", "");
            });
        });


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

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

        });

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

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

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

        });


        $('body').on('click', '.editPre', function () {
            var patientId = $('#patientId').val();
            var mainAntenatalId = $('#mainAntenatalId').val();
            var followid = $('#followId').val();
            var preDate = $(this).attr('data-date');
            var preFor = $(this).attr('data-for');
            var controller = $(this).attr('data-controller');

            $.post(hosturl + '/controllers/' + controller + '.php?ac=showprescription', {
                preFor: preFor,
                patientId: patientId,
                preDate: preDate,
                type: "edit",
                mainAntenatalId: mainAntenatalId,
                followid: followid
            }, function (res) {
                $("#drugContent").html("");
                $("#drugContent").html(res);
                $('#presDate').val(preDate);
                if (preFor == 1) {
                    $('#forHusband').attr('checked', 'checked');
                    $('#forHusband').parent().addClass('checked');
                } else if (preFor == 0) {
                    $('#forHusband').removeAttr('checked');
                    $('#forHusband').parent().removeClass('checked');
                }
                $('#preType').val('edit');
                $("#addPatientDrugs").modal('show');
            });
        });


        $('body').on('click', '#showDrugs', function () {
            var controller = $(this).attr('data-controller');
            var patientId = $('#patientId').val();
            var mainAntenatalId = $('#mainAntenatalId').val();
            var followid = $('#followId').val();
            var archive = $(this).attr('data-archive');
            $.post(hosturl + '/controllers/' + controller + '.php?ac=showprescription', {
                patientId: patientId,
                type: "show",
                mainAntenatalId: mainAntenatalId,
                followid: followid,
                archive: archive
            }, function (res) {
                $("#showPrescriptions").html("");
                $("#showPrescriptions").html(res);
                $("#showPatientDrugs").modal('show');
            });
        });

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

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

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

            $.post(hosturl + '/controllers/' + controller + '.php?ac=showInvs', {
                patientId: patientId,
                mainAntenatalId: mainAntenatalId,
                archive: archive
            }, function (res) {
                $("#showInvs").html("");
                $("#showInvs").html(res);
                $("#showPatientInvestigation").modal('show');
            });

        });

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

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

            });
        });

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

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

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

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

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


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

    };

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

        });

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

        });

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


        });

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

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

        });

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

        });

        $('body').on('click', '#closemodel_arrange', function () {
            window.location = hosturl + "/controllers/_menu.php?ac=show";
        });

        $('body').on('change', '.displayOption', function () {
            if ($(this).val() == "image") {
                $('#iconDiv').hide();
                $('#imageDiv').show();
            } else if ($(this).val() == "icon") {
                $('#imageDiv').hide();
                $('#iconDiv').show();
            }
        });

        $('body').on('click', '#deleteBackground', function () {
            $('#backgroundImageValue').val(0);
            $('#backgroundImage').attr('src', '');
        });


    };

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

            } else {

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

        });

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

            if (position == 4 || position == 5) {
                $('#username').removeAttr('required');
                $('#password').removeAttr('required');
                $('#confirmpassword').removeAttr('required');
                $('#loginInfoDiv').hide();
            } else {
                $('#loginInfoDiv').show();
                $('#username').attr('required', true);
                $('#password').attr('required', true);
                $('#confirmpassword').attr('required', true);
            }

        });

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

    };

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

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

            $("#patientvisitidNo").select2({
                minimumInputLength: 1
            });

            $("#pName").select2({
                minimumInputLength: 3
            });

            $("#pNo").select2({
                minimumInputLength: 1
            });
        });
    };

    var visits = function () {
        $('body').on('click', '#addNewEndRecord', function () {
            var patientId = $('#patientId').val();
            $.post(hosturl + '/controllers/patients.php?ac=addendvisits', {patientId: patientId}, function (res) {
                res = Number(res);

                if ($('#showDoctor').val() == 1) {
                    $('#endReportsBody').prepend('<tr><td>'
                            + '<input type="text" class="form-control datepicker updateElementVisit" readonly="" data-colName="enddate" data-id="' + res + '"  data-tableName="endvisitreports" value="' + $('#today').val() + '"/>'
                            + '</td>'
                            + '<td>'
                            + '<textarea class="form-control updateElementVisit txtc" rows="2" data-id="' + res + '" data-colName="reason" data-tableName="endvisitreports" placeholder="Enter more text" data-toggle="popover" data-trigger="hover" data-placement="bottom" data-content=""></textarea>'
                            + '</td>'
                            + '<td>'
                            + '<textarea class="form-control updateElementVisit txtc" rows="2" data-id="' + res + '" data-colName="notes" data-tableName="endvisitreports" placeholder="Enter more text" data-toggle="popover" data-trigger="hover" data-placement="bottom" data-content=""></textarea>'
                            + '</td>'
                            + '<td>'
                            + $('#doctorName').val()
                            + '</td>'
                            + '</tr>'
                            );
                } else {


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

        });

        $('body').on('change', '.updateElementVisit', function () {
            var id = $(this).attr("data-id");
            var colName = $(this).attr("data-colName");
            var tableName = $(this).attr("data-tableName");
            var value = $(this).val();

            var dated;
            if ($(this).hasClass("datepicker")) {
                dated = 1;
            } else {
                dated = 0;
            }

            $.post(hosturl + '/controllers/patients.php?ac=endvisit', {
                id: id,
                value: value,
                tableName: tableName,
                colName: colName,
                dated: dated
            }, function (res) {
            });
        });

        $('body').on('click', '.emptyDeptVisit', function () {
            $('#talks-loading').show();
            var deptId = $(this).attr("data-id");
            $.post(hosturl + '/controllers/visits.php?ac=emptydeptvisit', {deptId: deptId}, function (res) {
                $('#talks-loading').hide();
            });
        });

        $('body').on('click', '.editVisit', function () {
            var visitId = $(this).attr("data-visitId");
            var row = $(this).parent().parent();
            $.post(hosturl + '/controllers/visits.php?ac=editvisit', {visitId: visitId}, function (res) {
                var obj = JSON.parse(res);
                var detection = '<div class="col-md-12">';

                if (obj.setting != 1) {
                    //detection += '<label for="form_control_1">نوع الكشف</label>';
                    //detection += '<div class="form-group  form-md-floating-label has-info" style="margin: 0 0 0 0;">';
                    detection += '<select  class="form-control newDetect " data-id="' + visitId + '"  data-getPrice="1"  placeholder="اختر نوع الكشف " id="newDetect' + visitId + '"   data-tableName="visits"  data-colName="detectionid">';

                } else {
                    detection += '<label for="form_control_1"> القسم</label>';
                    detection += '<div class="form-group  form-md-floating-label has-info" style="margin: 0 0 0 0;">';
                    detection += '<select  class="form-control newDetect " data-id="' + visitId + '"  data-getPrice="1"  placeholder="اختر القسم " id="newDetect' + visitId + '"   data-tableName="visits"  data-colName="detectionid">';

                }


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

                if (obj.setting != 1) {


                    row.find("td").eq(4).html('<div class="col-md-12">'
                            + '<div class="form-group form-md-line-input form-md-floating-label has-info" style="margin: 0 0 0 0;">'
                            + ' <input  class="form-control digitsOnly edited" style="border: 1px solid #000000;border-radius: 4px;"  type="text" id="newDetectVal' + visitId + '"   value="' + obj.detectionvalue + '">'
                            + '<label for="form_control_1"  class="txtr"> قيمة الكشف </label>'
                            + '</div></div>');
                } else {
                    row.find("td").eq(3).html(obj.husbandName);
                }
                row.find("td").eq(3).html(obj.husbandName);
                row.find("td").eq(5).html(detection);

//                row.find("td").eq(5).html('<div class="col-md-12">'
//                        + '<div class="form-group form-md-line-input form-md-floating-label has-info" style="margin: 0 0 0 0;">'
//                        + ' <input  class="form-control datepicker edited" style="border: 1px solid #000000;border-radius: 4px;"  type="text"   value="' + obj.visitdate + '" >'
//                        + '<label for="form_control_1"  class="txtr">تاريخ الزيارة  </label>'
//                        + '</div></div>');
                row.find("td").eq(7).html('<a class=" bg-green dltbtn  saveEditVisit" data-visitId="' + visitId + '">حفظ </a>');
                row.find("td").eq(8).html('<a class=" bg-red dltbtn  cancelEditVisit" data-visitId="' + visitId + '">إلغاء</a>');

                $('select').select2({
                    width: '270px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                    }
                });
                $(".datepicker").datepicker({
                    todayBtn: "linked",
                    autoclose: true,
                    todayHighlight: true,
                    format: 'yy/mm/dd',
                    isRTL: true
                });
            });
        });


        $('body').on('change', '.newDetect', function () {
            var visitId = $(this).attr("data-id");
            var getPrice = $(this).attr("data-getPrice");
            var value = $(this).val();

            if (getPrice == 1) {
                $.post(hosturl + '/controllers/visits.php?ac=getdtprice', {dtID: value}, function (data) {
                    $('#newDetectVal' + visitId).val(data);
                });
            }
        });


        $('body').on('click', '.saveEditVisit', function () {
            var visitId = $(this).attr("data-visitId");
            var newDetectId = $('#newDetect' + visitId).val();
            var newDetectVal = $('#newDetectVal' + visitId).val();
            var row = $(this).parent().parent();
            $.post(hosturl + '/controllers/visits.php?ac=updatevisit', {
                visitId: visitId,
                newDetectId: newDetectId,
                newDetectVal: newDetectVal
            }, function (res) {
                var obj = JSON.parse(res);
                row.find("td").eq(4).html(obj.address);
                row.find("td").eq(3).html(obj.husbandName);
                row.find("td").eq(5).html(obj.detectionType);
                row.find("td").eq(7).html('<a class=" bg-green dltbtn  editVisit" data-visitId="' + visitId + '">تعديل</a>');
                row.find("td").eq(8).html('<a class="deletemsgEX bg-red dltbtn"  data-today="0" id="deleterowtoday" data-id="' + visitId + '" data-link="visits" data-fn="del">حذف</a>');
            });
        });

        $('body').on('click', '.cancelEditVisit', function () {
            var visitId = $(this).attr("data-visitId");
            var row = $(this).parent().parent();
            $.post(hosturl + '/controllers/visits.php?ac=restorevisit', {visitId: visitId}, function (res) {
                var obj = JSON.parse(res);
                row.find("td").eq(4).html(obj.address);
                row.find("td").eq(3).html(obj.husbandName);
                row.find("td").eq(5).html(obj.detectionType);
                row.find("td").eq(7).html('<a class=" bg-green dltbtn  editVisit" data-visitId="' + visitId + '">تعديل</a>');
                row.find("td").eq(8).html('<a class="deletemsgEX bg-red dltbtn"  data-today="0" id="deleterowtoday" data-id="' + visitId + '" data-link="visits" data-fn="del">حذف</a>');
            });
        });


    };

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

            });

        });
    }

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

        });


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

        });

        $('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');
                });
                realvalues.pop();
            }
            if ($.inArray("-1", realvalues) != -1) {
                $("#operationInstructions option[value='-1']").prop("selected", false);
                $("#operationInstructions").select2();
                $("#add_Inst").modal('show');
                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');
        });

    }


    return {
        //main function to initiate the module
        init: function () {
            forAll();
            patientDrug();
            patientInv();
            patientUs();
            addInvestigation();
            instruction();
            menu();
            members();
            getdata();
            merge();
            minSelectInput();
            visits();
            followupcard();
            fullReport();
            transfer();
        }

    };
}();
