var ant_gyna = function () {
    var hosturl = $('#hosturl').val();
    var drugArray = Array();
    var instructionArray = Array();
    var externalsArray = Array();
    var slideIndex = 1;
    if (Number($('#past_visits').val()) == 1) {
        $(".patientvisitidCheckDate").datepicker();
    } else {
        $(".patientvisitidCheckDate").datepicker({
            minDate: 0
        });
    }

    function vcalc() {
        var saudi = $('input[name="saudi"]:checked').val();
        var patientid = $("#patientvisitid").val();
        var patientName = $("#wifename").val();

        if ((patientid > 0 || patientName != "") && saudi == 1) {
            var total = Number($('#totaldetectionvalue').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());
            }
            total = total - discount;
            var vat = Number($('#vat').val());
            var vatAmount = (total * vat) / 100;
            $('#vatCalc').val(vatAmount);
        } else {
            $('#vatCalc').val(0);
        }

    }
    
    
            function visitInvestsPrice() {
            var totalPrice = 0;
        var totalOrgDiscount = 0;
        var totalOrgContract = 0;
        var totalOrgHold = 0;
        var totalOriginalPrice = 0;
                    var labDetectionPrice = 0;
        if (Number($('#labDetectionPrice').val()) > 0) {
            labDetectionPrice = Number($('#labDetectionPrice').val());
        }

        totalPrice = totalPrice + labDetectionPrice;
        var orgTotalDiscount = 0;
            $("#labInvests option:selected").each(function () {
//                var value = $(this).val();
                var price = Number($(this).attr('data-price'));
            var orgDiscount = Number($(this).attr('data-discount'));
            var orgHold = Number($(this).attr('data-hold'));
            var originalPrice = Number($(this).attr('data-originalPrice'));
                if (price > 0) {
                    totalPrice = totalPrice + price;
                }

            if (orgDiscount > 0) {
                 orgTotalDiscount = orgTotalDiscount + orgDiscount;
            }

            totalOrgDiscount += orgDiscount;
            totalOrgContract += price;
            totalOrgHold += orgHold;
            totalOriginalPrice += originalPrice;
            });
        $('#contractPrice').val(totalOrgContract);
        $('#discountRatio').val(totalOrgDiscount);
        $('#patient_hold').val(totalOrgHold);
        $('#originalPrice').val(totalOriginalPrice);
            $("#totaldetectionvalue").val(totalPrice);
       //  $('#discount').val(discount);
            var x = vcalc();

            var vatValue = Number($('#vatCalc').val());
            if (vatValue > 0) {
                totalPrice = totalPrice + vatValue;
            }


        var price_in = $('#price_in').val();
            if ($('#editView').val() == 1) {

            var rest = totalPrice - $("#detectionvalue_cash").val() - $("#detectionvalue_visa").val();
                $("#restdetectionvalue").val(rest);
            } else {
            $("#restdetectionvalue").val(0);
            $("#detectionvalue_cash").val(0);
                $("#detectionvalue_visa").val(0);
            $("#" + price_in).val(totalPrice);
            }

        $("#totaldetectionvalue").trigger('change');
        }

    function getLastVisit(patientId) {
        if (patientId > 0) {
            $.post(hosturl + '/controllers/visits.php?ac=getlastvisit', {patientId: patientId}, function (data) {

                if (Number(data) == -1) {
                    $('#lastVisitDetails').html('');
                } else {
                    $('#lastVisitDetails').html(data);
                    $(".positiveNo").forcepositiveNum();
                }
            });
        } else {
            $('#lastVisitDetails').html('');
        }

    }

    function getLastVisitAll(patientId) {
        if (patientId > 0) {
            $('#getLastVisitAll').html('Loading ..............');
            $('#getLastVisitAll').attr('disabled', true);
            $.post(hosturl + '/controllers/visits.php?ac=getlastvisitAll', {patientId: patientId}, function (data) {

                if (Number(data) == -1) {
                    $('#lastVisitDetails').html('');
                } else {
                    $('#lastVisitDetails').html(data);
                    $(".positiveNo").forcepositiveNum();
                }
            });
        } else {
            $('#lastVisitDetails').html('');
        }

    }

    function getRest(patientId) {
        ////// reload rest values
        $.post(hosturl + '/controllers/visits.php?ac=getrestvalues', {patientId: patientId}, function (data) {
            if (Number(data) == -1) {
                $('#restDiv').html('');
            } else {
                $('#restDiv').html(data);
            }
        });
    }

    function getLastAdvance(patientId) {
        if (patientId > 0) {
            $.post(hosturl + '/controllers/visits.php?ac=getLastAdvance', {patientId: patientId}, function (data) {

                if (Number(data) == -1) {
                    $('#advancedPaymentDiv').html('');
                } else {
                    $('#advancedPaymentDiv').html(data);
                    $(".positiveNo").forcepositiveNum();
                }
            });
        } else {
            $('#advancedPaymentDiv').html('');
        }
    }

    function getLastAdvanceAll(patientId) {
        if (patientId > 0) {
            $('#getLastAdvanceAll').html('Loading ..............');
            $('#getLastAdvanceAll').attr('disabled', true);
            $.post(hosturl + '/controllers/visits.php?ac=getLastAdvanceAll', {patientId: patientId}, function (data) {

                if (Number(data) == -1) {
                    $('#advancedPaymentDiv').html('');
                } else {
                    $('#advancedPaymentDiv').html(data);
                    $(".positiveNo").forcepositiveNum();
                }
            });
        } else {
            $('#advancedPaymentDiv').html('');
        }

    }

    function loadPatDept(patientId) {
        if (patientId > 0) {
            $.post(hosturl + '/controllers/visits.php?ac=getrestvaluesP', {patientId: patientId}, function (data) {
                $('#patientDeptContainer').html(Number(data));
            });
        } else {
            $('#patientDeptContainer').html('');
        }

    }

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

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

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

            if (Number(data) == -1) {
                $('#restDiv').html('');
            } else {
                $('#restDiv').html(data);
            }
        });
    }

    function getChilds(patientId) {
        $.post(hosturl + '/controllers/visits.php?ac=getChilds', {patientId: patientId}, function (data) {
            $("#childContain").html(data);
        });
    }

    function getBills(patientId) {
        ////// reload rest values
        $.post(hosturl + '/controllers/visits.php?ac=getBills', {patientId: patientId}, function (data) {
            if (Number(data) == -1) {
                $('#billsDiv').html('');
            } else {
                $('#billsDiv').html(data);
            }
        });
    }



    if (Number($('#past_search').val()) != 1 && Number($('#past_search_check').val()) == 1) {
        var date = new Date();
        date.setDate(date.getDate() - 2);
        var x = new Date(date.getFullYear(), date.getMonth(), date.getDate());
        $(".pastSearchDate").datepicker({
            minDate: x
        });
    } else {
        $(".pastSearchDate").datepicker();
    }

    $(".inputDeclare").hover(function () {
        var pop_value = $(this).attr('data-content');
        $(this).attr({
            "data-toggle": "popover",
            "data-trigger": "hover",
            "data-placement": "bottom",
            "data-content": pop_value
        });
        $(this).popover("show");
    });

    var connectWith;

    $('.attendDepts').each(function () {
        var id = $(this).attr('id');
        connectWith = connectWith + " , #" + id;
        $(this).sortable({
            connectWith: "#today_list",
            dropOnEmpty: true,
            //   items: "li:not(.ainli)",
            update: function () {
                var deptId = $(this).attr('data-id');
                var datasorted = $('#' + id).sortable('serialize');
                console.log(datasorted);
                $.post(hosturl + '/controllers/today_list.php?ac=sortable'
                        , {datasorted: datasorted, deptId: deptId}, function (res) {
                    $('#' + id).find('a.enterClinic').show();
                });
            }
        });
    });

    $("#today_list").sortable({
        items: "li:not(.unsortable)",
        connectWith: connectWith,
        dropOnEmpty: true,
        update: function () {
            var datasorted = $('#today_list').sortable('serialize');
            console.log(datasorted);
            $.post(hosturl + '/controllers/today_list.php?ac=sortable'
                    , {datasorted: datasorted, deptId: 0}, function (res) {
                $('#today_list').find('a.enterClinic').hide();
            });
        }
    });

    connectWith = connectWith + " , #today_list";

    $(".attendDepts").sortable("option", "connectWith", connectWith);

    $('body').on('click', '.enterClinic', function () {
        var visitId = $(this).attr('data-id');
        $.post(hosturl + '/controllers/today_list.php?ac=enterClinic', {visitId: visitId}, function (res) {
            var obj = JSON.parse(res);
            $('#item_' + visitId).hide();
            $('#roleCurrentPatient' + obj.clinicid).html(obj.patientName);
            playRecords(obj.visitId, obj.clinicid);
        });
    });

    $('body').on('click', '.exitClinic', function () {
        var clinicId = $(this).attr('data-id');
        $.post(hosturl + '/controllers/today_list.php?ac=exitClinic', {clinicId: clinicId}, function (res) {
            if (res == 1) {
                $('#roleCurrentPatient' + clinicId).html('');
                alert('Exit Done . ');
            }
        });
    });

    function playRecords(patId, clinicId) {
        if (Number(patId) > 0) {
            var audio1 = document.getElementById("patAudio" + Number(patId));
            var audio2 = document.getElementById("roleAudio" + Number(clinicId));
            audio1.play();
            audio2.pause();
            audio1.addEventListener("ended", function () {
                audio2.play();
            });
        }
    }

    $('body').on('keyup', '#indexVisitsSearch', function () {
        var search = $('#indexVisitsSearch').val();
        $.post(hosturl + '/controllers/index.php?ac=indexVisitsSearch', {search: search}, function (res) {
            $('#indexVisitsContainer').html('');
            $('#indexVisitsContainer').html(res);
        });
    });

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

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

    $(".hourPicker").timepicker({autoclose: !0, minuteStep: 60, showSeconds: !1, showMeridian: !1})

    $('.dataTableX').dataTable({
        dom: 'Blfrtip',
        buttons: [
            {
                extend: 'print',
                title: 'Financial Report',
                customize: function (win) {
                    var total = $('#totalDiv').html();
                    $(win.document.body).append(total); //after the table
                    //    $(win.document.body).prepend('<html elements here>'); //before the table
                }
            }
        ],
        "scrollX": true
    });

    $('body').on('click', '.activeIt', function () {
        var id = $(this).attr('data-id');
        var colName = $(this).attr('data-colName');
        var tableName = $(this).attr('data-tableName');
        var value = $(this).attr('data-val');
        $.post(hosturl + '/controllers/sms_control.php?ac=update', {
            id: id,
            tableName: tableName,
            colName: colName,
            value: value
        }, function (res) {
            if (res == 1) {
                if (value == 1) {
                    $('#active' + id).show();
                    $('#notActive' + id).hide();
                } else {
                    $('#notActive' + id).show();
                    $('#active' + id).hide();
                }

            }
        });
    });

    $("body").on('change', '.updateMultiSelect', function () {
        var id = $(this).attr("data-id");
        var selectId = $(this).attr("id");
        var colName = $(this).attr("data-colName");
        var tableName = $(this).attr("data-tableName");
        var controllName = $('#controllName').val();
        var patientId = $('#patientId').val();
        var realvalues = new Array(); //storing the selected values inside an array

        $('#' + selectId + ' :selected').each(function (i, selected) {
            realvalues[i] = $(selected).val();
        });
        $.ajax({
            url: hosturl + '/controllers/' + controllName + '.php?ac=update',
            data: {
                value: JSON.stringify(realvalues),
                id: id,
                tableName: tableName,
                colName: colName,
                patientId: patientId,
                multi: 1
            },
            type: 'POST',
            success: function (data) {
                console.log(data);
            }
        });
    });

    $('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 ajax = $(this).attr("data-ajax");
        var tr = $(this).parent().parent();
        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';
        }

        if (ajax == 1) {
            var control = 'updateajax';
        } else {
            var control = 'update';
        }


        $.post(hosturl + '/controllers/' + controllName + '.php?ac=' + control, {
            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 (selectClass == "refer_doctor") {
                    $('.h_refer_doctor').each(function () {
                        $(this).children('option[value = ' + id + ']').text(value);
                    });
                }

                if (selectClass == "h_refer_doctor") {
                    $('.refer_doctor').each(function () {
                        $(this).children('option[value = ' + id + ']').text(value);
                    });
                }


            }
            if (tableName == "diagnosis" || tableName == "diagnosisant" || tableName == "complaint"
                    || tableName == "complaintant" || id == "operationInstructions" || id == "anddiagnosis" || id == "andcomplaint"
                    || $.inArray(id, ['present_history', 'present_illness', 'comorbidities', 'prev_surgeries', 'allergies', 'vaccinations', 'family_history', 'cyanotic', 'chest_infection', 'exercise_tolerance', 'chest_pain', 'palpitations', 'hospitalization', 'edema', 'ped_comp_others'])) {
                $('select').select2();
            }

            if (tableName == "visits" && colName == "confirm_attend") {
                switch (value) {
                    case "1":
                        tr.css('background-color', '#d0f09f');
                        break;
                    case "2":
                        tr.css('background-color', '#d1a6d1');
                        break;
                    case "3":
                        tr.css('background-color', '#fd8591');
                        break;
                    default:
                        tr.css('background-color', '#C6D7F2');
                        break;
                }
            }
        });
    });

    $('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');
        if (tableName == "patients" && colName == "currently") {
            var gCount = Number($('#gCount').html());
            var ischecked = $(this).is(':checked');
            if (!ischecked) {
                value = 0;
                gCount = gCount - 1;
            } else {
                gCount = gCount + 1;
            }
            $('#gCount').html(gCount);
        }


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


        if (colName == "range" && (tableName == "invests" || tableName == "rays")) {
            value = value.replace(/(?:\r\n|\r|\n)/g, '<br />');
        }

        if (tableName == "price_lists" || tableName == "organizations_parents" || tableName == "organizations" || (tableName == "detections" && (colName == "for_customer"
                || colName == "for_operation" || colName == "units" || colName == "min_paid"
                || colName == "max_session"))) {
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=updateajax', {
                id: id,
                value: value,
                tableName: tableName,
                colName: colName,
            }, function (res) {
                if (colName == "organization_name") {
                    $("#organizations option[value='" + id + "']").text(value);
                    $("#organization option[value='" + id + "']").text(value);
                } else if (tableName == "price_lists") {
                    $("#price_lists option[value='" + id + "']").text(value);
                    $("#price_lists option[value='" + id + "']").text(value);
                } else if (tableName == "organizations_parents") {
                    $(".organizations_parents option[value='" + id + "']").text(value);
                    $(".organizations_parents option[value='" + id + "']").text(value);
                }

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

                    });
                }
//##
                else if (controllName == 'case_summary' && (colName == 'phl_mp' || colName == 'edd')) {
                    res = res.split(",");
                    $('#edd').val(res[0]);
                    $('#phl_mp').val(res[1]);
                }
            });
        }
    });

    $('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;
        } else {
            value = 1;
        }

        if ((tableName == "detections" && (colName == "for_customer" || colName == "for_operation" ||
                colName == "iserpzerobill" || colName == "type")) ||
                (tableName == "patients" && colName == "revisionedV")) {
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=updateajax', {
                id: id,
                value: value,
                tableName: tableName,
                colName: colName,
            }, function (res) { });
        } else {

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

    $('body').on('click', '.setActive', function () {
        var itemid = $(this).attr('data-id');
        var colName = $(this).attr('data-col');
        var tableName = $(this).attr('data-tableName');
        var value = $(this).attr('data-val');
        var btn = $(this);
        $.post(hosturl + '/controllers/invoffers.php?ac=update', {
            id: itemid,
            tableName: tableName,
            colName: colName,
            value: value
        }, function (res) {
            if (res == 1) {
                if (value == 1) {
                    btn.attr('data-val', 0);
                    btn.html('active');
                    btn.addClass('green');
                    btn.removeClass('gray');
                } else {
                    btn.attr('data-val', 1);
                    btn.html('not active');
                    btn.removeClass('green');
                    btn.addClass('gray');
                }

            }
        });
    });



    $('body').on('change', '#wifeData', function () {
        if ($(this).is(':checked')) {
            $('#wrfc').attr('required', true);
            $('#wifename').attr('required', true);
            $('#wifenationalid').attr('required', true);
            $('#phone').attr('required', true);
            $('#refer_doctor').attr('required', true);
            $('#doctor1').attr('required', true);
        } else {
            $('#wrfc').removeAttr('required');
            $('#wifename').removeAttr('required');
            $('#wifenationalid').removeAttr('required');
            $('#phone').removeAttr('required');
            $('#refer_doctor').removeAttr('required');
            $('#doctor1').removeAttr('required');
        }
        allowPatSaveBtn();
    });

    $('body').on('change', '#HusData', function () {
        if ($(this).is(':checked')) {
            $('#rfc').attr('required', true);
            $('#husdandname').attr('required', true);
            $('#h_refer_doctor').attr('required', true);
            $('#h_doctor1').attr('required', true);
            //     $('#husbandnationalid').attr('required', true);
        } else {
            $('#rfc').removeAttr('required');
            $('#husdandname').removeAttr('required');
            $('#h_refer_doctor').removeAttr('required');
            $('#h_doctor1').removeAttr('required');
            //   $('#husbandnationalid').removeAttr('required');
        }
        allowPatSaveBtn();
    });
    function allowPatSaveBtn() {
        if ($('#lb_ckwifename:visible').length) {
            console.log();
        }
        if (($('#wifeData').is(':checked') && ($('#lb_ckstatusno:visible').length
                || $('#lb_ckphone:visible').length || $('#lb_ckmobile:visible').length
                || $('#lb_ckeckwifenationalid:visible').length || $('#lb_ckwifename:visible').length))
                || ($('#HusData').is(':checked') && ($('#lb_ckeckhusbandnationalid:visible').length
                        || $('#lb_ckhusbandnationalid:visible').length))) {
            $('#patient_submit').attr('disabled', 'disabled');
            $('#patient_submit').css('opacity', '0.3');
            $('#patient_submit_v').attr('disabled', 'disabled');
            $('#patient_submit_v').css('opacity', '0.3');
        } else {
            $("#patient_submit").removeAttr('disabled');
            $('#patient_submit').css('opacity', '1');
            $("#patient_submit_v").removeAttr('disabled');
            $('#patient_submit_v').css('opacity', '1');
        }
    }


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

        var PatientAdd = $('#PatientAdd').val();
        if (PatientAdd == 1) {
            $('#HusData').trigger('change');
        }

        $('.timepicker-24').timepicker({
            autoclose: true,
            minuteStep: 30,
            showSeconds: false,
            showMeridian: false
        });
        $('.timepicker-5').timepicker({
            autoclose: true,
            minuteStep: 5,
            showSeconds: false,
            showMeridian: false
        });
        $('.timepicker1').timepicker({
            autoclose: true,
            minuteStep: 1,
            showSeconds: false,
            showMeridian: false
        });


        $('.timepickeraa').timepicker({
            autoclose: true,
            minuteStep: 1,
            showSeconds: false,
            showMeridian: false,
            format: "h:i a"
        });


        let modify_time_right = function (start_input, end_input) {
            if ($('#' + end_input).length > 0) {
                var startTime = $('#' + start_input).val();
                var endTime = $('#' + end_input).val();
                var currentDate = new Date()

                var startDate = new Date(currentDate.getTime());
                startDate.setHours(startTime.split(":")[0]);
                startDate.setMinutes(startTime.split(":")[1]);
                var endDate = new Date(currentDate.getTime());
                endDate.setHours(endTime.split(":")[0]);
                endDate.setMinutes(endTime.split(":")[1]);
                let time_valid = isFromBiggerThanTo(endDate, startDate); //startDate < endDate;//startDate < currentDate && endDate > currentDate
                if (time_valid) {
                    //true
                } else {
                    // false
                    var newDateObj = moment(startDate).add(30, 'm').toDate();
                    var endTimeNew = newDateObj.getHours() + ':' + String(newDateObj.getMinutes()).padStart(2, "0");
                    $('#' + end_input).val(endTimeNew)
                }
            }
        }

        modify_time_right('operation_start_time', 'operation_end_time');
        modify_time_right('residence_start_time', 'residence_end_time');
        // check if time change to make start less then end
        $('#operation_end_time,#operation_start_time').timepicker().on('changeTime.timepicker', function (e) {
            modify_time_right('operation_start_time', 'operation_end_time');
        });
        $('#residence_start_time,#residence_end_time').timepicker().on('changeTime.timepicker', function (e) {
            modify_time_right('residence_start_time', 'residence_end_time');
        });
        function isFromBiggerThanTo(dtmfrom, dtmto) {
            return new Date(dtmfrom).getTime() > new Date(dtmto).getTime();
        }

//operation reserve
        let check_operation_room_id = null;
        let check_residence_room_id = null;
        var hoursString = function () {
            let daySelected = $('.daySelected');
            if ($('.daySelected[data-type="1"]').length == 0) {
                check_operation_room_id = null;
                $('#operation_room_id').val(check_operation_room_id)
            }
            if ($('.daySelected[data-type="2"]').length == 0) {
                check_residence_room_id = null;
                $('#residence_room_id').val(check_residence_room_id)
            }
            var hours_st = '';
            var r_hours_st = '';
            daySelected.each(function (e) {
                let self = $(this);
                let type = self.attr('data-type');
                if (Number(type) === 1) {
                    // add room id check if room id is change
                    if (check_operation_room_id === self.attr('data-room-id') || check_operation_room_id == null) {
                        // same room good to go
                        check_operation_room_id = self.attr('data-room-id');
                        $('#operation_room_id').val(check_operation_room_id);
                        hours_st += self.attr('data-hour') + ',';
                    } else {
                        self.removeClass().addClass('dayFree');
                        swal({
                            title: 'تحذير',
                            text: 'لا يمكن اختيار اكثر من معاد لاكثر من غرفه لنفس العمليه',
                            type: 'error',
                            allowOutsideClick: true,
                            showConfirmButton: false,
                            showCancelButton: true,
                            closeOnConfirm: true,
                            closeOnCancel: true,
                            confirmButtonText: 'تاكيد',
                            cancelButtonText: 'الغاء',
                        });
                    }
                } else {
                    // add room id check if room id is change
                    if (check_residence_room_id === self.attr('data-room-id') || check_residence_room_id == null) {
                        // same room good to go
                        check_residence_room_id = self.attr('data-room-id');
                        $('#residence_room_id').val(check_residence_room_id);
                        r_hours_st += self.attr('data-hour') + ',';
                    } else {
                        self.removeClass().addClass('dayFree');
                        swal({
                            title: 'تحذير',
                            text: 'لا يمكن اختيار اكثر من معاد لاكثر من غرفه لنفس العمليه',
                            type: 'error',
                            allowOutsideClick: true,
                            showConfirmButton: false,
                            showCancelButton: true,
                            closeOnConfirm: true,
                            closeOnCancel: true,
                            confirmButtonText: 'تاكيد',
                            cancelButtonText: 'الغاء',
                        });
                    }
                }


            });
            $('#hours_string').val(hours_st)
            $('#residence_hours_string').val(r_hours_st)
        };
        $('body').on('click', '.dayFree', function () {
            $(this).removeClass().addClass('daySelected');
            // create op_hour when selected
            hoursString();
        });
        $('body').on('click', '.daySelected', function () {
            $(this).removeClass().addClass('dayFree');
            hoursString();
        });
        $('body').on('click', '.dayBusy', function () {
            $(this).removeClass().addClass('dayCancel');
        });
        $('body').on('click', '.dayCancel', function () {
            $(this).removeClass().addClass('dayBusy');
        });
        $('body').on('ifClicked', '.icheck', function (event) {
            var self = $(this);
            if (Number(self.attr('data-reserve-status')) === 1) {

            }

            let hours_chosen = [];
            $("input:checkbox[class=icheck]:checked").each(function () {
                let checked_input = $(this);
                if (Number(checked_input.attr('data-reserve-status')) === 0) {
                    hours_chosen.push(checked_input.attr('data-label'));
                }
            });
            if (hours_chosen.length == 0) {
                check_operation_room_id = null;
            }

            if (check_operation_room_id == self.attr('data-room-id') || check_operation_room_id == null) {
// same room good to go
                check_operation_room_id = self.attr('data-room-id');
                // check if user choose hours not in sequence

            } else {
                setTimeout(function () {
                    self.iCheck('uncheck');
                }, 1);
                // alert
                swal({
                    title: 'تحذير',
                    text: 'لا يمكن اختيار اكثر من معاد لاكثر من غرفه لنفس العمليه',
                    type: 'error',
                    allowOutsideClick: true,
                    showConfirmButton: false,
                    showCancelButton: true,
                    closeOnConfirm: true,
                    closeOnCancel: true,
                    confirmButtonText: 'تاكيد',
                    cancelButtonText: 'الغاء',
                });
            }
        });
        $('#body').on('loaded.bs.modal', '#reserve_room_modal', function (e) {
// do cool stuff here all day… no need to change bootstrap
            $('.icheck_res').each(function () {
                var self = $(this),
                        label = self.next(),
                        label_text = self.attr('data-label'),
                        label_color = self.attr('data-checkbox')

                label.remove();
                self.iCheck({
                    checkboxClass: label_color,
                    radioClass: 'iradio_line-blue',
                    insert: '<div class="icheck_line-icon"></div>' + label_text
                });
            });
        });
        $('body').on('click', '#reserve_room_btn', function () {
// get all checked with status = 0
            let hours_chosen = [];
            let data_room_id = null;
            $("input:checkbox[class=icheck]:checked").each(function () {
                let checked_input = $(this);
                if (Number(checked_input.attr('data-reserve-status')) === 0) {
                    hours_chosen.push(checked_input.attr('data-label'));
                    data_room_id = checked_input.attr('data-room-id');
                }
            });
            let hours_string = hours_chosen.toString();
            if (hours_chosen.length > 0) {
                $('#reserve_room_modal').modal('toggle');
                let operation_date = $('input[name=operation_date]').val();
                let operation_type = $('#operation_type_id').val();
                // get all room with last hour and operation
                $.post(hosturl + '/controllers/operations_reserve.php?ac=residence', {
                    last_hour: hours_chosen[hours_chosen.length - 1],
                    operation_date: operation_date,
                    hours_string: hours_string,
                    operation_type: operation_type,
                    data_room_id: data_room_id
                }, function (result) {
                    $('#residence_container').html(result);
                    $('.icheck_res').each(function () {
                        var self = $(this),
                                label = self.next(),
                                label_text = self.attr('data-label'),
                                label_color = self.attr('data-checkbox')

                        label.remove();
                        self.iCheck({
                            checkboxClass: label_color,
                            radioClass: 'iradio_line-blue',
                            insert: '<div class="icheck_line-icon"></div>' + label_text
                        });
                    });
                    $('#doctor_id').select2({width: null});
                })
            } else {
                swal({
                    title: 'تحذير',
                    text: 'اختر موعد بالغرفه لامكانيه الحجز',
                    type: 'error',
                    allowOutsideClick: true,
                    showConfirmButton: false,
                    showCancelButton: true,
                    closeOnConfirm: true,
                    closeOnCancel: true,
                    confirmButtonText: 'تاكيد',
                    cancelButtonText: 'الغاء',
                });
            }
        });
        $('body').on('click', '#delete_reserve_btn', function () {
            let cancel_class = $('.dayCancel');
            if (cancel_class.length) {

                var selected_items = '';
                var remove_input = $('#remove_rooms_hours');
                cancel_class.each(function () {
                    selected_items += $(this).find('.operation_reserve_id').val() + ':';
                    selected_items += $(this).find('.operation_reserve_id').attr('data-id') + ':';
                    selected_items += $(this).find('.operation_reserve_id').attr('data-tbl');
                    selected_items += ',';
                });
                remove_input.val(selected_items);
                $.post(hosturl + '/controllers/operations_reserve.php?ac=removeRoom', {
                    remove_items: remove_input.val()
                }, function (result) {
                    //console.log(result)
                    window.location.href = hosturl + "/controllers/operations_reserve.php?ac=index";
                    //$('#searchReserves').trigger('click');
                })

            } else {
                swal({
                    title: 'تحذير',
                    text: 'اختر موعد بالغرفه لالغاء الحجز',
                    type: 'error',
                    allowOutsideClick: true,
                    showConfirmButton: false,
                    showCancelButton: true,
                    closeOnConfirm: true,
                    closeOnCancel: true,
                    confirmButtonText: 'تاكيد',
                    cancelButtonText: 'الغاء',
                });
            }

//             let hours_chosen = [];
//             let data_room_id = null;
//             $("input:checkbox[class=icheck]:checked").each(function () {
//                 let checked_input = $(this);
//                 if (Number(checked_input.attr('data-reserve-status')) === 1) {
//                     hours_chosen.push(checked_input.attr('data-label'));
//                     data_room_id = checked_input.attr('data-room-id');
//                 }
//             });
//             let hours_string = hours_chosen.toString();
//
//             if (hours_chosen.length > 0) {
//                 $.post(hosturl + '/controllers/operations_reserve.php?ac=removeRoom', {
//                     operation_hours: hours_string,
//                     operation_date: $('input[name=operation_date]').val(),
//                     operation_room_id: data_room_id
//                 }, function (result) {
//                     //console.log(result)
// //                    window.location.href = hosturl + "/controllers/operations_reserve.php?ac=index";
//                     $('#searchReserves').trigger('click');
//                 })
//             } else {
//                 swal({
//                     title: 'تحذير',
//                     text: 'اختر موعد بالغرفه لالغاء الحجز',
//                     type: 'error',
//                     allowOutsideClick: true,
//                     showConfirmButton: false,
//                     showCancelButton: true,
//                     closeOnConfirm: true,
//                     closeOnCancel: true,
//                     confirmButtonText: 'تاكيد',
//                     cancelButtonText: 'الغاء',
//                 });
//             }
        })

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

            var hours_string = $('#hours_string').val(),
                    operation_date = $('#operation_date').val(),
                    residence_hours_string = $('#residence_hours_string').val(),
                    doctor_id = $('#doctor_id').val(),
                    operation_type_id = $('#operation_type_id').val(),
                    operation_room_id = $('#operation_room_id').val(),
                    residence_room_id = $('#residence_room_id').val();
            if (hours_string.length && operation_date.length && residence_hours_string.length
                    && doctor_id.length && operation_type_id.length && operation_room_id.length && residence_room_id.length) {
// check for other inputs
                $.post(hosturl + '/controllers/operations_reserve.php?ac=reserve', {
                    operation_hours: hours_string,
                    operation_date: operation_date,
                    residence_hours: residence_hours_string,
                    doctor_id: doctor_id,
                    operation_type: operation_type_id,
                    operation_room_id: operation_room_id,
                    residence_room_id: residence_room_id
                }, function (result) {
                    window.location.href = hosturl + "/controllers/operations_reserve.php?ac=index";
                    //                         $('#reserve_room_modal').modal('hide');
                    //                         var waitForClose = window.setInterval(function () {
                    //                             if ($('body').hasClass('modal-open') == false) {
                    //                                 $('#searchReserves').trigger('click');
                    //                                 window.clearInterval(waitForClose)
                    //                             }
                    //                         }, 100);

                })
            } else {
                swal({
                    title: 'تحذير',
                    text: 'اختر موعد و نوع العمليه و الطبيب و غرفه الاقامه وغرفه العمليات ثم تاكيد الحجز',
                    type: 'error',
                    allowOutsideClick: true,
                    showConfirmButton: false,
                    showCancelButton: true,
                    closeOnConfirm: true,
                    closeOnCancel: true,
                    confirmButtonText: 'تاكيد',
                    cancelButtonText: 'الغاء',
                });
            }

            /*
             if (hours_chosen.length > 0) {
             // check for some inputs date, times as string and type and doctor
             if ($('#doctor_id').valid()) {
             
             // check for other inputs
             $.post(hosturl + '/controllers/operations_reserve.php?ac=reserve', {
             operation_hours: $('#hours_string').val(),
             operation_date: $('#operation_date').val(),
             residence_hours: $('#residence_hours_string').val(),
             doctor_id: $('#doctor_id').val(),
             operation_type: $('#operation_type_id').val(),
             operation_room_id: $('#operation_room_id').val(),
             residence_room_id: $('#residence_room_id').val()
             }, function (result) {
             //console.log(result)
             // //                        window.location.href = hosturl + "/controllers/operations_reserve.php?ac=index";
             //                         $('#reserve_room_modal').modal('hide');
             //                         var waitForClose = window.setInterval(function () {
             //                             if ($('body').hasClass('modal-open') == false) {
             //                                 $('#searchReserves').trigger('click');
             //                                 window.clearInterval(waitForClose)
             //                             }
             //                         }, 100);
             
             })
             }
             } else {
             swal({
             title: 'تحذير',
             text: 'اختر موعد بغرفه الاقامه لامكانيه الحجز',
             type: 'error',
             allowOutsideClick: true,
             showConfirmButton: false,
             showCancelButton: true,
             closeOnConfirm: true,
             closeOnCancel: true,
             confirmButtonText: 'تاكيد',
             cancelButtonText: 'الغاء',
             });
             }*/
        });
        $('body').on('click', '#searchReserves', function () {

            $('#searchReserves').attr('disabled', true);
            var operation_type_id = $('#operation_type_id').val();
            var search = 1;
            if (operation_type_id > 0) {
                $('#operationTypeExist').html('');
            } else {
                $('#operationTypeExist').html('هذا الحقل إلزامي');
                $('#searchReserves').attr('disabled', false);
                search = 0;
            }

            if (search == 1) {
                var start_time = $('#operation_start_time').val();
                var end_time = $('#operation_end_time').val();
                var operation_date = $('#operation_date').val();
                $.post(hosturl + '/controllers/operations_reserve.php?ac=search', {
                    start_time: start_time, end_time: end_time
                    , operation_date: operation_date, operation_type_id: operation_type_id
                }, function (res) {
                    $('#reserveslDiv').html('');
                    $('#reserveslDiv').html(res);
                    $('#searchReserves').attr('disabled', false);
                    $('.icheck').each(function () {
                        var self = $(this),
                                label = self.next(),
                                label_text = self.attr('data-label'),
                                label_color = self.attr('data-checkbox')

                        label.remove();
                        self.iCheck({
                            checkboxClass: label_color,
                            radioClass: 'iradio_line-blue',
                            insert: '<div class="icheck_line-icon"></div>' + label_text
                        });
                    });
                    $('#doctor_id').select2({width: null});
                });
            }
        });
        $(".positiveNo").forcepositiveNum();
        // two sided multi select with search
        if ($("#labInvests").length > 0) {

            $('#labInvests').multiSelect({
                selectableHeader: "<div style='background-color: #4b8df8;;height: 10px;'></div>"
                        + "<input type='search' id='searchIn' class='search-input' style='text-align: center; width: -webkit-fill-available;' autocomplete='off' placeholder=''>",
                selectionHeader: "<div style='background-color: #4b8df8;;height: 10px;'></div>"
                        + "<input type='search' id='searchOut' class='search-input' style='text-align: center; width: -webkit-fill-available;'  autocomplete='off' placeholder=''>",
                selectableFooter: "<div style='background-color: #4b8df8;;height: 10px;'> </div>",
                selectionFooter: "<div style='background-color: #4b8df8;;height: 10px;'> </div>",
                afterInit: function (ms) {
                    var that = this,
                            $selectableSearch = that.$selectableUl.prev(),
                            $selectionSearch = that.$selectionUl.prev(),
                            selectableSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selectable:not(.ms-selected)',
                            selectionSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selection.ms-selected';
                    that.qs1 = $selectableSearch.quicksearch(selectableSearchString)
                            .on('keydown', function (e) {
                                if (e.which === 40) {
                                    that.$selectableUl.focus();
                                    return false;
                                }
                            });
                    that.qs2 = $selectionSearch.quicksearch(selectionSearchString)
                            .on('keydown', function (e) {
                                if (e.which == 40) {
                                    that.$selectionUl.focus();
                                    return false;
                                }
                            });
                },
                afterSelect: function (e) {
                    //    alert(e);
                    this.qs1.cache();
                    this.qs2.cache();
                    $('#searchIn').focus();
                    visitInvestsPrice();
                    externalVisitsSelect(e);
                    //   vcalc();
                },
                afterDeselect: function (d) {
                    this.qs1.cache();
                    this.qs2.cache();
                    visitInvestsPrice();
                    externalVisitsDSelect(d);
                    //  vcalc();
                },
                selectableOptgroup: true
            });
            $('#ms-labInvests').css("width", "100%");
        }

        $(".positivefloat").forcepositivefloat();
        function externalVisitsDSelect(deSelectedArray) {
            $.each(deSelectedArray, function (index, id) {
                if ($('#exLabsTr' + id).length > 0) {
                    $('#exLabsTr' + id).remove();
                }
            });
        }

        function externalVisitsSelect(selectedArray) {

            $.post(hosturl + '/controllers/visits.php?ac=get_externals', function (external_labs) {
                $.each(selectedArray, function (index, id) {
                    var external = Number($('#' + id).attr('data-external'));
                    var name = $('#' + id).attr('data-name');
                    if (external > 0) {
                        $('#externalContainer').append(' <tr  id="exLabsTr' + id + '" > '
                                + '<td class="txtl" >   '
                                + name
                                + '  </td> '
                                + ' <td > '
                                + ' <select class="form-control select2 external_labs"   id="exLabs' + id + '"   name="exLabs' + id + '"> '
                                + external_labs
                                + ' </select> '
                                + ' </td> '
                                + ' </tr> ');
                        $("#exLabs" + id).select2({
                            placeholder: "Select",
                            width: '240px',
                            allowClear: true,
                            formatNoMatches: function (term) {
                                /* customize the no matches output */
                                return "<input class='form-control' id='newTerm_" + id + "' value='" + term + "'><a href='#' data-id='" + id + "'  data-text='newTerm_" + id + "'  class='btn blue custombtnstyle addNew_ex'>إضافة جديد</a>"
                            }
                        }).parent().find('.select2-with-searchbox').on('click', '.addNew_ex', function () {
                            /* add the new term */
                            var text_id = $(this).attr('data-text');
                            var id = $(this).attr('data-id');
                            var new_name = $('#' + text_id).val();
                            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {
                                selectId: 'external_labs', new_name: new_name
                            }, function (data) {
                                //   alert($('#exLabs' + id).html());

                                $('#exLabs' + id + ' > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + new_name + '</option>');
                                $('#exLabs' + id).select2('val', Number(data)); // select the new term
                                $("#exLabs" + id).select2('close'); // close the dropdown

                            });
                        });
                        $("#exLabs" + id).on('change', function () {
                            var select = $(this);
                            var colName = 'name';
                            var delColName = 'deleted';
                            var tableName = 'external_labs';
                            var value = select.val();
                            if (value == '-2') {
                                $.post(hosturl + '/controllers/invsdept.php?ac=editModal', {
                                    tableName: tableName, delColName: delColName, selectClass: tableName
                                    , colName: colName}, function (data) {
                                    select.select2("val", "");
                                    $("#editModalDiv").html(data);
                                    $("#edit_model").modal('show');
                                });
                            }

                        });
                        $('#externalTable').show();
                        if ($('#editView').val() == 1) {
                            $.each(externalsArray, function (index, entry) {
                                if (entry.id == "exLabs" + id) {
                                    $("#exLabs" + id).select2("val", entry.val);
                                    //        console.log(entry.val);
                                    return false; // Ends the "loop"
                                }
                            });
                        }
                    }
                });
//                var externals = $('#externalsss').html();
//                $.each(externals, function (i, e) {
//                    $('#' + e.id).select2("val", e.val);
//                    //            console.log(e.id);
//                });
            });
        }

// pdf
        $('body').on('change', '.addInvPdfExtrnal', function ()
        {
            var id = $(this).attr("data-id");
            $('#talks-loading' + id).show();
            var files = $("#invPdf_" + id)[0].files;
            var isValid = 2;
            for (var i = 0; i < files.length; i++)
            {
//alert(files[i].name);
                var valid = checkFileEx(files[i].name, id);
                if (valid == 2)
                {

                } else if (valid == 1)
                {
                    isValid = 1;
                }
            }

            if (isValid == 2)
            {
                var myformdata = new FormData();
                myformdata.append("type", "All");
                myformdata.append("name", 'invPdf');
                myformdata.append("id", id);
                myformdata.append("imgCount", files.length);
                jQuery.each(jQuery("#invPdf_" + id)[0].files, function (i, file)
                {
                    myformdata.append('file-' + i, file);
                });
                $.ajax({
                    url: hosturl + '/controllers/invsdept.php?ac=uploadone', // Url to which the request is send
                    type: "POST", // Type of request to be send, called as method
                    data: myformdata, // Data sent to server, a set of key/value pairs representing form fields and values
                    contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
                    cache: false, // To unable request pages to be cached
                    processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
                    success: function (data)  		// A function to be called if request succeeds
                    {
                        if (data != -1 && data != 'no image')
                        {
                            var patientNo = $('#pdfDownload' + id).attr('data-statusno');
                            $('#pdfDownload' + id).attr('href', hosturl + '/../upload/inv_pdf/' + patientNo + '/' + data);
                            $('#pdfDownload' + id).show('');
                        } else {
                            alert('error while uploading ');
                        }

                        $('#talks-loading' + id).hide();
                    }
                });
            }

        });
        // pdf
        $('body').on('change', '.addDnaPdf', function ()
        {
            var id = $(this).attr("data-id");
            $('#loading_dna' + id).show();
            var files = $("#dnaPdf_" + id)[0].files;
            var isValid = 2;
            for (var i = 0; i < files.length; i++)
            {
//alert(files[i].name);
                var valid = checkFileEx(files[i].name, id);
                if (valid == 2)
                {

                } else if (valid == 1)
                {
                    isValid = 1;
                }
            }

            if (isValid == 2)
            {
                var myformdata = new FormData();
                myformdata.append("type", "All");
                myformdata.append("name", 'dnaPdf');
                myformdata.append("id", id);
                myformdata.append("imgCount", files.length);
                jQuery.each(jQuery("#dnaPdf_" + id)[0].files, function (i, file)
                {
                    myformdata.append('file-' + i, file);
                });
                $.ajax({
                    url: hosturl + '/controllers/invsdept.php?ac=uploadDna', // Url to which the request is send
                    type: "POST", // Type of request to be send, called as method
                    data: myformdata, // Data sent to server, a set of key/value pairs representing form fields and values
                    contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
                    cache: false, // To unable request pages to be cached
                    processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
                    success: function (data)  		// A function to be called if request succeeds
                    {
                        if (data != -1 && data != 'no image')
                        {
                            var patientNo = $('#dnaPdfDownload' + id).attr('data-statusno');
                            $('#dnaPdfDownload' + id).attr('href', hosturl + '/../upload/dna_pdf/' + patientNo + '/' + data);
                            $('#dnaPdfDownload' + id).show('');
                        } else {
                            alert('error while uploading ');
                        }

                        $('#loading_dna' + id).hide();
                    }
                });
            }

        });
        function checkFileEx(filename, id) {
            filename = filename.replace(/C:\\fakepath\\/i, '');
            if (filename != "")
            {
                var ext = filename;
                var extindex = ext.lastIndexOf(".") + 1;
                ext = ext.slice(extindex, ext.length);
                ext = ext.toLowerCase();
                if ($.inArray(ext, ['doc', 'docx', 'pdf']) == -1)
                {
                    alert("pictures only allowed ( doc , docx , pdf )");
                    $('#talks-loading' + id).hide();
                    return 1;
                } else
                {
                    return 2;
                }
            } else
            {
                return 1;
            }
        }





        var formatResult = function (data) {
            return data.statusno;
        }

        function formatSelection(data) {
            return data.statusno;
        }

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

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

        var lab_visit = $('#lab_visit').val();
        var addVisit = $('#addVisit').val();
        if (lab_visit == 1) {

            var momentNow = moment();
            $('#currentTime').html(momentNow.format('hh:mm A'));
            $('#receiveTime').html(momentNow.add(4, 'hour').format('hh:00 A'));
            setInterval(function () {
                var momentNow = moment();
                $('#currentTime').html(momentNow.format('hh:mm A'));
                $('#receiveTime').html(momentNow.add(4, 'hour').format('hh:00 A'));
            }, 60000);
            $("#patientvisitid").select2({
                placeholder: "Choose ",
                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) {
                        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);
                },
                formatNoMatches: function (term) {
                    var lab_visit = $('#lab_visit').val();
                    if (lab_visit == 1) {
                        return "<input class='form-control' id='newLabPatientName' value='" + term + "'>\n\
                            <a href='#' id='newLabPatient' class='btn blue custombtnstyle'>Add New </a>"
                    }
                }
            }).parent().find('.select2-with-searchbox').on('click', '#newLabPatient', function () {
                var patientName = $('#newLabPatientName').val();
                $("#patientvisitid").select2('close'); // close the dropdown
                $('#newPatientDiv').show();
                $('#wifename').val(patientName);
                $('#wifename').trigger('keyup');
            });

            $('.searchPatRemoteLab').live('keyup', function (e) {

                var statusNo = $('#statusNoRemoteLab').val();
                if (statusNo > 0) {
                    $.post(hosturl + '/controllers/visits.php?ac=getnameswithstatus', {statusNo: statusNo}, function (res) {
                        var obj = JSON.parse(res);
                        $('#patientvisitid').val(null).empty().trigger("change");
                        var option = new Option(obj.name, obj.id, true, true);
                        $("#patientvisitid").append(option);
                        $('#patientvisitid').select2("val", obj.id);
                        $("#select2-chosen-2").html(obj.name);
                        if (obj.saudi == 1) {
                            $("#saudi1").prop("checked", true);
                            $('#saudi1').parent().addClass('checked');
                            $("#saudi0").removeAttr('checked');
                            $("#saudi0").parent().removeClass('checked');
                            vcalc();
                        } else {
                            $("#saudi0").prop("checked", true);
                            $('#saudi0').parent().addClass('checked');
                            $("#saudi1").removeAttr('checked');
                            $("#saudi1").parent().removeClass('checked');
                            vcalc();
                        }
                    });
                } else {
                    $('#patientvisitid').val(null).empty().trigger("change");
                    $("#saudi0").prop("checked", true);
                    $('#saudi0').parent().addClass('checked');
                    $("#saudi1").removeAttr('checked');
                            $("#saudi1").parent().removeClass('checked');
                }
            });

            $('.searchPatRemoteLab').live('change', function (e) {

                var statusNo = $('#statusNoRemoteLab').val();
                var alerting = $(this).attr('data-alert');
                $("#phonesContainer").html(' ');
                if (statusNo > 0) {
                    $.post(hosturl + '/controllers/visits.php?ac=getnameswithstatus', {statusNo: statusNo}, function (res) {
                        var obj = JSON.parse(res);
                        var phonesContainer = ' ';
                        if (obj.governorate > 0) {
                            phonesContainer = phonesContainer + ' ' + obj.govName;
                        }

                        if (obj.governorate_center > 0) {
                            if (obj.governorate > 0) {
                                phonesContainer = phonesContainer + ' -  ';
                            }
                            phonesContainer = phonesContainer + ' ' + obj.centerName;
                        }

                        if (obj.visit_phones == 1) {
                            if (obj.governorate > 0 || obj.governorate_center > 0) {
                                phonesContainer = phonesContainer + ' -  ';
                            }
                            phonesContainer = phonesContainer + ' ' + obj.phoneTxt;
                        }

                        if (obj.revisionedTxt != -1) {
                            phonesContainer = phonesContainer + '  -  ' + obj.revisionedTxt;
                        }

                        $("#phonesContainer").html(phonesContainer);
                        if (obj.stopped == 1) {
                            $('#saveLabVisit').attr('disabled', true);
                            alert('  لا يمكن إضافة زيارة - هذا المريض موقوف .......');
                        } else if (obj.tempPatient == 1 && $('input[name="for_husband"]:checked').val() == 0) {
                            $('#saveLabVisit').attr('disabled', true);
                            alert('لا يمكن إضافة زيارة - يرجى إكمال بيانات المريض أولا ');
                        } else {
                            $('#saveLabVisit').attr('disabled', false);
                        }

                        if ($('#orgIn').val() == 2) {
                            if (obj.organization_id > 0) {
                                $("#organizations").select2("val", obj.organization_id).trigger("change");
                            } else {
                                $("#organizations").select2("val", "").trigger("change");
                            }
                        }

                        if (obj.innerInvestsCount > 0) {
                            bootbox.dialog({
                                message: "Internal Tests Exist Load It ?",
                                title: " confirmation",
                                buttons: {
                                    danger: {
                                        label: "Cancel",
                                        className: "btn-danger"
                                    },
                                    main: {
                                        label: "Load",
                                        className: "btn-primary",
                                        callback: function () {
                                            //do something else
                                            var orgId = $('#organizations').val();
                                            $.post(hosturl + '/controllers/visits.php?ac=getinternal', {
                                                forDepartment: 12, patientId: obj.id, orgId: orgId, labVisit: 1}, function (res) {
                                                $("#divShow").html("");
                                                $("#divShow").html(res);
                                                $("#internalShow").modal('show');
                                            });
                                        }
                                    }
                                }
                            }).find('.modal-content').addClass('modal-sm');
                        }

                        if (alerting != 'no') {
                            getLastVisit(obj.id);
                            getLastAdvance(obj.id);
                            getRestDetectionVlues(obj.id, 1);
                            getBills(obj.id);
                            getChilds(obj.id);
                        }
                    });
                }
            });

            $('.searchPatLab').live('change', function (e) {

                var patId = $('#patIdRemote').val();
                var mobile = $('#patMobileRemote').val();
                 var orgPatNo = $('#orgPatNoRemote').val();
                if (patId != '' || mobile != '' || orgPatNo != '') {
                    $.post(hosturl + '/controllers/visits.php?ac=searchPatLab', {
                        patId: patId, mobile: mobile  , orgPatNo : orgPatNo}, function (res) {
                        var obj = JSON.parse(res);
                        $('#patientvisitid').val(null).empty().trigger("change");
                        var option = new Option(obj.name, obj.id, true, true);
                        $("#patientvisitid").append(option);
                        $('#patientvisitid').select2("val", obj.id);
                        $("#select2-chosen-2").html(obj.name);
                        if (obj.saudi == 1) {
                            $("#saudi1").prop("checked", true);
                            $('#saudi1').parent().addClass('checked');
                            $("#saudi0").removeAttr('checked');
                            $("#saudi0").parent().removeClass('checked');
                            vcalc();
                        } else {
                            $("#saudi0").prop("checked", true);
                            $('#saudi0').parent().addClass('checked');
                            $("#saudi1").removeAttr('checked');
                            $("#saudi1").parent().removeClass('checked');
                            vcalc();
                        }
                    });
                } else {
                    $('#patientvisitid').val(null).empty().trigger("change");
                    $("#saudi0").prop("checked", true);
                    $('#saudi0').parent().addClass('checked');
                    $("#saudi1").removeAttr('checked');
                            $("#saudi1").parent().removeClass('checked');
                }
            });


        } else if (addVisit == 1) {

            $("#patientvisitid").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);
                }
            });
            $('.searchPatRemoteLab').live('keyup', function (e) {

                var statusNo = $('#statusNoRemoteLab').val();
                if (statusNo > 0) {
                    $.post(hosturl + '/controllers/visits.php?ac=getnameswithstatus', {statusNo: statusNo, checkAdd: 1}, function (res) {
                        var obj = JSON.parse(res);
                        $('#patientvisitid').val(null).empty();
                        var option = new Option(obj.name, obj.id, true, true);
                        $("#patientvisitid").append(option);
                        $('#patientvisitid').select2("val", obj.id);
                        $("#select2-chosen-2").html(obj.name);
                        if (obj.allowAdd == 1) {
                            $('#visitaddsubmit').attr('disabled', false);
                        }
                    });
                } else {
                    $('#patientvisitid').val(null).empty().trigger("change");
                    $('#visitaddsubmit').attr('disabled', false);
                }
            });

            $('.searchPatRemoteLab').live('change', function (e) {

                var statusNo = $('#statusNoRemoteLab').val();
                var alerting = $(this).attr('data-alert');
                var shareVersion = $('#shareVersion').val();
                $("#phonesContainer").html(' ');
                if (statusNo > 0) {
                    $.post(hosturl + '/controllers/visits.php?ac=getnameswithstatus', {statusNo: statusNo, checkAdd: 1}, function (res) {
                        var obj = JSON.parse(res);
                        if (obj.allowAdd == 1) {
                            $('#visitaddsubmit').attr('disabled', false);
                        } else {
                            $('#visitaddsubmit').attr('disabled', true);
                            alert(' يوجد زيارة مضافة مسبقا لهذا المريض عن طريق خدمة العملاء  ...');
                        }

                        var phonesContainer = ' ';
                        if (obj.governorate > 0) {
                            phonesContainer = phonesContainer + ' ' + obj.govName;
                        }

                        if (obj.governorate_center > 0) {
                            if (obj.governorate > 0) {
                                phonesContainer = phonesContainer + ' -  ';
                            }
                            phonesContainer = phonesContainer + ' ' + obj.centerName;
                        }

                        if (obj.visit_phones == 1) {
                            if (obj.governorate > 0 || obj.governorate_center > 0) {
                                phonesContainer = phonesContainer + ' -  ';
                            }
                            phonesContainer = phonesContainer + ' ' + obj.phoneTxt;
                        }

                        if (obj.revisionedTxt != -1) {
                            phonesContainer = phonesContainer + '  -  ' + obj.revisionedTxt;
                        }

                        $("#phonesContainer").html(phonesContainer);
                        if (obj.vip == 1) {
                            alert('  Note :  Vip  Patient !!!!!!');
                        }



                        if (obj.stopped == 1) {
                            $('#visitaddsubmit').attr('disabled', true);
                            alert('  لا يمكن إضافة زيارة - هذا المريض موقوف .......');
                        } else if (obj.tempPatient == 1 && $('input[name="for_husband"]:checked').val() == 0) {
                            $('#visitaddsubmit').attr('disabled', true);
                            alert('لا يمكن إضافة زيارة - يرجى إكمال بيانات المريض أولا ');
                        } else {
                            $('#visitaddsubmit').attr('disabled', false);
                        }

                        if (obj.visitsCount > 0 && shareVersion == 4) {
                            alert(' يوجد اليوم زيارات أخرى لنفس المريض .....');
                        }

                        if ($('#orgIn').val() == 2) {
                            if (obj.organization_id > 0) {
                                $("#organizations").select2("val", obj.organization_id).trigger("change");
                            } else {
                                $("#organizations").select2("val", "").trigger("change");
                            }
                        }

                        if (alerting != 'no') {

                            getLastVisit(obj.id);
                            getLastAdvance(obj.id);
                            getRestDetectionVlues(obj.id, 1);
                            getBills(obj.id);
                            getChilds(obj.id);
                        }
                    });
                }
            });

            if ($('#cardVisitId').val() > 0) {
                var cardVisitId = Number($('#cardVisitId').val());
                var row = $('#editvisit' + cardVisitId).parent().parent();
                editVisitCommon(cardVisitId, row);
            } else {
                if ($('#statusNoRemoteLab').val() > 0) {
                    $('#statusNoRemoteLab ').trigger('keyup');
                    $('#statusNoRemoteLab ').trigger('change');
                }
            }

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

        function editVisitCommon(visitId, row) {
            var shareVersion = $('#shareVersion').val();
            $('#visitaddsubmit').hide();
            $('.editVisit').hide();
            $('.deletevisit').hide();
            row.css('background-color', '#f36a5a')

            $.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').val(null).empty();
                    var option = new Option(obj.name, obj.patientid, true, true);
                    $("#patientvisitid").append(option);
                    $('#patientvisitid').select2("val", obj.patientid);
                    $("#select2-chosen-2").html(obj.name);
                    $("input[name=for_husband][value=" + obj.for_husband + "]").prop('checked', true);

                    if (obj.sub_region_id > 0) {
                        $('#subRegionId').select2("val", obj.sub_region_id);
                    }


                    if (obj.for_husband == 2) {
                        $.post(hosturl + '/controllers/visits.php?ac=getChilds', {patientId: obj.patientid}, function (data) {
                            $("#childContain").html(data);
                            if (obj.child > 0) {
                                $('#childFor').select2("val", obj.child);
                            }
                            $("#childHead").show();
                            $("#childContain").show();
                        });
                    } else {
                        $("#childHead").hide();
                        $("#childContain").hide();
                    }


                    getLastVisit(obj.patientid);
                    getLastAdvance(obj.patientid);
                    loadPatDept(obj.patientid);
                    getRest(obj.patientid);
                    getBills(obj.patientid);
//                    $('#patientvisitid').select2("val", obj.patientid);

                    $('#visitdate').val(obj.visitdate);
                    $('#visit_time').val(obj.visit_time);
                    if (obj.detectionid > 0) {
                        $('#detectionid').select2("val", obj.detectionid);
                        if (shareVersion == 2) {
                            $('#oldDetectionId').val(obj.detectionid);
                        }
                    }

                    if (obj.organization_id > 0) {
                        $('#organizations').select2("val", obj.organization_id);
                        $('#discountRatio').val(obj.discountRatio);
                        $('#discountRatioType').val(obj.discountRatioType);
                    }


                    $('#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);
                    $('#unitsConsumed').val(obj.unitsConsumed);
                    $('#refer_doctor').select2("val", obj.refer_doctor);
                    if (obj.for_department == 13) {
                        $('#oldOperation_main_id').val(obj.operation_main_id);
                    }

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

//                    if (obj.for_department == 5) {
//                        $('#invType').attr("disabled", true);
//                    }

                    if (obj.for_department == 12 || obj.for_department == 5) {
                        $('#selectedFromModel').html("");
                        $('#selectedFromModel').html(obj.invRes);
                        $('#selectedFromModel').show();
                    }

                    if (obj.for_doctor > 0) {
                        $('#oldVisitDoctor').val(obj.for_doctor);
                        $('#oldVisitHours').val(obj.visitHours);
                    }


                    $('#operation_time').val(obj.operation_time);
                    $('#saveEditVisit').attr("data-visitId", visitId);
                    $('#mVisitId').val(visitId);
                    $('#editView').val(1);
                    $('#saveEditVisit').show();
                    $('#cancelEditVisit').show();
                }

            });
        }


        $("#patientvisitidNo , #patNo").select2({
            placeholder: "اختر ",
            minimumInputLength: 1,
            width: '100%',
//            minimumInputLength: document.getElementById("searchvalue").value,
            //	  maximumSelectionSize:3,
            //    multiple: false,
            quietMillis: 100,
            ajax: {
                url: hosturl + '/controllers/visits.php?ac=getnos',
                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: formatResult,
            formatSelection: formatSelection,
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                var data = {
                    id: item[0],
                    statusno: item[1]
                };
                callback(data);
            }
        });

        $('body').on('keyup', '.searchPat', function () {
            var search = $('#statusNo').val();
            var alerting = $(this).attr('data-alert');
            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 if (controllName == 'visits' || alerting == 'no') {
                    $('#patientvisitid').select2("val", res);
                } else if (controllName == 'customer_service') {
                    $('#patientService').select2("val", res).trigger("change");
                } else {
                    $('#patientvisitid').select2("val", res).trigger("change");
                }

            });
        });

        $('body').on('change', '.searchPat', function () {
            var search = $('#statusNo').val();
            var alerting = $(this).attr('data-alert');
            $.post(hosturl + '/controllers/visits.php?ac=searchpatient', {search: search}, function (res) {
                if (alerting != 'no') {
                    getLastVisit(res);
                    getLastAdvance(res);
                    getRestDetectionVlues(res, 1);
                    getBills(res);
                }
            });
        });

        $("#patientIdRemote , #patientIdOld , #patientIdSelect").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 addVisit = $('#addVisit').val();
             var labCompleteVisit = $('#labCompleteVisit').val();
            var statusNo = $('#statusNoRemote').val();
            var alerting = $(this).attr('data-alert');
            if (statusNo > 0) {
                $.post(hosturl + '/controllers/visits.php?ac=getnameswithstatus', {statusNo: statusNo}, function (res) {
                    var obj = JSON.parse(res);
                    $('#patientIdRemote').val(null).empty().trigger("change");
                    var option = new Option(obj.name, obj.id, true, true);
                    $("#patientIdRemote").append(option);
                    $('#patientIdRemote').select2("val", obj.id).trigger("change").trigger('select2:select');
                       if (addVisit == 1 || labCompleteVisit == 1) {
                        $("#select2-chosen-3").html(obj.name);
                    } else {
                        $("#select2-chosen-1").html(obj.name);
                    }

                });
            } else {
                $('#patientIdRemote').val(null).empty().trigger("change");
            }
        });

        $('.searchPatOld').live('keyup', function (e) {

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

        $("#doctorIdRemote").select2({
            placeholder: "اختر ",
            minimumInputLength: 3,
            width: '100%',
            allowClear: true,
            quietMillis: 100,
            ajax: {
                url: hosturl + '/controllers/visits.php?ac=getDoctors',
                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);
            }
        });

        $('body').on('input', '.searchPatPhone', function () {
            var phone = $('#phone').val();
            var controllName = $("#controllName").val();
            $.post(hosturl + '/controllers/visits.php?ac=searchpatientphone', {phone: phone}, function (res) {
                console.log(res);
                var obj = JSON.parse(res);
                if (controllName == 'financialreport') {
                    $('#patientName').select2("val", obj.patientid).trigger("change");
                } else if (controllName == 'customer_service') {
                    $('#patientService').select2("val", obj.patientid).trigger("change");
                    $('#statusNo').val(obj.statusno);
                } else {
                    $('#patientvisitid').select2("val", obj.patientid).trigger("change");
                }

            });
        });

        $('body').on('change', '#patNo', function () {
            var selectedPatientId = $(this).val();
            $("#patientName").select2("val", selectedPatientId).trigger("change");
        });

        $(".select2h").select2({placeholder: "Select", allowClear: true});

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

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

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

    $('body').on('click', '.deleteElementDivs', function () {
        var itemid = $(this).attr('data-id');
        var tableName = $(this).attr('data-tableName');
        var controllName = $('#controllName').val();
        var tr = $(this).parent().parent().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
                        //window.location.href = hosturl + "/controllers/" + controllName + ".php?ac=delRows&id=" + itemid + "&tableName=" + tableName;
                        $.post(hosturl + '/controllers/' + controllName + '.php?ac=del', {id: itemid, tableName: tableName}, function (res) {

                            if (res == 1) {
                                tr.remove();
                            } else {
                                alert("!!!!!!!!!!!!! some thing wrong here");
                            }
                        });
                    }
                }
            }
        }).find('.modal-content').addClass('modal-sm');
    });

    var forAll = function () {
        $('.newitemH').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/invsdept.php?ac=update', {
                    tableName: tableName, colName: colName, id: id, value: value
                }, function (data) {
                    $('.' + tableName + ' option[value="' + id + '"]').text(value);
                });
            }
        });
        $("#addnewH").live('click', function () {
            var tableName = $(this).attr('data-tableName');
            var selectname = $(this).attr('data-selectClass');
            var colName = $(this).attr('data-colName');
            var defaultValue = $('#defaultValue').val();
            $.post(hosturl + "/controllers/instruction.php?ac=addNewRow",
                    {tableName: tableName, colName: colName}, function (data) {

                var dataid = Number(data);
                if (dataid > 0) {
                    var ext = '';
                    if (defaultValue == 1) {
                        ext = '  <td class="txtc">    '
                                + ' <input type="radio" id="radio' + dataid + '" name="defaultValue" class="md-radiobtn"'
                                + '   data-id="' + dataid + '"  data-tableName="' + tableName + '"'
                                + '    data-colName="default_value"   value="1" >  '
                                + ' <label for="radio' + dataid + '"><span></span>'
                                + ' <span class="check"></span><span class="box"></span>'
                                + ' </label> </div>'
                                + '   <td>';
                    }


                    $('.' + selectname + ' > .deleteoptincompo').before('<option value="' + dataid + '" ></option>');
                    $("#editTableH").prepend('<tr>'
                            + '<td style="width: 100%">'
                            + '<input type="text" class="form-control newitemH" '
                            + '  data-id="' + dataid + '"  data-tableName="' + tableName + '"'
                            + '    data-colName="' + colName + '"   value="">'
                            + ' </td>'
                            + '   <td>'
                            + '   <a href="#" class="btn btn-xs red fleft deleteModalH wds100" data-id="' + dataid + '" '
                            + '    data-tableName="' + tableName + '" >'
                            + ' <i class="fa fa-times" ></i>'
                            + '</a>'
                            + '</td>'
                            + ext
                            + ' </tr>'
                            );
                }
            });
        });
        $('.deleteModalH').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/invsdept.php?ac=tabdeleteabbr', {id: id, tableName: tableName}, function (res) {

                                if (res == 1) {
                                    tr.parent().remove();
                                    $('.' + tableName + ' option[value="' + id + '"]').remove();
                                } else {
                                    alert("!!!!!!!!!!!!! some thing wrong here");
                                }

                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $('input[type=radio][name=defaultValue]').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/invsdept.php?ac=update', {
                    tableName: tableName, colName: colName, id: id, value: value
                }, function (data) {
                });
            }
        });
        if ($('#floor_no').length) {

            $("#floor_no").select2({
                placeholder: "Select",
                width: '240px',
                allowClear: true,
                formatNoMatches: function (term) {
                    /* customize the no matches output */
                    return "<input class='form-control' id='newTerm_floor_no' value='" + term + "'><a href='#' id='addNew_floor_no' class='btn blue custombtnstyle'>إضافة جديد</a>"
                }
            }).parent().find('.select2-with-searchbox').on('click', '#addNew_floor_no', function () {
                /* add the new term */
                var new_name = $('#newTerm_floor_no').val();
                $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {
                    selectId: 'floors',
                    new_name: new_name
                }, function (data) {


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

                });
            });
        }


        $('body').on('click', '#addNextVisit', function () {
            $("#nextVisitModal").modal('show');
        });
        $('body').on('click', '#saveNextVisit', function () {
            var nextVisitDate = $('#nextVisitDate').val();
            //  var nextVisitTime = $('#nextVisitTime').val();
            var nextVisitService = $('#nextVisitService').val();
            var nextVisitNotes = $('#nextVisitNotes').val();
            var redirectTo = $('#redirectTo').val();
            var patientId = $('#patientId').val();
            $.post(hosturl + '/controllers/visits.php?ac=addNextVisit', {
                patientId: patientId,
                redirectTo: redirectTo,
                nextVisitDate: nextVisitDate,
                //    nextVisitTime: nextVisitTime,
                nextVisitService: nextVisitService,
                nextVisitNotes: nextVisitNotes}, function (data) {
                if (data != -1) {
                    $('#nextVisitsDiv').html('');
                    $('#nextVisitsDiv').html(data);
                    $('#nextVisitNotes').val('');
                    $('#nextVisitService').select2("val", "");
                    $('#redirectTo').select2("val", "");
                    var shortCutFunction = 'success';
                    var msg = 'Contiuno your job .. good';
                    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);
            });
        });


        $('.delTarget').live('click', function () {
            var itemid = $(this).attr('data-id');
            var urlgo = $(this).attr('data-link');
            var fun = $(this).attr('data-fun');
            var tableName = $(this).attr("data-tableName");
            var container = $(this).attr("data-container");
            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=" + fun, {id: itemid, tableName: tableName}, function (data) {
                                $('#' + container).remove();
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
    };

    var patients = function () {
        $('body').on('click', '#addChild', function () {
            var patientId = $(this).attr('data-patientId');
            $.post(hosturl + '/controllers/patients.php?ac=addChild', {patientId: patientId}, function (res) {
                $('#childsContainer').append(res);
                $(".mask_date_new").mask("99-99-9999", {placeholder: "0"});
            });
        });
        $('body').on('click', '#addBirthNotidy', function () {
            var patientId = $(this).attr('data-patientId');
            $.post(hosturl + '/controllers/patients.php?ac=addBirthNotidy', {patientId: patientId}, function (res) {
                $('#notifyContainer').append(res);
                $(".datepicker").datepicker();
            });
        });
        $('body').on('click', '#printBirthNotify', function () {
            var patientId = $(this).attr('data-patientId');
            var notifyDate = $('#notifyDate').val();
            $.post(hosturl + '/controllers/patients.php?ac=printBirthNotify', {patientId: patientId, notifyDate: notifyDate}, function (res) {
                $("#printPatDiv").html(res);
                $.print("#printPatDiv");
                $("#printPatDiv").html("");
                $.post(hosturl + '/controllers/patients.php?ac=loadBirthNotify', {patientId: patientId}, function (data) {
                    $("#notifyContainer").html('');
                    $("#notifyContainer").html(data);
                });
            });
        });
    };

    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) {
                console.log(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");
                    $("#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();
            });
            checkQuantity(itr);
        });
        $('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();
            }

            checkQuantity(itr);
        });
        function checkQuantity(itr) {
            var drugId = $('#dname' + itr).val();
            var type = $('#dtype' + itr).val();
            $.post(hosturl + '/controllers/gyna.php?ac=checkquantity', {drugId: drugId, type: type}, function (res) {
                $('#drugQuantity' + itr).html(res);
            });
        }

        $('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) {
                console.log(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(result[0]);
                }

            });
        });
        $('body').on('click', '.sendPre', function () {
            var itr = $(this).attr('data-itr');
            var forS = $(this).attr('data-for');
            $('#sendLoading' + forS + itr).show();
            $('#sendDone' + forS + itr).hide();
            $('#sendError' + forS + itr).hide();
            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;
                }

            } else {
                date = $(this).attr('data-date');
                preFor = $(this).attr('data-for');
            }

            $.post(hosturl + '/controllers/gyna.php?ac=sendpre', {
                preFor: preFor, controller: controller, date: date,
                patientId: patientId,
                mainAntenatalId: mainAntenatalId,
                followid: followid,
                printDate: printDate
            }, function (res) {
                //   console.log(res);
                if (Number(res) == 1) {
                    $('#sendLoading' + forS + itr).hide();
                    $('#sendDone' + forS + itr).show();
                    $('#sendError' + forS + itr).hide();
                } else {
                    $('#sendLoading' + forS + itr).hide();
                    $('#sendDone' + forS + itr).hide();
                    $('#sendError' + forS + itr).show();
                }
            });
        });
        $('.all').on('click', '#preparedTTT', function () {
            var controller = $(this).attr('data-controller');
            $.post(hosturl + '/controllers/gyna.php?ac=preparedTTT', {controller: controller}, function (res) {
                $("#tempModels").html("");
                $("#tempModels").html(res);
                $('#docIdPre').select2();
                $('#docAddIdPre').select2();
                $("#preparedTTTModal").modal('show');
            });
        });
        $('body').on('click', '#addPreTTT', function () {
            $("#addNewPreDrugRow").trigger('click');
            $("#addNewPreTTTModel").modal('show');
        });
        $('body').on('click', '#addNewPreDrugRow', function () {
            var itr = $('#drugPreItr').val();
            var newItr = Number(itr) + 1;
//            var doctorId = $('#docAddId').val();

            $('#drugPreItr').val(newItr);
            $.post(hosturl + '/controllers/gyna.php?ac=drawPreRow', {itr: newItr}, function (res) {
                console.log(res);
                $('#drugPreContent').append(res);
                $('#preCat' + newItr).select2({placeholder: "Select", allowClear: true});
                $('#preName' + newItr).select2({placeholder: "Select", allowClear: true});
                $('#preType' + newItr).select2({placeholder: "Select", allowClear: true});
                $('#preDos' + newItr).select2({placeholder: "Select", allowClear: true});
            });
        });
        $('body').on('click', '.deletePreRow', function () {
            var itr = $(this).attr('data-itr');
            $('#preRow' + itr).remove();
        });
        $('body').on('change', '.preCat', function () {
            var itr = $(this).attr('data-itr');
            var value = $(this).val();
            $.post(hosturl + '/controllers/gyna.php?ac=search', {value: value, type: "cat"}, function (res) {
                $('#preName' + itr).html(res);
                $('#preName' + itr).select2("val", "");
                $('#preType' + itr).select2("val", "");
                $('#preDos' + itr).select2("val", "");
            });
        });
        $('body').on('change', '.preName', function () {
            var itr = $(this).attr('data-itr');
            var createNew = $(this).attr('data-createNew'); // 0 not yet , 1 created before
            if (createNew == 0) {
                $(this).attr('data-createNew', 1);
                $("#addNewPreDrugRow").trigger('click');
            }
            var value = $(this).val();
            $.post(hosturl + '/controllers/gyna.php?ac=search', {value: value, type: "name_type"}, function (res) {
                $('#preType' + itr).html(res);
                var firstType = $('#preType' + itr + ' option:eq(1)').val();
                $('#preType' + itr).select2("val", firstType);
            });
            $.post(hosturl + '/controllers/gyna.php?ac=search', {value: value, type: "name_dos"}, function (res) {
                $('#preDos' + itr).html(res);
                var firstDos = $('#preDos' + itr + ' option:eq(1)').val();
                $('#preDos' + itr).select2("val", firstDos);
            });
        });
        $('body').on('change', '.preType', function () {
            var itr = $(this).attr('data-itr');
            var value = $(this).val();
            var drugId = $('#dname' + itr).val();
            if (!value) {
                $('#preDos' + itr).select2("val", "");
            } else {
                $.post(hosturl + '/controllers/gyna.php?ac=search', {
                    value: value,
                    type: "type",
                    drugId: drugId
                }, function (res) {

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

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

            var docId = $('#docAddIdPre').val();
            if (docId > 0) {
                $.post(hosturl + '/controllers/gyna.php?ac=addPreTTT', $('#addPreTTTForm').serialize(), function (res) {
                    if (Number(res) > 0) {
                        $('#preEditMode').val(0);
                        $('#drugPreId').val(0);
                        $('#docIdPre').select2("val", docId).trigger("change");
                        $('#addNewPreTTTModel').modal('hide');
                        $('#preparedTTTModal').modal('hide');
                        $(".modal-backdrop").remove();
                        $('#preparedTTT').trigger("click");
                    }
                });
            } else {
                alert(' choose doctor first ..........');
            }

        });
        $('body').on('change', '#docIdPre', function () {
            var id = $(this).val();
            var controller = $(this).attr('data-controller');
            $.post(hosturl + '/controllers/gyna.php?ac=getPreByDoctor', {id: id, controller: controller}, function (data) {
                $("#instPreDiv").html("");
                $('#instPreDiv').html(data);
            });
        });
        $('body').on('click', '.addPatPrePres', function () {
            var id = $(this).attr('data-id');
            var patientId = $('#patientId').val();
            var controller = $(this).attr('data-controller');
            var mainAntenatalId = $('#mainAntenatalId').val();
            var followid = $('#followId').val();
            var preFor = $(this).attr('data-for');
            $.post(hosturl + '/controllers/gyna.php?ac=addPatPrePres', {
                id: id, patientId: patientId, controller: controller, mainAntenatalId: mainAntenatalId
                , followid: followid, preFor: preFor
            }, function (data) {
                if (Number(data) > 0) {
                    $('#preparedTTTModal').modal('hide');
                    $(".modal-backdrop").remove();
                    $('#addPreLoading').show();
                    editPrePres(controller, preFor);
                }

            });
        });
        function editPrePres(controller, preFor) {
            var patientId = $('#patientId').val();
            var mainAntenatalId = $('#mainAntenatalId').val();
            var followid = $('#followId').val();
            var today = new Date();
            var preDate = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
            $.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');
                $('#addPreLoading').hide();
            });
        }

        $('body').on('click', '.editPrePres', function () {
            var id = $(this).attr('data-id');
            $.post(hosturl + '/controllers/gyna.php?ac=editPrePres', {id: id}, function (data) {
                $('#preEditMode').val(1);
                $("#preEditContent").html("");
                $('#preEditContent').html(data);
                $("#addNewPreTTTModel").modal('show');
            });
        });
        //################################################
        $('.all').on('click', '#addChronic', function () {
            var controller = $(this).attr('data-controller');
            var patientId = $('#patientId').val();
            $.post(hosturl + '/controllers/approvals.php?ac=chronicTTT', {controller: controller, patientId: patientId}, function (res) {
                $("#tempModels").html("");
                $("#tempModels").html(res);
                if ($('#drugChronicItr').val() == 0) {
                    $("#addChronicDrug").trigger('click');
                }
                $("#chronicTTTModal").modal('show');
            });
        });
        $('body').on('click', '#addChronicDrug', function () {
            var itr = $('#drugChronicItr').val();
            var presDate = $('#presChronicDate').val();
            var patientId = $('#patientId').val();
            var newItr = Number(itr) + 1;
            var preFor = 0;
            $('#drugChronicItr').val(newItr);
            if ($('#forChronicHusband').is(':checked')) {
                preFor = 1;
            } else {
                preFor = 0;
            }


            $.post(hosturl + '/controllers/approvals.php?ac=drawChronicRow', {
                itr: newItr, preFor: preFor, patientId: patientId, presDate: presDate}, function (res) {
                console.log(res);
                $('#preChronicContent').append(res);
            });
        });
        $('body').on('change', '.chronicCat', function () {
            var itr = $(this).attr('data-itr');
            var value = $(this).val();
            $.post(hosturl + '/controllers/gyna.php?ac=search', {value: value, type: "cat"}, function (res) {
                $('#chronicName' + itr).html(res);
                $('#chronicName' + itr).select2("val", "");
                $('#chronicType' + itr).select2("val", "");
                $('#chronicDos' + itr).select2("val", "");
            });
        });
        $('body').on('change', '.chronicName', function () {
            var itr = $(this).attr('data-itr');
            var createNew = $(this).attr('data-createNew'); // 0 not yet , 1 created before
            if (createNew == 0) {
                $(this).attr('data-createNew', 1);
                $("#addChronicDrug").trigger('click');
            }
            var value = $(this).val();
            $.post(hosturl + '/controllers/gyna.php?ac=search', {value: value, type: "name_type"}, function (res) {
                $('#chronicType' + itr).html(res);
                var firstType = $('#chronicType' + itr + ' option:eq(1)').val();
                $('#chronicType' + itr).select2("val", firstType);
                $('#chronicType' + itr).change();
            });
            $.post(hosturl + '/controllers/gyna.php?ac=search', {value: value, type: "name_dos"}, function (res) {
                $('#chronicDos' + itr).html(res);
                var firstDos = $('#chronicDos' + itr + ' option:eq(1)').val();
                $('#chronicDos' + itr).select2("val", firstDos);
                $('#chronicDos' + itr).change();
            });
        });
        $('body').on('change', '.chronicType', function () {
            var itr = $(this).attr('data-itr');
            var value = $(this).val();
            var drugId = $('#chronicName' + 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) {
                        $('#chronicDos' + itr).select2("val", "").trigger("change");
                    } else {
                        $('#chronicDos' + itr).select2("val", res).trigger("change");
                    }

                });
                $('#chronicDos' + itr).change();
            }
        });
        $('body').on('change', '#forChronicHusband , #presChronicDate', function () {

            var preDate = $('#presChronicDate').val();
            var patientId = $('#patientId').val();
            var preFor = 0;
            if ($('#forChronicHusband').is(':checked')) {
                preFor = 1;
            } else {
                preFor = 0;
            }

            $.post(hosturl + '/controllers/approvals.php?ac=chronicPres', {
                preFor: preFor, patientId: patientId, preDate: preDate}, function (res) {
                $("#preChronicContent").html("");
                $("#preChronicContent").html(res);
            });
        });
        $('body').on('click', '.printChronicPre', function () {
            var patientId = $('#patientId').val();
            var preDate = $('#presChronicDate').val();
            var printDate = $('printChronicDate').val();
            var preFor = 0;
            if ($('#forChronicHusband').is(':checked')) {
                preFor = 1;
            } else {
                preFor = 0;
            }

            $.post(hosturl + '/controllers/approvals.php?ac=printChronicPres', {
                preFor: preFor, patientId: patientId, preDate: preDate, printDate: printDate}, function (res) {
                $("#drugPrint").html(res);
                $.print("#drugPrint");
                $("#drugPrint").html("");
            });
        });
    };

    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', '.invResShow', function () {
            var id = $(this).attr('data-id');
            var itr = $(this).attr('data-itr');
            var show = $("#invResShowTd_" + itr).attr('data-show');
            var current = $("#invResShowTd_" + itr).attr('data-current');
            if (show == 1 && id == current) {
                $("#invResShowTd_" + itr).html("");
                $("#invResShowTd_" + itr).attr('data-show', 0);
                $("#invResShowTd_" + itr).attr('data-current', 0);
            } else {
                $.post(hosturl + '/controllers/invsdept.php?ac=invResShow', {id: id}, function (res) {
                    $("#invResShowTd_" + itr).html("");
                    $("#invResShowTd_" + itr).html(res);
                    $("#invResShowTd_" + itr).attr('data-show', 1);
                    $("#invResShowTd_" + itr).attr('data-current', id);
                });
            }
        });
        $('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', '.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');
            }
        });
        $('body').on('click', '#searchRecords', function () {

            $('#searchRecords').attr('disabled', true);
            var type = $(this).attr('data-type');
            var table = $(this).attr('data-type1');
            var status = $(this).attr('data-status');
            var searchValues = Array();
            searchValues.push(type);
            searchValues.push($('#searchValue1').val());
            searchValues.push($('#searchValue2').val());
            searchValues.push(status);
            searchValues.push($('#patientIdRemote').val());
            searchValues.push($('#branch_id').val());
                        searchValues.push($('#sampleIdShow').val());
            searchValues.push($('#patIdShow').val());
            searchValues.push($('#patMobileShow').val());
              searchValues.push($('#testId').val());
            searchValues.push($('#testStatus').val());
            var jsonString = JSON.stringify(searchValues);
               if ($('#patientIdRemote').val() > 0 || $('#searchValue1').val() != '' || $('#searchValue2').val() != '' || 
                    $('#sampleIdShow').val() != ''  || $('#patIdShow').val() != ''  || $('#patMobileShow').val() != '' ||
                    $('#testId').val() > 0) {
                $('#oldSearchError').hide();
                $.post(hosturl + '/controllers/invsdept.php?ac=searchrecord', {jsonString: jsonString}, function (data)
                {
                    console.log(data);
                    $('#resultTableDiv').html('');
                    $('#resultTableDiv').html(data.trim());
                    $("#invStatusDiv").html("");
                    $('#' + table + 'RequesrsTable').dataTable({
                        "order": [[0, "desc"]],
                        "pageLength": 25
                    });
                    $('#searchRecords').attr('disabled', false);
                });
            } else {
                $('#searchRecords').attr('disabled', false);
                $('#oldSearchError').show();
                //     $('#resultTableDiv').html('');
                //   $("#invStatusDiv").html("");
            }


        });
        $('body').on('change', '.searchRecords', function () {
            var type = $(this).attr('data-type');
            var table = $(this).attr('data-type1');
            var status = $(this).attr('data-status');
            var searchValues = Array();
            searchValues.push(type);
            searchValues.push($('#searchValue1').val());
            searchValues.push($('#searchValue2').val());
            searchValues.push(status);
            searchValues.push($('#patientIdRemote').val());
            var jsonString = JSON.stringify(searchValues);
            if ($('#patientIdRemote').val() > 0 || $('#searchValue1').val() != '' || $('#searchValue2').val() != '') {
                $.post(hosturl + '/controllers/invsdept.php?ac=searchrecord', {jsonString: jsonString}, function (data) {
                    console.log(data);
                    $('#resultTableDiv').html('');
                    $('#resultTableDiv').html(data.trim());
                    $("#invStatusDiv").html("");
                    $('#' + table + 'RequesrsTable').dataTable({
                        "order": [[0, "desc"]],
                        "pageLength": 25
                    });
                });
            } else {
                $('#resultTableDiv').html('');
                $('#resultTableDiv').html('<table class="table table-striped table-hover table-bordered rtl" style=" width: 98%;">'
                        + ' <thead>'
                        + '   <tr>'
                        + '     <th colspan="2">    عدد المرضى       '
                        + '       <span style="background-color: yellow;padding: 0 2% 0 2% ;margin: 0 2% 0 2% ;" '
                        + '             class="wds2"> 0 </span>'
                        + '    </th>'
                        + '  </tr>'
                        + '<tr>'
                        + '<th colspan="2">   '
                        + '<span class="col-md-2 wds20 searchRecords2 "  data-cat ="1"'
                        + ' style="background-color: white;" data-type="invests" data-type1="lab" >All</span>'
                        + '<span class="col-md-2 wds20 searchRecords2"   data-cat ="2"'
                        + '   style="background-color: antiquewhite;" data-type="invests" data-type1="lab" >new</span>'
                        + '  <span class="col-md-2 wds20 searchRecords2"   data-cat ="3"'
                        + '      style="background-color: aquamarine;" data-type="invests" data-type1="lab" >F</span>'
                        + ' <span class="col-md-2 wds20 searchRecords2"   data-cat ="4"'
                        + '     style="background-color: aliceblue;" data-type="invests" data-type1="lab" >F + V</span>'
                        + '  <span class="col-md-2 wds20 searchRecords2"   data-cat ="5"'
                        + '    style="background-color: #e1ff3f;" data-type="invests" data-type1="lab" >F + V  + P</span>'
                        + ' </th>'
                        + ' </tr>'
                        + ' </thead>'
                        + '</table>');
                $("#invStatusDiv").html("");
            }


        });
        $('body').on('click', '.searchRecords2', function () {
            var cat = Number($(this).attr('data-cat'));
            $('#result_1').hide();
            $('#result_2').hide();
            $('#result_3').hide();
            $('#result_4').hide();
            $('#result_5').hide();
            $('#result_6').hide();
            $('#result_9').hide();
            $('#result_' + cat).show();
        });
        $('body').on('click', '.invStatus', function () {
            var visitid = $(this).attr('data-visitid');
            $.post(hosturl + '/controllers/invsdept.php?ac=invStatus', {visitid: visitid}, function (res) {
                $("#invStatusDiv").html("");
                $("#invStatusDiv").html(res.trim());
//                $("#invStatusModal").modal('show');
            });
        });
        $('body').on('click', '.invStatusChange', function () {
            var id = $(this).attr('data-id');
            var colName = $(this).attr('data-colName');
            var val = $(this).attr('data-val');
            var paid = $(this).attr('data-paid');
            var dna = $(this).attr('data-dna');
            var clicked = $(this);
            if (colName == "delivered" && val == 1 && paid != 1) {
                alert(' لا يمكن  تسليم التحاليل قبل دفع قيمة التحليل  أولا ...');
            }
            //########################
            else if (val == 1 && colName == 'delivered') {
                bootbox.dialog({
                    message: "هل ترغب فى تسليم هذا التحليل ؟ ",
                    title: "   هل ترغب فى تسليم هذا التحليل ؟ ",
                    buttons: {
                        danger: {
                            label: "إلغاء ",
                            className: "btn-green"
                        },
                        main: {
                            label: "تأكيد ",
                            className: "btn-primary",
                            callback: function () {
                                //do something else
                                statusUpdate(clicked, id, colName, val, dna, 0);
                            }
                        }
                    }
                }).find('.modal-content').addClass('modal-sm');
            }
            //########################
            else if (val == 1 && colName == 'sent') {
                clicked.attr('disabled', true);
                $.post(hosturl + '/controllers/adddevices.php?ac=externalLabs', {id: id}, function (res) {
                    console.log(res);
                    if (Number(res) != 1) {
                        $('#externalSendDiv').html('');
                        $('#externalSendDiv').html(res);
                        $('#exLabs' + id).select2();
                        $("#externalSendModal").modal('show');
                    }
                    clicked.attr('disabled', false);
                    statusUpdate(clicked, id, colName, val, dna, 0);
                });
            }
            //########################
            else {
                statusUpdate(clicked, id, colName, val, dna, 0);
            }
        });
        $('body').on('click', '.invReDeliver', function () {
            var id = $(this).attr('data-id');
            var colName = 'delivered';
            var val = 1;
            var paid = $(this).attr('data-paid');
            var dna = $(this).attr('data-dna');
            var clicked = $(this);
            if (colName == "delivered" && val == 1 && paid != 1) {
                alert(' لا يمكن  تسليم التحاليل قبل دفع قيمة التحليل  أولا ...');
            }
            //########################
            else if (val == 1 && colName == 'delivered') {
                bootbox.dialog({
                    message: "هل ترغب فى تسليم هذا التحليل ؟ ",
                    title: "   هل ترغب فى تسليم هذا التحليل ؟ ",
                    buttons: {
                        danger: {
                            label: "إلغاء ",
                            className: "btn-green"
                        },
                        main: {
                            label: "تأكيد ",
                            className: "btn-primary",
                            callback: function () {
                                //do something else
                                statusUpdate(clicked, id, colName, val, dna, 1);
                            }
                        }
                    }
                }).find('.modal-content').addClass('modal-sm');
            }
        });
        $('body').on('click', '#searchPatientLabs', function () {

            $('#searchPatientLabs').attr('disabled', true);
            var searchValues = Array();
            searchValues.push($('#searchValue1').val());
            searchValues.push($('#searchValue2').val());
            searchValues.push($('#patientIdRemote').val());
            var jsonString = JSON.stringify(searchValues);
            if ($('#patientIdRemote').val() > 0 || $('#searchValue1').val() != '' || $('#searchValue2').val() != '') {
                $('#oldSearchError').hide();
                $.post(hosturl + '/controllers/invsdept.php?ac=searchPatientLabs', {jsonString: jsonString}, function (data)
                {
                    console.log(data);
                    $('#patientLabsDiv').html('');
                    $('#patientLabsDiv').html(data);
                    $("#labDetailsDiv").html("");
                    $("#labDetailsDiv").css('border', '0');
                    $('#searchPatientLabs').attr('disabled', false);
                });
            } else {
                $('#searchPatientLabs').attr('disabled', false);
                $('#oldSearchError').show();
            }
        });
        $('body').on('click', '.patientLabDtails', function () {
            var visitId = $(this).attr('data-visitId');
            $("#labDetailsDiv").html('<div id="talks-loading"    '
                    + '  style="z-index: 3000;position: absolute;top: 5%;right: 5%;    '
                    + ' left: 0%; height: 125px; background-color: rgba(0, 0, 0,0.27); padding-top: 7%;" align="center">   '
                    + '<img src="' + hosturl + '/../upload/loading.gif">  '
                    + '</div>');
            $.post(hosturl + '/controllers/invsdept.php?ac=patientLabDtails', {visitId: visitId}, function (res) {
                $("#labDetailsDiv").html("");
                $("#labDetailsDiv").html(res);
                $("#labDetailsDiv").css('padding', '15px');
                $("#labDetailsDiv").css('border', '1px solid #000000');
            });
        });
        function statusUpdate(clicked, id, colName, val, dna, reDeliver) {

            if (val == 1 && colName == 'delivered') {
                clicked.attr('disabled', true);
            }


            $.post(hosturl + '/controllers/invsdept.php?ac=invStatusChange'
                    , {id: id, colName: colName, value: val, dna: dna, reDeliver: reDeliver}, function (res) {
                console.log(res);
                if (Number(res) != 1) {
                    var obj = JSON.parse(res);
                    alert(obj);
                } else {
                    if (val == 1) {
                        var target = 'check';
                        var remove = 'times';
                        var color = '#119866';
                        var new_val = 0;
                    } else {
                        var target = 'times';
                        var remove = 'check';
                        var color = 'red';
                        var new_val = 1;
                    }

                    if (val == 1 && colName == 'delivered' && reDeliver != 1) {
                        clicked.removeClass('invStatusChange');
                        clicked.addClass('invReDeliver');
                        alert('تم الإرسال  بنجاح . ');
                    }


                    if (val == 1 && colName == 'delivered' && reDeliver == 1) {
                        alert('تم التحديث بنجاح . ');
                    }

                    clicked.removeClass('fa-' + remove);
                    clicked.addClass('fa-' + target);
                    clicked.css('color', color);
                    clicked.attr('data-val', new_val);
                }
                clicked.attr('disabled', false);
            });
        }

        $('body').on('change', '#invsCats', function () {
            var catId = $('#invsCats').val();
            $.post(hosturl + '/controllers/invsdept.php?ac=getinvbycatid', {catId: catId}, function (res) {
                $('#investsDiv').html('');
                $('#investsDiv').html(res);
                $('#invests').select2();
            });
        });

        $('body').on('change', '.searchInvData', function () {
            var catId = $('#invsCats').val();
            var invId = $('#invests').val();
            var from = $('#searchValue1').val();
            var to = $('#searchValue2').val();
            var branch_id = $("#branch_id").val();

            $.post(hosturl + '/controllers/invsdept.php?ac=searchinvs', {
                catId: catId, branch_id: branch_id
                , invId: invId, from: from, to: to
            }, function (data) {
                $('#resultTableDiv').html('');
                $('#resultTableDiv').html(data);
                $('#requesrsTable').dataTable({
                    "order": [[0, "desc"]],
                    "pageLength": 25
                });
            });
        });

        $('body').on('click', '.invStatusChangeAll', function () {
            var visitId = $(this).attr('data-visitid');
            var colName = $(this).attr('data-colName');
            var paid = $(this).attr('data-paid');
            var clicked = $(this);
            if (colName == "delivered" && paid != 1) {
                alert(' لا يمكن  تسليم التحاليل قبل دفع قيمة التحليل  أولا ...');
            } else if (paid == 1 && colName == 'delivered') {
                bootbox.dialog({
                    message: "هل ترغب فى تسليم التحاليل  ؟ ",
                    title: "   هل ترغب فى تسليم التحاليل ؟ ",
                    buttons: {
                        danger: {
                            label: "إلغاء ",
                            className: "btn-green"
                        },
                        main: {
                            label: "تأكيد ",
                            className: "btn-primary",
                            callback: function () {
                                //do something else
                                statusUpdateAll(clicked, visitId, colName);
                            }
                        }
                    }
                }).find('.modal-content').addClass('modal-sm');
            } else {
                statusUpdateAll(clicked, visitId, colName);
            }

        });

        function statusUpdateAll(clicked, visitId, colName) {

            if (colName == 'delivered') {
                clicked.attr('disabled', true);
            }

            $.post(hosturl + '/controllers/invsdept.php?ac=invStatusChangeAll', {visitId: visitId, colName: colName}, function (res) {
                console.log(res);
                $('#invStatus' + visitId).trigger('click');
            });
        }

        $('body').on('click', '#searchInvData', function () {
            var catId = $('#invsCats').val();
            var invId = $('#invests').val();
            var from = $('#searchValue1').val();
            var to = $('#searchValue2').val();
            var branch_id = $("#branch_id").val();

            $('#searchInvData').attr('disabled', true);
            $.post(hosturl + '/controllers/invsdept.php?ac=searchinvs', {
                catId: catId, branch_id: branch_id
                , invId: invId, from: from, to: to
            }, function (data) {
                $('#resultTableDiv').html('');
                $('#resultTableDiv').html(data);
                $('#requesrsTable').dataTable({
                    "order": [[0, "desc"]],
                    "pageLength": 25
                });
                $('#searchInvData').attr('disabled', false);
            });
        });


        $('body').on('click', '#searchOldRecords', function () {
            var date = $('#searchValue1').val();
            var patientId = $('#patientIdOld').val();
            var deptId = $(this).attr('data-dept');
            if (patientId > 0 || (date != '' && date != null)) {
                $('#oldSearchError').hide();
                $.post(hosturl + '/controllers/visits.php?ac=oldVisits', {date: date, patientId: patientId, deptId: deptId}, function (data) {
                    $('#resultTableDiv').html('');
                    $('#resultTableDiv').html(data);
                });
            } else {
                $('#oldSearchError').show();
            }
        });


        $('body').on('click', '#printInvData', function () {
            var catId = $('#invsCats').val();
            var invId = $('#invests').val();
            var from = $('#searchValue1').val();
            var to = $('#searchValue2').val();
            var branch_id = $("#branch_id").val();

            $('#printInvData').attr('disabled', true);
            $.post(hosturl + '/controllers/invsdept.php?ac=printinvs', {
                catId: catId, branch_id: branch_id
                , invId: invId, from: from, to: to
            }, function (data) {
                $('#printDiv').html(data);
                $.print("#printDiv");
                $("#printDiv").html("");
                $('#printInvData').attr('disabled', false);
            });
        });


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

            $.post(hosturl + '/controllers/invsdept.php?ac=suppliesModel', {useDate: 1}, function (data) {
                $('#suppliesDiv').html('');
                $('#suppliesDiv').html(data);
                $('#suppliesCats').select2();
                $('#supply_id').select2();
                $('#useDate').datepicker();
                $("#suppliesModal").modal('show');
            });
        });

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

            var useDate = $('#useDate').val();
            $.post(hosturl + '/controllers/invsdept.php?ac=suppliesCatModal', {useDate: useDate}, function (data) {
                $("#suppliesModal").modal('hide');
                $('#suppliesDiv').html('');
                $('#suppliesDiv').html(data);
                $("#suppliesCatModal").modal('show');
            });
        });

        $('body').on('click', '#suppCat_add', function () {
            $.post(hosturl + '/controllers/invsdept.php?ac=addnewcat', function (res) {
                $('#invSuppCatNew').append('<tr>'
                        + '<td>'
                        + '<input type="text" class="form-control updateElement " id="cat' + res + '"   '
                        + '  data-id="' + res + '" data-colName="name" data-tableName="suppliescats"/>'
                        + '</td>'
                        + '<td> '
                        + ' <a class="btn green btn-xs showSupp" data-id="' + res + '" style=" float: left;" href="#" > '
                        + ' <i class="fa fa-pencil"></i>Show </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="suppliescats"><i class="fa fa-close"></i></a> '
                        + ' </td>'
                        + '</tr>');
                $('#cat' + res).focus();
            });
        });

        $('body').on('click', '#newSupplyFinish', function () {
            var useDate = $('#useDateChosen').val();
            $.post(hosturl + '/controllers/invsdept.php?ac=suppliesModel', {useDate: useDate}, function (data) {
                $("#suppliesCatModal").modal('hide');
                $('#suppliesDiv').html('');
                $('#suppliesDiv').html(data);
                $('#suppliesCats').select2();
                $('#supply_id').select2();
                $("#suppliesModal").modal('show');
            });
        });

        $('body').on('change', '#useDate , #branch_idCat ', function () {
            var useDate = $('#useDate').val();
            var branch_id = $("#branch_idCat").val();

            $.post(hosturl + '/controllers/invsdept.php?ac=loadDateSupplies', {useDate: useDate, branch_id: branch_id}, function (data) {
                $('#suppliesContent').html('');
                $('#suppliesContent').html(data);
            });
        });

        $('body').on('click', '.showSupp', function () {
            var catId = $(this).attr("data-id");
            //    $('#catId').val(catId);
            $.post(hosturl + '/controllers/invsdept.php?ac=getsuppbycatid', {catId: catId}, function (res) {
                $('#suppliesByCatDiv').html('');
                $('#suppliesByCatDiv').html(res);
                $("#suppliesByCatModal").modal('show');
            });
        });

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

            var catId = $(this).attr("data-catId");
            $.post(hosturl + '/controllers/invsdept.php?ac=addnewSupp', {catId: catId}, function (res) {
                $('#suppByCatNew').append('<tr>'
                        + '<td>'
                        + '<input type="text" class="form-control updateElement " id="supp' + res + '"   '
                        + '  data-id="' + res + '" data-colName="name" data-tableName="supplies"/>'
                        + '</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="supplies"><i class="fa fa-close"></i></a> '
                        + ' </td>'
                        + '</tr>');
                $('#cat' + res).focus();
            });
        });

        $('body').on('click', '#addInvestSupply', function () {
            $('#addInvestSupply').attr('disabled', true);
            var catId = $('#suppliesCats').val();
            var branch_id = $("#branch_idCat").val();

            if ((catId > 0 || catId == -1) && branch_id > 0) {
                $.post(hosturl + '/controllers/invsdept.php?ac=addnewInvSupp', $('#suppForm').serialize(), function (res) {
                    $('#useDate').trigger('change');
                    $('#suppliesCats').select2('val', '').trigger('change');
                    $('#addInvestSupply').attr('disabled', false);
                });
            } else {
                alert(' Choose Category and Branch First .');
                $('#addInvestSupply').attr('disabled', false);
            }
        });

        $('body').on('click', '#closeSupply', function () {
            $("#suppliesCatModal").modal('hide');
            $("#suppliesByCatModal").modal('hide');
            $("#suppliesModal").modal('hide');
        });

        $('body').on('change', '#suppliesCats', function () {
            var catId = $('#suppliesCats').val();
            $.post(hosturl + '/controllers/invsdept.php?ac=supBycatid', {catId: catId}, function (res) {
                $('#suuuDiv').html('');
                $('#suuuDiv').html(res);
                $(".positivefloat").forcepositivefloat();
            });
        });
    };

    var patientRay = function () {
        $('body').on('click', '#addRay', function () {
            var patientId = $('#patientId').val();
            $('#pId11').val(patientId);
            var mainAntenatalId = $('#mainAntenatalId').val();
            $('#mainId11').val(mainAntenatalId);
            $("#addPatientRays").modal('show');
        });
        $('body').on('click', '#showRay', 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=showRays', {
                patientId: patientId,
                mainAntenatalId: mainAntenatalId,
                archive: archive
            }, function (res) {
                $("#showRays").html("");
                $("#showRays").html(res);
                $("#showPatientRays").modal('show');
            });
        });
        $('body').on('click', '.printRay', function () {
            var controller = $(this).attr('data-controller');
            var print = $(this).attr('data-print');
            $.post(hosturl + '/controllers/' + controller + '.php?ac=addray', $('#gynaRay').serialize(), function (res) {
                if (print == 1) {
                    $("#ray_div").html(res);
                    $.print("#ray_div");
                }

                $("#ray_div").html("");
                $('.iiin').each(function () {
                    $(this).removeAttr('checked');
                    if ($(this).parent().attr("class") === 'checked') {
                        $(this).parent().attr("class", '')
                    }
                });
                $('#addPatientRays').modal('hide');
            });
        });
        $('body').on('click', '.printRayShow', 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=printray', {
                date: date,
                patientId: patientId,
                mainAntenatalId: mainAntenatalId,
                dataFor: dataFor
            }, function (res) {
                $("#ray_divShow").html(res);
                $.print("#ray_divShow");
                $("#ray_divShow").html("");
            });
        });
        $('body').on('change', '#forHusbandRay', function () {
            if ($(this).is(":checked")) {
                $('.husbandCheck').attr('checked', true);
                $('.husbandCheck').parent().addClass('checked');
            } else {
                $('.husbandCheck').removeAttr('checked');
                $('.husbandCheck').parent().removeClass('checked');
            }
        });
        $("body").on('click', '.showRayImg', function () {
            var src = $(this).attr('src');
            $('#source_image').attr('src', src);
            $("#showRaysImgsM").modal('show');
        });
        $('body').on('click', '.delRImg', function ()
        {
            var tableName = $(this).attr('data-tableName');
            var id = $(this).attr('data-id');
            var folder = $(this).attr('data-folder');
            var colName = $(this).attr('data-colName');
            var tr = $(this).parent().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/raysdept.php?ac=delimg',
                                    {id: id, tableName: tableName, folder: folder, colName: colName}, function (res) {
                                if (res == 1) {
                                    tr.remove();
                                } else {
                                    alert("!!!!!!!!!!!!! some thing wrong here");
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $('body').on('change', '.rayImgMulti', function () {
            var Id = $(this).attr('data-id');
            var colName = $(this).attr('data-colName');
            var tableName = $(this).attr('data-tableName');
            var patientD = $(this).attr('data-patientD');
            $('#talks-loading' + Id).show();
            var files = $('#rayImg' + Id)[0].files;
            var isValid = 2;
            for (var i = 0; i < files.length; i++) {
                // alert(files[i].name);
                var valid = checkImage(files[i].name);
                if (valid == 2) {

                } else if (valid == 1) {
                    isValid = 1;
                }
            }

            if (isValid == 2) {
                var myformdata = new FormData();
                myformdata.append("Id", Id);
                myformdata.append("colName", colName);
                myformdata.append("tableName", tableName);
                myformdata.append("imgCount", files.length);
                myformdata.append("patientD", patientD);
                jQuery.each(jQuery('#rayImg' + Id)[0].files, function (i, file) {
                    myformdata.append('file-' + i, file);
                });
                $.ajax({
                    url: hosturl + '/controllers/raysdept.php?ac=uploadMulti', // Url to which the request is send
                    type: "POST", // Type of request to be send, called as method
                    data: myformdata, // Data sent to server, a set of key/value pairs representing form fields and values
                    contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
                    cache: false, // To unable request pages to be cached
                    processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
                    success: function (data)  		// A function to be called if request succeeds
                    {
                        if (data != -1) {
                            $('#rayImgDiv' + Id).html('');
                            $('#rayImgDiv' + Id).html(data);
                            console.log(data);
                            $('#talks-loading' + Id).hide();
                        }
                    }
                });
            }
        });
    };

    var patientUs = function () {
        $('body').on('click', '#addUS', function () {
            var ultrasoundForm = $('#ultrasoundForm').val();
            var controllName = $('#controllName').val();
            if (controllName == 'gyna' || controllName == 'and_visits') {
                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();
                $('#netWText').remove();
                $.post(hosturl + '/controllers/antenalvisit.php?ac=loadusrow', {
                    patientId: patientId,
                    itr: itr,
                    type: type,
                    mainAntenatalId: mainAntenatalId
                }, function (res) {
                    $('#' + type).prepend(res);
                    var antType = $('#netWText').val();
                    declareAntSelects(antType);
                });
            } else if (type == 'uscompleteAnd' || type == 'ussimpleAnd') {
                $.post(hosturl + '/controllers/and_visits.php?ac=loadusrow', {
                    patientId: patientId,
                    itr: itr,
                    type: type,
                }, function (res) {
                    $('#' + type).prepend(res);
                });
            } else {
                $.post(hosturl + '/controllers/gyna.php?ac=loadusrow', {
                    patientId: patientId,
                    itr: itr,
                    type: type
                }, function (res) {
                    $('#' + type).prepend(res);
                });
            }

        });
        function declareAntSelects(type) {
            if (type != 2) {
                $(".no_soc").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisId = $(this).attr("id");
                        return "<input class='form-control' id='newAntRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
                    /* add the new term */
                    var newTerm = $('#newAntRecordTerm').val();
                    var thisId = $(this).attr("data-id");
                    $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'no_soc', new_name: newTerm
                    }, function (data) {

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

                        $('.updateElement[id=' + thisId + ']').trigger("change");
                    });
                });
                $(".no_fetal").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisId = $(this).attr("id");
                        return "<input class='form-control' id='newAntRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
                    /* add the new term */
                    var newTerm = $('#newAntRecordTerm').val();
                    var thisId = $(this).attr("data-id");
                    $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'no_fetal', new_name: newTerm
                    }, function (data) {

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

                        $('.updateElement[id=' + thisId + ']').trigger("change");
                    });
                });
                $(".fetal_pulse").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisId = $(this).attr("id");
                        return "<input class='form-control' id='newAntRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
                    /* add the new term */
                    var newTerm = $('#newAntRecordTerm').val();
                    var thisId = $(this).attr("data-id");
                    $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'fetal_pulse', new_name: newTerm
                    }, function (data) {

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

                        $('.updateElement[id=' + thisId + ']').trigger("change");
                    });
                });
            }

            if (type != 1) {
                $(".fet_no").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisId = $(this).attr("id");
                        return "<input class='form-control' id='newAntRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
                    /* add the new term */
                    var newTerm = $('#newAntRecordTerm').val();
                    var thisId = $(this).attr("data-id");
                    $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'fet_no', new_name: newTerm
                    }, function (data) {

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

                        $('.updateElement[id=' + thisId + ']').trigger("change");
                    });
                });
                $(".visibility").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisId = $(this).attr("id");
                        return "<input class='form-control' id='newAntRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
                    /* add the new term */
                    var newTerm = $('#newAntRecordTerm').val();
                    var thisId = $(this).attr("data-id");
                    $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'visibility', new_name: newTerm
                    }, function (data) {

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

                        $('.updateElement[id=' + thisId + ']').trigger("change");
                    });
                });
                $(".ant_presentation").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisId = $(this).attr("id");
                        return "<input class='form-control' id='newAntRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
                    /* add the new term */
                    var newTerm = $('#newAntRecordTerm').val();
                    var thisId = $(this).attr("data-id");
                    $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'ant_presentation', new_name: newTerm
                    }, function (data) {

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

                        $('.updateElement[id=' + thisId + ']').trigger("change");
                    });
                });
                $(".ant_liquor").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisId = $(this).attr("id");
                        return "<input class='form-control' id='newAntRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
                    /* add the new term */
                    var newTerm = $('#newAntRecordTerm').val();
                    var thisId = $(this).attr("data-id");
                    $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'ant_liquor', new_name: newTerm
                    }, function (data) {

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

                        $('.updateElement[id=' + thisId + ']').trigger("change");
                    });
                });
            }
        }

        $('body').on('click', '.addLTovary', function () {
            var controllName = $('#controllName').val();
            if (controllName != "and_visits") {
                controllName = 'gyna';
            }
            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/' + controllName + '.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 controllName = $('#controllName').val();
            if (controllName != "and_visits") {
                controllName = 'gyna';
            }
            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/' + controllName + '.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>'
                        + '<div class="md-checkbox pathologyCheck" id="pathologyCheck' + res + '">'
                        + '<input type="checkbox" id="pathology' + res + '" data-id="' + res + '" '
                        + '    data-tableName="investcats"     value="1"    data-colName="pathology"     '
                        + '    class="md-check updateElementCheck" >'
                        + '   <label for="pathology' + res + '">'
                        + '    <span></span>'
                        + '  <span class="check"></span>'
                        + '    <span class="box"></span>'
                        + '  </label>'
                        + ' </div>'
                        + ' </td>'
                        + '<td><a class="btn green btn-xs showInv" data-id="' + res + '"  href="#" ><i class="fa fa-pencil"></i>Show </a></td>'
                        + '<td><a class="btn grey-cascade btn-xs editCat" data-id="' + res + '"  href="#" ><i class="fa fa-pencil"></i> </a></td>'
                        + '<td><a class="btn grey-cascade btn-xs deletemsgEX" data-id="' + res + '"  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 invest_itr = Number($('#invest_itr').val());
            invest_itr++;
            $('#invest_itr').val(invest_itr);
            var catId = $('#catId').val();
            $.post(hosturl + '/controllers/addinvestigation.php?ac=addnewinv', {catId: catId, invest_itr: invest_itr}, function (res) {
                $('#invests').prepend(res);
                $(".positivefloat").forcepositivefloat();
                var invest_id = Number($('#invest_id' + invest_itr).val());
                $('#inv' + invest_id).focus();
                $("#sampletype" + invest_itr).select2({
                    placeholder: "Select",
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisitr = $(this).attr('data-itr');
                        var id = $(this).attr('data-id');
                        return "<input class='form-control' id='newTerm_sampletype" + thisitr + "'  data-itr='" + thisitr + "' data-id='" + id + "'  value='" + term + "'>   <a href='#' id='addNew_sampletype" + thisitr + "' data-itr='" + thisitr + "' data-id='" + id + "' class='btn blue addNew_sampletype'>إضافة جديد</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '.addNew_sampletype', function () {
                    /* add the new term */
                    var hosturl = $('#hosturl').val();
                    var thisitr = $(this).attr('data-itr');
                    var investid = $(this).attr('data-id');
                    var newitem = $('#newTerm_sampletype' + thisitr).val();
                    $.post(hosturl + "/controllers/addinvestigation.php?ac=addnewrecord", {
                        investid: investid,
                        newitem: newitem,
                        inline: 1
                    }, function (data) {

                        $('select[name="sampletype"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                        $('#sampletype' + thisitr).select2('val', Number(data)); // select the new term
                        $('#sampletype' + thisitr).select2('close'); // close the dropdown
                    });
                });
            });
        });
        $('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");
            var itr = $(this).attr("data-itr");
            $('#price' + id).removeAttr('disabled');
            $('#lab_to_lab_price' + id).removeAttr('disabled');
            $('#measurements' + id).removeAttr('disabled');
            $('#range' + id).removeAttr('disabled');
            $('#range_high' + id).removeAttr('disabled');
            $('#range_low' + id).removeAttr('disabled');
            $('#inv' + id).removeAttr('disabled');
             $('#investcatid' + id).removeAttr('disabled');
            $('#sampletype' + itr).removeAttr('disabled');
            $('#special_inv_type' + itr).removeAttr('disabled');
            $('#type' + itr).removeAttr('disabled');
            $('#pdf' + id).removeAttr('disabled');
            $('#favoriteCheck' + id).hide();
            $('#finishEdit' + id).show();
            $('#inv' + id).focus();
            $('#editInv' + id).hide();
            $('#reviewInvSample' + id).hide();
            $('#printInvSample' + id).hide();
            $('#deleteInv' + id).hide();
            $('#showCustom' + id).hide();
        });
        $('body').on('blur', '.invCatName', function () {
            $(this).attr("disabled", true);
        });
        $('body').on('click', '.finishEdit', function () {
            var id = $(this).attr("data-id");
            var itr = $(this).attr("data-itr");
            var special_inv_type = $('#special_inv_type' + itr).val();
            $('#price' + id).attr("disabled", true);
            $('#lab_to_lab_price' + id).attr("disabled", true);
            $('#sampletype' + itr).attr("disabled", true);
            $('#special_inv_type' + itr).attr("disabled", true);
            $('#type' + itr).attr("disabled", true);
              $('#pdf' + id).attr("disabled", true);
            $('#measurements' + id).attr("disabled", true);
            $('#range' + id).attr("disabled", true);
            $('#range_high' + id).attr("disabled", true);
            $('#range_low' + id).attr("disabled", true);
            $('#inv' + id).attr("disabled", true);
             $('#investcatid' + id).attr("disabled", true);
            $('#favoriteCheck' + id).show();
            $('#finishEdit' + id).hide();
            $('#editInv' + id).show();
            $('#reviewInvSample' + id).show();
            $('#printInvSample' + id).show();
            $('#deleteInv' + id).show();
            if (special_inv_type == 11) {
                $('#showCustom' + id).show();
            }
        });
        $('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 () {
               $('#showCatInv').html('');
            $('#invSearchResult').html('');
            var catId = $(this).attr("data-id");
            $('#catId').val(catId);
            $.post(hosturl + '/controllers/addinvestigation.php?ac=getinvbycatid', {catId: catId}, function (res) {
                $('#showCatInv').html('');
                $('#showCatInv').html(res);
                $(".positivefloat").forcepositivefloat();
                var invest_itr = Number($('#invest_itr').val());
                for (var i = 1; i <= invest_itr; i++) {
                    $("#sampletype" + i).select2({
                        placeholder: "Select",
                        width: '240px',
                        allowClear: true,
                        formatNoMatches: function (term) {
                            /* customize the no matches output */
                            var thisitr = $(this).attr('data-itr');
                            var id = $(this).attr('data-id');
                            return "<input class='form-control' id='newTerm_sampletype" + thisitr + "'  data-itr='" + thisitr + "' data-id='" + id + "'  value='" + term + "'>   <a href='#' id='addNew_sampletype" + thisitr + "' data-itr='" + thisitr + "' data-id='" + id + "' class='btn blue addNew_sampletype'>إضافة جديد</a>"
                        }
                    }).parent().find('.select2-with-searchbox').on('click', '.addNew_sampletype', function () {
                        /* add the new term */
                        var hosturl = $('#hosturl').val();
                        var thisitr = $(this).attr('data-itr');
                        var investid = $(this).attr('data-id');
                        var newitem = $('#newTerm_sampletype' + thisitr).val();
                        $.post(hosturl + "/controllers/addinvestigation.php?ac=addnewrecord", {
                            investid: investid,
                            newitem: newitem,
                            inline: 1
                        }, function (data) {

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


                $("#investsModel").modal('show');
            });
        });
        $('body').on('change', '.sampletype', function () {
            var selectId = $(this).attr('id');
            var value = $(this).val();
            var colname = $(this).attr('data-ptname');
            if (value == 0) {
                $.post(hosturl + '/controllers/patients.php?ac=getalldata', {colname: colname, selectId: 'sampletype'}, function (data) {
                    $("#" + selectId).select2("val", "");
                    $('#editModal').html(data);
                    $('#editModal').modal('show');
                });
            }
        });
        $('body').on('click', '.showCustom', function () {
            var id = $(this).attr("data-id");
            $.post(hosturl + '/controllers/addinvestigation.php?ac=getcustom', {invId: id}, function (res) {
                $('#invCustomDiv').html('');
                $('#invCustomDiv').html(res);
                $("#customModel").modal('show');
            });
        });
        $('body').on('click', '#customAdd', function () {

            var custom_itr = Number($('#custom_itr').val());
            custom_itr++;
            var customInvId = $('#customInvId').val();
            $.post(hosturl + '/controllers/addinvestigation.php?ac=newcustomelement', {invId: customInvId}, function (res) {
                var elementId = Number(res);
                if (elementId > 0) {
                    var row = '<tr><td>' + custom_itr + '</td> '
                            + ' <td>   <input type="text" class="form-control updateElement"    id="invElement' + elementId + '"    '
                            + '   data-id="' + elementId + '"   data-colName="show_name" data-tableName="invest_elements"  '
                            + '  value=""   style="height: 26px;"/>     '
                            + '   </td>    <td> '
                            + '  <a class="btn red btn-xs deletemsgEX" data-id="' + elementId + '"   '
                            + ' href="#" data-link="addinvestigation" data-fn="del" data-tableName="invest_elements"> '
                            + '<i class="fa fa-close"></i>      </a> '
                            + '</td> </tr> ';
                    $('#customElements').prepend(row);
                    $('#invElement' + elementId).focus();
                }
            });
        });
        
          $('#allInvTable').DataTable({
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": hosturl + '/controllers/addinvestigation.php?ac=showInvs', //  server side processing
            "sPaginationType": "full_numbers",
            "lengthMenu": [
                [50, 100, 150, -1],
                [50, 100, 150, "All"] // change per page values here
            ],
            // set the initial value
            "pageLength": 50,
            "language": {
                "lengthMenu": " _MENU_"
            },
            "columnDefs": [
                {// set default column settings
                    "targets": [11],
                    "orderable": false,
                    "searchable": false
                },
                {
                    'orderable': false,
                    "searchable": false,
                    "targets": [12]
                }
            ],
            "order": [
                [1, "asc"]       // order by drug cat
            ] // set first column as a default sort by asc
        });
        
        
        var rangesTable = $('#rangesTable');
        var rangTable = rangesTable.DataTable({
            // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
            // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js).
            // So when dropdowns used the scrollable div should be removed.
            //"dom": "<'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",

            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": hosturl + '/controllers/addinvestigation.php?ac=showranges', //  server side processing
            "sPaginationType": "full_numbers",
            "lengthMenu": [
                [50, 100, 150, -1],
                [50, 100, 150, "All"] // change per page values here
            ],
            // set the initial value
            "pageLength": 50,
            "language": {
                "lengthMenu": " _MENU_"
            },
            "columnDefs": [
                {// set default column settings
                    "targets": [0],
                    "visible": false,
                    "searchable": false
                },
                {
                    'orderable': false,
                    "searchable": false,
                    "targets": [9]
                }, {
                    'orderable': false,
                    "searchable": false,
                    "targets": [10]
                }, {
                    'orderable': false,
                    "searchable": false,
                    "targets": [11]
                }
            ],
            "order": [
                [1, "asc"]       // order by drug cat
            ] // set first column as a default sort by asc
        });
        //   $('#rangesTable').DataTable().column(0).visible(false)


        var tableWrapper = $("#sample_editable_1_wrapper");
        tableWrapper.find(".dataTables_length select").select2({
            showSearchInput: false //hide search box with special css class
        }); // initialize select2 dropdown

        var nEditing = null;
        var nNew = false;
        var nid = 0;
        $('#invRange_add').click(function (e) {
            e.preventDefault();
            if (nNew || nEditing) {
                if (confirm("Previose row not saved. save or cancel  it ?Add")) {
                    /* continue where we left   */
                } else {
                    $('#rangesTable').DataTable().ajax.reload(); // cancel
                    nEditing = null;
                    nNew = false;
                    return;
                }
            } else {

                $.post(hosturl + '/controllers/addinvestigation.php?ac=getthisserach', {type: 'cats'}, function (data) {
                    var row = $("<tr></tr>");
                    var col1 = $('<td><select class="form-control"   id="catid" > </select></td>');
                    var col2 = $('<td><select class="form-control"   id="investid" ><option value=""></option> </select></td>');
                    var col3 = $('<td><select class="form-control"   id="element" ><option value=""></option> </select></td>');
                    //       var col4 = $('<td><input type="text"  id="range_txt" class="form-control " value=""></td>');
                    var col4 = $('<td><textarea  id="range_txt" style="style="width: auto;overflow-y: scroll;" class="form-control "></textarea></td>');
                    var col5 = $('<td><input type="text"  id="range_low" class="form-control positivefloat " value=""></td>');
                    var col6 = $('<td><input type="text"  id="range_high" class="form-control positivefloat " value=""></td>');
                    var col7 = $('<td><input type="text"  id="invest_units" class="form-control " value=""></td>');
                    var col8 = $('<td>'
                            + '<input type="text" style="width: 43%;display:inline;"  id="agefrom" class="form-control  positivefloat" placeholder="From"  value="">'
                            + ' - '
                            + '<input type="text" style="width: 43%;display:inline;"   id="ageto" class="form-control  positivefloat" placeholder="To"  value="">'
                            + '</td>');
                    var col9 = $('<td><select class="form-control"   id="age_units" ><option value=""></option>'
                            + '<option value="1">Year</option>'
                            + '<option value="2">Month</option>'
                            + '<option value="3">Day</option>'
                            + '<option value="4">Hour</option>'
                            + '<option value="5">Minute</option>'
                            + '<option value="6">Second</option>'
                            + '</select></td>');
                    var col10 = $('<select class="form-control"   id="gender" ><option value=""></option>'
                            + '<option value="-1">All</option>'
                            + '<option value="0">F</option>'
                            + '<option value="1">M</option>'
                            + '</select>');
                    var col11 = $('<td><a class="save_range" href="">Save</a></td>');
                    var col12 = $('<td><a class="cancel_range" href="">Cancel</a></td>');
                    row.append(col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12).prependTo("#rangesTable");
                    nEditing = row;
                    nNew = true;
                    $(".positivefloat").forcepositivefloat();
                    $('#catid').html(data);
                    $('#catid').select2();
                    $('#investid').select2();
                    $('#element').select2();
                    $('#age_units').select2();
                    $('#gender').select2();
                });
            }
        });
        rangesTable.on('change', '#catid', function (e) {
            var catid = $('#catid').val();
            $.post(hosturl + '/controllers/addinvestigation.php?ac=getthisserach', {type: 'invests', catid: catid}, function (data) {
                $('#investid').html(data);
                $('#investid').select2();
            });
        });
        rangesTable.on('change', '#investid', function (e) {
            var investid = $('#investid').val();
            $.post(hosturl + '/controllers/addinvestigation.php?ac=getthisserach', {type: 'elements', investid: investid}, function (data) {
                $('#element').html(data);
                $('#element').select2();
            });
        });
        rangesTable.on('click', '.save_range', function (e)     // save new row
        {
            e.preventDefault();
            //getdata();
            if (this.innerHTML == "Save") {
                var gender = $('#gender').val();
                var investid = $('#investid').val();
                var element = $('#element').val();
                var range_txt = $('#range_txt').val();
                range_txt = range_txt.replace(/(?:\r\n|\r|\n)/g, '<br>');
                var range_low = $('#range_low').val();
                var range_high = $('#range_high').val();
                var invest_units = $('#invest_units').val();
                var agefrom = $('#agefrom').val();
                var ageto = $('#ageto').val();
                var age_units = $('#age_units').val();
                if (investid == "") {
                    alert('من فضلك اختر   التحليل  .......');
                } else {

                    $.post(hosturl + '/controllers/addinvestigation.php?ac=addrange', {
                        investid: investid
                        , element: element
                        , range_txt: range_txt
                        , range_low: range_low
                        , range_high: range_high
                        , invest_units: invest_units
                        , agefrom: agefrom
                        , ageto: ageto
                        , age_units: age_units
                        , gender: gender
                        , id: 0
                    }, function (data) {
                        if (Number(data) == 1) {
                            $('#rangesTable').DataTable().ajax.reload();
                            nEditing = null;
                            nNew = false;
                        } else {
                            alert(' error ...try again ');
                        }

                    });
                }


            }
        });
        rangesTable.on('click', '.cancel_range', function (e) {
            e.preventDefault();
            if (nNew) {
                nEditing = null;
                nNew = false;
            } else {
                nEditing = null;
            }

            $('#rangesTable').DataTable().ajax.reload();
            nEditing = null;
            nNew = false;
        });
        rangesTable.on('click', '.delete', function (e) {
            e.preventDefault();
            if (confirm("Are you sure to delete this row ?") == false) {
                return;
            }

            var nRow = $(this).parents('tr')[0];
            var currentRow = $(this).closest("tr");
            var data = $('#rangesTable').DataTable().row(currentRow).data();
            var id = data[0];
            $.post(hosturl + '/controllers/addinvestigation.php?ac=deleterange', {id: id}, function (data) {
                if (Number(data) == 1) {
                    $('#rangesTable').DataTable().ajax.reload();
                    nEditing = null;
                    nNew = false;
                } else {
                    alert(' error ...try again ');
                }
            });
            //alert("Deleted! Do not forget to do some ajax to sync with backend :)");
        });
        rangesTable.on('click', '.edit', function (e) {
            e.preventDefault();
            var currentRow = $(this).closest("tr");
            var data = $('#rangesTable').DataTable().row(currentRow).data();
            var id = data[0];
//            /* Get the row as a parent of the link that was clicked on */
            var nRow = $(this).parents('tr')[0];
            // new added row not saved yet or   /* Currently editing - but not this row - restore the old before continuing to edit mode */
            if (nEditing !== null && nid != id && nid != 0) {
                if (confirm("Previose row not saved. save or cancel  it ?")) {
                    /* continue where we left   */
                } else {
                    $('#rangesTable').DataTable().ajax.reload(); // cancel
                    nEditing = null;
                    nNew = false;
                    return;
                }

            } else if (nEditing == nRow && this.innerHTML == "Save") {
                /* Editing this row and want to save it */

                var gender = $('#gender').val();
                var investid = $('#investid').val();
                var element = $('#element').val();
                var range_txt = $('#range_txt').val();
                range_txt = range_txt.replace(/(?:\r\n|\r|\n)/g, '<br>');
                var range_low = $('#range_low').val();
                var range_high = $('#range_high').val();
                var invest_units = $('#invest_units').val();
                var agefrom = $('#agefrom').val();
                var ageto = $('#ageto').val();
                var age_units = $('#age_units').val();
                if (investid == "") {
                    alert('من فضلك اختر   التحليل  .......');
                } else {

                    $.post(hosturl + '/controllers/addinvestigation.php?ac=addrange', {
                        investid: investid
                        , element: element
                        , range_txt: range_txt
                        , range_low: range_low
                        , range_high: range_high
                        , invest_units: invest_units
                        , agefrom: agefrom
                        , ageto: ageto
                        , age_units: age_units
                        , gender: gender
                        , id: id
                    }, function (data) {
                        if (Number(data) == 1) {
                            $('#rangesTable').DataTable().ajax.reload();
                            nEditing = null;
                            nNew = false;
                        } else {
                            alert(' error ...try again ');
                        }

                    });
                }


            } else {
                /* No edit in progress - let's start one */

                editRow(id, nRow, currentRow);
                nEditing = nRow;
                nid = id;
            }
        });
//
//        $('body').on('click', '.reviewInvSample', function () {
//            var investId = $(this).attr("data-id");
////            $.post(hosturl + '/controllers/addinvestigation.php?ac=getinvpreview', {investId: investId}, function (res) {
////                $('#invPreview').html('');
////                $('#invPreview').html(res);
////                $("#invPreviewModel").modal('show');
////            });
//        });


   $('body').on('change', '#invNameSearch', function () {
              $('#showCatInv').html('');
            $('#invSearchResult').html('');
            var searchText = $('#invNameSearch').val();
            if (searchText != '') {
                $.post(hosturl + '/controllers/addinvestigation.php?ac=invNameSearch', {searchText: searchText}, function (res) {
                    console.log(res);
                    if (res != -1) {
                        $('#showCatInv').html(res);
                        var resAll = $('#invests').html();
                        $('#showCatInv').html('');
                        $('#invSearchResult').html('');
                        $('#invSearchResult').html(resAll);
                        $(".positivefloat").forcepositivefloat();
                        var invest_itr = Number($('#invest_itr').val());
                        for (var i = 1; i <= invest_itr; i++) {
                            $("#sampletype" + i).select2({
                                placeholder: "Select",
                                width: '240px',
                                allowClear: true,
                                formatNoMatches: function (term) {
                                    /* customize the no matches output */
                                    var thisitr = $(this).attr('data-itr');
                                    var id = $(this).attr('data-id');
                                    return "<input class='form-control' id='newTerm_sampletype" + thisitr + "'  data-itr='" + thisitr + "' data-id='" + id + "'  value='" + term + "'>   <a href='#' id='addNew_sampletype" + thisitr + "' data-itr='" + thisitr + "' data-id='" + id + "' class='btn blue addNew_sampletype'>إضافة جديد</a>"
                                }
                            }).parent().find('.select2-with-searchbox').on('click', '.addNew_sampletype', function () {
                                /* add the new term */
                                var hosturl = $('#hosturl').val();
                                var thisitr = $(this).attr('data-itr');
                                var investid = $(this).attr('data-id');
                                var newitem = $('#newTerm_sampletype' + thisitr).val();
                                $.post(hosturl + "/controllers/addinvestigation.php?ac=addnewrecord", {
                                    investid: investid,
                                    newitem: newitem,
                                    inline: 1
                                }, function (data) {

                                    $('select[name="sampletype"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                                    $('#sampletype' + thisitr).select2('val', Number(data)); // select the new term
                                    $('#sampletype' + thisitr).select2('close'); // close the dropdown
                                });
                            });
                        }
                    }
                });
            } else {
                $('#invSearchResult').html('');
            }
        });
        
        
        
           $('body').on('click', '.disableBtn', function () {
            var btn = $(this);
            var tr = $(this).parent().parent();
            var itemid = $(this).attr('data-id');
            var urlgo = $(this).attr('data-link');
            var fngo = $(this).attr('data-fn');
            var value = $(this).attr('data-val');
            var tableName = $(this).attr('data-tableName');
            var colName = $(this).attr('data-colName');

            var txt = 'Enable';
            if (value == 1) {
                txt = 'Disable';
            }


            bootbox.dialog({
                message: "Do you want to " + txt + " this item?",
                title: txt + " confirmation",
                buttons: {
                    danger: {
                        label: "Cancel",
                        className: "btn-primary"
                    },
                    main: {
                        label: txt,
                        className: "btn-danger",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/' + urlgo + '.php?ac=' + fngo, {
                                id: itemid, tableName: tableName, colName: colName, value: value}, function (res)
                            {
                                if (res == 1) {
                                    if (value == 1) {
                                        tr.css('background-color', 'darkgray');
                                        btn.attr('data-val', 0);
                                        btn.html('EN');
                                        btn.removeClass('red');
                                        btn.addClass('default');
                                    } else {
                                        tr.css('background-color', '#C6D7F2');
                                        btn.attr('data-val', 1);
                                        btn.html('Dis');
                                        btn.removeClass('default');
                                        btn.addClass('red');
                                    }

                                    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 {
                                    alert("!!!!!!!!!!!!! some thing wrong here");
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        
        
                rangesTable.on('click', '.disableRange', function (e) {
            e.preventDefault();
            if (confirm("Are you sure to disable this range ?") == false) {
                return;
            }

            var nRow = $(this).parents('tr')[0];
            var currentRow = $(this).closest("tr");
            var data = $('#rangesTable').DataTable().row(currentRow).data();
            var id = data[0];
            $.post(hosturl + '/controllers/addinvestigation.php?ac=disableRange', {id: id, active: 0}, function (data) {
                if (Number(data) == 1) {
                    $('#rangesTable').DataTable().ajax.reload();
                    nEditing = null;
                    nNew = false;
                } else {
                    alert(' error ...try again ');
                }
            });
            //alert("Deleted! Do not forget to do some ajax to sync with backend :)");
        });

        rangesTable.on('click', '.enableRange', function (e) {
            e.preventDefault();
            if (confirm("Are you sure to enable this range ?") == false) {
                return;
            }

            var nRow = $(this).parents('tr')[0];
            var currentRow = $(this).closest("tr");
            var data = $('#rangesTable').DataTable().row(currentRow).data();
            var id = data[0];
            $.post(hosturl + '/controllers/addinvestigation.php?ac=disableRange', {id: id, active: 1}, function (data) {
                if (Number(data) == 1) {
                    $('#rangesTable').DataTable().ajax.reload();
                    nEditing = null;
                    nNew = false;
                } else {
                    alert(' error ...try again ');
                }
            });
            //alert("Deleted! Do not forget to do some ajax to sync with backend :)");
        });
        
    };

    function editRow(id, nRow, currentRow) {
        $.post(hosturl + '/controllers/addinvestigation.php?ac=geteditedrow', {id: id}, function (data) {
            var obj = JSON.parse(data);
            $.post(hosturl + '/controllers/addinvestigation.php?ac=getthisserach', {type: 'cats'}, function (data) {
                $('#rangesTable').DataTable().cell({row: currentRow.index(), column: 1}).data('<select class="form-control"   id="catid" > </select>');
                $('#catid').html(data);
                $('#catid').select2();
                $('#catid').select2("val", obj.catid);
            });
            $.post(hosturl + '/controllers/addinvestigation.php?ac=getthisserach', {type: 'invests', catid: obj.catid}, function (data) {
                $('#rangesTable').DataTable().cell({row: currentRow.index(), column: 2}).data('<select class="form-control"   id="investid" ><option value=""></option> </select>');
                $('#investid').html(data);
                $('#investid').select2();
                $('#investid').select2("val", obj.investid);
            });
            $.post(hosturl + '/controllers/addinvestigation.php?ac=getthisserach', {type: 'elements', investid: obj.investid}, function (data) {
                $('#rangesTable').DataTable().cell({row: currentRow.index(), column: 3}).data('<select class="form-control"   id="element" ><option value=""></option> </select>');
                $('#element').html(data);
                $('#element').select2();
                $('#element').select2("val", obj.invest_child);
            });
            var str = obj.range_txt;
            var regex = /<br\s*[\/]?>/gi;
            $('#rangesTable').DataTable().cell({row: currentRow.index(), column: 4}).data(
                    '<textarea  id="range_txt" class="form-control " style="width: auto; overflow-y: scroll;">' + str.replace(regex, "\n") + '</textarea>');
//            $('#rangesTable').DataTable().cell({row: currentRow.index(), column: 4}).data('<input type="text"  id="range_txt" class="form-control " value="' + obj.range_txt + '">');
            $('#rangesTable').DataTable().cell({row: currentRow.index(), column: 5}).data('<input type="text"  id="range_low" class="form-control positivefloat " value="' + obj.range_low + '">');
            $('#rangesTable').DataTable().cell({row: currentRow.index(), column: 6}).data('<input type="text"  id="range_high" class="form-control positivefloat " value="' + obj.range_high + '">');
            $('#rangesTable').DataTable().cell({row: currentRow.index(), column: 7}).data('<input type="text"  id="invest_units" class="form-control " value="' + obj.invest_units + '">');
            $('#rangesTable').DataTable().cell({row: currentRow.index(), column: 8}).data(
                    '<input type="text" style="width: 43%;display:inline;"  id="agefrom" class="form-control  positivefloat" placeholder="From"  value="' + obj.agefrom + '">'
                    + ' - '
                    + '<input type="text" style="width: 43%;display:inline;"  id="ageto" class="form-control  positivefloat"  placeholder="To" value="' + obj.ageto + '">'
                    );
            $('#rangesTable').DataTable().cell({row: currentRow.index(), column: 9}).data('<select class="form-control"   id="age_units" ><option value=""></option>'
                    + '<option value="1">Year</option>'
                    + '<option value="2">Month</option>'
                    + '<option value="3">Day</option>'
                    + '<option value="4">Hour</option>'
                    + '<option value="5">Minute</option>'
                    + '<option value="6">Second</option>'
                    + '</select>');
            $('#rangesTable').DataTable().cell({row: currentRow.index(), column: 10}).data('<select class="form-control"   id="gender" ><option value=""></option>'
                    + '<option value="-1">All</option>'
                    + '<option value="0">F</option>'
                    + '<option value="1">M</option>'
                    + '</select>');
            $('#age_units').select2();
            $('#age_units').select2("val", obj.age_units);
            $('#gender').select2();
            $('#gender').select2("val", obj.gender);
            $('#rangesTable').DataTable().cell({row: currentRow.index(), column: 11}).data('<a class="edit" href="">Save</a>');
            $('#rangesTable').DataTable().cell({row: currentRow.index(), column: 12}).data('<a class="cancel_range" href="">Cancel</a>');
            $(".positivefloat").forcepositivefloat();
        });
    }

    var addRays = function () {
        $('body').on('click', '#rayCat_add', function () {
            $.post(hosturl + '/controllers/addrays.php?ac=addnewcat', function (res) {
                $('#rayCat').append('<tr><td><input type="text" class="form-control updateElement rayCatName" id="cat' + res + '" data-id="' + res + '" data-colName="name" data-tableName="rayscats"/></td>'
                        + '<td><a class="btn green btn-xs showRay" 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="addrays" data-fn="del" data-tableName="rayscats"><i class="fa fa-close"></i></a></td>'
                        + '</tr>');
                $('#cat' + res).focus();
            });
        });
        $('body').on('click', '#ray_add', function () {
            var catId = $('#catId').val();
            $.post(hosturl + '/controllers/addrays.php?ac=addnewray', {catId: catId}, function (res) {
                $('#rays').append('<tr>'
                        + '<td>'
                        + '<input type="text" class="form-control updateElement" id="ray' + res + '" data-id="' + res + '" data-colName="name" data-tableName="rays"/>'
                        + '</td>'
                        + '<td>'
                        + '<textarea class="form-control updateElement" rows="2"   id="range' + res + '" data-id="' + res + '"    data-colName="range" data-tableName="rays"    placeholder="Enter more text" data-toggle="popover" data-trigger="hover" data-placement="bottom" data-content="">'
                        + '</textarea>'
                        + '</td>'
                        + '<td>'
                        + '<input type="text" class="form-control updateElement" style="text-transform: none;"  id="measurements' + res + '" data-id="' + res + '" data-colName="measurements" data-tableName="rays"/>'
                        + '</td>'
                        + '<td>'
                        + '<input type="text" class="form-control updateElement" id="price' + res + '" data-id="' + res + '" data-colName="price" data-tableName="rays" value="0" />'
                        + '</td>'
                        + '<td>'
                        + '<a class="btn btn-xs green finishEdit" id="finishEdit' + res + '" data-id="' + res + '" style=" float: right;" href="#" >finish  </a>'
                        + '<div class="md-checkbox" style="display: none;" id="favoriteCheck' + res + '">'
                        + '<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 editRay" 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="addrays" data-fn="del" data-tableName="rays"><i class="fa fa-close"></i></a>'
                        + '</td>'
                        + '</tr>');
                $('#ray' + res).focus();
            });
        });
        $('body').on('click', '.editCat', function () {
            var id = $(this).attr("data-id");
            $('#cat' + id).removeAttr('disabled');
            $('#cat' + id).focus();
        });
        $('body').on('click', '.editRay', function () {
            var id = $(this).attr("data-id");
            $('#price' + id).removeAttr('disabled');
            $('#measurements' + id).removeAttr('disabled');
            $('#range' + id).removeAttr('disabled');
            $('#ray' + id).removeAttr('disabled');
            $('#favoriteCheck' + id).hide();
            $('#finishEdit' + id).show();
            $('#ray' + id).focus();
        });
        $('body').on('blur', '.rayCatName', function () {
            $(this).attr("disabled", true);
        });
        $('body').on('click', '.finishEdit', function () {
            var id = $(this).attr("data-id");
            $('#price' + id).attr("disabled", true);
            $('#measurements' + id).attr("disabled", true);
            $('#range' + id).attr("disabled", true);
            $('#ray' + id).attr("disabled", true);
            $('#favoriteCheck' + id).show();
            $('#finishEdit' + id).hide();
        });
        $('body').on('click', '.addFavorite', function () {
            var rayId = $(this).attr("data-id");
            var check = $('#checkbox' + rayId).is(":checked")
            var value = 0;
            if (check == true) {
                value = 1;
            }
            $.post(hosturl + '/controllers/addrays.php?ac=addtofavorite', {
                rayId: rayId,
                value: value
            }, function (res) {
            });
        });
        $('body').on('click', '.showRay', function () {
            var catId = $(this).attr("data-id");
            $('#catId').val(catId);
            $.post(hosturl + '/controllers/addrays.php?ac=getraybycatid', {catId: catId}, function (res) {
                $('#showCatRay').html(res);
                $("#raysModel").modal('show');
            });
        });
    };

    var instruction = function () {
        $('body').on('click', '#printInstruction', function () {
            var patientId = $('#patientId').val();
            var printDate = $('#printDate').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,
                printDate: printDate
            }, 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');
            var printDate = $('#printDate').val();
            $.post(hosturl + '/controllers/instruction.php?ac=getinstdetail', {
                instructionId: instructionId,
                patientId: patientId,
                printDate: printDate
            }, 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 visits = function () {

        $('body').on('click', '#saveAdvancePay', function () {
            var patientId = $('#patientvisitid').val();
            var paid_cash = Number($('#advanceCash').val());
            var paid_visa = Number($('#advanceVisa').val());
            var advanceNotes = $('#advanceNotes').val();
            var paid = paid_cash + paid_visa;
            var branch_id = $('#branch_id').val();
            $('#saveAdvancePay').attr("disabled", true);

            if (branch_id > 0 && patientId > 0 && paid > 0) {
                bootbox.dialog({
                    message: "هل أنت متأكد من إعادة المبلغ ؟",
                    title: "تأكيد الإعادة  ",
                    buttons: {
                        danger: {
                            label: "إلغاء ",
                            className: "btn-danger"
                        },
                        main: {
                            label: "نعم ",
                            className: "btn-primary",
                            callback: function () {
                                //do something else
                                $.post(hosturl + '/controllers/visits.php?ac=saveAdvancePay', {
                                    paid_cash: paid_cash, paid_visa: paid_visa, branch_id: branch_id
                                    , patientId: patientId, advanceNotes: advanceNotes
                                }, function (res) {
                                    if (Number(res) != -1) {
                                        getLastAdvance(patientId);
                                        loadPatDept(patientId);
                                        if (paid_cash > 0) {
                                            $('#printingDiv').html("");
                                            $('#printingDiv').html(res);
                                            $.print("#printingDiv");
                                            $('#printingDiv').html("");
                                        }
                                    } else {
                                        $('#advancePayError').html(' حدث خطأ . حاول مرة أخرى   ');
                                        $('#saveAdvancePay').attr("disabled", false);
                                    }
                                });
                            }
                        }
                    }
                }).find('.modal-content').addClass('modal-sm');


            } else {
                $('#saveAdvancePay').attr("disabled", false);
                if (!(patientId > 0)) {
                    var errorTxt = ' قم بتحديد المريض أولا ';
                } else if (!(branch_id > 0)) {
                    var errorTxt = ' قم بتحديد الفرع أولا ';
                } else {
                    var errorTxt = ' قم بتحديد المبلغ المراد دفعه  أولا ';
                }
                $('#advancePayError').html(errorTxt);
            }
        });


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

            if (labPatientId != '') {
                $.post(hosturl + '/controllers/patients.php?ac=labPatientIdCheck', {labPatientId: labPatientId}, function (data) {
                    if (Number(data) == 1) {
                        $('input[id="labPatientId"]').css({"background-color": "#FFFF99", "border": "1px solid red", "animation": " fadein 6s", "transition": "opacity 0.5s"});
                        document.getElementById("lb_ckecklabPatientId").style.display = "";
                        document.getElementById("lb_ckecklabPatientId").style.color = "red";
                    } else {
                        $('input[id="labPatientId"]').css('background-color', '#fff');
                        document.getElementById("lb_ckecklabPatientId").style.display = "none";
                        $("#wifenamecontain").find('input[id="labPatientId"]').css('background-color', '');
                        $('input[id="labPatientId"]').css('border', '');
                    }
                });
            }

        });


        $('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 isLab = $(this).attr("data-isLab");
            var orgId = $(this).attr("data-orgId");
            var row = $(this).parent().parent();
            if (isLab == 1) {
                if (orgId > 0) {
                    var discountType = $('#orgDiscountType').val();
                    if (discountType == 3) {
                        $.post(hosturl + '/controllers/visits.php?ac=orgLabDiscount', {id: orgId, discountType: discountType}, function (data) {
                            $('#labInvestsTd').html('');
                            $('#labInvestsTd').html(data);
                editVisitLab(visitId, row);
                        });
                    }
            } else {
                    editVisitLab(visitId, row);
                }

            } else {
                editVisitCommon(visitId, row);
            }


        });
        $('body').on('click', '.payForVisit', function () {
            var visitId = $(this).attr("data-visitId");
            bootbox.dialog({
                message: "هل أنت متأكد من الدفع   ؟",
                title: "تأكيد الدفع  ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-danger"
                    },
                    main: {
                        label: "نعم ",
                        className: "btn-primary",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/visits.php?ac=payForVisit', {
                                visitId: visitId}, function (res) {
                                if (Number(res) == -1) {
                                    alert(' حدث خطأ . حاول مرة أخرى   ');
                                } else if (Number(res) == -2) {
                                    alert('لا يوجد مبالغ مستحقة لهذه الزيارة .');
                                } else {
                                    $('#payForVisit' + visitId).hide('');
                                    $('#printingDiv').html("");
                                    $('#printingDiv').html(res);
                                    $.print("#printingDiv");
                                    $('#printingDiv').html("");
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        function editVisitLab(visitId, row) {
            var shareVersion = $('#shareVersion').val();
            $('#saveLabVisit').hide();
            $('.editVisit').hide();
            $('.deletevisit').hide();
            $('.payForVisit').hide();
            row.css('background-color', '#f36a5a')

            $.post(hosturl + '/controllers/visits.php?ac=editlabvisit', {visitId: visitId}, function (res) {

                if (Number(res) == -1) {
                    $('#saveLabVisit').show();
                    reloadVisits();
                } else {
                    var obj = JSON.parse(res);
                    $('#patientvisitid').val(null).empty();
                    var option = new Option(obj.name, obj.patientid, true, true);
                    $("#patientvisitid").append(option);
                    $('#patientvisitid').select2("val", obj.patientid);
                    $("#select2-chosen-2").html(obj.name);
                    $("input[name=for_husband][value=" + obj.for_husband + "]").prop('checked', true);
                    $("input[name=saudi]").prop('checked', false);
                    $("input[name=saudi]").parent().removeClass('checked');
                    $("input[name=saudi][value=" + obj.saudi + "]").prop('checked', true);
                    $("input[name=saudi][value=" + obj.saudi + "]").parent().addClass('checked');
                    if (obj.for_husband == 2) {
                        $.post(hosturl + '/controllers/visits.php?ac=getChilds', {patientId: obj.patientid}, function (data) {
                            $("#childContain").html(data);
                            if (obj.child > 0) {
                                $('#childFor').select2("val", obj.child);
                            }
                            $("#childHead").show();
                            $("#childContain").show();
                        });
                    } else {
                        $("#childHead").hide();
                        $("#childContain").hide();
                    }

                    //   $('#externalsss').html(obj.externals);
                    externalsArray = obj.externals;
                    getLastVisit(obj.patientid);
                    getLastAdvance(obj.patientid);
                    loadPatDept(obj.patientid);
                    getRest(obj.patientid);
                    getBills(obj.patientid);
//                    $('#patientvisitid').select2("val", obj.patientid);

                    $('#visitdate').val(obj.visitdate);
                    $('#visit_time').val(obj.visit_time);
                    if (obj.organization_id > 0) {
                        $('#organizations').select2("val", obj.organization_id);
                        $('#discountRatio').val(obj.discountRatio);
                        $('#discountRatioType').val(obj.discountRatioType);
                    }

                    var values = obj.selectedInvs;
                    $.each(values.split(","), function (i, e) {
                        $('#labInvests').multiSelect('select', e);
                    });
                    if (obj.for_doctor > 0) {
                        $('#doctor1').select2("val", obj.for_doctor);
                    }

                    if (obj.branch_id > 0) {
                        $('#branch_id').select2("val", obj.branch_id);
                    } else {
                        $('#branch_id').select2("val", '');
                    }



                    $('#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);
                    $('#unitsConsumed').val(obj.unitsConsumed);
                    $('#refer_doctor').select2("val", obj.refer_doctor);
                    $('#vatCalc').val(obj.vat_value);
                    if (obj.saudi == 1) {
                        $("#saudi1").prop("checked", true);
                        $('#saudi1').parent().addClass('checked');
                        $("#saudi0").removeAttr('checked');
                            $("#saudi0").parent().removeClass('checked');
                    } else {
                        $("#saudi0").prop("checked", true);
                        $('#saudi0').parent().addClass('checked');
                        $("#saudi1").removeAttr('checked');
                            $("#saudi1").parent().removeClass('checked');
                    }
                    if (obj.for_doctor > 0) {
                        $('#oldVisitDoctor').val(obj.for_doctor);
                        $('#oldVisitHours').val(obj.visitHours);
                    }
                    
                    
                          $('#detectionidLab').select2("val", obj.detectionid);
                    $('#labDetectionPrice').val(obj.lab_detection_price);



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

            });
        }

        function editVisitCommon(visitId, row) {
            var shareVersion = $('#shareVersion').val();
            $('#visitaddsubmit').hide();
            $('.editVisit').hide();
            $('.deletevisit').hide();
            $('.payForVisit').hide();
            row.css('background-color', '#f36a5a')

            $.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').val(null).empty();
                    var option = new Option(obj.name, obj.patientid, true, true);
                    $("#patientvisitid").append(option);
                    $('#patientvisitid').select2("val", obj.patientid);
                    $("#select2-chosen-2").html(obj.name);
                    $("input[name=for_husband][value=" + obj.for_husband + "]").prop('checked', true);

                    if (obj.sub_region_id > 0) {
                        $('#subRegionId').select2("val", obj.sub_region_id);
                    }


                    if (obj.for_husband == 2) {
                        $.post(hosturl + '/controllers/visits.php?ac=getChilds', {patientId: obj.patientid}, function (data) {
                            $("#childContain").html(data);
                            if (obj.child > 0) {
                                $('#childFor').select2("val", obj.child);
                            }
                            $("#childHead").show();
                            $("#childContain").show();
                        });
                    } else {
                        $("#childHead").hide();
                        $("#childContain").hide();
                    }


                    getLastVisit(obj.patientid);
                    getLastAdvance(obj.patientid);
                    loadPatDept(obj.patientid);
                    getRest(obj.patientid);
                    getBills(obj.patientid);
//                    $('#patientvisitid').select2("val", obj.patientid);

                    $('#visitdate').val(obj.visitdate);
                    $('#visit_time').val(obj.visit_time);
                    if (obj.detectionid > 0) {
                        $('#detectionid').select2("val", obj.detectionid);
                        if (shareVersion == 2) {
                            $('#oldDetectionId').val(obj.detectionid);
                        }
                    }

                    if (obj.organization_id > 0) {
                        $('#organizations').select2("val", obj.organization_id);
                        $('#discountRatio').val(obj.discountRatio);
                        $('#discountRatioType').val(obj.discountRatioType);
                    }



                    $('#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);
                    $('#unitsConsumed').val(obj.unitsConsumed);
                    $('#refer_doctor').select2("val", obj.refer_doctor);
                    if (obj.for_department == 13) {
                        $('#oldOperation_main_id').val(obj.operation_main_id);
                    }

                    $('#contractPrice').val(obj.contract_price);

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

                    if (obj.branch_id > 0) {
                        $('#branch_id').select2("val", obj.branch_id);
                    } else {
                        $('#branch_id').select2("val", '');
                    }

//                    if (obj.for_department == 5) {
//                        $('#invType').attr("disabled", true);
//                    }

                    if (obj.for_department == 12 || obj.for_department == 5) {
                        $('#selectedFromModel').html("");
                        $('#selectedFromModel').html(obj.invRes);
                        $('#selectedFromModel').show();
                    }

                    if (obj.for_doctor > 0) {
                        $('#oldVisitDoctor').val(obj.for_doctor);
                        $('#oldVisitHours').val(obj.visitHours);
                    }

                    if (obj.showRedirectNote == 1) {
                        alert(' Dr Note :  ' + obj.redirect_note);
                    }


                    $('#operation_time').val(obj.operation_time);
                    $('#saveEditVisit').attr("data-visitId", visitId);
                    $('#mVisitId').val(visitId);
                    $('#editView').val(1);
                    $('#saveEditVisit').show();
                    $('#cancelEditVisit').show();
                }

            });
        }

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

            $('#saveEditLabVisit').attr('disabled', true);
            var patientId = $('#patientvisitid').val();
            var patientName = $('#wifename').val();
            var cash = $('#detectionvalue_cash').val();
            var printserial = $('#printserial').val();
            if (patientId > 0 || patientName != '') {
                //get invst ids, prices for erp bill
                var invstData = '';
                $('.ms-selected:visible').each(function () {
                    invstData += $(this).data('id') + '*' + $(this).data('price') + ',';
                })
                $("#invstDataForERP").val(invstData);
                $.post(hosturl + '/controllers/visits.php?ac=updatelabvisit', $("#myvisitform").serialize(), function (res) {
                    if (Number(res) != -1) {

                        $("#discountType_0").prop("checked", true);
                        $('#discountType_0').parent().addClass('checked');
                        $("#discountType_1").removeAttr('checked');
                        $("#discountType_1").parent().removeClass('checked');
                        $("#organizations").select2("val", "").trigger("change");
                        if (cash > 0 && printserial == 1) {

                            $.post(hosturl + '/controllers/visits.php?ac=printvisitrecept', {
                                visitId: res
                            }, function (res1) {
//                                console.log(res1);
                                $("#printRDiv").html(res1);
                                $.print("#printRDiv");
                                $("#printRDiv").html("");
                            });
                        }

                        var date_from = $('#date_from').val();
                        var date_to = $('#date_to').val();
                        $.post(hosturl + '/controllers/visits.php?ac=searchindex', {date_from: date_from, date_to: date_to, deptId: 12}, function (res) {
                            $('#visitNew').html(res);
                            $('#saveLabVisit').show();
                            $('#saveEditLabVisit').hide();
                            $('#cancelEditLabVisit').hide();
                            $('#mVisitId').val(0);
                            $('#editView').val(0);
                            instructionArray = [];
                            $('#statusNoRemoteLab').val('');
                            $('#statusNoRemoteLab ').trigger('keyup');
                            $("#patientvisitidNo").select2("val", "");
                            $("#detectionvalue_cash").val(0);
                            $("#cardVisitId").val(0);
                            $("#detectionvalue_visa").val(0);
                            $("#restdetectionvalue").val(0);
                            $("#totaldetectionvalue").val(0);
                            $("#discount").val(0);
                            $("#notes").val('');
                            $("input[name=for_husband][value=" + 0 + "]").prop('checked', true);
                            $("#childHead").hide();
                            $("#childContain").hide();
                            $('#discountRatio').val(0);
                            $('#discountRatioType').val(0);
                            $('#contractPrice').val(0);
                            $('#organizations').select2('val', '');
                            $('#visit_time').val('');
                            $('#labInvests').multiSelect('deselect_all');
                            $('#doctor1').select2("val", '');
                            $('#refer_doctor').select2('val', '');
                            $("#detectionidLab").select2("val", "");
                            $("#labDetectionPrice").val(0);
                        });
                        $('#saveEditLabVisit').attr('disabled', false);
                    } else {
                        alert('خطأ ... لم يتم التسجيل ');
                        $('#saveEditLabVisit').attr('disabled', false);
                    }
                });
            } else {
                alert(' اختر مريض أولا .............................');
                $('#saveEditLabVisit').attr('disabled', false);
            }

        });

        $('body').on('click', '#cancelEditLabVisit', function () {
            var date_from = $('#date_from').val();
            var date_to = $('#date_to').val();
            $.post(hosturl + '/controllers/visits.php?ac=searchindex', {date_from: date_from, date_to: date_to, deptId: 12}, function (res) {
                $('#visitNew').html(res);
                $('#saveLabVisit').show();
                $('#saveEditLabVisit').hide();
                $('#cancelEditLabVisit').hide();
                $('#mVisitId').val(0);
                $('#editView').val(0);
                instructionArray = [];
                $('#statusNoRemoteLab').val('');
                $('#statusNoRemoteLab ').trigger('keyup');
                $("#patientvisitidNo").select2("val", "");
                $("#detectionvalue_cash").val(0);
                $("#cardVisitId").val(0);
                $("#detectionvalue_visa").val(0);
                $("#restdetectionvalue").val(0);
                $("#totaldetectionvalue").val(0);
                $("#discount").val(0);
                $("#notes").val('');
                $("input[name=for_husband][value=" + 0 + "]").prop('checked', true);
                $("#childHead").hide();
                $("#childContain").hide();
                $('#discountRatio').val(0);
                $('#contractPrice').val(0);
                $('#discountRatioType').val(0);
                $('#organizations').select2('val', '');
                $('#visit_time').val('');
                $('#labInvests').multiSelect('deselect_all');
                $('#doctor1').select2("val", '');
                $('#refer_doctor').select2('val', '');
                $("#detectionidLab").select2("val", "");
                            $("#labDetectionPrice").val(0);
            });
        });

        $('body').on('change', '.newDetect', function () {
            var visitId = $(this).attr("data-id");
            var getPrice = $(this).attr("data-getPrice");
            var orgDiscountType = $('#orgDiscountType').val();
            var value = $(this).val();
            if (getPrice == 1) {
                $.post(hosturl + '/controllers/visits.php?ac=getdtprice', {dtID: value, orgDiscountType: 0}, function (data) {
                    var obj = JSON.parse(data);
                    $('#newDetectVal' + visitId).val(obj.price);
                });
            }
        });

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

            $('#saveEditVisit').attr('disabled', true);
            var shareVersion = $('#shareVersion').val();
            var cash = $('#detectionvalue_cash').val();
            var fordepartment = $('#fordepartment').val();
            var for_doctor = $('#for_doctor').val();
            var patientid = $('#patientvisitid').val();
            var visitdate = $('#visitdate').val();
            var detectionid = $('#detectionid').val();
            var printserial = $('#printserial').val();
            var branch_id = $('#branch_id').val();
            var needDr = 1;
            if (fordepartment == 11 || fordepartment == 12) {
                needDr = 0;
            }

            if ((needDr == 1 && for_doctor > 0) || needDr == 0) {
                $('#drExist').html('  ');
                if (patientid != '' && visitdate != '' && detectionid != '' && branch_id > 0) {
                    $.post(hosturl + '/controllers/visits.php?ac=updatevisit', $("#myvisitform").serialize(), function (data) {

                        $("#discountType_0").prop("checked", true);
                        $('#discountType_0').parent().addClass('checked');
                        $("#discountType_1").removeAttr('checked');
                        $("#discountType_1").parent().removeClass('checked');
                        $("#organizations").select2("val", "").trigger("change");
                        if (cash > 0 && printserial == 1) {
                            $.post(hosturl + '/controllers/visits.php?ac=printvisitrecept', {
                                visitId: Number(data)
                            }, function (res1) {
//                                console.log(res1);
                                $("#printRDiv").html(res1);
                                $.print("#printRDiv");
                                $("#printRDiv").html("");
                            });
                        }
                        console.log(data);
                        var date_from = $('#date_from').val();
                        var date_to = $('#date_to').val();
                        $.post(hosturl + '/controllers/visits.php?ac=searchindex', {date_from: date_from, date_to: date_to}, function (res) {
                            $('#visitNew').html(res);
                            $('#visitaddsubmit').show();
                            $('#saveEditVisit').hide();
                            $('#cancelEditVisit').hide();
                            $('#mVisitId').val(0);
                            $('#editView').val(0);
                            $('#statusNoRemoteLab').val('');
                            $('#statusNoRemoteLab ').trigger('keyup');
                            $("#patientvisitidNo").select2("val", "");
                            $("#detectionid").select2("val", 4);
                            $("#detectionvalue_cash").val(0);
                            $("#cardVisitId").val(0);
                            $("#unitsConsumed").val(0);
                            $("#detectionvalue_visa").val(0);
                            $("#restdetectionvalue").val(0);
                            $("#totaldetectionvalue").val(0);
                            $("#discount").val(0);
                            $("#notes").val('');
                            $('#visit_time').val('');
                            $('#discountRatio').val(0);
                            $('#contractPrice').val(0);
                            $('#discountRatioType').val(0);
                            $('#organizations').select2('val', '');
                            $('#selectedFromModel').html("");
                            $('#selectedFromModel').hide();
                            if (Number(data) > 0 && shareVersion == 2) {
                                var selected = Array();
                                var selectedHour = Array();
                                $('.qSelected').each(function () {
                                    var hour = $(this).attr('data-hour');
                                    var room = $(this).attr('data-room');
                                    selectedHour[0] = hour;
                                    selectedHour[1] = room;
                                    selected.push(selectedHour);
                                    selectedHour = [];
                                });
                                if (selected.length > 0) {
                                    var jsonString = JSON.stringify(selected);
                                    $.post(hosturl + '/controllers/visits.php?ac=visitHoursAdd', {edit: 1, visitId: data, jsonString: jsonString}, function (res) {
                                        console.log(res);
                                    });
                                }
                            }

                            $('#fordepartment').select2("val", 4).trigger("change");
                            $('#invType').attr("disabled", false);
                            $('#invType').val('');
                            $("input[name=for_husband][value=" + 0 + "]").prop('checked', true);
                            $("#childHead").hide();
                            $("#childContain").hide();
                            $('#refer_doctor').select2('val', '');
                            $('#saveEditVisit').attr('disabled', false);
                        });
                    });
                } else {
                    alert(' لابد من تحديد المريض ونوع الكشف والتاريخ والفرع  لاكمال التسجيل ...');
                    $('#saveEditVisit').attr('disabled', false);
                }

            } else {
                $('#drExist').html('   اختر طبيب أولا ');
                $('#saveEditVisit').attr('disabled', false);
            }

        });
        $('body').on('click', '.saveVisitComment', function () {

            var visitId = $(this).attr("data-visitId");
            var visitComment = $('#visitComment' + visitId).val();
            $.post(hosturl + '/controllers/visits.php?ac=updatevisitComment',
                    {visitComment: visitComment, visitId: visitId}, function (data) {
                if (data > 0) {
                    var shortCutFunction = 'success';
                    var msg = 'Contiuno your job .. good';
                    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);
            });
        });
        $('body').on('click', '.cancelEditVisit', function () {
            var date_from = $('#date_from').val();
            var date_to = $('#date_to').val();
            $.post(hosturl + '/controllers/visits.php?ac=searchindex', {date_from: date_from, date_to: date_to}, function (res) {
                $('#visitNew').html(res);
                $('#visitaddsubmit').show();
                $('#saveEditVisit').hide();
                $('#cancelEditVisit').hide();
                $('#mVisitId').val(0);
                $('#editView').val(0);
                $('#statusNoRemoteLab').val('');
                $('#statusNoRemoteLab ').trigger('keyup');
                $("#patientvisitidNo").select2("val", "");
                $("#detectionid").select2("val", 4);
                $("#detectionvalue_cash").val(0);
                $("#cardVisitId").val(0);
                $("#unitsConsumed").val(0);
                $("#detectionvalue_visa").val(0);
                $("#restdetectionvalue").val(0);
                $("#totaldetectionvalue").val(0);
                $("#discount").val(0);
                $("#notes").val('');
                $('#fordepartment').select2("val", 4).trigger("change");
                $('#invType').attr("disabled", false);
                $('#invType').val('');
                $("input[name=for_husband][value=" + 0 + "]").prop('checked', true);
                $("#childHead").hide();
                $("#childContain").hide();
                $('#discountRatio').val(0);
                $('#contractPrice').val(0);
                $('#discountRatioType').val(0);
                $('#organizations').select2('val', '');
                $('#visit_time').val('');
                $('#refer_doctor').select2('val', '');
            });
        });
        $('body').on('click', '#addVisitRays', function () {

            $('#selectedFromModel').html("");
            $('#selectedFromModel').show();
            var selectedId;
            var selectedName;
            var totalPrice = 0;
            var totalPrice = 0;
            var itr = 0;
            var selectedPrice = 0;
            var selectedContractPrice = 0;
            var selectedDiscount = 0;
            $("input[name='rayCheck[]']").each(function () {
                if ($(this).is(":checked")) {
                    itr++;
                    selectedId = $(this).val();
                    selectedName = $(this).attr('data-name');
                    selectedPrice = Number($(this).attr('data-price'));
                    selectedContractPrice = selectedContractPrice + Number($(this).attr('data-contract'));
                    selectedDiscount = selectedDiscount + Number($(this).attr('data-discount'));
                    totalPrice = totalPrice + selectedPrice;
                    console.log(($(this).val()));
                    $('#selectedFromModel').append('<div class="col-md-3" id="visitInvDiv' + itr + '">'
                            + '  <a class="btn red btn-xs wds7 deleteVisitInv " style="padding: 0; margin-left: -25px; margin-top: -11px;" '
                            + ' href="#" data-itr="' + itr + '"  ><i class="fa fa-close"></i> </a> '
                            + ' '
                            + '<input  class="form-control"  type="text"  value="' + selectedName + ' ( ' + selectedPrice + ' )" disabled="" name="selectedName' + itr + '" style="display: inline;">'
                            + '<input  class="form-control"  type="hidden"  value="' + selectedId + '"  name="selectedId' + itr + '">'
                            + '<input  class="form-control"  type="hidden"  value="' + selectedPrice + '"  name="selectedPrice' + itr + '" id="selectedPrice' + itr + '">'
                            + '<input  class="form-control"  type="hidden"  value="0"  name="invRes' + itr + '">'
                            + '</div> ');
                }
            });
            $('#selectedFromModel').append('<input type="hidden" id="itr" name="itr"   value="' + itr + '">');
//            $('#itr').val(itr);

            $("#contractPrice").val(selectedContractPrice);
            $("#discountRatio").val(selectedDiscount);
            $("#detectionvalue_cash").val(totalPrice);
            $("#detectionvalue_visa").val(0);
            $("#restdetectionvalue").val(0);
            $("#discount").val(0);
            $("#totaldetectionvalue").val(totalPrice);
            $('.iiin').each(function () {
                $(this).removeAttr('checked');
                if ($(this).parent().attr("class") === 'checked') {
                    $(this).parent().attr("class", '')
                }
            });
            $('#addPatientRays').modal('hide');
        });
        $('body').on('click', '#addVisitInvs', function () {

            var invArray = Array();
            var offerArray = Array();
            var invId;
            $("input[name='invCheck[]']").each(function () {
                if ($(this).is(":checked")) {
                    invId = $(this).val();
                    invArray.push(invId);
                }
            });
            var offerId;
            $("input[name='offersCheck[]']").each(function () {
                if ($(this).is(":checked")) {
                    offerId = $(this).val();
                    offerArray.push(offerId);
                }
            });
            var invests = JSON.stringify(invArray);
            var offers = JSON.stringify(offerArray);
            $.post(hosturl + '/controllers/visits.php?ac=getvisitinvests', {
                invests: invests,
                offers: offers
            }, function (res) {
                if (res != -1) {
                    $('#selectedFromModel').html("");
                    $('#selectedFromModel').html(res);
                    $('#selectedFromModel').show();
                    var totalPrice = $("#temp_price").val();
                    $("#detectionvalue_cash").val(totalPrice);
                    $("#detectionvalue_visa").val(0);
                    $("#restdetectionvalue").val(0);
                    $("#totaldetectionvalue").val(totalPrice);
                    $("#discount").val(0);
                    $('#addPatientInvestigation').modal('hide');
                    invArray = [];
                    offerArray = [];
                } else {
                    alert('error !!!!!!!');
                }
            });
        });
        $('body').on('change', '#invType', function () {
            var invType = $('#invType').val();
            var forDepartment = $('#fordepartment').val();
            var patientId = $('#patientvisitid').val();
            if (patientId == "") {
                alert("اختر مريض أولا ........");
                //  $('#invType').val(-1);
            } else {
                if (invType == 1) {
                    var orgId = $('#organizations').val();
                    $.post(hosturl + '/controllers/visits.php?ac=getinternal', {
                        forDepartment: forDepartment, patientId: patientId, orgId: orgId}, function (res) {
                        $("#divShow").html("");
                        $("#divShow").html(res);
                        $("#internalShow").modal('show');
                    });
                } else if (forDepartment == 5 && invType == 0) {
                    $("#addPatientRays").modal('show');
                } else if (forDepartment == 12 && invType == 0) {
                    $("#addPatientInvestigation").modal('show');
                }
            }

        });

        $('body').on('click', '#addLabVisitInternal', function () {
            var selectedId;
            $("input[name='internalCheck[]']").each(function () {
                if ($(this).is(":checked")) {
                    selectedId = $(this).val();
                    $(this).removeAttr('checked');
                    if ($(this).parent().attr("class") === 'checked') {
                        $(this).parent().attr("class", '')
                    }
                    $('#labInvests').multiSelect('select', selectedId);
                }
            });

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



        $('body').on('click', '#addVisitInvsInternal', function () {
            var price_in = $('#price_in').val();
            $('#selectedFromModel').html("");
            $('#selectedFromModel').show();
            var selectedId;
            var selectedName;
            var totalPrice = 0;
            var totalPrice = 0;
            var selectedContractPrice = 0;
            var selectedDiscount = 0;
            var itr = 0;
            var reqId;
            var reqTable;
            $("input[name='internalCheck[]']").each(function () {
                if ($(this).is(":checked")) {
                    itr++;
                    selectedId = $(this).val();
                    selectedName = $(this).attr('data-name');
                    reqId = $(this).attr('data-id');
                    reqTable = $(this).attr('data-tableName');
                    totalPrice = totalPrice + Number($(this).attr('data-price'));
                    selectedContractPrice = selectedContractPrice + Number($(this).attr('data-contract'));
                    selectedDiscount = selectedDiscount + Number($(this).attr('data-discount'));
                    console.log(($(this).val()));
                    $('#selectedFromModel').append('<div class="col-md-3">'
                            + '<input  class="form-control"  type="text"  value="' + selectedName + '" disabled="" name="selectedName' + itr + '">'
                            + '<input  class="form-control"  type="hidden"  value="' + selectedId + '"  name="selectedId' + itr + '">'
                            + '<input  class="form-control"  type="hidden"  value="' + reqId + '"  name="reqId' + itr + '">'
                            + '<input  class="form-control"  type="hidden"  value="' + reqTable + '"  name="reqTable' + itr + '">'
                            + '</div> ');
                }
            });
            $('#selectedFromModel').append('<input type="hidden" id="itr" name="itr"   value="' + itr + '">');
//            $('#itr').val(itr);

            $("#contractPrice").val(selectedContractPrice);
            $("#discountRatio").val(selectedDiscount);
            $("#restdetectionvalue").val(0);
            $("#detectionvalue_cash").val(0);
            $("#" + price_in).val(totalPrice);
            $("#detectionvalue_visa").val(0);
            $("#totaldetectionvalue").val(totalPrice);
            $("#discount").val(0);
            $('.iiin').each(function () {
                $(this).removeAttr('checked');
                if ($(this).parent().attr("class") === 'checked') {
                    $(this).parent().attr("class", '')
                }
            });
            $('#internalShow').modal('hide');
        });
        $('body').on('change', '.rayImg', function ()  // image
        {
            var Id = $(this).attr('data-id');
            var colName = $(this).attr('data-colName');
            var tableName = $(this).attr('data-tableName');
            $('#talks-loading' + Id).show();
            //alert(name);
            var filename = $(this).val().replace(/C:\\fakepath\\/i, '');
            if (filename != "") {
                var ext = filename;
                var extindex = ext.lastIndexOf(".") + 1;
                ext = ext.slice(extindex, ext.length);
                ext = ext.toLowerCase();
                if ($.inArray(ext, ['jpg', 'jepg', 'png', 'gif', 'jpeg']) == -1) {
                    alert("pictures only allowed (jpg , gif , png , jepg , jpeg)");
                    $('#talks-loading' + Id).hide();
                } else {
                    var myformdata = new FormData();
                    myformdata.append("Id", Id);
                    myformdata.append("colName", colName);
                    myformdata.append("tableName", tableName);
                    jQuery.each(jQuery('#rayImg' + Id)[0].files, function (i, file) {
                        myformdata.append('file-' + i, file);
                    });
                    $.ajax({
                        url: hosturl + '/controllers/raysdept.php?ac=upload', // Url to which the request is send
                        type: "POST", // Type of request to be send, called as method
                        data: myformdata, // Data sent to server, a set of key/value pairs representing form fields and values
                        contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
                        cache: false, // To unable request pages to be cached
                        processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
                        success: function (data)  		// A function to be called if request succeeds
                        {
                            $('#talks-loading' + Id).hide();
                        }
                    });
                }
            } else {
                //$(this).val("");
            }
        });
        $('body').on('click', '.printResults', function () {

            var controller = $('#controllName').val();
            var visitId = $('#visitId').val();
            var role = $(this).attr('data-role');
            var invResIds = Array();
            $('.checkGroup').each(function () {
                if ($(this).is(":checked") && $(this).is(":visible")) {
                    invResIds.push($(this).val());
                }
            });
            var jsonString = JSON.stringify(invResIds);
            $.post(hosturl + '/controllers/' + controller + '.php?ac=printresults', {visitId: visitId, jsonString: jsonString}, function (res) {

                if (Number(res) == -33) {
                    alert(' ملحوظة : لا يمكن طباعة النتائج   يوجد مبالغ مستحقة  على المريض ');
                } else {
                    $("#printDiv").html(res);
                    $.print("#printDiv");
                    $("#printDiv").html("");
                    invResIds.forEach(function (id) {

                        if (role == 3) {
                            $.post(hosturl + '/controllers/invsdept.php?ac=invStatusChange',
                                    {id: id, colName: "printed", value: 1}, function (res) {
                                $('#invStatus' + visitId).trigger('click');
                            });
                        } else {
                            var printed = $('#invPrinted' + id).attr('data-val');
                            if (printed == 1) {
                                $('#invPrinted' + id).trigger('click');
                            }
                        }

                    });
                }
            });
        });
        $('body').on('click', '.printResultsOne', function () {

            var controller = $('#controllName').val();
            var visitId = $('#visitId').val();
            var id = $(this).attr('data-id');
            var printed = $('#invPrinted' + id).attr('data-val');
            var invResIds = Array();
            invResIds.push(id);
            var jsonString = JSON.stringify(invResIds);
            $.post(hosturl + '/controllers/' + controller + '.php?ac=printresults', {visitId: visitId, jsonString: jsonString}, function (res) {

                if (Number(res) == -33) {
                    alert(' ملحوظة : لا يمكن طباعة النتائج   يوجد مبالغ مستحقة  على المريض ');
                } else {
                    $("#printDiv").html(res);
                    $.print("#printDiv");
                    $("#printDiv").html("");
                    if (printed == 1) {
                        $('#invPrinted' + id).trigger('click');
                    }

                }
            });
        });
        $('body').on('click', '.deleteInv', function () {
            var controller = $('#controllName').val();
            var invResId = $(this).attr('data-invResId');
            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/' + controller + '.php?ac=deleteinv', {invResId: invResId}, function (res) {
                                if (Number(res) == 1) {
                                    $('#invDiv' + invResId).remove();
                                } else {

                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $('body').on('click', '.deleteVisitInv', function () {

            var itr = $(this).attr('data-itr');
            var invprice = Number($('#selectedPrice' + itr).val());
            var total = Number($("#totaldetectionvalue").val());
            total = total - invprice;
            $("#detectionvalue_cash").val(total);
            $("#detectionvalue_visa").val(0);
            $("#restdetectionvalue").val(0);
            $("#totaldetectionvalue").val(total);
            $("#discount").val(0);
            $('.detectionvalue').trigger('change');
            $('#visitInvDiv' + itr).remove();
        });
        $('body').on('click', '.printLR', function () {

            var visitId = $(this).attr('data-visitId');
            var index = $(this).attr('data-index');
            $.post(hosturl + '/controllers/visits.php?ac=printrays', {
                visitId: visitId
            }, function (res) {
//                console.log(res);

                if (index == 1) {
                    $.ajax({
                        url: hosturl + "/controllers/visits.php?ac=visitviewed",
                        type: 'POST',
                        data: {id: visitId},
                        success: function (data) {
                            $('#visitDoneRow' + visitId).addClass("visitDone");
                        }
                    });
                }
                $("#printRDiv").html(res);
                $.print("#printRDiv");
                $("#printRDiv").html("");
            });
        });


        $('body').on('keyup change', '.detectionvalue', function ()  // image
        {
            var id = $(this).attr('id');
            var name = $(this).attr('name');
            var total = Number($('#totaldetectionvalue').val());
            var paid_cash = Number($('#detectionvalue_cash').val());
            var paid_visa = Number($('#detectionvalue_visa').val());
            var rest = Number($('#restdetectionvalue').val());

             if (id == 'discount' || name == 'discountType' || name == 'saudi') {
                vcalc();
            }


            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 vatValue = Number($('#vatCalc').val());
            if (vatValue > 0) {

            } else {
                vatValue = 0;
            }

            var paid = paid_cash + paid_visa;
             total = total + vatValue - 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);

        });

        $('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 branch_id = $('#branch_id').val();

            var deptRest = dept - restDiscount;

            if (branch_id > 0) {
                if (paid > deptRest) {
                    $('#res' + visitId).html(' المبلغ المراد دفعه أكبر من المبلغ المتبقى ');
                } else {
                    $.post(hosturl + '/controllers/visits.php?ac=payval',
                            {
                                visitId: visitId, paid_cash: paid_cash, paid_visa: paid_visa, branch_id: branch_id
                                , patientId: patientId, restDiscount: restDiscount, restNotes: restNotes
                            }, function (res) {
                        // print recept
                        if (paid_cash > 0) {
                            $('#printingDiv').html("");
                            $('#printingDiv').html(res);
                            $.print("#printingDiv");
                            $('#printingDiv').html("");
                        }

                        reloadVisits();
                        getLastVisit(patientId);
                        getLastAdvance(patientId);
                        loadPatDept(patientId);
                        getRest(patientId);
                        getBills(patientId);
                    });
                }

            } 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("");
            });
        });
        $('body').on('click', '.printAdvReceipt', function () {
            var id = $(this).attr('data-id');
            $.post(hosturl + '/controllers/visits.php?ac=printAdvReceipt', {id: id}, function (res) {
                console.log(res);
                $("#printAdvDiv").html(res);
                $.print("#printAdvDiv");
                $("#printAdvDiv").html("");
            });
        });
        $('body').on('click', '.printVisitBill', function () {
            var visitId = $(this).attr('data-visitId');
            $.post(hosturl + '/controllers/visits.php?ac=printVisitBill', {
                visitId: visitId
            }, function (res) {
                console.log(res);
                $("#printRDiv").html(res);
                $.print("#printRDiv");
                $("#printRDiv").html("");
            });
        });
        
        
                $('body').on('click', '.printJobOrder', function () {
            var visitId = $(this).attr('data-visitId');
            $.post(hosturl + '/controllers/visits.php?ac=printJobOrder', {
                visitId: visitId
            }, function (res) {
                console.log(res);
                $("#printRDiv").html(res);
                $.print("#printRDiv");
                $("#printRDiv").html("");
            });
        });

        $('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'));
            var branch_id = $('#branch_id').val();

            if (branch_id > 0) {
                if (paid < (refund_cash + refund_visa)) {
                    $('#refund' + visitId).html(' المبلغ المراد إعادته  أكبر من المبلغ المدفوع بالزيارة  ');
                } else {
                    bootbox.dialog({
                        message: "هل أنت متأكد من إعادة المبلغ ؟",
                        title: "تأكيد الإعادة  ",
                        buttons: {
                            danger: {
                                label: "إلغاء ",
                                className: "btn-danger"
                            },
                            main: {
                                label: "نعم ",
                                className: "btn-primary",
                                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,
                                        branch_id: branch_id
                                    }, function (res) {
                                        if (Number(res) != -1) {

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

                                            getLastVisit(patientId);
                                            getLastAdvance(patientId);
                                            loadPatDept(patientId);
                                            getRest(patientId);
                                            getBills(patientId);
                                            reloadVisits();
                                        } else {
                                            $('#refund' + visitId).html(' حدث خطأ . حاول مرة أخرى   ');
                                        }
                                    });
                                }
                            }
                        }
                    }).find('.modal-content').addClass('modal-sm');
                }
            } else {
                alert(' من فضلك قم بتحديد الفرع أولا .');
            }
        });

        $('.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');
        });
        $('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 style="width: 8%;"><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 readonly  class="form-control  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="3"><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 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="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', '.getLastVisitAll', function () {

            var patientId = $(this).attr("data-patientId");
            getLastVisitAll(patientId);
        });

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

            var patientId = $(this).attr("data-patientId");
            getLastAdvanceAll(patientId);
        });


        function reloadVisits() {
            var date_from = $('#date_from').val();
            var date_to = $('#date_to').val();
            var deptId = $('#searchvisitIndexBtn').attr('data-deptId');
            $.post(hosturl + '/controllers/visits.php?ac=searchindex', {date_from: date_from, date_to: date_to, deptId: deptId}, function (res) {
                $('#visitNew').html(res);
                $('#mVisitId').val(0);
            });
        }

        $('body').on('click', '#saveLabVisit', function () {
            $('#saveLabVisit').attr('disabled', true);
            var patientId = $('#patientvisitid').val();
            var patientName = $('#wifename').val();
            var cash = $('#detectionvalue_cash').val();
            var printserial = $('#printserial').val();
            var branch_id = $('#branch_id').val();
            var labPatientId = $('#labPatientId').val();
             var labStyle = $('#labStyle').val();
            var gender = $('input[name="gender"]:checked').val();
              var refer_doctor = $('#refer_doctor').val();
              var age = $('#age').val();
               var errorText = ' ';
                 var saveIt = 1;
            var PatientIdRequired = 0;
            
                 var orgPatNoAdd = $('#orgPatNoAdd').val();
            if (orgPatNoAdd != '') {
                PatientIdRequired = 0;
            }
            
            
            if (PatientIdRequired == 1) {
                              if (!(patientId > 0 || (patientName != '' && !($('#lb_ckwifename:visible').length) && gender >= 0
                    && age > 0 && labPatientId != '' && !($('#lb_ckecklabPatientId:visible').length)))) {
                    errorText += ' Choose old patient  or Add new patient name , gender and age and patient id   . </br> ';
                    saveIt = 0;
                }
            } else {
                if (!(patientId > 0 || (patientName != '' && !($('#lb_ckwifename:visible').length) && gender >= 0
                        && age > 0))) {
                errorText += ' Choose old patient  or Add new patient name , gender and age  . </br> ';
                saveIt = 0;
            }
            }
                 


                         if (refer_doctor == '') {
                                var orgId = $('#organizations').val();
                 if (orgPatNoAdd != '' || orgId > 0 ) {
                } else {
                    errorText += ' Choose Doctor First . </br> ';
                    saveIt = 0;
                }
            }
                 
                             if (!(branch_id > 0)) {
                errorText += ' Choose Branch First . </br> ';
                saveIt = 0;
            }




             if (saveIt == 1) {
                //get invst ids, prices for erp bill
                var invstData = '';
                $('.ms-selected:visible').each(function () {
                    invstData += $(this).data('id') + '*' + $(this).data('price') + ',';
                })
                $("#invstDataForERP").val(invstData);
                $.post(hosturl + '/controllers/visits.php?ac=addLabVisit', $("#myvisitform").serialize(), function (res) {
                    if (Number(res) != -1) {
                        $("#discountType_0").prop("checked", true);
                        $('#discountType_0').parent().addClass('checked');
                        $("#discountType_1").removeAttr('checked');
                        $("#discountType_1").parent().removeClass('checked');
                        $("#organizations").select2("val", "").trigger("change");
                        $("#detectionidLab").select2("val", "");
                        $("#labDetectionPrice").val(0);
                         $('#refer_doctor').select2('val', '');
                        $("#detectionvalue_cash").val(0);
                        $("#cardVisitId").val(0);
                        $("#detectionvalue_visa").val(0);
                        $("#restdetectionvalue").val(0);
                        $("#totaldetectionvalue").val(0);
                        $('#discount').val(0);
                        $("#notes").val('');
                         $('#statusNoRemoteLab').val('');
                                $('#statusNoRemoteLab ').trigger('keyup');
                        $("#patIdRemote").val('');
                        $("#patMobileRemote").val('');
                          $("#orgPatNoRemote").val('');
                        $("#orgPatNoAdd").val('');
                        $("#phone").val('');
                        $("#mobile").val('');
                        $("#wifename").val('');
                        $("#labPatientId").val('');
                        $("#address").val('');
                        $("#dateofbirth_cc").val('');
                        $("#fasting_hours").val('');
                        $("#age").val('');
                        $('#cardVisitPatient').val(0);
                        $('#cardVisitTime').val('');
                        $('#labInvests').multiSelect('deselect_all');
                        $('input:checkbox').removeAttr('checked');
                        $('input:checkbox').parent().removeClass('checked');
                        $('#wifetype').select2("val", '');
                        $('#patientvisitid').select2("val", '');
                        $('#doctor1').select2("val", '');
                        $("input[name=for_husband][value=" + 0 + "]").prop('checked', true);
                        $("#childHead").hide();
                        $("#childContain").hide();
                         if ((cash > 0 || labStyle == 2) && printserial == 1) {

                            $.post(hosturl + '/controllers/visits.php?ac=printvisitrecept', {
                                visitId: res
                            }, function (res1) {
//                                console.log(res1);
                                $("#printRDiv").html(res1);
                                $.print("#printRDiv");
                                $("#printRDiv").html("");
                            });
                        }
                           $('#addLabVisitError').html('');
                        $('#saveLabVisit').attr('disabled', false);
                    } else {
                        alert('خطأ ... لم يتم التسجيل ');
                          $('#addLabVisitError').html('خطأ ... لم يتم التسجيل ');
                        $('#saveLabVisit').attr('disabled', false);
                    }
                });
            } else {
            //     alert('   Complete Patient Information First...');
                 $('#addLabVisitError').html(errorText);
                $('#saveLabVisit').attr('disabled', false);
            }
        });

        $('body').on('change', '.for_husband', function () {
            var value = $(this).val();
            if (value == 2)

            {
                $("#childHead").show();
                $("#childContain").show();
            } else
            {
                $("#childHead").hide();
                $("#childContain").hide();
            }
            $('#statusNoRemoteLab ').trigger('change');
        });

        $("body").on('change', '#organizations', function () {
            var id = $("#opdetailsid").val(); //$(this).attr("data-id");
            var colName = $(this).attr("data-colName");
            var tableName = $(this).attr("data-tableName");
            var maintableName = $(this).attr("data-maintable");
            var orgId = $(this).val();
            var controllName = $('#controllName').val();
            var patientId = $('#patientId').val();
            var hosturl = $('#hosturl').val();
            var lab_visit = $('#lab_visit').val();
            var addVisit = $('#addVisit').val();
            $('#selectedFromModel').html('');
//##########################################################
            if (lab_visit == 1) {
                orgLabPrices(orgId);
            } else if (addVisit == 1) {
                orgRaysPrices(orgId);
            }
            if (orgId == -1) {
                $.post(hosturl + '/controllers/visits.php?ac=editselect', {tableName: maintableName, colName: colName, patientid: patientId, mainId: id}, function (data) {
                    $('#discountRatio').val(0);
                    $('#contractPrice').val(0);
                    $('#discountRatioType').val(0);
                    $('#organizations').select2('val', '');
                    if ($("#detectionid").val() > 0) {
                        $("#detectionid").trigger('change');
                    }
                    $("#detectionforview").html(data);
                    $("#edit_detectionforview").modal('show');
                });
            }
            //##########################################################
            else if (orgId > 0) {
                if (lab_visit != 1) {
                    orgDetectionPrices(orgId);
                }
            }
            //##########################################################
            else {
                $('#discountRatio').val(0);
                $('#contractPrice').val(0);
                $('#discountRatioType').val(0);
                if ($("#detectionid").val() > 0) {
                    $("#detectionid").trigger('change');
                }
            }
        });

        function orgRaysPrices(orgId) {
            var orgDiscountType = $('#orgDiscountType').val();
            if (orgDiscountType == 3 || orgDiscountType == 2) {
                $.post(hosturl + '/controllers/visits.php?ac=orgRaysPrices',
                        {id: orgId, orgDiscountType: orgDiscountType}, function (data) {
                    if (Number(data) != -1) {
                        $('#raysPricesDiv').html(data);
                    }
                });
            }
        }


        function orgDetectionPrices(orgId) {
            var orgDiscountType = $('#orgDiscountType').val();
            var detectionid = $('#detectionid').val();
                if (orgDiscountType == 2 || (orgDiscountType == 3 && detectionid > 0)) {
                    $.post(hosturl + '/controllers/visits.php?ac=getOrgDiscount',
                        {id: orgId, orgDiscountType: orgDiscountType, detectionid: detectionid}, function (data) {
                        var obj = JSON.parse(data);
                        $('#discountRatio').val(obj.discountRatio);
                        $('#discountRatioType').val(obj.discountRatioType);
                        if (orgDiscountType == 3) {
                            $('#contractPrice').val(obj.contract_price);
                            $('#totaldetectionvalue').val(obj.patient_hold);
                            $('.detectionvalue').trigger('change');
                        }
                        if ($("#detectionid").val() > 0) {
                            $("#detectionid").trigger('change');
                        }

                    });
                }
            }

        function orgLabPrices(orgId) {
            var discountType = $('#orgDiscountType').val();
            if (discountType == 2 || discountType == 3) {
                $.post(hosturl + '/controllers/visits.php?ac=orgLabDiscount', {id: orgId, discountType: discountType}, function (data) {
                    if (discountType == 2) {
                        var obj = JSON.parse(data);
                        $('#discount').val(obj.discountRatio);
                        $('#discountRatioType').val(obj.discountRatioType);
                        if (obj.discountRatioType == 1) {
                            $("#discountType_1").prop("checked", true);
                            $('#discountType_1').parent().addClass('checked');
                            $("#discountType_0").removeAttr('checked');
                            $("#discountType_0").parent().removeClass('checked');
                        } else {
                            $("#discountType_0").prop("checked", true);
                            $('#discountType_0').parent().addClass('checked');
                            $("#discountType_1").removeAttr('checked');
                            $("#discountType_1").parent().removeClass('checked');
                }

                        $('#discount').trigger('change');
                    } else if (discountType == 3) {
                        $('#labInvestsTd').html('');
                        $('#labInvestsTd').html(data);
            }
        });
            }
        }

        $('body').on('click', '#addRowOrg', function () {
            var tableName = $(this).attr("data-tableName");
            var selectId = $(this).attr("data-selectId");
            var notAll = $(this).attr("data-notAll");
            var itr = $('#orgItr').val();
            var newItr = Number(itr) + 1;
            $('#orgItr').val(newItr);
            $.post(hosturl + '/controllers/visits.php?ac=addOrgRow', {tableName: tableName, itr: newItr, notAll: notAll}, function (res) {
                $('#orgContainer').prepend(res);
                var dataid = $('#organization_name' + newItr).attr("data-id");
                $('#' + selectId + ' > .deleteoptincompo').before('<option value="' + dataid + '" ></option>');
            });
        });

        $('body').on('click', '#addRowList', function () {
            var tableName = $(this).attr("data-tableName");
            var selectId = $(this).attr("data-selectId");
            var notAll = $(this).attr("data-notAll");
            var itr = $('#listItr').val();
            var newItr = Number(itr) + 1;
            $('#listItr').val(newItr);
            $.post(hosturl + '/controllers/visits.php?ac=addOrgRow', {tableName: tableName, itr: newItr, notAll: notAll}, function (res) {
                $('#ListContainer').prepend(res);
                var dataid = $('#name' + newItr).attr("data-id");
                $('#' + selectId + ' > .deleteoptincompo').before('<option value="' + dataid + '" ></option>');
            });
        });

        $('body').on('click', '#addRowOrgParent', function () {
            var tableName = $(this).attr("data-tableName");
            var selectId = $(this).attr("data-selectId");
            var notAll = $(this).attr("data-notAll");
            var itr = $('#listItr').val();
            var newItr = Number(itr) + 1;
            $('#listItr').val(newItr);
            $.post(hosturl + '/controllers/visits.php?ac=addOrgRow', {tableName: tableName, itr: newItr, notAll: notAll}, function (res) {
                $('#ListContainer').prepend(res);
                var dataid = $('#name' + newItr).attr("data-id");
                $('.organizations_parents > .deleteoptincompo').before('<option value="' + dataid + '" ></option>');
            });
        });

        $('body').on('click', '#addOrganization', function () {
            $.post(hosturl + '/controllers/detection.php?ac=addNewOrg', function (res) {
                $('#orgContainer').prepend(res);
            });
        });
//######################################################

        $('body').on('change', '#operationId', function ()
        {
            var operationId = $('#operationId').val();
            $.post(hosturl + '/controllers/visits.php?ac=getoperationdata', {operationId: operationId}, function (data) {
                var obj = JSON.parse(data);
                $('#operation_duration').val(obj.operation_duration);
                $('#residence_duration').val(obj.residence_duration);
            });
        });
        $('body').on('click', '#searchRooms', function ()
        {
            var operationId = $('#operationId').val();
            var operation_time_start = $('#operation_time_start').val();
            var operation_duration = $('#operation_duration').val();
            var residence_duration = $('#residence_duration').val();
            $.post(hosturl + '/controllers/visits.php?ac=getrooms',
                    {
                        operationId: operationId, operation_time_start: operation_time_start
                        , operation_duration: operation_duration, residence_duration: residence_duration
                    }, function (data) {
                $('#searchDatesResult').html('');
                $('#searchRoomsResult').html('');
                $('#searchRoomsResult').html(data);
            });
        });
        $('body').on('click', '#searchDates', function ()
        {
            var operationId = $('#operationId').val();
            var visitdate = $('#visitdate').val();
            $.post(hosturl + '/controllers/visits.php?ac=getdates',
                    {
                        operationId: operationId, visitdate: visitdate
                    }, function (data) {
                $('#searchRoomsResult').html('');
                $('#searchDatesResult').html('');
                $('#searchDatesResult').html(data);
            });
        });
        $('body').on('change', '#operationRoomId', function ()
        {
            var operationRoomId = $('#operationRoomId').val();
            if (operationRoomId > 0) {
                $.post(hosturl + '/controllers/visits.php?ac=getroomdates', {roomId: operationRoomId, roomType: 1}, function (data) {
                    $('#operationDates').html('');
                    $('#operationDates').html(data);
                });
            } else {
                $('#operationDates').html('');
            }
        });
        $('body').on('change', '#residenceRoomId', function ()
        {
            var residenceRoomId = $('#residenceRoomId').val();
            if (residenceRoomId > 0) {
                $.post(hosturl + '/controllers/visits.php?ac=getroomdates', {roomId: residenceRoomId, roomType: 2}, function (data) {
                    $('#residenceDates').html('');
                    $('#residenceDates').html(data);
                });
            } else {
                $('#residenceDates').html('');
            }
        });
        $('body').on('click', '.timeFree', function ()
        {
            var selected = $(this).attr('data-sel');
            if (selected == 1) {
                $(this).attr('data-sel', 0);
                $(this).css('background-color', '#a3dfa2');
            } else {
                $(this).attr('data-sel', 1);
                $(this).css('background-color', '#dfb3a2');
            }
        });
//################################################

        $('body').on('change', '#visitdate , #branch_id', function () {
            var doctorId = $('#for_doctor').val();
            var shareVersion = $('#shareVersion').val();
            var department = $('#fordepartment').val();
            var branch_id = $('#branch_id').val();
            if (doctorId > 0 && shareVersion != 2) {
                var visitdate = $('#visitdate').val();
                $.post(hosturl + '/controllers/visits.php?ac=getVisitsByDoctor', {branch_id: branch_id, doctorId: doctorId, visitdate: visitdate, forDept: department}, function (res) {
                    $("#visitCountDiv").html("");
                    $("#visitCountDiv").html(res);
                });
            } else {
                $("#visitCountDiv").html("");
            }

        });


        $('body').on('change', '#for_doctor', function ()
        {
            var doctorId = $('#for_doctor').val();
            var shareVersion = $('#shareVersion').val();
            var department = $('#fordepartment').val();
            var branch_id = $('#branch_id').val();
            if (doctorId > 0 && shareVersion == 2) {
                $.post(hosturl + '/controllers/visits.php?ac=getDetectionsByDoctor', {doctorId: doctorId}, function (res) {
                    $("#detectionid").html("");
                    $("#detectionid").html(res);
                    $("#detectionid").select2();
                    var oldDetectionId = $('#oldDetectionId').val();
                    if (oldDetectionId > 0) {
                        $('#oldDetectionId').val(0);
                        $('#detectionid').select2("val", oldDetectionId);
                    } else {
                        $("#detectionvalue_cash").val(0);
                        $("#detectionvalue_visa").val(0);
                        $("#restdetectionvalue").val(0);
                        $("#totaldetectionvalue").val(0);
                        $('#discount').val(0);
                    }

                });
            } else {
                //   alert("اختر طبيب  أولا ........");
            }


            if (doctorId > 0 && shareVersion != 2) {
                var visitdate = $('#visitdate').val();
                $.post(hosturl + '/controllers/visits.php?ac=getVisitsByDoctor', {branch_id: branch_id, doctorId: doctorId, visitdate: visitdate, forDept: department}, function (res) {
                    $("#visitCountDiv").html("");
                    $("#visitCountDiv").html(res);
                });
            }
            //####
            else if (doctorId > 0 && shareVersion != 2 && department == 13) {
                operationResidentDetails();
            }
            //####
            else {
                $("#visitCountDiv").html("");
            }

        });
        $('body').on('change', '#reserveId', function ()
        {
            var reserveId = $('#reserveId').val();
            if (reserveId > 0) {
                $.post(hosturl + '/controllers/visits.php?ac=getDetectionsByReserve', {reserveId: reserveId}, function (res) {
                    if (Number(res) > 0) {
                        $('#detectionid').select2("val", Number(res));
                        $('#detectionid').trigger("change");
                    }
                });
            } else {
//                $('#detectionid').select2("val", '4');
//                $('#detectionid').trigger("change");
            }
        });
        function operationResidentDetails()
        {
            var visitdate = $('#visitdate').val();
            var doctorId = $('#for_doctor').val();
            $.post(hosturl + '/controllers/visits.php?ac=operationreserves', {
                visitdate: visitdate
                , doctorId: doctorId
            }, function (res) {
                $('#reserveId').html(res);
                $('#reserveId').select2();
                var mainId = $('#oldOperation_main_id').val();
                if (mainId > 0) {
                    $('#oldOperation_main_id').val(0);
                    $('#reserveId').select2("val", mainId);
                } else {
                    $('#reserveId').trigger("change");
                }


                $('#time_containers_head').show();
                $('#time_containers').show();
            });
        }

        $('body').on('change', '.showRDetails', function () {
            var doctorId = $('#for_doctor').val();
            var visitdate = $('#visitdate').val();
            var shareVersion = $('#shareVersion').val();
            var visitId = $('#mVisitId').val();
            if (doctorId > 0 && shareVersion == 2) {
                $.post(hosturl + '/controllers/visits.php?ac=getDoctorRDetails', {visitId: visitId, doctorId: doctorId, visitdate: visitdate}, function (res) {
                    $("#reserveDetails").html("");
                    $("#reserveDetails").html(res);
                    $("#reserveDetails").show();
                });
                $.post(hosturl + '/controllers/visits.php?ac=getDoctorweekDates', {doctorId: doctorId}, function (res) {
                    $("#weekDates").html("");
                    $("#weekDates").html(res);
                    $("#weekDates").show();
                });
            } else {
                $("#reserveDetails").hide();
                $("#weekDates").hide();
            }
        });
        $('body').on('click', '.qFree', function () {
            $(this).removeClass('qFree');
            $(this).addClass('qSelected');
        });
        $('body').on('click', '.qSelected', function () {
            $(this).removeClass('qSelected');
            $(this).addClass('qFree');
        });
        //################################################
        $('body').on('click', '.addPackVisit', function () {
            var visitId = $(this).attr("data-visitId");
            $.post(hosturl + '/controllers/visits.php?ac=packVisitDetails', {visitId: visitId}, function (data) {
                $('#packVisitError').html(data);
                $('#visitaddsubmit').hide();
                $('#savePackVisit').attr("data-visitId", visitId);
                $('#detectionid').attr("disabled", true);
                $('#patientvisitid').attr("disabled", true);
                $('#statusNoRemoteLab').attr("disabled", true);
                $('#detectionvalue_visa').attr("disabled", true);
                $('#detectionvalue_cash').attr("disabled", true);
                $('#discount').attr("disabled", true);
                $('#totaldetectionvalue').attr("disabled", true);
                $('#for_husband0').attr("disabled", true);
                $('#for_husband_1').attr("disabled", true);
                $('#for_husband2').attr("disabled", true);
                $('#mVisitId').val(visitId);
                $('#savePackVisit').show();
                $('#cancelPackVisit').show();
            });
        });
        $('body').on('click', '.cancelPackVisit', function () {
            $('#packVisitError').html('');
            $('#visitaddsubmit').show();
            $('#savePackVisit').attr("data-visitId", 0);
            $('#detectionid').attr("disabled", false);
            $('#patientvisitid').attr("disabled", false);
            $('#statusNoRemoteLab').attr("disabled", false);
            $('#detectionvalue_visa').attr("disabled", false);
            $('#detectionvalue_cash').attr("disabled", false);
            $('#discount').attr("disabled", false);
            $('#totaldetectionvalue').attr("disabled", false);
            $('#for_husband0').attr("disabled", false);
            $('#for_husband_1').attr("disabled", false);
            $('#for_husband2').attr("disabled", false);
            $('#mVisitId').val(0);
            $('#savePackVisit').hide();
            $('#cancelPackVisit').hide();
        });
        $('body').on('click', '.savePackVisit', function () {
            var for_doctor = $('#for_doctor').val();
            var unitsConsumed = $('#unitsConsumed').val();
            if (for_doctor > 0 && unitsConsumed > 0) {
                $.post(hosturl + '/controllers/visits.php?ac=savePackVisit', $("#myvisitform").serialize(), function (data) {
                    var date_from = $('#date_from').val();
                    var date_to = $('#date_to').val();
                    $.post(hosturl + '/controllers/visits.php?ac=searchindex', {date_from: date_from, date_to: date_to}, function (res) {
                        $("#discountType_0").prop("checked", true);
                        $('#discountType_0').parent().addClass('checked');
                        $("#discountType_1").removeAttr('checked');
                        $("#discountType_1").parent().removeClass('checked');
                        $("#organizations").select2("val", "").trigger("change");
                        $('#packVisitError').html('');
                        $('#visitNew').html(res);
                        $('#visitaddsubmit').show();
                        $('#savePackVisit').attr("data-visitId", 0);
                        $('#detectionid').attr("disabled", false);
                        $('#patientvisitid').attr("disabled", false);
                        $('#statusNoRemoteLab').attr("disabled", false);
                        $('#detectionvalue_visa').attr("disabled", false);
                        $('#detectionvalue_cash').attr("disabled", false);
                        $('#discount').attr("disabled", false);
                        $('#totaldetectionvalue').attr("disabled", false);
                        $('#for_husband0').attr("disabled", false);
                        $('#for_husband_1').attr("disabled", false);
                        $('#for_husband2').attr("disabled", false);
                        $('#mVisitId').val(0);
                        $('#savePackVisit').hide();
                        $('#cancelPackVisit').hide();
                        $('#statusNoRemoteLab').val('');
                        $('#statusNoRemoteLab ').trigger('keyup');
                        $("#patientvisitidNo").select2("val", "");
                        $("#detectionid").select2("val", 4);
                        $("#detectionvalue_cash").val(0);
                        //     $("#cardVisitId").val(0);
                        $("#unitsConsumed").val(0);
                        $("#detectionvalue_visa").val(0);
                        $("#restdetectionvalue").val(0);
                        $("#totaldetectionvalue").val(0);
                        $("#discount").val(0);
                        $("#notes").val('');
                        $('#discountRatio').val(0);
                        $('#contractPrice').val(0);
                        $('#discountRatioType').val(0);
                        $('#organizations').select2('val', '');
                        $('#fordepartment').select2("val", 4).trigger("change");
                        $('#invType').attr("disabled", false);
                        $('#invType').val('');
                        $("input[name=for_husband][value=" + 0 + "]").prop('checked', true);
                        $("#childHead").hide();
                        $("#childContain").hide();
                    });
                });
            }
        });
//################################################

        $('body').on('click', '#searchvisitIndexBtn', function () {
            $('#searchvisitIndexBtn').attr('disabled', true);
            var date_from = $('#date_from').val();
            var date_to = $('#date_to').val();
            var patientId = $('#patientIdRemote').val();
              var patNationalId = $('#patIdShow').val();
            var patMobile = $('#patMobileShow').val();
              var sampleId = $('#sampleIdShow').val();
            var doctorId = $('#doctorIdRemote').val();
            var deptId = $(this).attr('data-deptId');
            var branchSearch = $('#branchSearch').val();
            var ischecked = $("#ignoreDate").is(':checked');
            if (!ischecked) {
                var ignoreDate = 0;
            } else {
                var ignoreDate = 1;
            }

            if (ignoreDate == 1 && !(patientId > 0)) {
                alert(' لعرض النتائج  كاملة لابد من اختيار مريض أولا .');
                $('#searchvisitIndexBtn').attr('disabled', false);
            } else {
                $.post(hosturl + '/controllers/visits.php?ac=searchindex', {branchSearch: branchSearch,
                    date_from: date_from, date_to: date_to, deptId: deptId, patientId: patientId, doctorId: doctorId
                    , ignoreDate: ignoreDate , patNationalId: patNationalId, patMobile: patMobile  , sampleId: sampleId}, function (data) {
                    $('#visitNew').html(data);
                    $('#mVisitId').val(0);
                    $('#searchvisitIndexBtn').attr('disabled', false);
                });
            }
        });
        //################################################

        $('body').on('click', '.todayListChange', function () {
            var id = $(this).attr("data-visitId");
            var value = $(this).attr('data-val');
            $.post(hosturl + '/controllers/visits.php?ac=updateajax', {
                id: id, value: value, tableName: 'visits', colName: 'today_list'}, function (data) {
                if (value == 1) {
                    $('#todayListCanc' + id).show();
                    $('#todayListConf' + id).hide();
                } else {
                    $('#todayListCanc' + id).hide();
                    $('#todayListConf' + id).show();
                }
            });
        });

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

        $('body').on('click', '.collectIt', function () {
            var id = $(this).attr("data-visitId");
            var value = $(this).attr('data-val');
            $.post(hosturl + '/controllers/visits.php?ac=updateajax', {
                id: id, value: value, tableName: 'visits', colName: 'collect'}, function (data) {
                if (value == 1) {
                    $('#collectItNo' + id).show();
                    $('#collectYes' + id).hide();
                } else {
                    $('#collectItNo' + id).hide();
                    $('#collectYes' + id).show();
                }
            });
        });
        $('.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();
            var branchId = $('#branch_id').val();
            if (periodId == '-2') {
                $.post(hosturl + '/controllers/visits.php?ac=visitPeriodEdit', function (data) {
                    $('#visit_period').select2("val", "");
                    $("#editModalDiv").html(data);
                    $("#edit_model").modal('show');
                });
            } else if (periodId > 0 && branchId) {
                $.post(hosturl + "/controllers/visits.php?ac=patPerPeriod",
                        {periodId: periodId, visitdate: visitdate, branchId: branchId}, function (data) {
                    $('#periodPatCount').val(data);
                });
            } else {
                $('#periodPatCount').val('');
            }
        });
    };

    $('body').on('click', '#sendGroupSmsBtn', function () {
        $('#sendGroupSmsBtn').attr('disabled', true);
        var date_from = $('#date_from').val();
        var date_to = $('#date_to').val();
        $.post(hosturl + '/controllers/visits.php?ac=sendGroupSmsBtn', {
            date_from: date_from, date_to: date_to}, function (data) {
            alert(data);
            $('#sendGroupSmsBtn').attr('disabled', false);
        });
    });

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


        $("select.hospitalnames").select2({
            width: '170px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */

                return "<input class='form-control' id='newddTerm'  value='" + term + "'><a href='#' id='addddNew'  class='btn btn-default'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addddNew', function () {

            var colName = $("#hospitalnames").attr("data-colName");
            var tableName = $("#hospitalnames").attr("select-tableName");
            var selectedhospital = $('#newddTerm').val();
            $.post(hosturl + '/controllers/instruction.php?ac=addnewhospital', {selectedhospital: selectedhospital}, function (data) {
                $('.hospitalnames > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + selectedhospital + '</option>');
                //$('<option value="' + Number(data) + '" >' + newitem + '</option>').appendTo('#childj');
                $('#hospitalnames').select2('val', Number(data)); // select the new term
                $('#hospitalnames').select2('close'); // close the dropdown
            });
        });
//end safy


        $('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();
            });
        });
        ////////safy///////
        $("select.selecthospital").on('change', function () {
// Do something wi.on('change', function () {
            var colName = $(this).attr("data-colName");
            var tableName = $(this).attr("select-tableName");
            var thisvalue = $("#hospitalnames").val();
            if (thisvalue == '-2') {

                $.post(hosturl + '/controllers/instruction.php?ac=editModal', {tableName: tableName, colName: colName}, function (data) {
                    $("#hospitalnames").select2("val", "");
                    $("#alldatadiv").html(data);
                    $("#edit_model").modal('show');
                });
            }

        })


        $("#addnewRow").live('click', function () {
            var tableName = $(this).attr('data-tableName');
            var selectname = $(this).attr('data-selectClass');
            var colName = $("#colName").val();
            $.post(hosturl + "/controllers/instruction.php?ac=addNewRow", {tableName: tableName, colName: colName}, function (data) {
                var dataid = Number(data);
                $('.selecthospital > .deleteoptincompo').before('<option value="' + dataid + '" ></option>');
                $("#dtAddTbl").prepend('<tr>\
                                            <td style="width: 100%">\
                                                <a href="#" >\
                                                    <input type="text" id="newitem_name" class="form-control updateElementSelect" data-selectClass="' + tableName + '"  data-select2="yes" data-id="' + dataid + '" data-colName="name" data-tableName="' + tableName + '" value="" name="newamount_name"/>\
                                                </a>\
                                            </td>\
                                            <td>\
                                                <a class="delrow fa fa-times btn red fleft" data-colName="conditions" data-link="gyna" data-tableName="' + tableName + '" data-fn="deldiagnosis" data-id="' + dataid + '" ></a>\
                                            </td>\
                                        </tr>');
            });
        });
        // edit the new row of modaled
        $("#newitem_name").live('change', function (e) {
            e.preventDefault();
            var value = $(this).val();
            var id = $(this).attr("data-id");
            var tablename = $("#tablename").val();
            var patientid = $("#patientid").val();
            var colName = $("#colName").val();
            if (id != '') {
                $.post(hosturl + '/controllers/instruction.php?ac=updateModal', {tablename: tablename, colName: colName, id: id, value: value, patientid: patientid}, function (data) {
                    if (tablename === "hospitalnames") {
                        $(".hospitalnames option[value='" + id + "']").text(value);
                        $('#hospitalnames').select2('val', id);
                    }

                });
            }
        });
        ///////////////////////////////////////////////////// delete row from modal and database and select2////////////////////////

        $('.deleteModal').live('click', function () {
            var id = $(this).attr('data-id');
            var tablename = $("#tablename").val();
            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/instruction.php?ac=delRowsommedel', {id: id, tableName: tablename}, function (res) {

                                if (res == 1) {
                                    tr.parent().remove();
                                    if (tablename === "hospitalnames") {
                                        $(".selecthospital option[value='" + id + "']").remove();
                                    }
                                } else {
                                    alert("!!!!!!!!!!!!! some thing wrong here");
                                }

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


        // $('#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 colName = $(this).attr('data-colName');
            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, colName: colName, tableName: tableName
                            }, function (res) {
                                if (res == 1) {

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

    var and_examination = function () {

        $('body').on('click', '#and_exam_add', function () {
            var patientId = $('#patientId').val();
            $.post(hosturl + '/controllers/and_examination.php?ac=newexam', {patientId: patientId}, function (res) {
                $('#and_exam_table').prepend(res);
            });
        });
    };

    var and_visits = function () {

        $('.andDiagnosis').live('change', 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 dated = 0;
            var realvalues = new Array(); //storing the selected values inside an array
            var lastvalue;
            var slcttable;
            if (colName == "diagnosisid") {
                $('#andDiagnosis' + id + ' :selected').each(function (i, selected) {
                    realvalues[i] = $(selected).val();
                    lastvalue = $(selected).val();
                });
                slcttable = "anddiagnosis";
            } else {
                $('#andComplaint' + id + ' :selected').each(function (i, selected) {
                    realvalues[i] = $(selected).val();
                    lastvalue = $(selected).val();
                });
                slcttable = "andcomplaint";
            }
            //var lastvalue = realvalues[realvalues.length-1];

            if (lastvalue == -2) {
                var selectId = $(this).attr('id');
                $("#" + selectId + " option[value='-2']").prop("selected", false);
                $("#" + selectId + "").select2();
                $.post(hosturl + '/controllers/and_visits.php?ac=alldiagnosis', {colName: colName}, function (data) {
                    $("#alldatadiv").html(data);
                    $("#newitem_name").val("");
                    $("#newitem_id").val("");
                    $("#slctTbl").val(slcttable);
                    $("#edit_model").modal('show');
                    $("#edtSlct").attr("data-tableName", slcttable);
                    realvalues.pop();
                });
            }
            if ($.inArray("-1", realvalues) != -1) {
                var selectId = $(this).attr('id');
                $("#" + selectId + " option[value='-1']").prop("selected", false);
                $("#" + selectId + "").select2();
                $("#add_model").modal('show');
                realvalues.pop();
                $("#diagnosisName").val('');
                $("#diagnosisName").attr("data-select", selectId);
                $("#diagnosisName").attr("data-tablename", slcttable);
                $("#diagnosisName").attr("data-id", id);
            }
            if (lastvalue != '-1' && lastvalue != '-2' && $.inArray("-1", realvalues) == -1) {
                $.ajax({
                    url: hosturl + '/controllers/' + controllName + '.php?ac=update',
                    data: {
                        value: JSON.stringify(realvalues),
                        id: id,
                        tableName: tableName,
                        colName: colName,
                        patientId: patientId,
                        dated: dated
                    },
                    type: 'POST',
                    success: function (data) {

                    }
                });
            }
        });
        $(".addDiagnosisName").live('change', function () {
            var hosturl = $('#hosturl').val();
            var selectId = $(this).attr('data-select');
            var table = $(this).attr('data-tablename');
            var id = $(this).attr("data-id");
            var newitem = $(this).val();
            var select;
            $.post(hosturl + '/controllers/and_visits.php?ac=adddiagnosis', {diagnosisName: newitem, id: id, table: table}, function (data) {

                $('.' + table + ' > .addDiagnosis').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                $('#' + selectId + ' option[value="' + Number(data) + '"]').attr('selected', true);
                $('select').select2();
                //$('#diagnosis' + $thisitr).select2('val', Number(data)); // select the new term
            });
        });
        $('body').on('click', '#andVisitsAdd', function () {
            var patientId = $('#patientId').val();
            var tableName = 'andvisits';
            var type = 'and_visits';
            $.post(hosturl + '/controllers/and_visits.php?ac=newrow', {patientId: patientId, tableName: tableName, type: type}, function (res) {
                $('#andVisits').prepend(res);
            });
        });
        $('body').on('click', '#addSemen', function () {
            $("#semenModel").modal('show');
        });
        $('body').on('click', '#addGenetic', function () {
            $("#geneticTestingModel").modal('show');
        });
        $('body').on('click', '#addSemenRow', function () {
            var patientId = $('#patientId').val();
            var tableName = 'andvisitssemen';
            var type = 'semen';
            $.post(hosturl + '/controllers/and_visits.php?ac=newrow', {patientId: patientId, tableName: tableName, type: type}, function (res) {
                $('#semenAnd').prepend(res);
            });
        });
        $('body').on('click', '#addGeneticRow', function () {
            var patientId = $('#patientId').val();
            var tableName = 'andvisitsgenetictesting';
            var type = 'genetictesting';
            $.post(hosturl + '/controllers/and_visits.php?ac=newrow', {patientId: patientId, tableName: tableName, type: type}, function (res) {
                $('#geneticTestingAnd').prepend(res);
            });
        });
        $('body').on('click', '#printGeneticRow', function () {

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

            var patientId = $('#patientId').val();
            var usRows = Array();
            $('.semenPrint').each(function () {
                if ($(this).is(":checked") && $(this).is(":visible")) {
                    usRows.push($(this).val());
                }
            });
            var jsonString = JSON.stringify(usRows);
            $.post(hosturl + '/controllers/and_visits.php?ac=printselected', {
                type: 'semenPrint',
                patientId: patientId,
                jsonString: jsonString
            }, function (res) {
                $("#newDrugTableDiv").html("");
                $("#newDrugTableDiv").html(res);
                $.print("#newDrugTableDiv");
                $("#newDrugTableDiv").html("");
            });
        });
    };

    var and_history = function () {
        $('.durationid').each(function () {
            var id = $(this).attr('data-id');
            $('#durationid' + id).select2({
                width: '170px',
                allowClear: true,
                formatNoMatches: function (term) {
                    /* customize the no matches output */
                    return "<input class='form-control' id='newDuration" + id + "' value='" + term + "' data-id='" + id + "'><a href='#' id='addNewDuration" + id + "' data-id=" + id + "   class='btn btn-default addnewselect'>Add</a>"
                }
            }).parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
                var id = $(this).attr('data-id');
                var patientId = $('#patientId').val();
                var newitem = $('#newDuration' + id).val();
                $.post(hosturl + '/controllers/and_history.php?ac=addduration', {newitem: newitem, id: id, inline: 1, patientId: patientId}, function (data) {
                    $('select[name="durationid"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                    //$('<option value="' + Number(data) + '" >' + newitem + '</option>').appendTo('select[name="phregularity"]');
                    $('#durationid' + id).select2('val', Number(data)); // select the new term
                    $('#durationid' + id).select2('close'); // close the dropdown


                });
            });
        });
        $('.mdiseaseid').each(function () {
            var id = $(this).attr('data-id');
            $('#mdiseaseid' + id).select2({
                width: '170px',
                allowClear: true,
                formatNoMatches: function (term) {
                    /* customize the no matches output */
                    return "<input class='form-control' id='newMDisease" + id + "' value='" + term + "' data-id='" + id + "'><a href='#' id='addNewMDisease" + id + "' data-id=" + id + "   class='btn btn-default addnewselect'>Add</a>"
                }
            }).parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
                var id = $(this).attr('data-id');
                var patientId = $('#patientId').val();
                var newitem = $('#newMDisease' + id).val();
                $.post(hosturl + '/controllers/and_history.php?ac=adddmdisease', {newitem: newitem, id: id, inline: 1, patientId: patientId}, function (data) {
                    $('select[name="mdiseaseid"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                    //$('<option value="' + Number(data) + '" >' + newitem + '</option>').appendTo('select[name="phregularity"]');
                    $('#mdiseaseid' + id).select2('val', Number(data)); // select the new term
                    $('#mdiseaseid' + id).select2('close'); // close the dropdown


                });
            });
        });
        $('.erectiondiseaseid').each(function () {
            var id = $(this).attr('data-id');
            $('#erectiondiseaseid' + id).select2({
                width: '170px',
                allowClear: true,
                formatNoMatches: function (term) {
                    /* customize the no matches output */
                    return "<input class='form-control' id='newerectiondisease" + id + "' value='" + term + "' data-id='" + id + "'><a href='#' id='addNewerectiondisease" + id + "' data-id=" + id + "   class='btn btn-default addnewselect'>Add</a>"
                }
            }).parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
                var id = $(this).attr('data-id');
                var patientId = $('#patientId').val();
                var newitem = $('#newerectiondisease' + id).val();
                $.post(hosturl + '/controllers/and_history.php?ac=addderectiondisease', {newitem: newitem, id: id, inline: 1, patientId: patientId}, function (data) {
                    $('select[name="erectiondiseaseid"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                    //$('<option value="' + Number(data) + '" >' + newitem + '</option>').appendTo('select[name="phregularity"]');
                    $('#erectiondiseaseid' + id).select2('val', Number(data)); // select the new term
                    $('#erectiondiseaseid' + id).select2('close'); // close the dropdown


                });
            });
        });
        $('.ejaculationdiseaseid').each(function () {
            var id = $(this).attr('data-id');
            $('#ejaculationdiseaseid' + id).select2({
                width: '170px',
                allowClear: true,
                formatNoMatches: function (term) {
                    /* customize the no matches output */
                    return "<input class='form-control' id='newejaculationdisease" + id + "' value='" + term + "' data-id='" + id + "'><a href='#' id='addNewejaculationdisease" + id + "' data-id=" + id + "   class='btn btn-default addnewselect'>Add</a>"
                }
            }).parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
                var id = $(this).attr('data-id');
                var patientId = $('#patientId').val();
                var newitem = $('#newejaculationdisease' + id).val();
                $.post(hosturl + '/controllers/and_history.php?ac=addejaculationdisease', {newitem: newitem, id: id, inline: 1, patientId: patientId}, function (data) {
                    $('select[name="ejaculationdiseaseid"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                    //$('<option value="' + Number(data) + '" >' + newitem + '</option>').appendTo('select[name="phregularity"]');
                    $('#ejaculationdiseaseid' + id).select2('val', Number(data)); // select the new term
                    $('#ejaculationdiseaseid' + id).select2('close'); // close the dropdown


                });
            });
        });
        $('.typeid').each(function () {
            var id = $(this).attr('data-id');
            $('#typeid' + id).select2({
                width: '170px',
                allowClear: true,
                formatNoMatches: function (term) {
                    /* customize the no matches output */
                    return "<input class='form-control' id='newtype" + id + "' value='" + term + "' data-id='" + id + "'><a href='#' id='addNewtype" + id + "' data-id=" + id + "   class='btn btn-default addnewselect'>Add</a>"
                }
            }).parent().find('.select2-with-searchbox').on('click', '.addnewselect', function () {
                var id = $(this).attr('data-id');
                var patientId = $('#patientId').val();
                var newitem = $('#newtype' + id).val();
                $.post(hosturl + '/controllers/and_history.php?ac=addcontraception', {newitem: newitem, id: id, inline: 1, patientId: patientId}, function (data) {
                    $('select[name="typeid"] > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                    //$('<option value="' + Number(data) + '" >' + newitem + '</option>').appendTo('select[name="phregularity"]');
                    $('#typeid' + id).select2('val', Number(data)); // select the new term
                    $('#typeid' + id).select2('close'); // close the dropdown


                });
            });
        });
//#####################################################################################################

        $('body').on('click', '#historyAdd', function () {
            var patientId = $('#patientId').val();
            var tableName = 'andhistory';
            var type = 'general_history';
            $.post(hosturl + '/controllers/and_history.php?ac=newrow', {patientId: patientId, tableName: tableName, type: type}, function (res) {
                $('#historyDiv').prepend(res);
            });
        });
        $('body').on('click', '#mProblemAdd', function () {
            var patientId = $('#patientId').val();
            var tableName = 'andmedicalproblems';
            var type = 'mProblems';
            $.post(hosturl + '/controllers/and_history.php?ac=newrow', {patientId: patientId, tableName: tableName, type: type}, function (res) {
                $('#mProblemDiv').prepend(res);
            });
        });
        $('body').on('click', '#erectionAdd', function () {
            var patientId = $('#patientId').val();
            var tableName = 'anderection';
            var type = 'erection';
            $.post(hosturl + '/controllers/and_history.php?ac=newrow', {patientId: patientId, tableName: tableName, type: type}, function (res) {
                $('#erectionDiv').prepend(res);
            });
        });
        $('body').on('click', '#ejaculationAdd', function () {
            var patientId = $('#patientId').val();
            var tableName = 'andejaculation';
            var type = 'ejaculation';
            $.post(hosturl + '/controllers/and_history.php?ac=newrow', {patientId: patientId, tableName: tableName, type: type}, function (res) {
                $('#ejaculationDiv').prepend(res);
            });
        });
        $('body').on('click', '#contraceptionAdd', function () {
            var patientId = $('#patientId').val();
            var tableName = 'andcontraception';
            var type = 'contraception';
            $.post(hosturl + '/controllers/and_history.php?ac=newrow', {patientId: patientId, tableName: tableName, type: type}, function (res) {
                $('#contraceptionDiv').prepend(res);
            });
        });
//#####################################################################################################


        $('body').on('change', '.editSelect', function () {
            var value = $(this).val();
            var tableName = $(this).attr('select-tableName');
            var name = $(this).attr('name');
            var pervious = $(this).attr('data-val');
            var patientid = $("#patientId").val();
            var rowoftableid = $(this).attr('data-id');
            var maintableName = $(this).attr('data-tableName');
            if (value == '-2') {
                $('#' + name + '' + rowoftableid).select2('val', pervious, true);
                $.post(hosturl + '/controllers/and_history.php?ac=editselect', {
                    tableName: tableName,
                    name: name,
                    rowoftableid: rowoftableid,
                    patientid: patientid,
                    maintableName: maintableName
                }, function (data) {
                    $("#alldatadiv").html(data);
                    $("#edit_model").modal('show');
                });
            } else {
                $('#' + name + '' + rowoftableid).attr('data-val', value, true);
            }

        });
//        $('body').on('change', '.smoking', function () {
//            var value = $(this).val();
//            var id = $(this).attr('data-id');
//
//            if (value == '2') {
//                $('#smokinglevel' + id).show();
//            } else
//            {
//                $('#smokinglevel' + id).hide();
//            }
//
//        })

        $('body').on('change', '.fertile', function () {
            var value = $(this).val();
            var id = $(this).attr('data-id');
            if (value == '2') {
                $('#fertiletype' + id).show();
            } else {
                $('#fertiletype' + id).hide();
            }

        })

        $(".deleteElementSelect").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 = $(this).attr('data-selectClass');
            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).each(function () {
                                        if ($(this).val() == itemid) {
                                            $(this).select2("val", '');
                                        } else if ($(this).val() == -2) {
                                            $(this).select2("val", '');
                                        }

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

    $('body').on('change', '#patientFiles', function () {
        $('#talks-loading').show();
        var files = $("#patientFiles")[0].files;
        var isValid = 2;
        for (var i = 0; i < files.length; i++) {
//alert(files[i].name);
            var valid = checkFile(files[i].name);
            if (valid == 2) {

            } else if (valid == 1) {
                isValid = 1;
            }
        }

        if (isValid == 2) {
            var myformdata = new FormData();
            myformdata.append("type", "All");
            myformdata.append("name", 'patientFiles');
            myformdata.append("patientId", $("#ptntid").val());
            myformdata.append("imgCount", files.length);
            jQuery.each(jQuery('#patientFiles')[0].files, function (i, file) {
                myformdata.append('file-' + i, file);
            });
            $.ajax({
                url: hosturl + '/controllers/patients.php?ac=uploadmulti', // Url to which the request is send
                type: "POST", // Type of request to be send, called as method
                data: myformdata, // Data sent to server, a set of key/value pairs representing form fields and values
                contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
                cache: false, // To unable request pages to be cached
                processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
                success: function (data)  		// A function to be called if request succeeds
                {
                    if (data != -1) {
                        $('#patientFilesDiv').html('');
                        $('#patientFilesDiv').html(data);
                        $('#talks-loading').hide();
                    }
                }
            });
        }

    });

    $('body').on('click', '.delPImg', function () {
        var pId = $(this).attr('data-pId');
        var name = $(this).attr('data-name');
        var tr = $(this).parent().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/patients.php?ac=delimg', {pId: pId, name: name}, function (res) {
                            if (res == 1) {
                                tr.remove();
                            } else {
                                alert("!!!!!!!!!!!!! some thing wrong here");
                            }
                        });
                    }
                }
            }
        }).find('.modal-content').addClass('modal-sm');
    });

    function checkFile(filename) {
        filename = filename.replace(/C:\\fakepath\\/i, '');
        if (filename != "") {
            var ext = filename;
            var extindex = ext.lastIndexOf(".") + 1;
            ext = ext.slice(extindex, ext.length);
            ext = ext.toLowerCase();
            if ($.inArray(ext, ['jpg', 'jepg', 'png', 'jpeg', 'gif', 'doc', 'docx', 'pdf']) == -1) {
                alert("pictures only allowed (jpg , gif , png , jepg , jpeg , doc , docx , pdf )");
                $('#talks-loading').hide();
                return 1;
            } else {
                return 2;
            }
        } else {
            return 1;
        }
    }

    function checkImage(filename) {
        filename = filename.replace(/C:\\fakepath\\/i, '');
        if (filename != "") {
            var ext = filename;
            var extindex = ext.lastIndexOf(".") + 1;
            ext = ext.slice(extindex, ext.length);
            ext = ext.toLowerCase();
            if ($.inArray(ext, ['jpg', 'jepg', 'png', 'jpeg', 'gif']) == -1) {
                alert("pictures only allowed (jpg , gif , png , jepg , jpeg)");
                $('#talks-loading').hide();
                return 1;
            } else {
                return 2;
            }
        } else {
            return 1;
        }
    }

    $("body").on('click', '.showPatFile', function () {
        var src = $(this).attr('src');
        //   $('#source_image').attr('src', hosturl + '/../upload/sonarvedio/1/' + videoName);
        $('#source_image').attr('src', src);
        $("#showPatFileM").modal('show');
    });

    $("body").on('click', '.showOpPicFile', function () {
        var src = $(this).attr('src');
        $('#source_image').attr('src', src);
        $("#showFileM").modal('show');
    });

    $(".vidOpShow").live('click', function () {
        var videoName = $(this).attr('data-file');
        $('#source_vediourl').attr('src', hosturl + '/../upload/sonarvedio/1/' + videoName);
        $('#video_vediourl').load();
        $("#showVideo").modal('show');
        var vid = document.getElementById("video_vediourl");
        vid.play();
    });

    $("body").on('click', '.printPtCard', function () {
        var id = $(this).attr('data-id');
        $.post(hosturl + '/controllers/patients.php?ac=printcard', {
            id: id
        }, function (res) {
            console.log(res);
            $("#forPrint").html(res);
            $.print("#forPrint");
            $("#forPrint").html("");
        });
    });

    $("body").on('click', '.printPtBar', function () {
        var id = $(this).attr('data-id');
        $.post(hosturl + '/controllers/patients.php?ac=printbarcode', {
            id: id
        }, function (res) {
            console.log(res);
            $("#forPrint").html(res);
            $.print("#forPrint");
            $("#forPrint").html("");
        });
    });

    $("body").on('click', '.printPtQr', function () {
        var id = $(this).attr('data-id');
        $.post(hosturl + '/controllers/patients.php?ac=printqrcard', {
            id: id
        }, function (res) {
            console.log(res);
            $("#forPrint").html(res);
            $.print("#forPrint");
            $("#forPrint").html("");
        });
    });

    $("body").on('click', '#case_print', function () {
        var patientId = $('#patientId').val();
        var followup = $(this).attr('data-followup');
        $.post(hosturl + '/controllers/patienthistory.php?ac=printcase', {
            patientId: patientId, followup: followup
        }, function (res) {

            $("#forPrint").html(res);
            $.print("#forPrint");
            $("#forPrint").html("");
        });
    });

    $("body").on('click', '#caseSumPrint', function () {
        var patientId = $('#patientId').val();
        $.post(hosturl + '/controllers/case_summary.php?ac=printcase', {patientId: patientId}, function (res) {

            $("#forPrint").html(res);
            $.print("#forPrint");
            $("#forPrint").html("");
        });
    });

    $("body").on('click', '#sumAbortionAdd', function () {
        var patientId = $('#patientId').val();
        $.post(hosturl + '/controllers/case_summary.php?ac=sumAbortionAdd', {patientId: patientId}, function (res) {
            if (res != -1) {
                var row = '   <tr>'
                        + '<th>Gestational age :  </th> '
                        + ' <td> '
                        + '   <input type="text" placeholder="Gestational age" name="obstrduration"   '
                        + '         class="form-control updateElement"  data-colName="obstrduration"   '
                        + '         data-id="' + Number(res) + '" data-tableName="summary_obstetric_abortion"  '
                        + '         style="    display: inline-block; width: 85%"/> W'
                        + '  </td>  '
                        + '  <th>Date Of  Abortion :  </th>'
                        + '   <td> '
                        + '  <input type="text" placeholder="Date Of  Abortion" name="obsdate"   '
                        + '       class="form-control updateElement datepicker"  data-colName="obsdate"   '
                        + '       data-id="' + Number(res) + '" data-tableName="summary_obstetric_abortion"  '
                        + '         value=""/>'
                        + '    </td>  '
                        + '  </tr>';
                $("#sumAbortionContainer").append(row);
                $(".datepicker").datepicker();
            }
        });
    });

    $("body").on('click', '#opCaseSumPrint', function () {
        var patientId = $('#patientId').val();
        $.post(hosturl + '/controllers/case_summary.php?ac=printopcase', {patientId: patientId}, function (res) {

            $("#forPrint").html(res);
            $.print("#forPrint");
            $("#forPrint").html("");
        });
    });

    var customer_service = function () {

        $('body').on('change', '#visit_dept', function () {
            var visit_dept = $('#visit_dept').val();
            $.post(hosturl + '/controllers/customer_service.php?ac=usersbydept', {visit_dept_id: visit_dept}, function (res) {
                $('#dept_doctors_div').html('');
                $('#dept_doctors_div').html(res);
                $("#dept_doctors").select2();
            });
        });
        $('body').on('click', '#doctorVisitsBtn', function () {
            var date_from = $('#date_from').val();
            var date_to = $('#date_to').val();
            var dept_doctors = $('#dept_doctors').val();
            var visit_dept = $('#visit_dept').val();
            var rfc = $('#rfc_patient').val();
            var branch_id = $('#branch_id').val();

            if (branch_id > 0) {
                if (dept_doctors > 0 || visit_dept > 0 || rfc > 0) {
                    $.post(hosturl + '/controllers/customer_service.php?ac=getvisits', {branch_id: branch_id,
                        date_from: date_from, date_to: date_to, deptId: visit_dept, doctorId: dept_doctors, rfc: rfc
                    }, function (res) {
                        $('#doctor_visits_div').html('');
                        $('#doctor_visits_div').html(res);
                        //           $('.dataTable').dataTable();
                    });
                } else {
                    $('#doctor_visits_div').html('');
                }
            } else {
                $('#doctor_visits_div').html('');
                alert('اختر الفرع أولا .');
            }

        });
        $('body').on('click', '.visitDetails', function () {
            var date_from = $('#date_from').val();
            var date_to = $('#date_to').val();
            var dept_doctors = $(this).attr("data-id");
            var confirmed = $(this).attr('data-confirmed');
            var attended = $(this).attr('data-attended');
            var rfc = $(this).attr('data-rfc');
            var branch_id = $('#branch_id').val();

            if (dept_doctors > 0 && branch_id > 0) {
                $.post(hosturl + '/controllers/customer_service.php?ac=visitbydoctor', {
                    date_from: date_from, date_to: date_to, doctorId: dept_doctors
                    , confirmed: confirmed, attended: attended, rfc: rfc, branch_id: branch_id
                }, function (res) {
                    $('#drVisitsDiv').html('');
                    $('#drVisitsDiv').html(res);
                    $("#drVisitsModel").modal('show');
                });
            }

        });
        $("#patientService").select2({
            minimumInputLength: 3
        });
        $('body').on('change', '#patientService', function () {
            var id = $('#patientService').val();
            if (id > 0) {
                $.post(hosturl + '/controllers/customer_service.php?ac=patientInfo', {id: id}, function (res) {
                    console.log(res);
                    var obj = JSON.parse(res);
                    $('#patAddress').val(obj.address);
                    $('#patPhone').val(obj.phone);
                    $('#patMobile').val(obj.mobile);
                    $("#patientInfo").show();
                });
            } else {
                $('#patAddress').val('');
                $('#patPhone').val('');
                $('#patMobile').val('');
                $("#patientInfo").hide();
            }
        });
        $('body').on('click', '#doctorVisitsPrint', function () {
            var date_from = $('#date_from').val();
            var date_to = $('#date_to').val();
            var dept_doctors = $('#dept_doctors').val();
            var visit_dept = $('#visit_dept').val();
            var rfc = $('#rfc_patient').val();
            var branch_id = $('#branch_id').val();

            if (branch_id > 0) {
                $('#doctorVisitsPrint').attr('disabled', true);
                $.post(hosturl + '/controllers/customer_service.php?ac=printvisits', {branch_id: branch_id,
                    date_from: date_from, date_to: date_to, deptId: visit_dept, doctorId: dept_doctors, rfc: rfc
                }, function (res) {
                    $("#printDiv").html(res);
                    $.print("#printDiv");
                    $("#printDiv").html("");
                    $('#doctorVisitsPrint').attr('disabled', false);
                });
            } else {
                $('#doctor_visits_div').html('');
                alert('اختر الفرع أولا .');
            }
        });
        $('body').on('click', '.doctorVisitsPrint', function () {
            var date_from = $('#date_from').val();
            var date_to = $('#date_to').val();
            var dept_doctors = $(this).attr('data-doctorId');
            var confirmed = $(this).attr('data-confirmed');
            var attended = $(this).attr('data-attended');
            var rfc = $(this).attr('data-rfc');
            var branch_id = $('#branch_id').val();

            if (branch_id > 0) {
                $.post(hosturl + '/controllers/customer_service.php?ac=printvisits', {branch_id: branch_id,
                    date_from: date_from, date_to: date_to, doctorId: dept_doctors
                    , confirmed: confirmed, attended: attended, rfc: rfc
                }, function (res) {
                    $("#printDiv").html(res);
                    $.print("#printDiv");
                    $("#printDiv").html("");
                });
            } else {
                $('#doctor_visits_div').html('');
                alert('اختر الفرع أولا .');
            }
        });
        $('body').on('click', '.arrivedHos', function () {
            var id = $(this).attr('data-id');
            $.post(hosturl + '/controllers/customer_service.php?ac=arrivedHos', {id: id}, function (res) {
                if (res != -1) {
                    $('#arrivedHos' + id).html('');
                    $('#arrivedHos' + id).html(res);
                }
            });
        });
    };

    var reserve_clinic = function () {

        $('body').on('change', '#reserve_dept', function () {
            var deptId = $('#reserve_dept').val();
            if (deptId > 0) {
                $.post(hosturl + '/controllers/visits.php?ac=getDoctor', {role_id: deptId}, function (data) {
                    var obj = JSON.parse(data);
                    if (obj.doctor_show == 1) {
                        $('#reserve_doctor').html(obj.doctors);
                        $('#reserve_doctor').select2();
                        $('#reserve_action_div').show();
                    } else {
                        $('#reserve_action_div').hide();
                    }
                });
            } else {
                $('#reserve_action_div').hide();
            }
        });
        $('body').on('click', '#deptClinicsDisplay', function () {
            $.post(hosturl + '/controllers/reserve_clinic.php?ac=displayDeptClinics', function (res) {
                $('#displayClinicsDiv').html('');
                $('#displayClinicsDiv').html(res);
                $("#displayClinicsModel").modal('show');
            });
        });
        $('body').on('click', '.dayFree', function () {
            $(this).removeClass('dayFree');
            $(this).addClass('daySelected');
        });
        $('body').on('click', '.daySelected', function () {
            $(this).removeClass('daySelected');
            $(this).addClass('dayFree');
        });
        $('body').on('click', '#reserve_clinic', function () {

            $('#reserve_clinic').attr('disabled', true);
            var reserve = 1;
            var deptId = $('#reserve_dept').val();
            var doctorId = $('#reserve_doctor').val();
            var start_date = $('#start_date').val();
            var selected = Array();
            if (deptId > 0 && doctorId > 0) {
                $('#reserve_clinicError').hide();
                var selectedHour = Array();
                $('.daySelected').each(function () {

                    var hour = $(this).attr('data-hour');
                    var dayNo = $(this).attr('data-dayNo');
                    var room = $(this).attr('data-room');
                    selectedHour[0] = dayNo;
                    selectedHour[1] = hour;
                    selectedHour[2] = room;
                    selected.push(selectedHour);
                    selectedHour = [];
                });
            } else {
                reserve = 0;
                $('#reserve_clinicError').html('قم باختيار القسم والطبيب أولا ');
                $('#reserve_clinicError').show();
            }

            if (reserve == 1 && selected.length > 0) {
                $('#reserve_clinicError').hide();
                var jsonString = JSON.stringify(selected);
                $.post(hosturl + '/controllers/reserve_clinic.php?ac=reserveClinic', {
                    doctorId: doctorId
                    , jsonString: jsonString, start_date: start_date
                }, function (res) {
                    console.log(res);
                    if (Number(res) != 1) {
                        alert('خطأ  ....لم يتم الحفظ ')
                    }
                    restoreDays();
                    $('#reserve_clinic').attr('disabled', false);
                });
            } else {
                $('#reserve_clinicError').html('قم باختيار الساعات   والطبيب أولا ');
                $('#reserve_clinicError').show();
                $('#reserve_clinic').attr('disabled', false);
            }
        });
        $('body').on('click', '#new_room', function () {
            $.post(hosturl + '/controllers/reserve_clinic.php?ac=newRoom', function (res) {
                $('#roomsContainer').html('');
                $('#roomsContainer').html(res);
                $(".select2B").select2({placeholder: "Select", allowClear: true});
            });
        });
        $('body').on('click', '.endRooms', function () {
            restoreDays();
        });
        $('body').on('click', '.dayBusy', function () {
            $(this).removeClass('dayBusy');
            $(this).addClass('dayCancel');
        });
        $('body').on('click', '.dayCancel', function () {
            $(this).removeClass('dayCancel');
            $(this).addClass('dayBusy');
        });
        $('body').on('click', '#reserve_cancel', function () {

            $('#reserve_cancel').attr('disabled', true);
            $('#reserve_cancelError').hide();
            var canceled = Array();
            var canceledHour = Array();
            $('.dayCancel').each(function () {

                var hour = $(this).attr('data-hour');
                var dayNo = $(this).attr('data-dayNo');
                var room = $(this).attr('data-room');
                canceledHour[0] = dayNo;
                canceledHour[1] = hour;
                canceledHour[2] = room;
                canceled.push(canceledHour);
                canceledHour = [];
            });
            if (canceled.length > 0) {

                bootbox.dialog({
                    message: "Do you want to delete this item?",
                    title: "Delete confirmation",
                    buttons: {
                        danger: {
                            label: "Cancel",
                            className: "btn-primary",
                            callback: function () {
                                $('#reserve_cancel').attr('disabled', false);
                            }
                        },
                        main: {
                            label: "Delete",
                            className: "btn-danger",
                            callback: function () {
                                //do something else
                                $('#reserve_cancelError').hide();
                                var jsonString = JSON.stringify(canceled);
                                $.post(hosturl + '/controllers/reserve_clinic.php?ac=cancel', {jsonString: jsonString}, function (res) {
                                    console.log(res);
                                    if (Number(res) != 1) {
                                        alert('خطأ  ....لم يتم الإلغاء  ')
                                    }
                                    restoreDays();
                                    $('#reserve_cancel').attr('disabled', false);
                                });
                            }
                        }
                    }
                }).find('.modal-content').addClass('modal-sm');
            } else {
                $('#reserve_cancelError').show();
                $('#reserve_cancel').attr('disabled', false);
            }
        });
        function restoreDays() {
            $.post(hosturl + '/controllers/reserve_clinic.php?ac=getDeptClinics', function (res) {
                $('#dept_clinics_div').html('');
                $('#dept_clinics_div').html(res);
                var currenturl = window.location.href;
                var tabpatientid = $('#patientid').val();
                var send = currenturl.indexOf("#t");
                function rememberTabSelection(tabPaneSelector, useHash, tabpatientid) {
                    var key = 'selectedTabFor' + tabPaneSelector + tabpatientid;
                    if (get(key)) {
                        $(tabPaneSelector).find('a[href=' + get(key) + ']').tab('show');
                        ''
                    }

                    $(tabPaneSelector).on("click", 'a[data-toggle]', function (event) {
                        set(key, this.getAttribute('href'));
                    });
                    function get(key) {
                        return useHash ? location.hash : localStorage.getItem(key);
                    }

                    function set(key, value) {
                        if (useHash)
                            location.hash = value;
                        else
                            localStorage.setItem(key, value);
                    }
                }

                if (send.toString() == "-1") {
                    rememberTabSelection('#rowTab', !localStorage, tabpatientid);
                    rememberTabSelection('#rowTab2', !localStorage, tabpatientid);
                }

            });
        }


        $('body').on('click', '.printDay', function () {
            var dayNo = $(this).attr('data-dayNo');
            var branchId = $(this).attr('data-branchId');
            $.post(hosturl + '/controllers/reserve_clinic.php?ac=printDay', {dayNo: dayNo, branchId: branchId}, function (res) {
                $("#printDayDiv").html(res);
                $.print("#printDayDiv");
                $("#printDayDiv").html("");
            });
        });
    };

    var operation_data = function () {

        $(document).ready(function (e) {

            var opPatId = $('#opPatId').val();
            if (opPatId > 0) {
                $.post(hosturl + '/controllers/operationreport.php?ac=sheet_details', {opPatId: opPatId}, function (res) {
                    $('#sheetDiv').html('');
                    $('#sheetDiv').html(res);
                });
            }

            var labVisitId = $('#labVisitId').val();
            if (labVisitId > 0) {
                $.post(hosturl + '/controllers/operationreport.php?ac=lab_details', {labVisitId: labVisitId}, function (res) {
                    $('#labVisitDiv').html('');
                    $('#labVisitDiv').html(res);
                });
            }
        });
        // ###########
        $("#opSearchBtn").live('click', function () {

            $('#talks-loading').show();
            var value = $("#patientName").val();
            var hvalue = $("#husband").val();
            if (value > 0 || hvalue > 0) {
                if ($(this).attr('id') == "husband")
                    value = '';
                $.post(hosturl + '/controllers/' + controllName + '.php?ac=operation_search', {value: value, hvalue: hvalue}, function (res)
                {
                    $("#financialDiv").html("");
                    $("#financialDiv").append(res);
                    $('#talks-loading').hide();
                });
            } else {
                alert('اختر مريض أولا .......................');
                $('#talks-loading').hide();
            }
        });
        $("body").on('click', '.showOpRayImgs', function () {
            var id = $(this).attr('data-id');
            $.post(hosturl + '/controllers/operationreport.php?ac=getrayimg', {id: id}, function (res)
            {
                $("#scrollImgDiv").html(res);
                slideIndex = 1;
                showDivs(1);
                $('#showFileM').modal({keyboard: true});
            });
        });
        if ($('#controllName').val() == 'operationreport') {
            setInterval(function () {
                console.log(111);
                $('#card_patient_id').focus();
            }, 3000);
            $("body").on('keypress', '#card_patient_id', function (e) {
                if (e.keyCode == 63) {    // ? key
                    $('#card_patient_id').blur();
                    var deviceNo = $('#deviceNo').val();
                    var data = $('#card_patient_id').val();
                    var dataArray = data.split('?');
                    var opPatNo = dataArray[0];
                    $('#card_patient_id').blur();
                    $('#card_patient_id').val('');
                    if (opPatNo > 0) {
                        $('#talks-loading').show();
                        $('#talks-loading1').show();
                        $('#talks-loading2').show();
                        $('#talks-loading3').show();
                        $('#talks-loading4').show();
                        var x = tab1_content(opPatNo, deviceNo);
                        x = tab2_content(opPatNo);
                        x = tab3_content(opPatNo);
                        x = tab4_content(opPatNo);
                        x = tab5_content(opPatNo);
                    } else {
                        $('#tab1').html('<h3 style="text-align: center;color: red;">  Patient Not Exist .</h3>');
                        $('#tab2').html('<h3 style="text-align: center;color: red;"> Patient Not Exist .</h3>');
                        $('#sheetDiv').html('  <div class="col-md-12">'
                                + '<h3 style="text-align: center;color: red;"> Patient Not Exist.</h3>'
                                + '</div>');
                        $('#tab4').html('<h3 style="text-align: center;color: red;"> Patient Not Exist .</h3>');
                        $('#tab5').html('<h3 style="text-align: center;color: red;"> Patient Not Exist .</h3>');
                    }


                    return false; // prevent the button click from happening
                }
            });
        }

        function tab1_content(opPatNo, deviceNo) {
            $.post(hosturl + '/controllers/operationreport.php?ac=tab1_content'
                    , {opPatNo: opPatNo, deviceNo: deviceNo}, function (res) {
                if (res != -1) {
                    $('#tab1').html('');
                    $('#tab1').html(res);
                } else {
                    $('#tab1').html('<h3 style="text-align: center;color: red;"> No Operation Visits Available Today For This  Patient .</h3>');
                    $('#tab2').html('<h3 style="text-align: center;color: red;"> No Operation Visits Available Today For This  Patient .</h3>');
                    $('#sheetDiv').html('  <div class="col-md-12">'
                            + '<h3 style="text-align: center;color: red;"> No Operation Visits Available Today For This  Patient.</h3>'
                            + '</div>');
                    $('#tab4').html('<h3 style="text-align: center;color: red;"> No Operation Visits Available Today For This  Patient .</h3>');
                    $('#tab5').html('<h3 style="text-align: center;color: red;"> No Operation Visits Available Today For This  Patient .</h3>');
                }
                $('#talks-loading1').hide();
            });
        }

        function tab2_content(opPatNo) {
            $.post(hosturl + '/controllers/operationreport.php?ac=tab2_content', {opPatNo: opPatNo}, function (res) {
                if (res != -1) {
                    $('#tab2').html('');
                    $('#tab2').html(res);
                } else {
                    $('#tab1').html('<h3 style="text-align: center;color: red;"> No Operation Visits Available Today For This  Patient .</h3>');
                    $('#tab2').html('<h3 style="text-align: center;color: red;"> No Operation Visits Available Today For This  Patient .</h3>');
                    $('#sheetDiv').html('  <div class="col-md-12">'
                            + '<h3 style="text-align: center;color: red;"> No Operation Visits Available Today For This  Patient.</h3>'
                            + '</div>');
                    $('#tab4').html('<h3 style="text-align: center;color: red;"> No Operation Visits Available Today For This  Patient .</h3>');
                    $('#tab5').html('<h3 style="text-align: center;color: red;"> No Operation Visits Available Today For This  Patient .</h3>');
                }
                $('#talks-loading2').hide();
            });
        }

        function tab4_content(opPatNo) {
            $.post(hosturl + '/controllers/operationreport.php?ac=tab4_content', {opPatNo: opPatNo}, function (res) {
                $('#tab4').html('');
                $('#tab4').html(res);
                $('#talks-loading4').hide();
                $('#talks-loading').hide();
            });
        }

        function tab5_content(opPatNo) {
            $.post(hosturl + '/controllers/operationreport.php?ac=tab5_content', {opPatNo: opPatNo}, function (res) {
                $('#tab5').html('');
                $('#tab5').html(res);
                $('#talks-loading5').hide();
                $('#talks-loading').hide();
            });
        }


        function tab3_content(opPatNo) {
            if (opPatNo > 0) {
                $('#sheetDiv').html('');
                $('#sheetDiv').html('  <div class="col-md-12">'
                        + '<h3 style="text-align: center;color: green;"> Loading  Now.....</h3>'
                        + '</div>');
                $.post(hosturl + '/controllers/operationreport.php?ac=sheet_details', {opPatNo: opPatNo}, function (res) {
                    $('#sheetDiv').html('');
                    $('#sheetDiv').html(res);
                });
            } else {
                $('#sheetDiv').html('');
                $('#sheetDiv').html('  <div class="col-md-12">'
                        + '<h3 style="text-align: center;color: red;"> No Data Available Now.</h3>'
                        + '</div>');
            }
            $('#talks-loading3').hide();
        }



        $(document).keydown(function (e) {
            console.log($('#showFileM').is(':visible'));
            if ($('#showFileM').is(':visible')) {
                switch (e.which) {
                    case 37:
                        plusDivs(-1);
                        break;
                    case 39:
                        plusDivs(1);
                        break;
                }
            }
        });
        function plusDivs(n) {
            slideIndex = Number(slideIndex) + Number(n);
            showDivs(slideIndex);
//        showDivs(slideIndex += n);
        }

        function currentDiv(n) {
            showDivs(slideIndex = n);
        }

        function showDivs(n) {
            var i;
            var x = document.getElementsByClassName("mySlides");
            var notes = document.getElementsByClassName("notes");
            var dots = document.getElementsByClassName("demo");
            if (n > x.length) {
                slideIndex = 1;
            }
            if (n < 1) {
                slideIndex = x.length;
            }
            for (i = 0; i < x.length; i++) {
                x[i].style.display = "none";
                notes[i].style.display = "none";
            }
            for (i = 0; i < dots.length; i++) {
                dots[i].className = dots[i].className.replace(" w3-red", "");
            }
            x[slideIndex - 1].style.display = "block";
            notes[slideIndex - 1].style.display = "block";
            dots[slideIndex - 1].className += " w3-red";
        }


        $("body").on('click', '.plusOne', function () {
            var target = $(this).attr('data-target');
            var No = Number($('#' + target).val());
            var NoNew = 1;
            if (No > 0) {
                NoNew = No + 1;
            }

            $('#' + target).val(NoNew);
            $('#' + target).trigger('change');
        });
        $("body").on('click', '.minusOne', function () {
            var target = $(this).attr('data-target');
            var No = Number($('#' + target).val());
            var NoNew = 0;
            if (No > 0) {
                NoNew = No - 1;
            }

            $('#' + target).val(NoNew);
            $('#' + target).trigger('change');
        });
    };

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

                $('#devicesContainer').append(res);
            });
        });
        $('body').on('change', '.deviceLocation', function () {
            var elemId = $(this).attr("data-id");
            var value = $(this).val();
            if (value == 2) {
                $('#roomNoDiv' + elemId).show();
            } else {
                $('#roomNoDiv' + elemId).hide();
            }
        });
        $("#trackingSearchBtn").live('click', function () {
            $('#talks-loading').show();
            var findate = $("#findate").val();
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            $.post(hosturl + '/controllers/adddevices.php?ac=tracking_search'
                    , {date: findate, wId: wId, hId: hId}, function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
                $('#talks-loading').hide();
            });
        });
        $("#archiveSearchBtn").live('click', function () {
            $('#talks-loading').show();
            var findate = $("#findate").val();
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            var dateType = $("#dateType").val();
            $.post(hosturl + '/controllers/archive.php?ac=archive_search'
                    , {date: findate, wId: wId, hId: hId, dateType: dateType}, function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
                $('#talks-loading').hide();
            });
        });
        $("#archiveSearchExitBtn").live('click', function () {
            $('#talks-loading').show();
            $.post(hosturl + '/controllers/archive.php?ac=archive_search_exit', function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
                $('#talks-loading').hide();
            });
        });
    };

    var external_labs = function () {

        $("#externalSearchBtn").live('click', function () {
            $('#talks-loading').show();
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            var external_lab = $("#external_lab").val();
            var idD = $("#idD").val();
            var branch_id = $("#branch_id").val();

            $.post(hosturl + '/controllers/adddevices.php?ac=external_search'
                    , {findate: findate, todate: todate, wId: wId, hId: hId, external_lab: external_lab
                        , idD: idD, branch_id: branch_id}, function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
                $('#talks-loading').hide();
            });
        });

        $('body').on('click', '.receiveExternalTest', function () {
            var resId = $(this).attr('data-resId');
            var btn = $(this).attr('data-btn');
            bootbox.dialog({
                message: "هل ترغب فى إكمال  هذا الطلب  ؟ ",
                title: "   هل ترغب فى إكمال هذا الطلب ؟ ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-green"
                    },
                    main: {
                        label: "تأكيد ",
                        className: "btn-primary",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/adddevices.php?ac=receiveExternalTest', {resId: resId}, function (res) {
                                if (res != -1) {
                                    $('#' + btn).trigger('click');
                                }

                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $('body').on('click', '.deliverExternalTest', function () {
            var resId = $(this).attr('data-resId');
            var dna = $(this).attr('data-dna');
            var btn = $(this).attr('data-btn');
            var patientId = $(this).attr('data-patientId');
            $.post(hosturl + '/controllers/visits.php?ac=getrestvaluesP', {patientId: patientId}, function (data) {
                if (Number(data) != -1) {
                    alert(' ملحوظة : يوجد مبالغ مستحقة  على المريض ');
                }
                bootbox.dialog({
                    message: "هل ترغب فى تسليم هذا الطلب  ؟ ",
                    title: "   هل ترغب فى تسليم هذا الطلب ؟ ",
                    buttons: {
                        danger: {
                            label: "إلغاء ",
                            className: "btn-green"
                        },
                        main: {
                            label: "تأكيد ",
                            className: "btn-primary",
                            callback: function () {
                                //do something else
                                $.post(hosturl + '/controllers/adddevices.php?ac=deliverExternalTest', {resId: resId, dna: dna}, function (res) {
                                    if (res != -1) {
                                        $('#' + btn).trigger('click');
                                    }

                                });
                            }
                        }
                    }
                }).find('.modal-content').addClass('modal-sm');
            });
        });
        $('body').on('click', '.labExternalTest', function () {
            var resId = $(this).attr('data-resId');
            var btn = $(this).attr('data-btn');
            bootbox.dialog({
                message: "هل ترغب فى إكمال هذا الطلب  ؟ ",
                title: "   هل ترغب فى إكمال  هذا الطلب ؟ ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-green"
                    },
                    main: {
                        label: "تأكيد ",
                        className: "btn-primary",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/adddevices.php?ac=labExternalTest', {resId: resId}, function (res) {
                                if (res != -1) {
                                    $('#' + btn).trigger('click');
                                }

                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $("#toSearchBtn").live('click', function () {
            $('#talks-loading').show();
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            var external_lab = $("#external_lab").val();
            $.post(hosturl + '/controllers/adddevices.php?ac=to_search'
                    , {findate: findate, todate: todate, wId: wId, hId: hId, external_lab: external_lab}, function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
                $('#talks-loading').hide();
            });
        });
        $('body').on('click', '.printExternal', function () {
            var resId = $(this).attr('data-resId');
            $.post(hosturl + '/controllers/adddevices.php?ac=printExternal', {resId: resId}, function (res) {
                if (res != -1) {
                    $("#financialPrint").html(res);
                    $.print("#financialPrint");
                    $("#financialPrint").html("");
                }

            });
        });
        $("#labDeliverySearchBtn").live('click', function () {
            $('#talks-loading').show();
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            var dna = $(this).attr('data-dna');
            var branch_id = $("#branch_id").val();

            $.post(hosturl + '/controllers/adddevices.php?ac=lab_delivery_search'
                    , {findate: findate, todate: todate, wId: wId, hId: hId, dna: dna, branch_id: branch_id}, function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
                $('#talks-loading').hide();
            });
        });
        $("#requestSrchiveBtn").live('click', function () {
            $('#requestSrchiveBtn').attr('disabled', true);
            $('#requestError').hide();
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            var doctorId = $("#doctorId").val();
            var branch_id = $("#branch_id").val();
            if (branch_id > 0) {
                $.post(hosturl + '/controllers/adddevices.php?ac=archiveRequestAdd', {wId: wId, hId: hId, doctorId: doctorId, branch_id: branch_id}, function (res) {
                    if (res == -2) {
                        $('#requestError').show();
                        $('#requestSrchiveBtn').attr('disabled', false);
                    } else if (res == 1) {
                        $('#requestSrchiveBtn').attr('disabled', false);
                        $('#statusNoRemote').val('');
                        $('#patientName').val(null).empty().trigger("change");
                        $('#husband').val(null).empty().trigger("change");
                        $('#archiveRequwstSearchBtn').trigger('click');
                        //                $('#archiveRequestsTb').DataTable().ajax.reload();
                    }
                });
            } else {
                alert('choose branch first .');
                $('#requestSrchiveBtn').attr('disabled', false);
            }

        });
        $('body').on('click', '.readyRequest', function () {
            var id = $(this).attr('data-id');
            bootbox.dialog({
                message: "هل ترغب فى تجهيز  هذا الطلب  ؟ ",
                title: "   هل ترغب فى تجهيز هذا الطلب ؟ ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-green"
                    },
                    main: {
                        label: "تأكيد ",
                        className: "btn-primary",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/adddevices.php?ac=readyRequest', {id: id}, function (res) {
                                if (res != -1) {
                                    //   $('#archiveRequestsTb').DataTable().ajax.reload();
                                    var obj = JSON.parse(res);
                                    $('#readyTime' + id).html(obj.ready_date);
                                    $('#readyUser' + id).html(obj.ready_userName);
                                    $('#archiveRequestTr' + id).css("background-color", "#cceda5");
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $('body').on('click', '.cancelRequest', function () {
            var id = $(this).attr('data-id');
            bootbox.dialog({
                message: "هل ترغب فى إلغاء طلب   هذا الطلب  ؟ ",
                title: "   هل ترغب فى  إلغاء طلب  هذا الطلب ؟ ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-green"
                    },
                    main: {
                        label: "تأكيد ",
                        className: "btn-primary",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/adddevices.php?ac=cancelRequest', {id: id}, function (res) {
                                if (res != -1) {
                                    var obj = JSON.parse(res);
                                    var requestNote = $('#requestNote' + id).val();
                                    $('#requestNote' + id).remove();
                                    $('#requestNoteTd' + id).html(requestNote);
                                    $('#readyTime' + id).html(' تم إلغاء الطلب ');
                                    $('#readyUser' + id).html(obj.cancel_userName);
                                    $('#receiveTime' + id).html('');
                                    $('#receiveUser' + id).html('');
                                    $('#receiveNote' + id).html('');
                                    $('#returnTime' + id).html('');
                                    $('#returnUser' + id).html('');
                                    $('#archiveRequestTr' + id).css("background-color", "#ff6b3c");
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $('body').on('click', '.receiveRequest', function () {
            var id = $(this).attr('data-id');
            bootbox.dialog({
                message: "هل ترغب فى تسليم هذا الطلب  ؟ ",
                title: "   هل ترغب فى تسليم هذا الطلب ؟ ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-green"
                    },
                    main: {
                        label: "تأكيد ",
                        className: "btn-primary",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/adddevices.php?ac=receiveRequest', {id: id}, function (res) {
                                if (res != -1) {
                                    //    $('#archiveRequestsTb').DataTable().ajax.reload();
                                    var obj = JSON.parse(res);
                                    $('#receiveTime' + id).html(obj.receive_date);
                                    $('#receiveUser' + id).html(obj.receive_userName);
                                    $('#receiveNote' + id).html('<input type="text" class="form-control updateElement"  '
                                            + '   data-id="' + id + '"     data-colName="receive_note"  data-tableName="archive_request"   '
                                            + ' id="receiveNoteIn' + id + '"   value=""    style="    width: 115px;"/>');
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });

        $("#archiveRequwstSearchBtn").live('click', function () {
            $('#talks-loading').show();
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            var doctorId = $("#doctorId").val();
            var branch_id = $("#branch_id").val();

            $.post(hosturl + '/controllers/adddevices.php?ac=archive_request_search'
                    , {findate: findate, todate: todate, wId: wId, hId: hId, doctorId: doctorId, branch_id: branch_id}, function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
                $('#talks-loading').hide();
            });
        });

        $('body').on('click', '.cancelReceive', function () {
            var resId = $(this).attr('data-resId');
            var colName = $(this).attr('data-colName');
            var tableName = $(this).attr('data-tableName');
            var btn = $(this).attr('data-btn');
            bootbox.dialog({
                message: "هل ترغب فى إكمال  هذا الطلب  ؟ ",
                title: "   هل ترغب فى إكمال هذا الطلب ؟ ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-green"
                    },
                    main: {
                        label: "تأكيد ",
                        className: "btn-primary",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/adddevices.php?ac=cancelReceive', {resId: resId, colName: colName, tableName: tableName}, function (res) {
                                if (res != -1) {
                                    $('#' + btn).trigger('click');
                                }

                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $('body').on('click', '.returnRequest', function () {
            var id = $(this).attr('data-id');
            bootbox.dialog({
                message: "هل ترغب فى إستلام  هذا الطلب  ؟ ",
                title: "   هل ترغب فى إستلام  هذا الطلب ؟ ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-green"
                    },
                    main: {
                        label: "تأكيد ",
                        className: "btn-primary",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/adddevices.php?ac=returnRequest', {id: id}, function (res) {
                                if (res != -1) {
                                    //   $('#archiveRequestsTb').DataTable().ajax.reload();
                                    var obj = JSON.parse(res);
                                    $('#returnTime' + id).html(obj.return_date);
                                    $('#returnUser' + id).html(obj.return_userName);
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });

        $(".doctorPatSearchBtn").live('click', function () {
            $('#talks-loading').show();
            $('.doctorPatSearchBtn').attr('disabled', true);
            var print = $(this).attr('data-print');
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            var detection = $("#detection").val();
            var doctorId = $("#doctorId").val();
            var result = $("#result").val();
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            $.post(hosturl + '/controllers/adddevices.php?ac=dr_patients_search'
                    , {findate: findate, todate: todate, detection: JSON.stringify(detection), doctorId: doctorId
                        , result: result, print: print, wId: wId, hId: hId}, function (res) {
                if (print == 1) {
                    $('#printItDiv').html("");
                    $('#printItDiv').html(res);
                    $.print("#printItDiv");
                    $('#printItDiv').html("");
                    $('#talks-loading').hide();
                    $('.doctorPatSearchBtn').attr('disabled', false);
                } else {
                    $("#financialDiv").html("");
                    $("#financialDiv").append(res);
                    $('#talks-loading').hide();
                    $('.doctorPatSearchBtn').attr('disabled', false);
                }
            });
        });

        $("#manualOperationBtn").live('click', function () {
            $('#manualOperationBtn').attr('disabled', true);
            $('#requestError').html('');
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            var doctorId = $("#doctorId").val();
            var detection = $("#detection").val();
            var findate = $("#findate").val();
            if (doctorId > 0 && detection > 0) {
                $.post(hosturl + '/controllers/adddevices.php?ac=manualOperationAdd'
                        , {date: findate, wId: wId, hId: hId, doctorId: doctorId, detection: detection}, function (res) {
                    if (res == -2) {
                        $('#requestError').html('يجب تحديد  الطبيب والعملية أولا ');
                        $('#manualOperationBtn').attr('disabled', false);
                    } else if (res == 1) {
                        $('#manualOperationBtn').attr('disabled', false);
                        $('#statusNoRemote').val('');
                        $('#patientName').val(null).empty().trigger("change");
                        $('#husband').val(null).empty().trigger("change");
                        $('#manualOperationSearchBtn').trigger('click');
                    }
                });
            } else {
                $('#requestError').html('يجب تحديد  الطبيب والعملية أولا ');
                $('#manualOperationBtn').attr('disabled', false);
            }


        });
        $("#manualOperationSearchBtn").live('click', function () {
            $('#talks-loading').show();
            var print = $(this).attr('data-print');
            var findate = $("#findate").val();
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            var doctorId = $("#doctorId").val();
            var detection = $("#detection").val();
            $.post(hosturl + '/controllers/adddevices.php?ac=manual_operation_search'
                    , {date: findate, wId: wId, hId: hId, doctorId: doctorId, detection: detection, print: print}, function (res) {
                if (print == 1) {
                    $('#printItDiv').html("");
                    $('#printItDiv').html(res);
                    $.print("#printItDiv");
                    $('#printItDiv').html("");
                    $('#talks-loading').hide();
                } else {
                    $("#financialDiv").html("");
                    $("#financialDiv").append(res);
                    $('#talks-loading').hide();
                    $(".amrpop,input[type='text']:not(.datepicker):not(.notPop),textarea:not(.notPop)").hover(function () {
                        var pop_value = $(this).val();
                        $(this).attr({
                            "data-toggle": "popover",
                            "data-trigger": "hover",
                            "data-placement": "bottom",
                            "data-content": pop_value
                        });
                        $(this).popover("show");
                    });
                }
            });
        });
        $('body').on('click', '.arrivedOperation', function () {
            var id = $(this).attr('data-id');
            var mVisitId = $('#mVisitId').val();
            var editView = $('#editView').val();
            bootbox.dialog({
                message: "هل ترغب فى إكمال  هذا الطلب  ؟ ",
                title: "   هل ترغب فى إكمال هذا الطلب ؟ ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-green"
                    },
                    main: {
                        label: "تأكيد ",
                        className: "btn-primary",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/adddevices.php?ac=arrivedOperation'
                                    , {id: id, mVisitId: mVisitId, editView: editView}, function (res) {
                                if (res != -1) {
                                    var obj = JSON.parse(res);
                                    var content = obj.date
                                            + ' <input type="hidden"   id="arrivedDateFull' + id + '" value="' + obj.dateFull + '" > '
                                            + ' <input type="hidden"   id="arrivedUserId' + id + '" value="' + obj.userId + '" > '
                                            + ' <a class="btn blue-hoki btn-sm    arrivedOperation" data-id="' + id + '"     data-btn="manualOperationSearchBtn"   id="arrivedOperation' + id + '"   style="display: block;"   > وصول    </a> ';
                                    $('#arrived_time' + id).html(content);
                                    $('#arrivedOperation' + id).css("display", 'block');
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $('body').on('click', '.enterOperation', function () {
            var id = $(this).attr('data-id');
            var mVisitId = $('#mVisitId').val();
            var editView = $('#editView').val();
            bootbox.dialog({
                message: "هل ترغب فى إكمال  هذا الطلب  ؟ ",
                title: "   هل ترغب فى إكمال هذا الطلب ؟ ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-green"
                    },
                    main: {
                        label: "تأكيد ",
                        className: "btn-primary",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/adddevices.php?ac=enterOperation'
                                    , {id: id, mVisitId: mVisitId, editView: editView}, function (res) {
                                if (res != -1) {
                                    var obj = JSON.parse(res);
                                    var content = obj.date
                                            + ' <input type="hidden"   id="enterDateFull' + id + '" value="' + obj.dateFull + '" > '
                                            + ' <input type="hidden"   id="enterUserId' + id + '" value="' + obj.userId + '" > '
                                            + ' <a class="btn blue-hoki btn-sm    enterOperation" data-id="' + id + '"     data-btn="manualOperationSearchBtn"   id="enterOperation' + id + '"   style="display: block;"   > دخول    </a> ';
                                    $('#enter_time' + id).html(content);
                                    $('#enter_userid' + id).html(obj.userName);
                                    $('#enterOperation' + id).css("display", 'block');
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $('body').on('click', '.exitOperation', function () {
            var id = $(this).attr('data-id');
            var mVisitId = $('#mVisitId').val();
            var editView = $('#editView').val();
            bootbox.dialog({
                message: "هل ترغب فى إكمال  هذا الطلب  ؟ ",
                title: "   هل ترغب فى إكمال هذا الطلب ؟ ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-green"
                    },
                    main: {
                        label: "تأكيد ",
                        className: "btn-primary",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/adddevices.php?ac=exitOperation'
                                    , {id: id, mVisitId: mVisitId, editView: editView}, function (res) {
                                if (res != -1) {
                                    var obj = JSON.parse(res);
                                    $('#exit_time' + id).html('');
                                    var content = obj.date
                                            + ' <input type="hidden"   id="exitDateFull' + id + '" value="' + obj.dateFull + '" > '
                                            + ' <input type="hidden"   id="exitUserId' + id + '" value="' + obj.userId + '" >  '
                                            + ' <a class="btn blue-hoki btn-sm    exitOperation" data-id="' + id + '"     data-btn="manualOperationSearchBtn"   id="exitOperation' + id + '"   style="display: block;"   > خروج    </a> ';
                                    $('#exit_time' + id).html(content);
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $('body').on('click', '.editManualOp', function () {
            var id = $(this).attr("data-id");
            var row = $(this).parent().parent();
            $('#manualOperationSearchBtn').hide();
            $('#manualOperationBtn').hide();
            $('.editManualOp').hide();
            $('.delManualOp').hide();
            row.css('background-color', '#f36a5a');
            $.post(hosturl + '/controllers/adddevices.php?ac=editManualOp', {id: id}, function (res) {
                if (Number(res) == -1) {
                    $('#mVisitId').val(0);
                    $('#editView').val(0);
                    $('#manualOperationSearchBtn').show();
                    $('#manualOperationBtn').show();
                    $('#manualOperationSearchBtn').trigger('click');
                } else {
                    var obj = JSON.parse(res);
                    $('#findate').val(obj.visitdate);
                    if (obj.patientId > 0) {
                        $('#statusNoRemote ').val(obj.statusno).trigger('keyup');
                    }
                    if (obj.detectionId > 0) {
                        $('#detection').select2("val", obj.detectionId);
                    }
                    if (obj.doctorId > 0) {
                        $('#doctorId').select2("val", obj.doctorId);
                    }
                    $('#saveEditManualOp').attr("data-visitId", id);
                    $('#mVisitId').val(id);
                    $('#editView').val(1);
                    $('#saveEditManualOp').show();
                    $('#cancelEditManualOp').show();
                    $('#status_no' + id).attr("disabled", true);
                    $('#patient_name' + id).attr("disabled", true);
                    $('#case_cost' + id).attr("disabled", true);
                    $('#case_time' + id).attr("disabled", true);
                    $('#case_note' + id).attr("disabled", true);
                    $('#case_call' + id).attr("disabled", true);
                    $('#arrivedOperation' + id).css("display", 'block');
                    $('#enterOperation' + id).css("display", 'block');
                    $('#exitOperation' + id).css("display", 'block');
                    $('#kashfExitOperation' + id).css("display", 'block');
                }
            });
        });
        $('body').on('click', '#cancelEditManualOp', function () {
            $('#mVisitId').val(0);
            $('#editView').val(0);
            $('#manualOperationSearchBtn').show();
            $('#manualOperationBtn').show();
            $('#saveEditManualOp').attr("data-visitId", 0);
            $('#saveEditManualOp').hide();
            $('#cancelEditManualOp').hide();
            $('#statusNoRemote ').val('').trigger('keyup');
            $('#detection').select2("val", '');
            $('#doctorId').select2("val", '');
            $('#manualOperationSearchBtn').trigger('click');
        });
        $('body').on('click', '#saveEditManualOp', function () {

            $('#saveEditManualOp').attr('disabled', true);
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            var doctorId = $("#doctorId").val();
            var detection = $("#detection").val();
            var findate = $("#findate").val();
            var id = $("#mVisitId").val();
            $('#requestError').html('');
            var arrivedDateFull = $("#arrivedDateFull" + id).val();
            var arrivedUserId = $("#arrivedUserId" + id).val();
            var enterDateFull = $("#enterDateFull" + id).val();
            var enterUserId = $("#enterUserId" + id).val();
            var exitDateFull = $("#exitDateFull" + id).val();
            var exitUserId = $("#exitUserId" + id).val();
            var kashfExitDateFull = $("#kashfExitDateFull" + id).val();
            var kashfExitUserId = $("#kashfExitUserId" + id).val();
            if (doctorId > 0 && detection > 0 && id > 0) {
                $.post(hosturl + '/controllers/adddevices.php?ac=updateManualOp'
                        , {id: id, date: findate, wId: wId, hId: hId, doctorId: doctorId, detection: detection
                            , arrivedDateFull: arrivedDateFull, arrivedUserId: arrivedUserId
                            , enterDateFull: enterDateFull, enterUserId: enterUserId
                            , exitDateFull: exitDateFull, exitUserId: exitUserId
                            , kashfExitDateFull: kashfExitDateFull, kashfExitUserId: kashfExitUserId
                        }, function (res) {
                    if (res == -2) {
                        $('#requestError').html('يجب تحديد  الطبيب والعملية أولا ');
                        $('#saveEditManualOp').attr('disabled', false);
                    } else if (res == 1) {
                        $('#mVisitId').val(0);
                        $('#editView').val(0);
                        $('#manualOperationSearchBtn').show();
                        $('#manualOperationBtn').show();
                        $('#saveEditManualOp').attr("data-visitId", 0);
                        $('#saveEditManualOp').hide();
                        $('#cancelEditManualOp').hide();
                        $('#statusNoRemote ').val('').trigger('keyup');
                        $('#detection').select2("val", '');
                        $('#doctorId').select2("val", '');
                        $('#saveEditManualOp').attr('disabled', false);
                        $('#manualOperationSearchBtn').trigger('click');
                    }
                });
            } else {
                $('#requestError').html('يجب تحديد  الطبيب والعملية أولا ');
                $('#saveEditManualOp').attr('disabled', false);
            }
        });
        $('body').on('click', '.kashfExitOperation', function () {
            var id = $(this).attr('data-id');
            var mVisitId = $('#mVisitId').val();
            var editView = $('#editView').val();
            bootbox.dialog({
                message: "هل ترغب فى إكمال  هذا الطلب  ؟ ",
                title: "   هل ترغب فى إكمال هذا الطلب ؟ ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-green"
                    },
                    main: {
                        label: "تأكيد ",
                        className: "btn-primary",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/adddevices.php?ac=kashfExitOperation'
                                    , {id: id, mVisitId: mVisitId, editView: editView}, function (res) {
                                if (res != -1) {
                                    var obj = JSON.parse(res);
                                    $('#kashf_exit_time' + id).html('');
                                    var content = obj.date
                                            + ' <input type="hidden"   id="kashfExitDateFull' + id + '" value="' + obj.dateFull + '" > '
                                            + ' <input type="hidden"   id="kashfExitUserId' + id + '" value="' + obj.userId + '" >  '
                                            + ' <a class="btn blue-hoki btn-sm    kashfExitOperation" data-id="' + id + '"     data-btn="manualOperationSearchBtn"   id="kashfExitOperation' + id + '"   style="display: block;"   > خروج    </a> ';
                                    $('#kashf_exit_time' + id).html(content);
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });

        $("#rfcReportSearchBtn").live('click', function () {
            $('#talks-loading').show();
            var print = $(this).attr('data-print');
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            var doctorId = $("#doctorId").val();
            var branch_id = $("#branch_id").val();
            $.post(hosturl + '/controllers/adddevices.php?ac=rfc_report_search'
                    , {findate: findate, todate: todate, doctorId: doctorId, print: print, branch_id: branch_id}, function (res) {
                if (print == 1) {
                    $('#printItDiv').html("");
                    $('#printItDiv').html(res);
                    $.print("#printItDiv");
                    $('#printItDiv').html("");
                    $('#talks-loading').hide();
                } else {
                    $("#financialDiv").html("");
                    $("#financialDiv").append(res);
                    $('#talks-loading').hide();
                }
            });
        });

        $('body').on('click', '.rfcVisitDetails', function () {
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            var patientId = $(this).attr("data-id");
            var patientName = $(this).attr("data-patientName");
            var branch_id = $(this).attr("data-branchId");

            if (patientId > 0) {
                $.post(hosturl + '/controllers/adddevices.php?ac=rfcByPatient', {
                    findate: findate, todate: todate, patientId: patientId, patientName: patientName, branch_id: branch_id
                }, function (res) {
                    if (res != -1) {
                        $('#patVisitsDiv').html('');
                        $('#patVisitsDiv').html(res);
                        $("#patVisitsModel").modal('show');
                    }
                });
            }
        });

        $('body').on('click', '#newPatients', function () {
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            var branch_id = $(this).attr("data-branchId");

            $.post(hosturl + '/controllers/adddevices.php?ac=newPatients', {findate: findate, todate: todate, branch_id: branch_id}, function (res) {
                if (res != -1) {
                    $('#patVisitsDiv').html('');
                    $('#patVisitsDiv').html(res);
                    $("#newPatientsModel").modal('show');
                }
            });
        });

        $('body').on('click', '#firstVisitBtn', function () {
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            var branch_id = $("#branch_id").val();
            $.post(hosturl + '/controllers/adddevices.php?ac=firstVisit', {findate: findate, todate: todate, branch_id: branch_id}, function (res) {
                if (res != -1) {
                    $('#firstVisitsDiv').html('');
                    $('#firstVisitsDiv').html(res);
                    $("#firstVisitsModel").modal('show');
                }
            });
        });

        $("#governorateR").live('change', function () {
            var governorate = $('#governorateR').val();
            $.post(hosturl + '/controllers/patients.php?ac=getGovernorateCenters'
                    , {governorate: governorate}, function (data) {
                $("#governorateCentersR").select2("val", "");
                $('#governorateCentersR').html(data);
                $("#governorateCentersR option[value='0']").remove();
            });
        });
        $("#addressSearchBtn").live('click', function () {
            $('#addressSearchBtn').attr('disabled', true);
            $('#talks-loading').show();
            var print = $(this).attr('data-print');
            var governorate = $("#governorateR").val();
            var center = $("#governorateCentersR").val();
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            $.post(hosturl + '/controllers/adddevices.php?ac=address_report_search'
                    , {governorate: governorate, center: center, print: print, findate: findate, todate: todate}, function (res) {
                if (print == 1) {
                    $('#printItDiv').html("");
                    $('#printItDiv').html(res);
                    $.print("#printItDiv");
                    $('#printItDiv').html("");
                    $('#talks-loading').hide();
                    $('#addressSearchBtn').attr('disabled', false);
                } else {
                    $("#financialDiv").html("");
                    $("#financialDiv").append(res);
                    $('#talks-loading').hide();
                    $('#addressSearchBtn').attr('disabled', false);
                }
            });
        });
        $(".addressDetails").live('click', function () {
            $('.addressDetails').attr('disabled', true);
            $('#talks-loading').show();
            var center = $(this).attr('data-centerId');
            var govId = $(this).attr('data-govId');
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            $.post(hosturl + '/controllers/adddevices.php?ac=addressSearchDetail'
                    , {center: center, govId: govId, findate: findate, todate: todate}, function (res) {
                //   console.log(res);
                $('#talks-loading').hide();
                $('.addressDetails').attr('disabled', false);
                $("#patDetailsDiv").html("");
                $('#patDetailsDiv').html(res);
                $('#patDetailsModal').modal('show');
            });
        });
        $("#nationalitySearchBtn").live('click', function () {
            $('#nationalitySearchBtn').attr('disabled', true);
            $('#talks-loading').show();
            var print = $(this).attr('data-print');
            var nationality = $("#nationality").val();
            var hNationality = $("#hNationality").val();
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            $.post(hosturl + '/controllers/adddevices.php?ac=nationality_report_search'
                    , {nationality: nationality, hNationality: hNationality, print: print, findate: findate, todate: todate}, function (res) {
                if (print == 1) {
                    $('#printItDiv').html("");
                    $('#printItDiv').html(res);
                    $.print("#printItDiv");
                    $('#printItDiv').html("");
                    $('#talks-loading').hide();
                    $('#nationalitySearchBtn').attr('disabled', false);
                } else {
                    $("#financialDiv").html("");
                    $("#financialDiv").append(res);
                    $('#talks-loading').hide();
                    $('#nationalitySearchBtn').attr('disabled', false);
                }
            });
        });
        $(".nationalityDetails").live('click', function () {
            $('.nationalityDetails').attr('disabled', true);
            $('#talks-loading').show();
            var nationality = $(this).attr('data-nationalityId');
            var hNationality = $(this).attr('data-h_nationalityId');
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            $.post(hosturl + '/controllers/adddevices.php?ac=nationalitySearchDetail'
                    , {nationalityId: nationality, h_nationalityId: hNationality, findate: findate, todate: todate}, function (res) {
                console.log(res);
                $('#talks-loading').hide();
                $('.nationalityDetails').attr('disabled', false);
                $("#patDetailsDiv").html("");
                $('#patDetailsDiv').html(res);
                $('#patDetailsModal').modal('show');
            });
        });
        $(".ivfReportSearchBtn").live('click', function () {
            $('#talks-loading').show();
            var print = $(this).attr('data-print');
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            var searchFn = $("#searchFn").val();
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            $.post(hosturl + '/controllers/ivf_reports.php?ac=ivf_report_search'
                    , {findate: findate, todate: todate, searchFn: searchFn, print: print, wId: wId, hId: hId}
            , function (res) {
                if (print == 1) {
                    $('#printItDiv').html("");
                    $('#printItDiv').html(res);
                    $.print("#printItDiv");
                    $('#printItDiv').html("");
                    $('#talks-loading').hide();
                } else {
                    $("#financialDiv").html("");
                    $("#financialDiv").append(res);
                    $('#talks-loading').hide();
                }
            });
        });
        $("#excelSearchBtn").live('click', function () {
            $('#excelSearchBtn').attr('disabled', true);
            $('#talks-loading').show();
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            var url = hosturl + '/controllers/patients.php?ac=caseSearch&findate=' + findate + '&todate=' + todate;
            $('#talks-loading').hide();
            $('#excelSearchBtn').attr('disabled', false);
            window.open(url, '_blank');
        });
        $(".casesDetails").live('click', function () {
            $('.casesDetails').attr('disabled', true);
            var type = $(this).attr('data-type');
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            $.post(hosturl + '/controllers/ivf_reports.php?ac=casesDetails'
                    , {findate: findate, todate: todate, type: type, wId: wId, hId: hId}
            , function (res) {
                $('.casesDetails').attr('disabled', false);
                $('#casesContainer').html('');
                $('#casesContainer').html(res);
                $('#casesModal').modal('show');
            });
        });

        $("#presSearchBtn").live('click', function () {
            $('#talks-loading').show();
            $('#presSearchBtn').attr('disabled', true);
            var findate = $("#findate").val();
            var todate = $("#tofindate").val();
            var doctorId = $("#doctorId").val();
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            $.post(hosturl + '/controllers/pharmacy.php?ac=presSearch'
                    , {findate: findate, todate: todate, doctorId: doctorId, wId: wId, hId: hId}, function (res) {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
                $('#talks-loading').hide();
                $('#presSearchBtn').attr('disabled', false);

            });
        });


        $('body').on('click', '.presStatus', function () {
            var id = $(this).attr('data-id');
            var colName = $(this).attr('data-colName');
            $.post(hosturl + '/controllers/pharmacy.php?ac=updatePre', {id: id, colName: colName}, function (res) {
                if (Number(res) == 1) {
                    $('#' + colName + '_' + id).html('<i class="fa fa-check "   style="color: #119866;font-size: 20px;margin-top: 5%;"></i> ');
                }
            });
        });
    };

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

    var patientICSI = function () {
        $('body').on('click', '#addICSI', function () {

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

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

            var patientId = $('#patientId').val();
            var type = $(this).attr('data-type');
            var itr = Number($('#' + type + 'Itr').val())
            var newItr = itr + 1;
            $('#' + type + 'Itr').val(newItr)


            $.post(hosturl + '/controllers/gyna.php?ac=addIcsiRow', {itr: newItr, patientId: patientId, type: type}, function (data) {
                $('#' + type + 'Container').append(data);
            });
        });

        $("#icsiSearchBtn").live('click', function () {
            $('#icsiSearchBtn').attr('disabled', true);
            $('#talks-loading').show();

            var fdate = $("#findate").val();
            var todate = $("#tofindate").val();
            var wId = $("#patientName").val();
            var hId = $("#husband").val();
            var type = $("#type").val();

            $.post(hosturl + '/controllers/gyna.php?ac=icsiSearch'
                    , {wId: wId, hId: hId, fdate: fdate, todate: todate, type: type}, function (res) {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
                $('#icsiSearchBtn').attr('disabled', false);
                $('#talks-loading').hide();
            });

        });
    };

    $("body").on('click', '#syncStructure', function () {
        var oldDbName = $('#oldDbName').val();
        var newDbName = $('#newDbName').val();
        $('#syncStructure').attr('disabled', true);
        $('#talks-loading').show();
        $.post(hosturl + '/controllers/syncstructure.php?ac=sync', {
            newDbName: newDbName, oldDbName: oldDbName
        }, function (res) {
            //    $("#mergeResult").html("");
            $("#mergeResult").append(res);
            $('#syncStructure').attr('disabled', false);
            $('#talks-loading').hide();
        });
    });

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

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

                $('.updateItemH[id=' + thisId + ']').trigger("change");
            });
        });
    }

    $("body").on('click', '#addIvfRecord', function () {
        var id = $(this).attr('data-id');
        var tableName = $(this).attr('data-tableName');
        $.post(hosturl + '/controllers/ivf_reports.php?ac=addNewRow', {
            id: id, tableName: tableName
        }, function (res) {
            if (res != -1) {
                $("#ivfContent").append(res);
            }
        });
    });

    $(".ddosIvf").select2({
        // width: '240px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            var thisId = $(this).attr("id");
            return "<input class='form-control' id='newddosIvfTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
        /* add the new term */
        var newTerm = $('#newddosIvfTerm').val();
        var thisId = $(this).attr("data-id");
        $.post(hosturl + "/controllers/ivf_reports.php?ac=addnewrecord", {selectId: 'drugs'
            , new_name: newTerm, colname: "drugdos"
        }, function (data) {

            $('.ddosIvf > .deleteoptincompo').before('<option value="' + data + '" >' + newTerm + '</option>');
            $('#' + thisId + '').select2('val', data); // select the new term
            $('.ddosIvf').select2('close'); // close the dropdown
            $('.updateElement[id=' + thisId + ']').trigger("change");
        });
    });

    $(".dnameIvf").select2({
        // width: '240px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            var thisId = $(this).attr("id");
            return "<input class='form-control' id='newdnameIvfTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
        /* add the new term */
        var newTerm = $('#newdnameIvfTerm').val();
        var thisId = $(this).attr("data-id");
        $.post(hosturl + "/controllers/ivf_reports.php?ac=addnewrecord", {selectId: 'drugs'
            , new_name: newTerm, colname: "drugname"
        }, function (data) {

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

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

        $.post(hosturl + '/controllers/ivf_reports.php?ac=dateDayName', {trigDate: trigDate}, function (res) {
            if (res != -1) {
                $("#trigDateName").html(res);
            }
        });
    });

    $("body").on('click', '#addIvfDrug , .addIvfRecordDrug', function () {
        var id = $(this).attr('data-id');
        var tableName = $(this).attr('data-tableName');
        var container = $(this).attr('data-container');
        $.post(hosturl + '/controllers/ivf_reports.php?ac=addNewRow', {
            id: id, tableName: tableName
        }, function (res) {
            if (res != -1) {
                $("#" + container).append(res);
            }
        });
    });

    $('body').on('change', '.dnameIvf', function () {
        var value = $(this).val();
        var itr = $(this).attr('data-itr');
        var origin = $(this).attr('data-origin');
        var tableName = $(this).attr('data-tableName');
        var createNew = $(this).attr('data-createNew'); // 0 not yet , 1 created before
        if (createNew == 0) {
            $(this).attr('data-createNew', 1);
            if (tableName == "ivf_drugs") {
                $('#addIvfDrug').trigger('click');
            } else if (tableName == "ivf_records_drugs") {
                $("#addIvfRecordDrug" + origin).trigger('click');
            }
        }
//        if (tableName == "ivf_drugs") {
//            $.post(hosturl + '/controllers/gyna.php?ac=search', {value: value, type: "name_dos"}, function (res) {
//                $('#ddosIvf' + itr).html(res);
//                var firstDos = $('#ddosIvf' + itr + ' option:eq(1)').val();
//                $('#ddosIvf' + itr).select2("val", firstDos);
//                $('#ddosIvf' + itr).change();
//            });
//        } else if (tableName == "ivf_records_drugs") {
//            $.post(hosturl + '/controllers/gyna.php?ac=search', {value: value, type: "name_dos"}, function (res) {
//                $('#ddosRec' + itr).html(res);
//                var firstDos = $('#ddosRec' + itr + ' option:eq(1)').val();
//                $('#ddosRec' + itr).select2("val", firstDos);
//                $('#ddosRec' + itr).change();
//            });
//        }

    });

    $("body").on('click', '.printIvfReport', function () {
        var id = $(this).attr('data-id');
        $.post(hosturl + '/controllers/ivf_reports.php?ac=ivf_print', {id: id}, function (res) {
            if (res != -1) {
                $('#printIvfDiv').html("");
                $('#printIvfDiv').html(res);
                $.print("#printIvfDiv");
                $('#printIvfDiv').html("");
            }
        });
    });

    $('body').on('click', '.addInvRow', function () {
        var patientId = $("#patientId").val();
        var tableName = $(this).attr("data-tableName");
        var hus = $(this).attr("data-hus");
        var itr = $(this).attr("data-itr");
        itr++;
        $(this).attr("data-itr", itr);
        $.post(hosturl + '/controllers/case_summary.php?ac=addInvRow'
                , {patientId: patientId, tableName: tableName, hus: hus, itr: itr}, function (res) {
            if (res != -1) {
                //    $('#inv' + tableName).hide();
                if (hus == 1) {
                    $('#' + tableName + 'HusDiv').append(res);
                } else {
                    $('#' + tableName + 'Div').append(res);
                }

            }
        });
    });
//    if ($('#archiveReport').val() == 1) {
//        setInterval(function () {
//            $.post(hosturl + '/controllers/archive.php?ac=newRequests', function (res) {
//                if (res != -1) {
//                    $("#newRequestsContainer").html('');
//                    $("#newRequestsContainer").html(res);
//                }
//            });
//        }, 60000);
//    }


    var case_summary = function () {

        $(".addDiagnosisName").live('change', function () {
            var hosturl = $('#hosturl').val();
            var selectId = $(this).attr('data-select');
            var table = $(this).attr('data-tablename');
            var id = $(this).attr("data-id");
            var newitem = $(this).val();
            var select;
            $.post(hosturl + '/controllers/case_summary.php?ac=adddiagnosis', {diagnosisName: newitem, id: id, table: table}, function (data) {

                $('.' + table + ' > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + newitem + '</option>');
                $('#' + selectId + ' option[value="' + Number(data) + '"]').attr('selected', true);
                $('select').select2();
                //$('#diagnosis' + $thisitr).select2('val', Number(data)); // select the new term
            });
        });
        $('.updateDiagnosis').live('change', function () {
            var id = $(this).attr("data-id");
            var colName = $(this).attr("data-colName");
            var tableName = $(this).attr("data-tableName");
            var controllName = $('#controllName').val();
            var patientId = $('#patientId').val();
            var dated = 0;
            var realvalues = new Array(); //storing the selected values inside an array
            var lastvalue;
            var slcttable;
            if (colName == "diagnosis") {
                $('#diagnosis :selected').each(function (i, selected) {
                    realvalues[i] = $(selected).val();
                    lastvalue = $(selected).val();
                });
                slcttable = "diagnosis";
            }
            //#####
            else if (colName == "recommend") {
                $('#recommend :selected').each(function (i, selected) {
                    realvalues[i] = $(selected).val();
                    lastvalue = $(selected).val();
                });
                slcttable = "recommend";
            }
            //#####
            else if (colName == "complaint") {
                $('#complaint :selected').each(function (i, selected) {
                    realvalues[i] = $(selected).val();
                    lastvalue = $(selected).val();
                });
                slcttable = "complaintant";
            }
            //#####
            else if (colName == "blood_transfusion") {
                $('#blood_transfusion :selected').each(function (i, selected) {
                    realvalues[i] = $(selected).val();
                    lastvalue = $(selected).val();
                });
                slcttable = "blood_transfusion";
            }
            //#####
            else if (colName == "drug_sensitivity") {
                $('#drug_sensitivity :selected').each(function (i, selected) {
                    realvalues[i] = $(selected).val();
                    lastvalue = $(selected).val();
                });
                slcttable = "drug_sensitivity";
            }
            //#####
            else if (colName == "complaint_analysis") {
                $('#complaint_analysis :selected').each(function (i, selected) {
                    realvalues[i] = $(selected).val();
                    lastvalue = $(selected).val();
                });
                slcttable = "complaint_analysis";
            }
            //#####
            else if (colName == "symptoms") {
                $('#symptoms :selected').each(function (i, selected) {
                    realvalues[i] = $(selected).val();
                    lastvalue = $(selected).val();
                });
                slcttable = "symptoms";
            }
            //#####
            else if (colName == "pre_history") {
                $('#pre_history :selected').each(function (i, selected) {
                    realvalues[i] = $(selected).val();
                    lastvalue = $(selected).val();
                });
                slcttable = "pre_history";
            }

            if (lastvalue == -2)
            {
                var selectId = $(this).attr('id');
                $("#" + selectId + " option[value='-2']").prop("selected", false);
                $("#" + selectId + "").select2();
                $.post(hosturl + '/controllers/ovumpickupembryotrans.php?ac=alldiagnosis', {colName: colName}, function (data)
                {
                    $("#alldatadiv").html(data);
                    $("#newitem_name").val("");
                    $("#newitem_id").val("");
                    $("#slctTbl").val(slcttable);
                    $("#edit_model").modal('show');
                    $("#edtSlct").attr("data-tableName", slcttable);
                    realvalues.pop();
                });
            }

            if ($.inArray("-1", realvalues) != -1)
            {
                var selectId = $(this).attr('id');
                $("#" + selectId + " option[value='-1']").prop("selected", false);
                $("#" + selectId + "").select2();
                $("#add_model").modal('show');
                realvalues.pop();
                $("#diagnosisName").val('');
                $("#diagnosisName").attr("data-select", selectId);
                $("#diagnosisName").attr("data-tablename", slcttable);
                $("#diagnosisName").attr("data-id", id);
            }


            if (lastvalue != '-1' && lastvalue != '-2' && $.inArray("-1", realvalues) == -1)
            {
                $.ajax({
                    url: hosturl + '/controllers/' + controllName + '.php?ac=update',
                    data: {
                        value: JSON.stringify(realvalues),
                        id: id,
                        tableName: tableName,
                        colName: colName,
                        patientId: patientId,
                        dated: dated
                    },
                    type: 'POST',
                    success: function (data) {

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

                $('.ftndsSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + ftndsSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.ftndsSelect').select2('close'); // close the dropdown
            });
        });
        $(".pretermSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newpretermSelectTerm' value='" + term + "'><a href='#' id='addNewpretermSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewpretermSelect', function () {
            /* add the new term */
            var pretermSelect = $('#newpretermSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: pretermSelect, table: 'preterm'}, function (data) {

                $('.pretermSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + pretermSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.pretermSelect').select2('close'); // close the dropdown
            });
        });
        $(".still_birthSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newstill_birthSelectTerm' value='" + term + "'><a href='#' id='addNewstill_birthSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewstill_birthSelect', function () {
            /* add the new term */
            var still_birthSelect = $('#newstill_birthSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: still_birthSelect, table: 'still_birth'}, function (data) {

                $('.still_birthSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + still_birthSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.still_birthSelect').select2('close'); // close the dropdown
            });
        });
        $(".difficultsSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newdifficultsSelectTerm' value='" + term + "'><a href='#' id='addNewdifficultsSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewdifficultsSelect', function () {
            /* add the new term */
            var difficultsSelect = $('#newdifficultsSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: difficultsSelect, table: 'difficults'}, function (data) {

                $('.difficultsSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + difficultsSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.difficultsSelect').select2('close'); // close the dropdown
            });
        });
        $(".csSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newcsSelectTerm' value='" + term + "'><a href='#' id='addNewcsSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewcsSelect', function () {
            /* add the new term */
            var csSelect = $('#newcsSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: csSelect, table: 'cs'}, function (data) {

                $('.csSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + csSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.csSelect').select2('close'); // close the dropdown
            });
        });
        $(".appearanceSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newappearanceSelectTerm' value='" + term + "'><a href='#' id='addNewappearanceSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewappearanceSelect', function () {
            /* add the new term */
            var appearanceSelect = $('#newappearanceSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: appearanceSelect, table: 'appearance'}, function (data) {

                $('.appearanceSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + appearanceSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.appearanceSelect').select2('close'); // close the dropdown
            });
        });
        $(".gaintSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newgaintSelectTerm' value='" + term + "'><a href='#' id='addNewgaintSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewgaintSelect', function () {
            /* add the new term */
            var gaintSelect = $('#newgaintSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: gaintSelect, table: 'gaint'}, function (data) {

                $('.gaintSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + gaintSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.gaintSelect').select2('close'); // close the dropdown
            });
        });
        $(".headSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newheadSelectTerm' value='" + term + "'><a href='#' id='addNewheadSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewheadSelect', function () {
            /* add the new term */
            var headSelect = $('#newheadSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: headSelect, table: 'head'}, function (data) {

                $('.headSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + headSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.headSelect').select2('close'); // close the dropdown
            });
        });
        $(".neckSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newneckSelectTerm' value='" + term + "'><a href='#' id='addNewneckSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewneckSelect', function () {
            /* add the new term */
            var neckSelect = $('#newneckSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: neckSelect, table: 'neck'}, function (data) {

                $('.neckSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + neckSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.neckSelect').select2('close'); // close the dropdown
            });
        });
        $(".breastSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newbreastSelectTerm' value='" + term + "'><a href='#' id='addNewbreastSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewbreastSelect', function () {
            /* add the new term */
            var breastSelect = $('#newbreastSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: breastSelect, table: 'breast'}, function (data) {

                $('.breastSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + breastSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.breastSelect').select2('close'); // close the dropdown
            });
        });
        $(".chestSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newchestSelectTerm' value='" + term + "'><a href='#' id='addNewchestSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewchestSelect', function () {
            /* add the new term */
            var chestSelect = $('#newchestSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: chestSelect, table: 'chest'}, function (data) {

                $('.chestSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + chestSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.chestSelect').select2('close'); // close the dropdown
            });
        });
        $(".limbsSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newlimbsSelectTerm' value='" + term + "'><a href='#' id='addNewlimbsSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewlimbsSelect', function () {
            /* add the new term */
            var limbsSelect = $('#newlimbsSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: limbsSelect, table: 'limbs'}, function (data) {

                $('.limbsSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + limbsSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.limbsSelect').select2('close'); // close the dropdown
            });
        });
        $(".backSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newbackSelectTerm' value='" + term + "'><a href='#' id='addNewbackSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewbackSelect', function () {
            /* add the new term */
            var backSelect = $('#newbackSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: backSelect, table: 'back'}, function (data) {

                $('.backSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + backSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.backSelect').select2('close'); // close the dropdown
            });
        });
        $(".contourSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newcontourSelectTerm' value='" + term + "'><a href='#' id='addNewcontourSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewcontourSelect', function () {
            /* add the new term */
            var contourSelect = $('#newcontourSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: contourSelect, table: 'contour'}, function (data) {

                $('.contourSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + contourSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.contourSelect').select2('close'); // close the dropdown
            });
        });
        $(".skinSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newskinSelectTerm' value='" + term + "'><a href='#' id='addNewskinSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewskinSelect', function () {
            /* add the new term */
            var skinSelect = $('#newskinSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: skinSelect, table: 'skin'}, function (data) {

                $('.skinSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + skinSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.skinSelect').select2('close'); // close the dropdown
            });
        });
        $(".abdominalSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newabdominalSelectTerm' value='" + term + "'><a href='#' id='addNewabdominalSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewabdominalSelect', function () {
            /* add the new term */
            var abdominalSelect = $('#newabdominalSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: abdominalSelect, table: 'abdominal'}, function (data) {

                $('.abdominalSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + abdominalSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.abdominalSelect').select2('close'); // close the dropdown
            });
        });
        $(".umbilicusSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newumbilicusSelectTerm' value='" + term + "'><a href='#' id='addNewumbilicusSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewumbilicusSelect', function () {
            /* add the new term */
            var umbilicusSelect = $('#newumbilicusSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: umbilicusSelect, table: 'umbilicus'}, function (data) {

                $('.umbilicusSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + umbilicusSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.umbilicusSelect').select2('close'); // close the dropdown
            });
        });
        $(".subcostalSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newsubcostalSelectTerm' value='" + term + "'><a href='#' id='addNewsubcostalSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewsubcostalSelect', function () {
            /* add the new term */
            var subcostalSelect = $('#newsubcostalSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: subcostalSelect, table: 'subcostal'}, function (data) {

                $('.subcostalSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + subcostalSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.subcostalSelect').select2('close'); // close the dropdown
            });
        });
        $(".divaricationSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newdivaricationSelectTerm' value='" + term + "'><a href='#' id='addNewdivaricationSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewdivaricationSelect', function () {
            /* add the new term */
            var divaricationSelect = $('#newdivaricationSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: divaricationSelect, table: 'divarication'}, function (data) {

                $('.divaricationSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + divaricationSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.divaricationSelect').select2('close'); // close the dropdown
            });
        });
        $(".hairSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newhairSelectTerm' value='" + term + "'><a href='#' id='addNewhairSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewhairSelect', function () {
            /* add the new term */
            var hairSelect = $('#newhairSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: hairSelect, table: 'hair'}, function (data) {

                $('.hairSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + hairSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.hairSelect').select2('close'); // close the dropdown
            });
        });
        $(".superficialSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newsuperficialSelectTerm' value='" + term + "'><a href='#' id='addNewsuperficialSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewsuperficialSelect', function () {
            /* add the new term */
            var superficialSelect = $('#newsuperficialSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: superficialSelect, table: 'superficial'}, function (data) {

                $('.superficialSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + superficialSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.superficialSelect').select2('close'); // close the dropdown
            });
        });
        $(".deep_palpationSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newdeep_palpationSelectTerm' value='" + term + "'><a href='#' id='addNewdeep_palpationSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewdeep_palpationSelect', function () {
            /* add the new term */
            var deep_palpationSelect = $('#newdeep_palpationSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: deep_palpationSelect, table: 'deep_palpation'}, function (data) {

                $('.deep_palpationSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + deep_palpationSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.deep_palpationSelect').select2('close'); // close the dropdown
            });
        });
        $(".fundal_levelSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newfundal_levelSelectTerm' value='" + term + "'><a href='#' id='addNewfundal_levelSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewfundal_levelSelect', function () {
            /* add the new term */
            var fundal_levelSelect = $('#newfundal_levelSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: fundal_levelSelect, table: 'fundal_level'}, function (data) {

                $('.fundal_levelSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + fundal_levelSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.fundal_levelSelect').select2('close'); // close the dropdown
            });
        });
        $(".fundal_gripSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newfundal_gripSelectTerm' value='" + term + "'><a href='#' id='addNewfundal_gripSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewfundal_gripSelect', function () {
            /* add the new term */
            var fundal_gripSelect = $('#newfundal_gripSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: fundal_gripSelect, table: 'fundal_grip'}, function (data) {

                $('.fundal_gripSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + fundal_gripSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.fundal_gripSelect').select2('close'); // close the dropdown
            });
        });
        $(".umbilical_gripSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newumbilical_gripSelectTerm' value='" + term + "'><a href='#' id='addNewumbilical_gripSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewumbilical_gripSelect', function () {
            /* add the new term */
            var umbilical_gripSelect = $('#newumbilical_gripSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: umbilical_gripSelect, table: 'umbilical_grip'}, function (data) {

                $('.umbilical_gripSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + umbilical_gripSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.umbilical_gripSelect').select2('close'); // close the dropdown
            });
        });
        $(".pelvicfSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newpelvicfSelectTerm' value='" + term + "'><a href='#' id='addNewpelvicfSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewpelvicfSelect', function () {
            /* add the new term */
            var pelvicfSelect = $('#newpelvicfSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: pelvicfSelect, table: 'pelvicf'}, function (data) {

                $('.pelvicfSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + pelvicfSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.pelvicfSelect').select2('close'); // close the dropdown
            });
        });
        $(".pelvicsSelect").select2({
            //   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newpelvicsSelectTerm' value='" + term + "'><a href='#' id='addNewpelvicsSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewpelvicsSelect', function () {
            /* add the new term */
            var pelvicsSelect = $('#newpelvicsSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: pelvicsSelect, table: 'pelvics'}, function (data) {

                $('.pelvicsSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + pelvicsSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.pelvicsSelect').select2('close'); // close the dropdown
            });
        });
        $(".obs_noSelect").select2({
//   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newobs_noSelectTerm' value='" + term + "'><a href='#' id='addNewobs_noSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewobs_noSelect', function () {
            /* add the new term */
            var obs_noSelect = $('#newobs_noSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: obs_noSelect, table: 'obs_no'}, function (data) {

                $('.obs_noSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + obs_noSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.obs_noSelect').select2('close'); // close the dropdown
            });
        });
        $(".viabilitySelect").select2({
//   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newviabilitySelectTerm' value='" + term + "'><a href='#' id='addNewviabilitySelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewviabilitySelect', function () {
            /* add the new term */
            var viabilitySelect = $('#newviabilitySelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: viabilitySelect, table: 'viability'}, function (data) {

                $('.viabilitySelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + viabilitySelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.viabilitySelect').select2('close'); // close the dropdown
            });
        });
        $(".fetal_genderSelect").select2({
//   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newfetal_genderSelectTerm' value='" + term + "'><a href='#' id='addNewfetal_genderSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewfetal_genderSelect', function () {
            /* add the new term */
            var fetal_genderSelect = $('#newfetal_genderSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: fetal_genderSelect, table: 'fetal_gender'}, function (data) {

                $('.fetal_genderSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + fetal_genderSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.fetal_genderSelect').select2('close'); // close the dropdown
            });
        });
        $(".presentationSelect").select2({
//   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newpresentationSelectTerm' value='" + term + "'><a href='#' id='addNewpresentationSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewpresentationSelect', function () {
            /* add the new term */
            var presentationSelect = $('#newpresentationSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: presentationSelect, table: 'presentation'}, function (data) {

                $('.presentationSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + presentationSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.presentationSelect').select2('close'); // close the dropdown
            });
        });
        $(".liquorSelect").select2({
//   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newliquorSelectTerm' value='" + term + "'><a href='#' id='addNewliquorSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewliquorSelect', function () {
            /* add the new term */
            var liquorSelect = $('#newliquorSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: liquorSelect, table: 'liquor'}, function (data) {

                $('.liquorSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + liquorSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.liquorSelect').select2('close'); // close the dropdown
            });
        });
        $(".placenta_siteSelect").select2({
//   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newplacenta_siteSelectTerm' value='" + term + "'><a href='#' id='addNewplacenta_siteSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewplacenta_siteSelect', function () {
            /* add the new term */
            var placenta_siteSelect = $('#newplacenta_siteSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: placenta_siteSelect, table: 'placenta_site'}, function (data) {

                $('.placenta_siteSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + placenta_siteSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.placenta_siteSelect').select2('close'); // close the dropdown
            });
        });
        $(".placenta_abnormalitesSelect").select2({
//   width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newplacenta_abnormalitesSelectTerm' value='" + term + "'><a href='#' id='addNewplacenta_abnormalitesSelect' data-id='" + thisId + "' class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewplacenta_abnormalitesSelect', function () {
            /* add the new term */
            var placenta_abnormalitesSelect = $('#newplacenta_abnormalitesSelectTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/embryoslab.php?ac=addRow", {value: placenta_abnormalitesSelect, table: 'placenta_abnormalites'}, function (data) {

                $('.placenta_abnormalitesSelect > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + placenta_abnormalitesSelect + '</option>');
                $('#' + thisId + '').select2('val', Number(data)).trigger("change"); // select the new term
                $('.placenta_abnormalitesSelect').select2('close'); // close the dropdown
            });
        });
        $(".ftndsSelect , .pretermSelect , .still_birthSelect, .difficultsSelect, .csSelect, .appearanceSelect, .gaintSelect\n\
            , .headSelect, .neckSelect, .breastSelect, .chestSelect, .limbsSelect, .backSelect, .contourSelect, .skinSelect\n\
             , .abdominalSelect, .umbilicusSelect, .subcostalSelect, .divaricationSelect, .hairSelect, .superficialSelect\n\
            , .deep_palpationSelect, .fundal_levelSelect , .fundal_gripSelect, .umbilical_gripSelect, .pelvicfSelect\n\
             , .obs_noSelect, .viabilitySelect , .fetal_genderSelect, .presentationSelect, .liquorSelect\n\
            , .pelvicsSelect, .placenta_siteSelect, .placenta_abnormalitesSelect").live('change', function () {
            // Do something wi.on('change', function () {
            var colName = "name"
            var tableName = $(this).attr("select-tableName");
            var data_selectid = $(this).attr("id");
            var thisvalue = $(this).val();
            if (thisvalue == '-2') {
                $.post(hosturl + '/controllers/embryoslab.php?ac=editModal',
                        {tableName: tableName, colName: colName, data_selectid: data_selectid}, function (data) {
                    $('#' + data_selectid + '').select2("val", "");
                    $("#newitem_name").val('');
                    $("#newitem_id").val('');
                    $("#alldatadiv").html(data);
                    $("#edit_model").modal('show');
                });
            }
        })

        $("#newitem_name").live('change', function () {
            var value = $(this).val();
            var id = $(this).attr("data-id");
            var data_selectid = $("#data_selectid").val();
            var tablename = $("#tablename").val();
            var patientid = $("#patientid").val();
            var colName = $("#colName").val();
            if (id > 0) {
                $.post(hosturl + '/controllers/embryoslab.php?ac=updateModal',
                        {tablename: tablename, colName: colName, id: id, value: value, patientid: patientid}, function (data) {
                    $("." + tablename + "Select option[value='" + id + "']").text(value);
                    $('#' + data_selectid + '').select2('val', id).trigger("change");
                });
            }
        });
        $('.deleteModalEmb').live('click', function () {
            var id = $(this).attr('data-id');
            var tablename = $("#tablename").val();
            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/embryoslab.php?ac=delRowsommedel', {id: id, tableName: tablename}, function (res) {

                                if (res == 1) {
                                    tr.parent().remove();
                                    $("." + tablename + "Select option[value='" + id + "']").remove();
                                } else
                                {
                                    alert("!!!!!!!!!!!!! some thing wrong here");
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $("#addnewRowEmb").live('click', function () {
            var tablename = $(this).attr('data-tableName');
            var selectname = tablename + "Select";
            var colName = $("#colName").val();
            $.post(hosturl + "/controllers/embryoslab.php?ac=addNewRow", {tablename: tablename, colName: colName}, function (data) {

                var dataid = Number(data);
                $('.' + selectname + ' > .deleteoptincompo').before('<option value="' + dataid + '" ></option>');
                $("#dtAddTbl").prepend('<tr>'
                        + '<td>'
                        + ' <a href="#" >'
                        + '<input type="text" id="newitem_name"  class="form-control"   data-id="' + dataid + '"  value="" name="newamount_name"/>'
                        + '</a>'
                        + '</td>'
                        + '<td>'
                        + '<a class="btn  btn-xs red  deleteModalEmb wds100"  data-tableName="' + tablename + '"  data-id="' + dataid + '" ><i class="fa fa-times" ></i></a>'
                        + '</td>'
                        + '</tr>'
                        );
            });
        });
        $(".bp_mask").inputmask("999/999", {autoUnmask: true});
        $(".addNewRow").live('click', function () {
            var tableName = $(this).attr('data-tableName');
            var colName = $(this).attr('data-colName');
            var isDate = $(this).attr('data-isDate');
            var patientId = $("#patientId").val();
            $.post(hosturl + '/controllers/case_summary.php?ac=newRecord',
                    {tableName: tableName, colName: colName, isDate: isDate, patientId: patientId}, function (res) {
                if (res != -1) {
                    $('#' + tableName + 'Container').append(res);
                }
            });
        });
    };
    var detection = function () {
        $(".price_lists").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newprice_listsTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
            /* add the new term */
            var newTerm = $('#newprice_listsTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'price_lists', new_name: newTerm
            }, function (data) {

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

                //      $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $("body").on('change', '#price_lists', function () {
            var id = $("#opdetailsid").val(); //$(this).attr("data-id");
            var colName = $(this).attr("data-colName");
            var maintableName = $(this).attr("data-maintable");
            var myvalue = $(this).val();
            var patientId = $('#patientId').val();
            var hosturl = $('#hosturl').val();
            $("#offerDetailsDiv").html("");
//##########################################################
            if (myvalue == -1) {
                $('#price_lists').select2('val', '');
                $.post(hosturl + '/controllers/visits.php?ac=editselect', {tableName: 'price_lists', notAll: 1}, function (data) {
                    $("#detectionforview").html(data);
                    $("#edit_detectionforview").modal('show');
                });
            } else if (myvalue > 0) {
                var listId = $('#price_lists').val();
                $('#orgDetects').DataTable().ajax.url(hosturl + '/controllers/detection.php?ac=orgDetects&listId=' + listId).load();
                $('#orgInvests').DataTable().ajax.url(hosturl + '/controllers/detection.php?ac=orgInvests&listId=' + listId).load();
                $('#orgRays').DataTable().ajax.url(hosturl + '/controllers/detection.php?ac=orgRays&listId=' + listId).load();
                $('#orgOffers').DataTable().ajax.url(hosturl + '/controllers/detection.php?ac=orgOffers&listId=' + listId).load();
            }
        });
        $("body").on('click', '#addDetectionControl', function () {
            $.post(hosturl + '/controllers/detection.php?ac=addDetectionControl', function (res) {
                if (res != -1) {
                    $("#detectionControlContainer").prepend(res);
                }
            });
        });

        $("body").on('click', '.discountDetails', function () {
            var id = $(this).attr('data-id');
            var cat = $(this).attr('data-cat');
            var organization = $('#organization').val();
            if (organization > 0) {
                $.post(hosturl + '/controllers/detection.php?ac=discountDetails', {id: id, cat: cat, organization: organization}, function (res) {
                    if (res != -1) {
                        $("#detailsContainer").html('');
                        $("#detailsContainer").html(res);
                        $("#detailsModal").modal('show');
                    }
                });
            } else {
                alert(' Choose Organization First . ');
            }
        });

        $(".organization").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newOrganizationTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
            /* add the new term */
            var newTerm = $('#newOrganizationTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'organizations', new_name: newTerm
            }, function (data) {

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

                //      $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });

        $("body").on('change', '#organization', function () {
            var id = $("#opdetailsid").val(); //$(this).attr("data-id");
            var colName = $(this).attr("data-colName");
            var maintableName = $(this).attr("data-maintable");
            var myvalue = $(this).val();
            var patientId = $('#patientId').val();
            var hosturl = $('#hosturl').val();
            $("#offerDetailsDiv").html("");
//##########################################################
            if (myvalue == -1) {
                $('#organization').select2('val', '');
                $.post(hosturl + '/controllers/visits.php?ac=editselect', {tableName: 'organizations', notAll: 1}, function (data) {
                    $("#detectionforview").html(data);
                    $("#edit_detectionforview").modal('show');
                });
            } else if (myvalue > 0) {
                var orgId = $('#organization').val();
                $('#orgDetects').DataTable().ajax.url(hosturl + '/controllers/detection.php?ac=orgDetects&orgId=' + orgId).load();
                $('#orgInvests').DataTable().ajax.url(hosturl + '/controllers/detection.php?ac=orgInvests&orgId=' + orgId).load();
                $('#orgRays').DataTable().ajax.url(hosturl + '/controllers/detection.php?ac=orgRays&orgId=' + orgId).load();
            }
        });
        $("body").on('click', '.offerDetailBtn', function () {
            var offerId = $(this).attr('data-offerId');
            var listId = $('#price_lists').val();
            if (listId > 0) {
                $.post(hosturl + '/controllers/detection.php?ac=orgOfferDetail', {offerId: offerId, listId: listId}, function (res) {
                    $("#offerDetailsDiv").html("");
                    $("#offerDetailsDiv").html(res);
                });
            }
        });
        $("body").on('click', '.orgSearchBtn', function () {

            $('#talks-loading').show();

            var fdate = $("#findate").val();
            var todate = $("#tofindate").val();
            var orgId = $("#orgRep").val();
            var print = $(this).attr('data-print');

            if (orgId > 0) {
                $.post(hosturl + '/controllers/detection.php?ac=orgSearch',
                        {fdate: fdate, todate: todate, orgId: orgId, print: print}, function (res) {
                    $("#financialDiv").html("");
                    $("#financialDiv").append(res);
                    $('#talks-loading').hide();
                });
            }
        });

        $('#orgDetects').dataTable({
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": hosturl + '/controllers/detection.php?ac=orgDetects&listId=' + $('#price_lists').val(), //  server side processing
            "sPaginationType": "full_numbers",
            "lengthMenu": [
                [50, 100, 150, -1],
                [50, 100, 150, "All"] // change per page values here
            ],
            // set the initial value
            "pageLength": 10,
            "language": {
                "lengthMenu": " _MENU_"
            },
            "columnDefs": [{// set default column settings
                    'orderable': true,
                    'targets': [0]
                }, {
                    "searchable": true,
                    "targets": [0]
                }],
            "order": [
                [0, "asc"]
            ] // set first column as a default sort by asc
        });

        $('#orgInvests').dataTable({
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": hosturl + '/controllers/detection.php?ac=orgInvests&listId=' + $('#price_lists').val(), //  server side processing
            "sPaginationType": "full_numbers",
            "lengthMenu": [
                [50, 100, 150, -1],
                [50, 100, 150, "All"] // change per page values here
            ],
            // set the initial value
            "pageLength": 10,
            "language": {
                "lengthMenu": " _MENU_"
            },
            "columnDefs": [{// set default column settings
                    'orderable': true,
                    'targets': [0]
                }, {
                    "searchable": true,
                    "targets": [0]
                }],
            "order": [
                [0, "asc"]
            ] // set first column as a default sort by asc
        });

        $('#orgRays').dataTable({
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": hosturl + '/controllers/detection.php?ac=orgRays&listId=' + $('#price_lists').val(), //  server side processing
            "sPaginationType": "full_numbers",
            "lengthMenu": [
                [50, 100, 150, -1],
                [50, 100, 150, "All"] // change per page values here
            ],
            // set the initial value
            "pageLength": 10,
            "language": {
                "lengthMenu": " _MENU_"
            },
            "columnDefs": [{// set default column settings
                    'orderable': true,
                    'targets': [0]
                }, {
                    "searchable": true,
                    "targets": [0]
                }],
            "order": [
                [0, "asc"]
            ] // set first column as a default sort by asc
        });
        
        
              $('#orgOffers').dataTable({
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": hosturl + '/controllers/detection.php?ac=orgOffers&listId=' + $('#price_lists').val(), //  server side processing
            "sPaginationType": "full_numbers",
            "lengthMenu": [
                [50, 100, 150, -1],
                [50, 100, 150, "All"] // change per page values here
            ],
            // set the initial value
            "pageLength": 10,
            "language": {
                "lengthMenu": " _MENU_"
            },
            "columnDefs": [{// set default column settings
                    'orderable': true,
                    'targets': [0]
                }, {
                    "searchable": true,
                    "targets": [0]
                }],
            "order": [
                [0, "asc"]
            ] // set first column as a default sort by asc
        });

        $("body").on('change', '.updateOrgDis', function () {
            var colName = $(this).attr("data-colName");
            var listId = $(this).attr("data-listId");
            var catId = $(this).attr("data-cat");
            var detectId = $(this).attr("data-detectId");
            var offerId = $(this).attr("data-offerId");
            var value = $(this).val();

            $.post(hosturl + '/controllers/detection.php?ac=updateOrgDis',
                    {colName: colName, listId: listId, catId: catId, detectId: detectId, value: value, offerId: offerId}, function (data) {
                if (data != -1) {
                    var shortCutFunction = 'success';
                    var msg = 'Contiuno your job .. good';
                    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);
            });
        });

        $(".organizations_parents").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='neworganizations_parentsTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
            /* add the new term */
            var newTerm = $('#neworganizations_parentsTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'organizations_parents', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });

        $("body").on('change', '.organizations_parents', function () {
            var id = $(this).attr("data-id");
            var value = $(this).val();
            var hosturl = $('#hosturl').val();
            var selectId = 'organizations_parents' + id;
//##########################################################
            if (value == -1) {
                $('#' + selectId).select2('val', '');
                $.post(hosturl + '/controllers/visits.php?ac=editselect', {selectId: selectId, tableName: 'organizations_parents', notAll: 1}
                , function (data) {
                    $("#detectionforview").html(data);
                    $("#edit_detectionforview").modal('show');
                });
            }
        });
        
        
          $("body").on('click', '.orgFinSearchBtn', function () {
            var btn = $(this);
            btn.attr('disabled', true);
            $('#talks-loading').show();
            var fdate = $("#findate").val();
            var todate = $("#tofindate").val();
            var orgId = $("#orgRep").val();
            var print = $(this).attr('data-print');
            if (orgId > 0) {
                $.post(hosturl + '/controllers/detection.php?ac=orgFinSearch',
                        {fdate: fdate, todate: todate, orgId: orgId, print: print}, function (res) {
                    if (print == 1) {
                        $('#printItDiv').html("");
                        $('#printItDiv').html(res);
                        $.print("#printItDiv");
                        $('#printItDiv').html("");
                        $('#talks-loading').hide();
                        btn.attr('disabled', false);
                    } else {
                        $("#financialDiv").html("");
                        $("#financialDiv").append(res);
                        $('#talks-loading').hide();
                        btn.attr('disabled', false);
                    }

                });
            }else {
                $('#talks-loading').hide();
                btn.attr('disabled', false);
            }
        });
    };

    var usAntSelects = function () {

        declareAntSelects(0);
        function declareAntSelects(type) {
            if (type != 2) {
                $(".no_soc").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisId = $(this).attr("id");
                        return "<input class='form-control' id='newAntRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
                    /* add the new term */
                    var newTerm = $('#newAntRecordTerm').val();
                    var thisId = $(this).attr("data-id");
                    $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'no_soc', new_name: newTerm
                    }, function (data) {

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

                        $('.updateElement[id=' + thisId + ']').trigger("change");
                    });
                });
                $(".no_fetal").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisId = $(this).attr("id");
                        return "<input class='form-control' id='newAntRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
                    /* add the new term */
                    var newTerm = $('#newAntRecordTerm').val();
                    var thisId = $(this).attr("data-id");
                    $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'no_fetal', new_name: newTerm
                    }, function (data) {

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

                        $('.updateElement[id=' + thisId + ']').trigger("change");
                    });
                });
                $(".fetal_pulse").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisId = $(this).attr("id");
                        return "<input class='form-control' id='newAntRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
                    /* add the new term */
                    var newTerm = $('#newAntRecordTerm').val();
                    var thisId = $(this).attr("data-id");
                    $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'fetal_pulse', new_name: newTerm
                    }, function (data) {

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

                        $('.updateElement[id=' + thisId + ']').trigger("change");
                    });
                });
            }

            if (type != 1) {
                $(".fet_no").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisId = $(this).attr("id");
                        return "<input class='form-control' id='newAntRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
                    /* add the new term */
                    var newTerm = $('#newAntRecordTerm').val();
                    var thisId = $(this).attr("data-id");
                    $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'fet_no', new_name: newTerm
                    }, function (data) {

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

                        $('.updateElement[id=' + thisId + ']').trigger("change");
                    });
                });
                $(".visibility").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisId = $(this).attr("id");
                        return "<input class='form-control' id='newAntRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
                    /* add the new term */
                    var newTerm = $('#newAntRecordTerm').val();
                    var thisId = $(this).attr("data-id");
                    $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'visibility', new_name: newTerm
                    }, function (data) {

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

                        $('.updateElement[id=' + thisId + ']').trigger("change");
                    });
                });
                $(".ant_presentation").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisId = $(this).attr("id");
                        return "<input class='form-control' id='newAntRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
                    /* add the new term */
                    var newTerm = $('#newAntRecordTerm').val();
                    var thisId = $(this).attr("data-id");
                    $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'ant_presentation', new_name: newTerm
                    }, function (data) {

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

                        $('.updateElement[id=' + thisId + ']').trigger("change");
                    });
                });
                $(".ant_liquor").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        var thisId = $(this).attr("id");
                        return "<input class='form-control' id='newAntRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewTableRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNewTableRow', function () {
                    /* add the new term */
                    var newTerm = $('#newAntRecordTerm').val();
                    var thisId = $(this).attr("data-id");
                    $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'ant_liquor', new_name: newTerm
                    }, function (data) {

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

                        $('.updateElement[id=' + thisId + ']').trigger("change");
                    });
                });
            }
        }
    };

    var patient_history = function () {

        $("body").on('change', '#complaint', function () {
            var id = $(this).attr("data-id");
            var colName = $(this).attr("data-colName");
            var tableName = $(this).attr("data-tableName");
            var controllName = $('#controllName').val();
            var patientId = $('#patientId').val();
            var dated = 0;
            var realvalues = new Array(); //storing the selected values inside an array

            $('#complaint :selected').each(function (i, selected) {
                realvalues[i] = $(selected).val();
            });
            $.ajax({
                url: hosturl + '/controllers/' + controllName + '.php?ac=update',
                data: {
                    value: JSON.stringify(realvalues),
                    id: id,
                    tableName: tableName,
                    colName: colName,
                    patientId: patientId,
                    dated: dated
                },
                type: 'POST',
                success: function (data) {
                    console.log(data);
                }
            });
        });
        $("body").on('click', '#evaluation_print', function () {
            var patientId = $('#patientId').val();
            $.post(hosturl + '/controllers/patienthistory.php?ac=evaluation_print', {patientId: patientId}, function (res) {
                $("#forPrint").html(res);
                $.print("#forPrint");
                $("#forPrint").html("");
            });
        });
        $("body").on('click', '.opFormPrint', function () {
            var id = $(this).attr("data-id");
            $.post(hosturl + '/controllers/ivf_reports.php?ac=operation_print', {id: id}, function (res) {
                $("#forPrint").html(res);
                $.print("#forPrint");
                $("#forPrint").html("");
            });
        });
        $("body").on('change', '.devices', function () {
            var value = $(this).val();
            if (value == 1) {
                $('.devicesDetails').show();
            } else {
                $('.devicesDetails').hide();
            }

        });
        $(".post_diagnoses").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newPostRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewPostRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewPostRow', function () {
            /* add the new term */
            var newTerm = $('#newPostRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'post_diagnoses', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $(".discharge").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newdischargeRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewdischargeRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewdischargeRow', function () {
            /* add the new term */
            var newTerm = $('#newdischargeRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'discharge', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $(".trans_to").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newtrans_toRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewtrans_toRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewtrans_toRow', function () {
            /* add the new term */
            var newTerm = $('#newtrans_toRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'trans_to', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $(".followup_app").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newfollowup_appRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewfollowup_appRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewfollowup_appRow', function () {
            /* add the new term */
            var newTerm = $('#newfollowup_appRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'followup_app', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $("body").on('click', '.exitPrint', function () {
            var id = $(this).attr("data-id");
            $.post(hosturl + '/controllers/ivf_reports.php?ac=exit_print', {id: id}, function (res) {
                $("#forPrint").html(res);
                $.print("#forPrint");
                $("#forPrint").html("");
            });
        });
        $("body").on('click', '#DrugTherapyAdd', function () {
            var id = $(this).attr("data-id");
            var itr = $('#DrugTherapyItr').val();
            itr++;
            $('#DrugTherapyItr').val(itr);
            $.post(hosturl + '/controllers/ivf_reports.php?ac=DrugTherapyAdd', {id: id, itr: itr}, function (res) {
                $("#DrugTherapyDiv").append(res);
            });
        });
        $("body").on('click', '.prePrint', function () {
            var id = $(this).attr("data-id");
            $.post(hosturl + '/controllers/ivf_reports.php?ac=pre_print', {id: id}, function (res) {
                $("#forPrint").html(res);
                $.print("#forPrint");
                $("#forPrint").html("");
            });
        });
        $("body").on('click', '.intraPrint', function () {
            var id = $(this).attr("data-id");
            $.post(hosturl + '/controllers/ivf_reports.php?ac=intra_print', {id: id}, function (res) {
                $("#forPrint").html(res);
                $.print("#forPrint");
                $("#forPrint").html("");
            });
        });
        $(".posture").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newpostureRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewpostureRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewpostureRow', function () {
            /* add the new term */
            var newTerm = $('#newpostureRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'posture', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $(".introduction").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newintroductionRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewintroductionRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewintroductionRow', function () {
            /* add the new term */
            var newTerm = $('#newintroductionRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'introduction', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $(".maintenance").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newmaintenanceRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewmaintenanceRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewmaintenanceRow', function () {
            /* add the new term */
            var newTerm = $('#newmaintenanceRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'maintenance', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $(".ventilation").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newventilationRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewventilationRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewventilationRow', function () {
            /* add the new term */
            var newTerm = $('#newventilationRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'ventilation', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $(".endotracheal_tube").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newendotracheal_tubeRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewendotracheal_tubeRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewendotracheal_tubeRow', function () {
            /* add the new term */
            var newTerm = $('#newendotracheal_tubeRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'endotracheal_tube', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $(".mention").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newmentionRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewmentionRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewmentionRow', function () {
            /* add the new term */
            var newTerm = $('#newmentionRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'mention', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $(".no_title").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newno_titleRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewno_titleRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewno_titleRow', function () {
            /* add the new term */
            var newTerm = $('#newno_titleRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'no_title', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $(".m_relaxants").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newm_relaxantsRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewm_relaxantsRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewm_relaxantsRow', function () {
            /* add the new term */
            var newTerm = $('#newm_relaxantsRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'm_relaxants', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $(".antidotes").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newantidotesRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewantidotesRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewantidotesRow', function () {
            /* add the new term */
            var newTerm = $('#newantidotesRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'antidotes', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $(".complications").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newcomplicationsRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewcomplicationsRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewcomplicationsRow', function () {
            /* add the new term */
            var newTerm = $('#newcomplicationsRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'complications', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
        $(".infusions").select2({
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                var thisId = $(this).attr("id");
                return "<input class='form-control' id='newinfusionsRecordTerm' value='" + term + "'>\n\
                               <a href='#' id='addNewinfusionsRow' data-id='" + thisId + "'  \n\
                                  class='btn blue custombtnstyle'>ADD</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNewinfusionsRow', function () {
            /* add the new term */
            var newTerm = $('#newinfusionsRecordTerm').val();
            var thisId = $(this).attr("data-id");
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {selectId: 'infusions', new_name: newTerm
            }, function (data) {

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

                $('.updateElement[id=' + thisId + ']').trigger("change");
            });
        });
    };

    var regions = function () {
        $("body").on('click', '#addRegionControl', function () {
            $.post(hosturl + '/controllers/regions.php?ac=addRow', {tableName: 'regions'}, function (res) {
                if (res != -1) {
                    $("#regionsContainer").prepend(res);
                }
            });
        });

        $("body").on('click', '.addSubRegion', function () {
            var regionId = $(this).attr('data-regionId');
            $.post(hosturl + '/controllers/regions.php?ac=addRow',
                    {tableName: 'sub_regions', parent: 'region_id', parentId: regionId}, function (res) {
                if (res != -1) {
                    $('#subRegionContainer_' + regionId).prepend(res);
                }
            });
        });

        $("body").on('change', '#subRegionId', function () {
            $('#fordepartment').trigger("change");
        });

        $("body").on('click', '#addVisitFollow', function () {
            var visitId = $(this).attr('data-visitId');
            $.post(hosturl + '/controllers/visits.php?ac=addFollows', {visitId: visitId}, function (res) {
                if (res != -1) {
                    $("#followsContainer").append(res);
                }
            });
        });
    };
    
    
    var invOffers = function () {

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

        $('body').on('change', '.catInv', function () {
            var id = $(this).val();
            if ($(this).is(":checked")) {
                selectInv(id);
            } else {
                unSelectInv(id);
            }
        });

        $('body').on('click', '.removeRow', function () {
            var id = $(this).attr('data-id');
            unSelectInv(id);
            $('#inv_' + id).removeAttr('checked');
            $('#inv_' + id).parent().removeClass('checked');
        });

        $('body').on('click', '.chooseInv', function () {
            $.post(hosturl + '/controllers/invoffers.php?ac=chooseinv', $('#gynaInvest').serialize(), function (res) {
                //$("#invoffers").html("");
                $("#invoffers").append(res);
                $(".positivefloat").forcepositivefloat();
                calcoffer();
                $('#addPatientInvestigation').modal('hide');
            });
        });

        $('body').on('keyup', '.calcoffer', function () {
            calcoffer();
        });

        function calcoffer() {
            var price = 0;
            var inv_itr = $('#inv_itr').val();
            for (var i = 1; i <= inv_itr; i++) {
                if ($('#price' + i).length) {
                    price = price + Number($('#price' + i).val());
                }
            }

            $('#totalPrice').val(price);
        }

        function selectInv($invId) {
            var inv_itr = $('#inv_itr').val();
            inv_itr++;
            $('#inv_itr').val(inv_itr);
            var name = $('#inv_' + $invId).attr('data-name');
            var price = $('#inv_' + $invId).attr('data-price');
            var res = ' <div class="col-md-4">'
                    + ' <table class="table table-striped table-hover table-bordered"  id="tb_' + $invId + '"  '
                    + ' style="    margin-bottom: 0;">  <tr > '
                    + ' <th class="wds70">' + name + '</th>'
                    + ' <td><input type="text" class="form-control positivefloat calcoffer" name="price' + inv_itr + '" '
                    + '   id="price' + inv_itr + '"  value="' + price + '"/>   '
                    + ' <input type="hidden"  name="invId' + inv_itr + '"   value="' + $invId + '"/></td>'
                    + '<td  class="wds8">'
                    + '<a class="btn grey-cascade btn-xs removeRow" data-id="' + $invId + '" href="#">'
                    + '  <i class="fa fa-close"></i> </a></td>'
                    + ' </tr></table></div>';
            $("#invoffers").append(res);
            $(".positivefloat").forcepositivefloat();
            calcoffer();
        }

        function unSelectInv($invId) {
            $('#tb_' + $invId).remove();
            calcoffer();
        }
    };
    
    
    
    
  var completeLab = function () {

        $("#detectionidLab").select2();

        $("body").on('change', '#detectionidLab', function () {
            var id = $("#opdetailsid").val(); //$(this).attr("data-id");
            var colName = $(this).attr("data-colName");
            var maintableName = $(this).attr("data-maintable");
            var myvalue = $(this).val();
            var patientId = $('#patientId').val();
            var hosturl = $('#hosturl').val();

            if (myvalue == -1) {
                $("#doctorName").html('');
                $("#detectionidLab").val('');
                $("#labDetectionPrice").val(0);
                visitInvestsPrice();
                $('#detectionadd').html();
                $('#detectionadd').modal('show');
            } else if (myvalue == -2) {
                $("#detectionidLab").val('');
                $("#detectionidLab").select2();
                $("#labDetectionPrice").val(0);
                visitInvestsPrice();
                $.post(hosturl + '/controllers/visits.php?ac=editselect', {tableName: maintableName
                    , colName: colName, patientid: patientId, mainId: id}, function (data) {

                    $("#detectionforview").html(data);
                    $("#edit_detectionforview").modal('show');
                });
            } else {
                $.post(hosturl + '/controllers/visits.php?ac=getdtprice', {dtID: myvalue}, function (data) {
                    var obj = JSON.parse(data);
                    $("#labDetectionPrice").val(obj.price);
                    visitInvestsPrice();
                });
            }

        });

    };
    
     var labDevice = function () {
        $('body').on('click', '#addDeviceInv', function () {
            $("#addPatientInvestigation").modal('show');
        });
        
                $('body').on('change', '.checkDeviceInvGroup', function () {
            var groupClass = $(this).attr('data-gClass');
            $('.' + groupClass).each(function () {
                if ($(this).is(":checked")) {
                    $(this).removeAttr('checked');
                    $(this).parent().removeClass('checked');
                } else {
                    $(this).attr('checked', true);
                    $(this).parent().addClass('checked');
                }
            });
        });
        
        
           $('body').on('click', '.chooseDeviceInv', function () {
            $.post(hosturl + '/controllers/labdevices.php?ac=saveDeviceInvests', $('#gynaInvest').serialize(), function (res) {
                  $("#investigationsContainer").html("");
                $("#investigationsContainer").html(res);
                $(".positivefloat").forcepositivefloat();
                $('#addPatientInvestigation').modal('hide');
            });
        });
    };
    var approvals = function () {
    
        $('body').on('click', '#approvalSearchBtn', function () {
            $('#talks-loading').show();
            var findate = $("#findate").val();
            $.post(hosturl + '/controllers/approvals.php?ac=approvalSearch'
                    , {date: findate}, function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
                $('#talks-loading').hide();
            });
        });
        $('body').on('click', '.approveDept', function () {
            var visitId = $(this).attr('data-id');
            bootbox.dialog({
                message: "هل أنت متأكد من الموافقة  ؟",
                title: "تأكيد الموافقة  ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-danger"
                    },
                    main: {
                        label: "نعم ",
                        className: "btn-primary",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/approvals.php?ac=approveDept', {
                                visitId: visitId}, function (res) {
                                if (Number(res) != -1) {
                                    $('#approveDeptTd' + visitId).html('');
                                    $('#approveDeptTd' + visitId).html(res);
                                } else {
                                    alert(' حدث خطأ . حاول مرة أخرى   ');
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $('body').on('click', '.approveLimit', function () {
            var visitId = $(this).attr('data-id');
            bootbox.dialog({
                message: "هل أنت متأكد من الموافقة  ؟",
                title: "تأكيد الموافقة  ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-danger"
                    },
                    main: {
                        label: "نعم ",
                        className: "btn-primary",
                        callback: function () {
                            //do something else
                            $.post(hosturl + '/controllers/approvals.php?ac=approveLimit', {
                                visitId: visitId}, function (res) {
                                if (Number(res) != -1) {
                                    $('#approveLimitTd' + visitId).html('');
                                    $('#approveLimitTd' + visitId).html(res);
                                } else {
                                    alert(' حدث خطأ . حاول مرة أخرى   ');
                                }
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        //############################################

        $("body").on('click', '.showExFile', function () {
            var itr = $(this).attr('data-itr');
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=getpatientimg', {patientId: patientId}, function (res)
            {
                $("#scrollImgDiv").html(res);
                slideIndex = itr;
                showDivs(itr);
                //  $("#showFileM").modal('show');
                $('#showFileM').modal({keyboard: true});
            });
        });
        $('body').on('click', '#searchExternalBtn', function () {
            $('#talks-loading').show();
            var dateFrom = $("#dateFrom").val();
            var dateTo = $("#dateTo").val();
            var patientId = $("#patientIdRemote").val();
            $.post(hosturl + '/controllers/approvals.php?ac=external_search'
                    , {dateFrom: dateFrom, dateTo: dateTo, patientId: patientId}, function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
                $('#talks-loading').hide();
            });
        });
        //############################################
        $('body').on('click', '#searchChronicBtn', function () {

            var patientId = $("#patientIdRemote").val();
            if (patientId > 0) {
                $('#talks-loading').show();
                $.post(hosturl + '/controllers/approvals.php?ac=chronic_search', {patientId: patientId}, function (res) {
                    $("#financialDiv").html("");
                    $("#financialDiv").append(res);
                    $('#talks-loading').hide();
                });
            }
        });
        $('body').on('click', '.cashChronicPres', function () {
            var presId = $(this).attr('data-id');
            bootbox.dialog({
                message: "هل أنت متأكد من صرف الروشتة   ؟",
                title: "تأكيد   ",
                buttons: {
                    danger: {
                        label: "إلغاء ",
                        className: "btn-danger"
                    },
                    main: {
                        label: "نعم ",
                        className: "btn-primary",
                        callback: function () {
                            $('#cashChronicPres' + presId).hide();
                            $.post(hosturl + '/controllers/approvals.php?ac=cashPres', {
                                presId: presId}, function (res) {
                                if (Number(res) != -1) {
                                    var shortCutFunction = 'success';
                                    var msg = 'تم الصرف ';
                                    var title = 'Success';
                                } else {
                                    var shortCutFunction = 'error';
                                    var msg = ' حدث خطأ . حاول مرة أخرى   ';
                                    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);
                                $('#searchChronicBtn').trigger('click');
                            });
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        });
        $('body').on('click', '.cashingDetails', function () {
            var presId = $(this).attr('data-id');
            $.post(hosturl + '/controllers/approvals.php?ac=cashingDetails', {presId: presId}, function (data) {
                $("#detailsDiv").html('');
                $("#detailsDiv").html(data);
                $("#detailsModel").modal('show');
            });
        });
    };
    var organizations = function () {
                $("#sales_persons").select2({
            placeholder: "Select",
            width: '240px',
            allowClear: true,
            formatNoMatches: function (term) {
                /* customize the no matches output */
                return "<input class='form-control' id='newTerm_sales_persons' value='" + term + "'><a href='#' id='addNew_sales_persons' class='btn blue custombtnstyle'>إضافة جديد</a>"
            }
        }).parent().find('.select2-with-searchbox').on('click', '#addNew_sales_persons', function () {
            /* add the new term */
            var new_name = $('#newTerm_sales_persons').val();
            $.post(hosturl + "/controllers/invsdept.php?ac=addnewrecord", {
                selectId: 'sales_persons',
                new_name: new_name,
            }, function (data) {


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

            });
        });

        $("#sales_persons").on('change', function () {
            var select = $(this);
            var colName = 'name';
            var delColName = 'deleted';
            var tableName = 'sales_persons';
            var value = select.val();
            if (value == '-1') {
                $.post(hosturl + '/controllers/invsdept.php?ac=editModal', {
                    tableName: tableName, delColName: delColName, selectClass: tableName
                    , colName: colName}, function (data) {
                    select.select2("val", "");
                    $("#editModalDiv").html(data);
                    $("#edit_model").modal('show');
                });
            }

        });

        $("body").on('click', '.printReferBQ', function () {
            var id = $(this).attr('data-id');
            $.post(hosturl + '/controllers/detection.php?ac=bqPrint', {id: id}, function (res) {
                if (res != -1) {
                    $('#printIvfDiv').html("");
                    $('#printIvfDiv').html(res);
                    $.print("#printIvfDiv");
                    $('#printIvfDiv').html("");
                }
            });
        });
        
        
         $("body").on('click', '.printOrgBQ', function () {
            var id = $(this).attr('data-id');
            $.post(hosturl + '/controllers/detection.php?ac=bqOrgPrint', {id: id}, function (res) {
                if (res != -1) {
                    $('#printIvfDiv').html("");
                    $('#printIvfDiv').html(res);
                    $.print("#printIvfDiv");
                    $('#printIvfDiv').html("");
                }
            });
        });
        
        
               $("body").on('click', '#prepareTestExcel', function (e) {
            $.post(hosturl + '/controllers/detection.php?ac=prepareTestExcel', function (res) {
                if (res != -1) {
                    e.preventDefault();  //stop the browser from following
                    window.location.href = hosturl + '/../upload/all_tests.xlsx';
                }
            });
        });


        $("body").on('click', '#preparePackExcel', function (e) {
            $.post(hosturl + '/controllers/detection.php?ac=preparePackExcel', function (res) {
                if (res != -1) {
                    e.preventDefault();  //stop the browser from following
                    window.location.href = hosturl + '/../upload/all_packs.xlsx';
                }
            });
        });
        
        
        
                $('body').on('click', '#addOrgPatNo', function () {
            var patientId = $(this).attr('data-patientId');
            $.post(hosturl + '/controllers/patients.php?ac=addOrgPatNo', {patientId: patientId}, function (res) {
                $('#orgPatNosContainer').append(res);
            });
        });
        
        
                $('body').on('change', '#orgPatNoAdd', function () {
            var orgPatNoAdd = $('#orgPatNoAdd').val();
            if (orgPatNoAdd != '') {
                $("#saudi1").prop("checked", true);
                $('#saudi1').parent().addClass('checked');
                $("#saudi0").removeAttr('checked');
                $("#saudi0").parent().removeClass('checked');
            }
        });
        
        
                $("body").on('click', '#printPriceList', function () {
                     $('#printPriceList').attr('disabled', true);
            var listId = $('#price_lists').val();
            if (listId > 0) {
                $.post(hosturl + '/controllers/detection.php?ac=printPriceList', {listId: listId}, function (res) {
                    if (res != -1) {
                        $('#printIvfDiv').html("");
                        $('#printIvfDiv').html(res);
                        $.print("#printIvfDiv");
                        $('#printIvfDiv').html("");
                    }
                     $('#printPriceList').attr('disabled', false);
                });
            }
        });
        
        
                var form3 = $('#org_add_form');
        var error3 = $('.alert-danger', form3);
        var success3 = $('.alert-success', form3);

        form3.validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-block help-block-error', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            ignore: "", // validate all fields including form hidden input
            rules: {
                org_id: {
                    required: true
                },
                name: {
                    required: true
                },
                username: {
                    required: true
                },
                password: {
                    required: true,
                    minlength: 6
                },
                confirmpassword: {
                    equalTo: '#password'
                },
                econfirmpassword: {
                    equalTo: '#epassword'
                }

            },
            errorPlacement: function (error, element) { // render error placement for each input type
                if (element.parent(".input-group").size() > 0) {
                    error.insertAfter(element.parent(".input-group"));
                } else if (element.attr("data-error-container")) {
                    error.appendTo(element.attr("data-error-container"));
                } else if (element.parents('.radio-list').size() > 0) {
                    error.appendTo(element.parents('.radio-list').attr("data-error-container"));
                } else if (element.parents('.radio-inline').size() > 0) {
                    error.appendTo(element.parents('.radio-inline').attr("data-error-container"));
                } else if (element.parents('.checkbox-list').size() > 0) {
                    error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
                } else if (element.parents('.checkbox-inline').size() > 0) {
                    error.appendTo(element.parents('.checkbox-inline').attr("data-error-container"));
                } else {
                    error.insertAfter(element); // for other inputs, just perform default behavior
                }
            },
            invalidHandler: function (event, validator) { //display error alert on form submit
                success3.hide();
                error3.show();
                Metronic.scrollTo(error3, -200);
            },
            highlight: function (element) { // hightlight error inputs
                $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
            },
            unhighlight: function (element) { // revert the change done by hightlight
                $(element)
                        .closest('.form-group').removeClass('has-error'); // set error class to the control group

            },
            success: function (label) {
                label
                        .closest('.form-group').removeClass('has-error'); // set success class to the control group
            },
            submitHandler: function (form) {
                success3.show();
                error3.hide();

                var username = $("#org_add_form #username").val();
                var id = $("#id").val();
                var checkusername = false;

                //check username after vaildation
                $.post(hosturl + '/controllers/detection.php?ac=checkusername',
                        {username: username, id: id}, function (data) {
                    if (data.replace(/\s/g, "") == 'yes') {
                        $("#showerrorusername").css({'display': 'block'});
                        checkusername = false;
                    } else {
                        $("#showerrorusername").css({'display': 'none'});
                        checkusername = true;
                        if (checkusername == true) {
                            form.submit(); // submit the form
                        }
                    }
                });

            }

        });
        
        
    };
    return {
        //main function to initiate the module
        init: function () {
            forAll();
            patients();
            patientDrug();
            patientInv();
            patientRay();
            patientUs();
            visits();
            if ($('#controllName').val() == "addinvestigation") {
                addInvestigation();
            } else if ($('#controllName').val() == "addrays") {
                addRays();
            } else if ($('#controllName').val() == "and_examination") {
                and_examination();
            } else if ($('#controllName').val() == "and_visits") {
                and_visits();
            } else if ($('#controllName').val() == "and_history") {
                and_history();
            } else if ($('#controllName').val() == "customer_service") {
                customer_service();
            } else if ($('#controllName').val() == "reserve_clinic") {
                reserve_clinic();
            }
            instruction();
            menu();
            members();
            getdata();
            merge();
            //      minSelectInput();
            device_tracking();
            external_labs();
            followupcard();
            fullReport();
            transfer();
            patientInfertility();
            patientICSI();
            if ($('#operationData').val() == 1) {
                operation_data();
            }

            if ($('#controllName').val() == "case_summary" || $('#updateD').val() == 1) {
                case_summary();
            }

            if ($('#controllName').val() == "detection") {
                detection();
            }

            if ($('#usAntSelects').val() == 1) {
                usAntSelects();
            }

            if ($('#patient_history').val() == 1) {
                patient_history();
            }

            if ($('#regions').val() == 1) {
                regions();
            }
            
                    if ($('#invOffers').val() == 1) {
                invOffers();
            }
            
            
            if ($('#labStyle').val() == 2) {
                completeLab();
            }
            
                        if ($('#labDevice').val() == 1) {
                labDevice();
            }

            approvals();
            organizations();
        }

    };
}();
