
var patientcustom = function () {
//global hosturlf
    var hosturl = $('#hosturl').val();
    var path = $('#path').val();
    var patientId = $('#ptntid').val();
    //remove the selected
    $('.deleteelement').live('click', function () {
//check for edit
        var itemid = $(this).attr('data-id');
        var urlgo = $(this).attr('data-link');
        var fun = $(this).attr('data-fun');
        var selectClass = $(this).attr('data-selectClass');
        var isSelect2 = $(this).attr("data-select2");
        var tableName = $(this).attr("data-tableName");
        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=" + fun, {id: itemid, tableName: tableName}, function (data) {
                            if (fun == 'delwifetype') {
                                $("#wifetype").html(data);
                            } else if (fun == 'deleducation') {

                                if (isSelect2 == "yes")
                                {
                                    // see how to change the value of updated option in the select
                                    $('.' + selectClass).each(function ()
                                    {
                                        if ($(this).val() == itemid)
                                        {
                                            $(this).select2("val", "");
                                        }
                                    });
                                }
                                $("#education").html(data);
                                $("#educationhus").html(data);
                            } else if (fun == 'delgovernorate') {

                                if (isSelect2 == "yes")
                                {
                                    // see how to change the value of updated option in the select
                                    $('.' + selectClass).each(function ()
                                    {
                                        if ($(this).val() == itemid)
                                        {
                                            $(this).select2("val", "");
                                        }
                                    });
                                }
                                $("#governorate").html(data);
                            } else if (fun == 'delgovernorate_center') {

                                if (isSelect2 == "yes")
                                {
                                    // see how to change the value of updated option in the select
                                    $('.' + selectClass).each(function ()
                                    {
                                        if ($(this).val() == itemid)
                                        {
                                            $(this).select2("val", "");
                                        }
                                    });
                                }
                                $("#governorate_centers").html(data);
                            } else if (fun == 'delwifejob') {
                                $("#wifejob").html(data);
                            } else if (fun == 'delstatus') {
                                $("#wifestatus").html(data);
                            } else if (fun == 'delhusstatus') {
                                $("#husstatus").html(data);
                            } else if (fun == 'delbl') {

                                if (isSelect2 == "yes")
                                {
                                    // see how to change the value of updated option in the select
                                    $('.' + selectClass).each(function ()
                                    {
                                        if ($(this).val() == itemid)
                                        {
                                            $(this).select2("val", "");
                                        }
                                    });
                                }

                                $("#bloodtype").html(data);
                                $("#bloodtypehus").html(data);
                            } else if (fun == 'delhustype') {
                                $("#husbandtype").html(data);
                            } else if (fun == 'delhusjob') {
                                $("#husbandjob").html(data);
                            } else if (fun == 'deldata') {

                                if (isSelect2 == "yes")
                                {
                                    // see how to change the value of updated option in the select
                                    $('.' + selectClass).each(function ()
                                    {
                                        if ($(this).val() == itemid)
                                        {
                                            $(this).select2("val", "");
                                        }
                                        $(this).children('option[value = ' + itemid + ']').remove();
                                    });
                                    if (selectClass == "refer_doctor")
                                    {
                                        $('.h_refer_doctor').each(function () {
                                            if ($(this).val() == itemid)
                                            {
                                                $(this).select2("val", "");
                                            }
                                            $(this).children('option[value = ' + itemid + ']').remove();
                                        });
                                    }

                                    if (selectClass == "h_refer_doctor")
                                    {
                                        $('.refer_doctor').each(function () {
                                            if ($(this).val() == itemid)
                                            {
                                                $(this).select2("val", "");
                                            }
                                            $(this).children('option[value = ' + itemid + ']').remove();
                                        });
                                    }
                                }

                            }
                            if (fun == 'deldetection') {

                                $('#detectionid').load(hosturl + '/controllers/visits.php?ac=visitselected');
                            }

                            if (tableName == "organizations")
                            {
                                $('#organizations').children('option[value = ' + itemid + ']').remove();
                                $('#organization').children('option[value = ' + itemid + ']').remove();
                            }
                            tr.remove();
                        });
                    }
                }
            }
        }).find('.modal-content').addClass('modal-sm');
    });

    if ($('#patShowTb').length) {
// it exists
        $('#patShowTb').dataTable({
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": hosturl + '/controllers/patients.php?ac=showpt&doctorId=' + $('#patDoctor1').val(), //  server side processing
            "sPaginationType": "full_numbers",
            "aoColumnDefs": [
                {
                    'orderable': false,
                    "searchable": false,
                    "targets": [7]
                }
            ],
            "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
                    'orderable': true,
                    'targets': [0]
                }, {
                    "searchable": true,
                    "targets": [0]
                }],
            "order": [
                [0, "asc"]
            ] // set first column as a default sort by asc
        });

        $('body').on('click', '.suspendPat', function () {
            var id = $(this).attr('data-id');
            var value = $(this).attr('data-status');
            $(this).attr('disabled', 'true');

            $.post(hosturl + '/controllers/invoffers.php?ac=update', {
                id: id, tableName: 'patients', colName: 'status', value: value
            }, function (res) {
                $('#patShowTb').DataTable().ajax.reload();
            });
        });

        $('body').on('change', '#patDoctor1', function () {
            var doctorId = $('#patDoctor1').val();
            $('#patShowTb').DataTable().ajax.url(hosturl + '/controllers/patients.php?ac=showpt&doctorId=' + doctorId).load();
        });
    }

    var deletemsg = function () {
        var table = $('#sample_3').DataTable({"lengthMenu": [[15, 20, -1], [15, 20, "All"]], "pageLength": 15});
        $('#sample_3 tbody').on('click', '.deletemsgnew', function () {
            table
                    .row($(this).parents())
                    .remove()
                    .draw(false);
        });
    }

    var deletemsgvisit = function () {

//remove the selected
        $('.deletevisit').live('click', function () {
//check for edit

            var itemid = $(this).attr('data-id');
            var urlgo = $(this).attr('data-link');
            var today = $(this).attr('data-today');
            //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 () {
                            //do something elseeditwifetype_submit
                            window.location.href = hosturl + "/controllers/" + urlgo + ".php?ac=delv&id=" + itemid;
                        }
                    }
                }
            }).find('.modal-content').addClass('modal-sm');
        })
    }

    $(".calcdatew").live('change', function () {
        var patientdate = $('#dateofbirth_cc').val();
        var patientID = $(this).attr('data-id');
        $.post(hosturl + "/controllers/patients.php?ac=calcage", {patientdate: patientdate}, function (data) {
            if (data == -1) {
                $('#wifeage').val('');
                $('#dateofbirth_cc').val("00-00-0000");
            } else {
                $('#wifeage').val(data);
                if (data) {
                    $.post(hosturl + "/controllers/patients.php?ac=saveage", {value: data, ptid: patientID, patientdate: patientdate}, function (data) {
                        if (data) {
                            var shortCutFunction = 'success';
                            var msg = 'The date of birth and age  has been saved Successfully';
                            var title = 'Success';
                        } else {
                            var shortCutFunction = 'error';
                            var msg = 'Sorry , an error has been occured ';
                            var title = 'Error';
                        }
                        toastr.options = {
                            closeButton: $('#closeButton').prop('checked'),
                            debug: $('#debugInfo').prop('checked'),
                            positionClass: $('#positionGroup input:checked').val() || 'toast-top-left',
                            onclick: null
                        };
                        //var $toast = toastr[shortCutFunction](msg, title);
                    });
                }
            }
        });
    });

    $(".calcdatehusband").live('change', function () {
        var patientdate = $('#husbanddateofbirth').val();
        var patientID = $(this).attr('data-id');
        $.post(hosturl + "/controllers/patients.php?ac=calcage", {patientdate: patientdate}, function (data) {
            if (data == -1) {
                $('#husbandage').val('');
                $('#husbanddateofbirth').val("00-00-0000");
            } else {
                $('#husbandage').val(data);
                if (data) {
                    $.post(hosturl + "/controllers/patients.php?ac=saveagehus", {value: data, ptid: patientID, patientdate: patientdate}, function (data) {
                    });
                }
            }
        });
    });

    $('body').on('keyup', '#wifeage', function () {
        var wAge = $(this).val();
        var patientId = $(this).attr('data-id');
        $.post(hosturl + '/controllers/patients.php?ac=caldatefromage', {age: wAge, patientId: patientId, type: 'w'}, function (res)
        {
            //alert(res);
            $('#dateofbirth_cc').val(res);
        });
    });

    $('body').on('keyup', '#husbandage', function () {
        var hAge = $(this).val();
        var patientId = $(this).attr('data-id');
        $.post(hosturl + '/controllers/patients.php?ac=caldatefromage', {age: hAge, patientId: patientId, type: 'h'}, function (res)
        {
            $('#husbanddateofbirth').val(res);
        });
    });

    $('#wifename').live('keyup', function () {
        var wifename = $(this).val();
        var patientId = $(this).attr('data-id');
        var edit = Number($('#edited').val());

        $.post(hosturl + '/controllers/patients.php?ac=checkingwifename', {wifename: wifename, patientId: patientId}, function (data) {
            if (data == 1) {
                $('input[id="wifename"]').css({"background-color": "#FFFF99", "border": "1px solid red", "animation": " fadein 6s", "transition": "opacity 0.5s"});
                document.getElementById("lb_ckwifename").style.display = "";
                document.getElementById("lb_ckwifename").style.color = "red";

            } else {
                $('input[id="wifename"]').css('background-color', '#fff');
                document.getElementById("lb_ckwifename").style.display = "none";
                $("#wifenamecontain").find('input[id="wifename"]').css('background-color', '');
                $('input[id="wifename"]').css('border', '');

                if (edit != 1 && patientId > 0) {
                    $.post(hosturl + '/controllers/patients.php?ac=updateajax',
                            {colname: 'wifename', valuenew: wifename, id: patientId}, function (res1) {

                    });
                }
            }
            allowPatSaveBtn();
        });
    });

    $('.uniquePhone').live('keyup', function () {
        var phone = $(this).val();
        var id = $(this).attr('id');
        var patientId = $('#ptntid').val();
        if (phone != '') {
            $.post(hosturl + '/controllers/patients.php?ac=checkmobile', {phone: phone, patientId: patientId}, function (data) {
                if (data == 1) {
                    $('input[id="' + id + '"]').css({"background-color": "#FFFF99", "border": "1px solid red", "animation": " fadein 6s", "transition": "opacity 0.5s"});
                    document.getElementById('lb_ck' + id + '').style.display = "";
                    document.getElementById('lb_ck' + id + '').style.color = "red";
                } else {
                    $('input[id="' + id + '"]').css('background-color', '#fff');
                    document.getElementById('lb_ck' + id + '').style.display = "none";
                    //    $("#wifenamecontain").find('input[id="wifename"]').css('background-color', '');
                    $('input[id="' + id + '"]').css('border', '');
                }
                allowPatSaveBtn();
            });
        }


    });

    $('#statusno').live('keyup', function () {
        var wifestatusno = $(this).val();
        var patientId = $(this).attr('data-id');
        $.post(hosturl + '/controllers/patients.php?ac=checkingwifestatusno', {wifestatusno: wifestatusno, patientId: patientId}, function (data) {
            if (data == 1) {
                $('input[id="statusno"]').css({"background-color": "#FFFF99", "border": "1px solid red", "animation": " fadein 6s", "transition": "opacity 0.5s"});
                document.getElementById("lb_ckwifestatusno").style.display = "";
                document.getElementById("lb_ckwifestatusno").style.color = "red";
            } else {
                $('input[id="statusno"]').css('background-color', '#fff');
                document.getElementById("lb_ckwifestatusno").style.display = "none";
                $("#wifestatuscontain").find('input[id="statusno"]').css('background-color', '');
                $('input[id="statusno"]').css('border', '');
            }
            allowPatSaveBtn();
        });
    });

    $('body').on('change', '#wifenationalid', function () {
        var wifenationalid = $(this).val();
        var patientId = $(this).attr('data-id');
        var colname = $(this).attr('data-ptname');
        var id = $(this).attr('data-id');
        var edit = Number($('#edited').val());


        if (wifenationalid != '') {
            var c = checkNationalId(wifenationalid);
            if (c == 1)    // not match
            {
                $('input[id="wifenationalid"]').css({"background-color": "#FFFF99", "border": "1px solid red", "animation": " fadein 6s", "transition": "opacity 0.5s"});
                document.getElementById("lb_ckeckwifenationalid").style.display = "";
                document.getElementById("lb_ckeckwifenationalid").style.color = "red";
                $('#lb_ckeckwifenationalid').html('هذا الرقم خاطئ');
            } else    // match
            {
                $.post(hosturl + '/controllers/patients.php?ac=checkingnationalwifename',
                        {wifenationalid: wifenationalid, patientId: patientId}, function (data) {
                    if (Number(data) == 1) {
                        $('input[id="wifenationalid"]').css({"background-color": "#FFFF99", "border": "1px solid red", "animation": " fadein 6s", "transition": "opacity 0.5s"});
                        $('#lb_ckeckwifenationalid').html('هذا الرقم موجود من قبل');
                        document.getElementById("lb_ckeckwifenationalid").style.display = "";
                        document.getElementById("lb_ckeckwifenationalid").style.color = "red";
                    } else {
                        $('#wifenationalid').css({"background-color": "#FFF"});
                        document.getElementById("lb_ckeckwifenationalid").style.display = "none";
                        $("#wifenationalidcontain").find('#wifenationalid').css('background-color', '');
                        $('#lb_ckeckwifenationalid').html('');
                        $('#wifenationalid').css('border', '');
                        var bDate = getBirthDate(wifenationalid);
                        $('#dateofbirth_cc').val(bDate);
                        calcDate('w');
                        if (edit != 1) {
                            $.post(hosturl + '/controllers/patients.php?ac=updateajax',
                                    {colname: colname, valuenew: wifenationalid, id: id}, function (res1) { });
                            $.post(hosturl + '/controllers/patients.php?ac=updateajax',
                                    {colname: 'dateofbirth', valuenew: bDate, id: id}, function (res) { });
                        }
                    }

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

    $('body').on('change', '#passport', function () {
        var passport = $(this).val();
        var patientId = $(this).attr('data-id');
        var colname = $(this).attr('data-ptname');
        var id = $(this).attr('data-id');
        var edit = Number($('#edited').val());
        if (edit != 1) {
            $.post(hosturl + '/controllers/patients.php?ac=updateajax', {colname: colname, valuenew: passport, id: id}, function (res1)
            {

            });
        }

        if (passport != '') {
            $.post(hosturl + '/controllers/patients.php?ac=checkpassport', {passport: passport, patientId: patientId}, function (data)
            {
                if (Number(data) == 1)
                {

                    $('input[id="passport"]').css({"background-color": "#FFFF99", "border": "1px solid red", "animation": " fadein 6s", "transition": "opacity 0.5s"});
                    $('#lb_ckeckpassport').html('هذا الرقم موجود من قبل');
                    document.getElementById("lb_ckeckpassport").style.display = "";
                    document.getElementById("lb_ckeckpassport").style.color = "red";
                } else
                {
                    $('#wifenationalid').css({"background-color": "#FFF"});
                    document.getElementById("lb_ckeckpassport").style.display = "none";
                    $("#passportcontain").find('#passport').css('background-color', '');
                    $('#lb_ckeckpassport').html('');
                    $('#passport').css('border', '');
                }
            });
        }
    });

    $('body').on('change', '#hus_passport', function () {
        var passport = $(this).val();
        var patientId = $(this).attr('data-id');
        var colname = $(this).attr('data-ptname');
        var id = $(this).attr('data-id');
        var edit = Number($('#edited').val());
        if (edit != 1) {
            $.post(hosturl + '/controllers/patients.php?ac=updateajax', {colname: colname, valuenew: passport, id: id}, function (res1)
            {

            });
        }

        if (passport != '') {
            $.post(hosturl + '/controllers/patients.php?ac=checkhpassport', {passport: passport, patientId: patientId}, function (data)
            {
                if (Number(data) == 1)
                {

                    $('input[id="hus_passport"]').css({"background-color": "#FFFF99", "border": "1px solid red", "animation": " fadein 6s", "transition": "opacity 0.5s"});
                    $('#lb_ckeckpassporth').html('هذا الرقم موجود من قبل');
                    document.getElementById("lb_ckeckpassporth").style.display = "";
                    document.getElementById("lb_ckeckpassporth").style.color = "red";
                } else
                {
                    $('#hus_passport').css({"background-color": "#FFF"});
                    document.getElementById("lb_ckeckpassporth").style.display = "none";
                    $("#hpassportcontain").find('#hus_passport').css('background-color', '');
                    $('#lb_ckeckpassporth').html('');
                    $('#hus_passport').css('border', '');
                }
            });
        }
    });

    function calcDate(type) {
        if (type == 'h')
        {
            var patientdate = $('#husbanddateofbirth').val();
            var patientID = $('#husbanddateofbirth').attr('data-id');
            $.post(hosturl + "/controllers/patients.php?ac=calcage", {patientdate: patientdate}, function (data)
            {
                if (data == -1) {
                    $('#husbandage').val('');
                    $('#husbanddateofbirth').val("00-00-0000");
                } else {
                    $('#husbandage').val(data);
                    if (data) {
                        $.post(hosturl + "/controllers/patients.php?ac=saveagehus", {value: data, ptid: patientID, patientdate: patientdate}, function (data) {
                        });
                    }
                }
            });
        } else if (type == 'w')
        {
            var patientdate = $('#dateofbirth_cc').val();
            var patientID = $('#dateofbirth_cc').attr('data-id');
            $.post(hosturl + "/controllers/patients.php?ac=calcage", {patientdate: patientdate}, function (data) {
                if (data == -1) {
                    $('#wifeage').val('');
                    $('#dateofbirth_cc').val("00-00-0000");
                } else {
                    $('#wifeage').val(data);
                    if (data) {
                        $.post(hosturl + "/controllers/patients.php?ac=saveage", {value: data, ptid: patientID, patientdate: patientdate}, function (data) {
                        });
                    }
                }
            });
        }
    }

    function  checkNationalId(wifenationalid)
    {
// check format regex

//var patt = /(2|3)[0-9][1-9][0-1][1-9][0-3][1-9](01|02|03|04|11|12|13|14|15|16|17|18|19|21|22|23|24|25|26|27|28|29|31|32|33|34|35|88)\d\d\d\d\d/i;
        var patt = /(2|3)[0-9][0-9][0-1][0-9][0-3][0-9]\d\d\d\d\d\d\d/i;
        //var patt = /(2|3)\d\d\d\d\d\d\d\d\d\d\d\d\d/i;
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        if (!patt.test(wifenationalid)) {
            return 1;
        } else {
            return 0;
        }
    }

    $('body').on('change', '#husbandnationalid', function ()
    {
        var husbandnationalid = $(this).val();
        var patientId = $(this).attr('data-id');
        var colname = $(this).attr('data-ptname');
        var id = $(this).attr('data-id');
        var edit = Number($('#edited').val());
        if (edit != 1) {
            $.post(hosturl + '/controllers/patients.php?ac=updateajax', {colname: colname, valuenew: husbandnationalid, id: id}, function (res1)
            {

            });
        }

        if (husbandnationalid != '') {
            var c = checkNationalId(husbandnationalid);
            if (c == 1)    // not match
            {
                $('input[id="husbandnationalid"]').css({"background-color": "#FFFF99", "border": "1px solid red", "animation": " fadein 6s", "transition": "opacity 0.5s"});
                document.getElementById("lb_ckeckhusbandnationalid").style.display = "";
                document.getElementById("lb_ckeckhusbandnationalid").style.color = "red";
                $('#lb_ckeckhusbandnationalid').html('هذا الرقم خاطئ');
            } else    // match
            {
                $.post(hosturl + '/controllers/patients.php?ac=checkingnationalhusband', {husbandnationalid: husbandnationalid, patientId: patientId}, function (data)
                {
                    if (Number(data) == 1)
                    {

                        $('#lb_ckeckhusbandnationalid').html('هذا الرقم موجود من قبل');
                        $('input[id="husbandnationalid"]').css({"background-color": "#FFFF99", "border": "1px solid red", "animation": " fadein 6s", "transition": "opacity 0.5s"});
                        document.getElementById("lb_ckeckhusbandnationalid").style.display = "";
                        document.getElementById("lb_ckeckhusbandnationalid").style.color = "red";
                    } else
                    {
                        $('input[id="husbandnationalid"]').css('background-color', '#fff');
                        document.getElementById("lb_ckeckhusbandnationalid").style.display = "none";
                        $("#husbandnationalidcontent").find('input[id="husbandnationalid"]').css('background-color', '');
                        $('input[id="husbandnationalid"]').css('border', '');
                        $('#lb_ckeckhusbandnationalid').html('');
                    }

                });
                var bDate = getBirthDate(husbandnationalid);
                $('#husbanddateofbirth').val(bDate);
                $.post(hosturl + '/controllers/patients.php?ac=updateajax', {colname: 'husbanddateofbirth', valuenew: bDate, id: id}, function (res)
                {
                });
                calcDate('h');
            }
        }
    });
    function getBirthDate(nationalId)
    {
        var dArray = nationalId.split('');
        var year;
        var month;
        var day;
        if (dArray[0] == 2)
        {
            year = 1900 + (Number(dArray[1]) * 10) + Number(dArray[2]);
        } else if (dArray[0] == 3)
        {
            year = 2000 + (Number(dArray[1]) * 10) + Number(dArray[2]);
        }
        month = (Number(dArray[3]) * 10) + Number(dArray[4]);
        day = (Number(dArray[5]) * 10) + Number(dArray[6]);
        return day + '-' + month + '-' + year;
    }
    var searchresult = function ()
    {
        $('body').on('keyup', '.search', function () {
            var search = $('#wifenamesearchable').val();
            var statusid = $('#wifenamesearchable').val();
            var husbandname = $('#husbandname').val();
            var address = $('#address').val();
            var jobtitle = $('#jobtitle').val();
            var age = $('#age').val();
            var phone = $('#phone').val();
            var mobile = $('#mobile').val();
            var nationalid = $('#nationalid').val();
            var detectionSearch = $('#detectionSearch').val();
            var search_letters_no = 1;
            if (($('#search_letters_no').length) && $('#search_letters_no').val() > 1) {
                search_letters_no = $('#search_letters_no').val();
            } else {
                search_letters_no = 1;
            }

            var search_length = ($('#wifenamesearchable').val()).length;

            if (search == '' && husbandname == '' && address == '' && jobtitle == '' && age == '' && phone == '' && mobile == '' && nationalid == '' && detectionSearch == '') {
                $('#ermsg').css('display', 'block');
                $('.success').html('');
            } else {
                if (search_length >= search_letters_no) {
                    $.post($('form').attr('action'), {search: search, husbandname: husbandname, address: address, age: age, phone: phone, mobile: mobile, nationalid: nationalid, jobtitle: jobtitle, statusid: statusid, detectionSearch: detectionSearch}, function (data)
                    {
//console.log(data);
                        if (data) {
                            $('.success').html(data);
                            $('#ermsg').css('display', 'none');
                        } else {
                            $('.success').html('');
                        }
                    });
                } else {
                    $('.success').html('');
                }
            }

        });
        $('body').on('change', '#detectionSearch', function () {
            var search = $('#wifenamesearchable').val();
            var statusid = $('#wifenamesearchable').val();
            var husbandname = $('#husbandname').val();
            var address = $('#address').val();
            var jobtitle = $('#jobtitle').val();
            var age = $('#age').val();
            var phone = $('#phone').val();
            var mobile = $('#mobile').val();
            var nationalid = $('#nationalid').val();
            var detectionSearch = $('#detectionSearch').val();
            //alert(husbandname);
            if (search == '' && husbandname == '' && address == '' && jobtitle == '' && age == '' && phone == '' && mobile == '' && nationalid == '' && detectionSearch == '') {
//                        $('#ermsg').css('display', 'block');
                $('.success').html('');
            } else {
                $.post($('form').attr('action'),
                        {search: search, husbandname: husbandname, address: address, age: age, phone: phone, mobile: mobile, nationalid: nationalid, jobtitle: jobtitle, statusid: statusid, detectionSearch: detectionSearch}, function (data) {
                    if (data) {
                        $('.success').html(data);
                        $('#ermsg').css('display', 'none');
                    } else {
//$('.faild').html();
                    }
                });
            }

        });
        $('body').on('keyup', '.searchvisit', function () {
            var search_visit = $('#search_visit_wife_name').val();
            var search_visit_hus = $('#search_visit_hus_name').val();
            var searchvisitdatefrom = $('#search_visit_date_from').val();
            var searchvisitdateto = $('#search_visit_date_to').val();
            if (search_visit == '' && search_visit_hus == '' && searchvisitdatefrom == '' && searchvisitdateto == '') {
                $('#ermsgvisit').css('display', 'block');
                $('.successvisit').html('');
            } else {
                $.post($('form').attr('action'), {search: search_visit, searchhus: search_visit_hus, searchvisitdatefrom: searchvisitdatefrom, searchvisitdateto: searchvisitdateto}, function (data) {
                    $('.successvisit').html(data);
                    $('#ermsgvisit').css('display', 'none');
                });
            }
        });
        $('body').on('change', '.searchvisitCal', function () {
            var search_visit = $('#search_visit_wife_name').val();
            var search_visit_hus = $('#search_visit_hus_name').val();
            var searchvisitdatefrom = $('#search_visit_date_from').val();
            var searchvisitdateto = $('#search_visit_date_to').val();
            if (search_visit == '' && search_visit_hus == '' && searchvisitdatefrom == '' && searchvisitdateto == '') {
                $('#ermsgvisit').css('display', 'block');
                $('.successvisit').html('');
            } else {
                $.post($('form').attr('action'), {search: search_visit, searchhus: search_visit_hus, searchvisitdatefrom: searchvisitdatefrom, searchvisitdateto: searchvisitdateto}, function (data) {
                    $('.successvisit').html(data);
                    $('#ermsgvisit').css('display', 'none');
                });
            }
        });
        $('body').on('change', '.searchvisitIndex', 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 (data) {
                $('#visitNew').html(data);
                $('#mVisitId').val(0);
            });
        });
    }


    $('.btnsve').click(function () {
        $('#visitaddsubmit').attr('disabled', true);
        var patientid = $('#patientvisitid').val();
        var visitdate = $('#visitdate').val();
        var fordepartment = $('#fordepartment').val();
        var for_doctor = $('#for_doctor').val();
        var detectionid = $('#detectionid').val();
        var cash = $('#detectionvalue_cash').val();
        var printserial = $('#printserial').val();
        var shareVersion = $('#shareVersion').val();
        var branch_id = $('#branch_id').val();
        var regions = $('#regions').val();
        var subRegionId = $('#subRegionId').val();
        var needDr = 1;
        var minPaid = 1;
        var unitsNo = 1;

        $('#minPaidOk').html('  ');
        $('#unitsNoOk').html('  ');

        if (shareVersion == 3) {
            var min_paid = $("#min_paid_in").val();
            var units_no = $("#units_no_in").val();

            var unitsConsumed = $("#unitsConsumed").val();
            var visa_paid = $("#detectionvalue_visa").val();
            var cash_paid = $("#detectionvalue_cash").val();
            var total_paid = Number(cash_paid) + Number(visa_paid);
            if (min_paid > total_paid) {
                minPaid = 0;
            }

            if (Number(unitsConsumed) > Number(units_no)) {
                unitsNo = 0;
            }
        }

        if (fordepartment == 11 || fordepartment == 12) {
            needDr = 0;
        }

        if (regions == 1 && !(subRegionId > 0 && for_doctor > 0)) {
            $('#drExist').html('   حدد الطبيب والمنطقة  أولا ');
            $('#visitaddsubmit').attr('disabled', false);
        } else {
            if ((needDr == 1 && for_doctor > 0) || needDr == 0) {
                $('#drExist').html('  ');

                if (minPaid == 1 && unitsNo == 1) {


                    if (patientid != '' && visitdate != '' && detectionid != '' && branch_id > 0) {
                        $.post(hosturl + '/controllers/visits.php?ac=add', $("#myvisitform").serialize(), function (visitId) {
                            if (Number(visitId) != -1) {

                                if (Number(visitId) > 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', {visitId: visitId, jsonString: jsonString}, function (res) {
                                            console.log(res);
                                            $('#for_doctor').trigger('change');
                                        });
                                    } else {
                                        $('#for_doctor').trigger('change');
                                    }
                                }
                                $('#subRegionId').select2('val', '');
                                $('#visit_time').val('');
                                $('#selectedFromModel').html("");
                                $('#selectedFromModel').hide();
                                $('#discountRatio').val(0);
                                $('#contractPrice').val(0);
                                $('#organizations').select2('val', '');
                                $('#refer_doctor').select2('val', '');
                                $("#detectionid").select2("val", 4);
                                $("#detectionvalue_cash").val(0);
                                $("#cardVisitId").val(0);
                                $("#unitsConsumed").val(0);
                                $("#notes").val('');
                                $("#detectionvalue_visa").val(0);
                                $("#restdetectionvalue").val(0);
                                $("#totaldetectionvalue").val(0);
                                $('#discount').val(0);
                                $('#cardVisitPatient').val(0);
                                $('#cardVisitTime').val('');
                                $('#fordepartment').select2("val", "4").trigger('change');
                                $('#statusNoRemoteLab').val('');
                                $('#statusNoRemoteLab ').trigger('keyup');
                                $("input[name=for_husband][value=" + 0 + "]").prop('checked', true);
                                $("#childHead").hide();
                                $("#childContain").hide();
                                if (cash > 0 && printserial == 1) {
                                    $.post(hosturl + '/controllers/visits.php?ac=printvisitrecept', {
                                        visitId: visitId
                                    }, 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}, function (data) {
                                    $('#visitNew').html(data);
                                    $('#mVisitId').val(0);
                                });
                                $('.iiin').each(function () {
                                    $(this).removeAttr('checked');
                                    if ($(this).parent().attr("class") === 'checked') {
                                        $(this).parent().attr("class", '')
                                    }
                                });
                            } else {
                                alert('خطأ ... لم يتم التسجيل ');
                            }
                            $('#visitaddsubmit').attr('disabled', false);
                        });
                    } else {
                        alert(' لابد من تحديد المريض ونوع الكشف والتاريخ لاكمال التسجيل ...');
                        $('#visitaddsubmit').attr('disabled', false);
                    }
                } else {
                    if (minPaid != 1) {
                        $('#minPaidOk').html('    لابد من دفع مقدم الحجز كاملا  أولا ');
                    }

                    if (unitsNo != 1) {
                        $('#unitsNoOk').html('    عدد الوحدات أكبر من عدد الوحدات المتاحة  ');
                    }
                    $('#visitaddsubmit').attr('disabled', false);
                }

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

    $('body').on('change', '#patientvisitidNo', function () {
        var selectedPatientId = $(this).val();
        $("#patientvisitid").select2("val", selectedPatientId);
        getLastVisit(selectedPatientId);
        getRestDetectionVlues(selectedPatientId);
        getChilds(selectedPatientId);
        //getModels();
    });

    $('body').on('change', '#patientvisitid', function () {
        var selectedPatientId = $(this).val();
        $("#patientvisitidNo").select2("val", selectedPatientId);
        getPhoneNo(selectedPatientId);
         getSaudi(selectedPatientId);
        getLastVisit(selectedPatientId);
        getRestDetectionVlues(selectedPatientId);
        getChilds(selectedPatientId);
        vcalc();
    });

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

        if (patientid > 0 && 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 getSaudi(patientId) {
        $.post(hosturl + '/controllers/visits.php?ac=getSaudi', {patientId: patientId}, function (data) {
            var saudi = Number(data);
            if (saudi == 1) {
                $("#saudi1").prop("checked", true);
                $('#saudi1').parent().addClass('checked');
            } else {
                $("#saudi0").prop("checked", true);
                $('#saudi0').parent().addClass('checked');
                $("#saudi1").removeAttr('checked');
                $("#saudi1").parent().removeClass('checked');
            }
        });
    }

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

    function getStatusNo(patientId) {
        $.post(hosturl + '/controllers/visits.php?ac=getStatus', {patientId: patientId}, function (data) {
            $("#statusNoRemoteLab").val(data);
        });
    }

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

    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 getRestDetectionVlues(patientId)
    {
        $.post(hosturl + '/controllers/visits.php?ac=getrestvalues', {patientId: patientId}, function (data) {

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

    function getModels()
    {
        var roleId = $('#roleId').val();
        if (roleId == 5 || roleId == 12) {
            {
                $('#invType').trigger("change");
            }
        }

    }

    $('.select2me_aw').select2({language: "ar"});

    $("#wifejob").live('change', function () {
        var del = $(this).val();
        if (del == 0) {
            $.post(hosturl + '/controllers/patients.php?ac=getallwifejob', function (data) {
                $("#wifejob").select2("val", "");
                $('#datareceivedwifejob').html(data);
                $('#datareceivedwifejob').modal('show');
//                    $('#wifejobsdelete').html(data);
//                    $('#wifejobsdelete').modal('show');
            });
        }
    });

    $("#wifejob").select2({
        width: '240px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn blue custombtnstyle'>إضافة جديد</a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
        /* add the new term */
        var jobname = $('#newTerm').val();
        var hosturl = $('#hosturl').val();
        $.post(hosturl + "/controllers/patients.php?ac=addwifejob", {jobname: jobname, inline: patientId}, function (data) {
            $('#wifejob > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + jobname + '</option>');
            //$('<option value="' + Number(data) + '" >' + jobname + '</option>').appendTo('#wifejob');
            $('#wifejob').select2('val', Number(data)); // select the new term
            $("#wifejob").select2('close'); // close the dropdown

            if (Number(data)) {
                var shortCutFunction = 'success';
                var msg = 'The Job has been Added successfully';
                var title = 'Success';
                $('.todayvisit').html();
            } else {
                var shortCutFunction = 'error';
                var msg = 'Sorry , an error has been occured ';
                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);
        });
    });
    //ADD EDUCATION WIFE
    $("#education").live('change', function () {
        var del = $(this).val();
        if (del == 0) {
            $.post(hosturl + '/controllers/patients.php?ac=getalleducation', function (data) {
                $("#education").select2("val", "");
                $('#allEducation').html(data);
                $('#allEducation').modal('show');
            });
        }
    });

    $("#governorate").live('change', function () {
        var del = $(this).val();
        var governorate = $('#governorate').val();
        if (del == 0) {
            $.post(hosturl + '/controllers/patients.php?ac=getallgovernorate', function (data) {
                $("#governorate").select2("val", "");
                $('#allgovernorate').html(data);
                $('#allgovernorate').modal('show');
            });
        }
        $.post(hosturl + '/controllers/patients.php?ac=getGovernorateCenters'
                , {governorate: governorate}, function (data) {
            $("#governorate_centers").select2("val", "");
            $('#governorate_centers').html(data);
        });
    });

    $("#governorate_centers").live('change', function () {
        var del = $(this).val();
        var governorate = $('#governorate').val();
        if (del == 0) {
            $.post(hosturl + '/controllers/patients.php?ac=getallgovernorate_centers'
                    , {governorate: governorate}, function (data) {
                $("#governorate_centers").select2("val", "");
                $('#allgovernorate').html(data);
                $('#allgovernorate').modal('show');
            });
        }
    });

    $("#education").select2({
        width: '240px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn blue custombtnstyle'>إضافة جديد</a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
        /* add the new term */
        var education = $('#newTerm').val();
        var hosturl = $('#hosturl').val();
        $.post(hosturl + "/controllers/patients.php?ac=addwifeeducation", {education: education, inline: patientId, type: 'w'}, function (data) {
            $('.edu > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + education + '</option>');
            //$('<option value="' + Number(data) + '" >' + education + '</option>').appendTo('#education');
            $('#education').select2('val', Number(data)); // select the new term
            $("#education").select2('close'); // close the dropdown

            if (Number(data)) {
                var shortCutFunction = 'success';
                var msg = 'The education has been Added successfully';
                var title = 'Success';
                $('.todayvisit').html();
            } else {
                var shortCutFunction = 'error';
                var msg = 'Sorry , an error has been occured ';
                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);
        });
    });

    $("#governorate").select2({
        width: '240px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            return "<input class='form-control' id='newTermgovernorate' value='" + term + "'><a href='#' id='addNewgovernorate' class='btn blue custombtnstyle'>إضافة جديد</a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNewgovernorate', function () {
        /* add the new term */
        var governorate = $('#newTermgovernorate').val();
        var hosturl = $('#hosturl').val();
        $.post(hosturl + "/controllers/patients.php?ac=addgovernorate", {governorate: governorate, inline: patientId}, function (data) {
            $('.governorate > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + governorate + '</option>');
            //$('<option value="' + Number(data) + '" >' + governorate + '</option>').appendTo('#governorate');
            $('#governorate').select2('val', Number(data)); // select the new term
            $("#governorate").select2('close'); // close the dropdown

            if (Number(data)) {
                var shortCutFunction = 'success';
                var msg = 'The governorate has been Added successfully';
                var title = 'Success';
                $('.todayvisit').html();
            } else {
                var shortCutFunction = 'error';
                var msg = 'Sorry , an error has been occured ';
                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);
        });
    });

    $("#governorate_centers").select2({
        width: '240px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            return "<input class='form-control' id='newTermgovernorate_centers' value='" + term + "'><a href='#' id='addNewgovernorate_centers' class='btn blue custombtnstyle'>إضافة جديد</a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNewgovernorate_centers', function () {
        /* add the new term */
        var governorate_centers = $('#newTermgovernorate_centers').val();
        var governorate = $('#governorate').val();
        var hosturl = $('#hosturl').val();
        if (governorate > 0) {
            $.post(hosturl + "/controllers/patients.php?ac=addgovernorate_center"
                    , {governorate_center: governorate_centers, inline: patientId, governorate: governorate}, function (data) {
                $('.governorate_centers > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + governorate_centers + '</option>');
                $('#governorate_centers').select2('val', Number(data)); // select the new term
                $("#governorate_centers").select2('close'); // close the dropdown
            });
        } else {
            alert('اختر محافظة أولا ......');
        }
    });

    $("#educationhus").live('change', function () {
        var del = $(this).val();
        if (del == 0) {
            $.post(hosturl + '/controllers/patients.php?ac=getalleducation', function (data) {
                $("#educationhus").select2("val", "");
                $('#allEducation').html(data);
                $('#allEducation').modal('show');
            });
        }
    });

    $("#educationhus").select2({
        width: '240px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn blue custombtnstyle'>إضافة جديد</a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
        /* add the new term */
        var education = $('#newTerm').val();
        var hosturl = $('#hosturl').val();
        $.post(hosturl + "/controllers/patients.php?ac=addwifeeducation", {education: education, inline: patientId, type: 'h'}, function (data) {
            $('#educationhus > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + education + '</option>');
            //$('<option value="' + Number(data) + '" >' + education + '</option>').appendTo('#educationhus');
            $('#educationhus').select2('val', Number(data)); // select the new term
            $("#educationhus").select2('close'); // close the dropdown

            if (Number(data)) {
                var shortCutFunction = 'success';
                var msg = 'The education has been Added successfully';
                var title = 'Success';
                $('.todayvisit').html();
            } else {
                var shortCutFunction = 'error';
                var msg = 'Sorry , an error has been occured ';
                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);
        });
    });
    //ADD EDUCATION HUSBAND
    $("#husbandjob").live('change', function () {
        var del = $(this).val();
        if (del == 0) {
            $.post(hosturl + '/controllers/patients.php?ac=getallhusbandjobs', function (data) {
                $("#husbandjob").select2("val", "");
                $('#allEducation').html(data);
                $('#allEducation').modal('show');
            });
        }
    });

    $("#husbandjob").select2({
        width: '240px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn blue custombtnstyle'>إضافة جديد</a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
        /* add the new term */
        var husjob = $('#newTerm').val();
        var hosturl = $('#hosturl').val();
        $.post(hosturl + "/controllers/patients.php?ac=addhusbandjob", {husjob: husjob, inline: patientId}, function (data) {
            $('#husbandjob > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + husjob + '</option>');
            //$('<option value="' + Number(data) + '" >' + husjob + '</option>').appendTo('#husbandjob');
            $('#husbandjob').select2('val', Number(data)); // select the new term
            $("#husbandjob").select2('close'); // close the dropdown

            if (Number(data)) {
                var shortCutFunction = 'success';
                var msg = 'The Job has been Added successfully';
                var title = 'Success';
                $('.todayvisit').html();
            } else {
                var shortCutFunction = 'error';
                var msg = 'Sorry , an error has been occured ';
                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);
        });
    });
    //ADD SOCIAL STATUS
    $("#wifestatus").live('change', function () {
        var del = $(this).val();
        if (del == 0) {
            $.post(hosturl + '/controllers/patients.php?ac=getallwifestatus', function (data) {
                $("#wifestatus").select2("val", "");
                $('#wifestatusmodel').html(data);
                $('#wifestatusmodel').modal('show');
            });
        }
        if (del == 1) {

            $('.displaynot').css('display', 'none');
            $('#HusData').removeAttr('checked');
            $('#HusData').parent().removeClass('checked');
            $('#HusData').trigger('change');
            $('#rfc').removeAttr('required');
            $('#husdandname').removeAttr('required');
            $('.hiddenforsng').css('display', 'none');
        } else if (del == 3) {

            $('.displaynot').css('display', 'block');
            $('#husbandLive').html('  منذ');
            $('#HusData').removeAttr('checked');
            $('#HusData').parent().removeClass('checked');
            $('#HusData').trigger('change');
            $('#rfc').removeAttr('required');
            $('#husdandname').removeAttr('required');
            $('.hiddenforsng').css('display', 'none');
        } else if (del == 2) {

            $('.displaynot').css('display', '');
            $('#husbandLive').html('  منذ');
            $('#HusData').attr('checked', 'checked');
            $('#HusData').parent().addClass('checked');
            $('#HusData').trigger('change');
            $('#rfc').attr('required', true);
            $('#husdandname').attr('required', true);
            $('.hiddenforsng').css('display', '');
        } else if (del == 4) {

            $('.displaynot').css('display', '');
            $('#husbandLive').html('  منذ');
            $('#HusData').removeAttr('checked');
            $('#HusData').parent().removeClass('checked');
            $('#HusData').trigger('change');
            $('#rfc').removeAttr('required');
            $('#husdandname').removeAttr('required');
            $('.hiddenforsng').css('display', 'none');
        } else {

            $('#HusData').attr('checked', 'checked');
            $('#HusData').parent().addClass('checked');
            $('#HusData').trigger('change');
            $('.displaynot').css('display', '');
            $('#husbandLive').html('  منذ');
            $('#rfc').attr('required', true);
            $('#husdandname').attr('required', true);
            $('.hiddenforsng').css('display', '');
        }

    });

    $("#wifestatus").select2({
        width: '150px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn blue custombtnstyle'>إضافة جديد </a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
        /* add the new term */
        var status = $('#newTerm').val();
        var hosturl = $('#hosturl').val();
        $.post(hosturl + "/controllers/patients.php?ac=addwifestatus", {status: status, inline: patientId}, function (data) {
            $('#wifestatus > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + status + '</option>');
            //$('<option value="' + Number(data) + '" >' + status + '</option>').appendTo('#wifestatus');
            $('#wifestatus').select2('val', Number(data)); // select the new term
            $("#wifestatus").select2('close'); // close the dropdown

            if (Number(data)) {
                var shortCutFunction = 'success';
                var msg = 'The status has been Added successfully';
                var title = 'Success';
                $('.todayvisit').html();
            } else {
                var shortCutFunction = 'error';
                var msg = 'Sorry , an error has been occured ';
                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);
        });
    });

    $("#husstatus").select2({
        width: '150px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn blue custombtnstyle'>إضافة جديد </a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
        /* add the new term */
        var status = $('#newTerm').val();
        var hosturl = $('#hosturl').val();
        $.post(hosturl + "/controllers/patients.php?ac=addhusstatus", {status: status, inline: patientId}, function (data) {
            $('#husstatus > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + status + '</option>');
            //$('<option value="' + Number(data) + '" >' + status + '</option>').appendTo('#husstatus');
            $('#husstatus').select2('val', Number(data)); // select the new term
            $("#husstatus").select2('close'); // close the dropdown

            if (Number(data)) {
                var shortCutFunction = 'success';
                var msg = 'The status has been Added successfully';
                var title = 'Success';
                $('.todayvisit').html();
            } else {
                var shortCutFunction = 'error';
                var msg = 'Sorry , an error has been occured ';
                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);
        });
    });

    $("#husstatus").live('change', function () {
        var del = $(this).val();
        if (del == 0) {
            $.post(hosturl + '/controllers/patients.php?ac=getallhusstatus', function (data) {
                $("#husstatus").select2("val", "");
                $('#husstatusmodel').html(data);
                $('#husstatusmodel').modal('show');
            });
        }
    });

    $("#detectionid").select2({
        width: '150px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn blue custombtnstyle'>إضافة جديد</a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
        /* add the new term */
        var detection = $('#newTerm').val();
        var hosturl = $('#hosturl').val();
        $.post(hosturl + "/controllers/visits.php?ac=adddetection", {detection: detection, dtvalue: ''}, function (data) {
            $('#detectionid > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + detection + '</option>');
            //$('<option value="' + Number(data) + '" >' + detection + '</option>').appendTo('#detectionid');
            $('#detectionid').select2('val', Number(data)); // select the new term
            $("#detectionvalue_cash").val(0);
            $("#unitsConsumed").val(0);
            $("#detectionvalue_visa").val(0);
            $("#restdetectionvalue").val(0);
            $("#totaldetectionvalue").val(0);
            $('#discount').val(0);
            $("#detectionid").select2('close'); // close the dropdown

            if (Number(data)) {
                var shortCutFunction = 'success';
                var msg = 'The Detection has been Added successfully';
                var title = 'Success';
                $('.todayvisit').html();
            } else {
                var shortCutFunction = 'error';
                var msg = 'Sorry , an error has been occured ';
                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('change', '#detectionid', 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 myvalue = $(this).val();
        var controllName = $('#controllName').val();
        var patientId = $('#patientId').val();
        var hosturl = $('#hosturl').val();
        var organizations = $('#organizations').val();
        var discountRatio = $('#discountRatio').val();
        var discountRatioType = $('#discountRatioType').val();
        var doctorId = $('#for_doctor').val();
        var shareVersion = $('#shareVersion').val();
        var orgDiscountType = $('#orgDiscountType').val();
//##########################################################
        if (myvalue == -1) {
            if (shareVersion == 2) {
                if (doctorId > 0) {
                    var doctorName = $('#for_doctor').select2('data');
                    $("#doctorName").html(' ( ' + doctorName.text + ' ) ');
                    $("#detectionid").val('');
                    $('#detectionadd').html();
                    $('#detectionadd').modal('show');
                } else {
                    alert("اختر طبيب  أولا ........");
                    $("#detectionid").val('');
                }
            } else {
                $("#doctorName").html('');
                $("#detectionid").val('');
                $('#detectionadd').html();
                $('#detectionadd').modal('show');
            }

        }
//##########################################################
        else {
//##########################################################
            if (myvalue == 0) {

                if (shareVersion == 2) {
                    if (doctorId > 0) {
                        var doctorName = $('#for_doctor').select2('data');
                        $("#doctorName2").html(' ( ' + doctorName.text + ' ) ');
                        $("#detectionid").val('');
                        $("#detectionid").select2();
                        $("#detectionvalue_cash").val(0);
                        $("#unitsConsumed").val(0);
                        $("#detectionvalue_visa").val(0);
                        $("#restdetectionvalue").val(0);
                        $("#totaldetectionvalue").val(0);
                        $('#discount').val(0);
                        $.post(hosturl + '/controllers/visits.php?ac=editselect', {doctorId: doctorId, tableName: maintableName, colName: colName, patientid: patientId, mainId: id}, function (data) {

                            $("#detectionforview").html(data);
                            $("#edit_detectionforview").modal('show');
                        });
                    } else {
                        alert("اختر طبيب  أولا ........");
                        $("#detectionid").val('');
                    }
                } else {
                    $("#detectionid").val('');
                    $("#detectionid").select2();
                    $("#detectionvalue_cash").val(0);
                    $("#unitsConsumed").val(0);
                    $("#detectionvalue_visa").val(0);
                    $("#restdetectionvalue").val(0);
                    $("#totaldetectionvalue").val(0);
                    $('#discount').val(0);
                    $.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, orgDiscountType: orgDiscountType, organizations: organizations}
                , function (data) {
                    var obj = JSON.parse(data);

                    if (orgDiscountType != 3) {
                        if (discountRatio > 0 && organizations > 0) {
                            if (discountRatioType == 1) {
                                var discountValue = (discountRatio * Number(obj.price)) / 100;
                            } else {
                                var discountValue = discountRatio;
                            }

                            var restValue = Number(obj.price) - discountValue;
                            $("#detectionvalue_cash").val(restValue);
                            $('#discount').val(discountValue);
                        } else {
                            $("#detectionvalue_cash").val(obj.price);
                            $('#discount').val(0);
                        }

                        $("#detectionvalue_visa").val(0);
                        $("#totaldetectionvalue").val(obj.price);
                        $("#restdetectionvalue").val(0);
                        $("#min_paid_in").val(obj.min_paid);
                        $("#units_no_in").val(obj.units_no);
                    } else {
                        orgDiscountDetails(obj, organizations);
                    }


                });
            }

        }
    });

    function orgDiscountDetails(obj, organizations) {
        if (organizations > 0) {
            $('#discountRatio').val(obj.discountRatio);
            $('#discountRatioType').val(obj.discountRatioType);
            $('#contractPrice').val(obj.contract_price);
            $('.detectionvalue').trigger('change');
        } else {

        }

        $("#detectionvalue_visa").val(0);
        $("#totaldetectionvalue").val(obj.price);
        $("#detectionvalue_cash").val(obj.price);
        $("#restdetectionvalue").val(0);
        $("#min_paid_in").val(obj.min_paid);
        $("#units_no_in").val(obj.units_no);
    }

    $("body").on('change', '.updateDetectionModel', function () {
        var hosturl = $('#hosturl').val();
        var controllName = $('#controllName').val();
        var id = $(this).attr('data-id');
        var itr = $(this).attr('data-itr');
        var value = $("#allnewitem_value" + itr).val();
        var title = $("#allnewitem_name" + itr).val();
        var isERPPayment = 0;
        if ($("#isERPPayment" + itr).is(':checked')) {
            isERPPayment = 1;
        }
        var tablename = $("#tablename").val();
        // var patientid = $("#patientid").val();
        var colName = $("#colName").val();
        //var mainId = $("#mainId").val();
        if (id != '') {
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=updatedetection', {id: id, value: value, title: title, isERPPayment: isERPPayment}, function (data) {

                $("#detectionid option[value='" + id + "']").text(title);
                if ($("#detectionid").val() == id)
                {
                    $('#detectionid').select2('val', id);
                }
                $("#detectionid").select2({
                    width: '150px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        /* customize the no matches output */
                        return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn blue custombtnstyle'>إضافة جديد</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
                    /* add the new term */
                    var detection = $('#newTerm').val();
                    var hosturl = $('#hosturl').val();
                    $.post(hosturl + "/controllers/visits.php?ac=adddetection", {detection: detection, inline: 1}, function (data) {
                        $('#detectionid > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + detection + '</option>');
                        //$('<option value="' + Number(data) + '" >' + detection + '</option>').appendTo('#detectionid');
                        $('#detectionid').select2('val', Number(data)); // select the new term
                        $("#detectionvalue_cash").val(0);
                        $("#unitsConsumed").val(0);
                        $("#detectionvalue_visa").val(0);
                        $("#restdetectionvalue").val(0);
                        $("#totaldetectionvalue").val(0);
                        $('#discount').val(0);
                        $("#detectionid").select2('close'); // close the dropdown

                        if (Number(data)) {
                            var shortCutFunction = 'success';
                            var msg = 'The Detection has been Added successfully';
                            var title = 'Success';
                            $('.todayvisit').html();
                        } else {
                            var shortCutFunction = 'error';
                            var msg = 'Sorry , an error has been occured ';
                            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', '.actAsRadioBtn', function () {
        var thisis = $(this);
        var itr = thisis.attr('data-itr');
        var colName = thisis.attr('data-colName');
        if (thisis.is(':checked')) {
            if (thisis.attr('data-colName') == "iserppayment" && $('#iserpzerobill' + itr).is(':checked')) {
                $('#iserpzerobill' + itr).prop('checked', false).change();//.uniform('refresh');
            }
            if (thisis.attr('data-colName') == "iserpzerobill" && $('#isERPPayment' + itr).is(':checked')) {
                $('#isERPPayment' + itr).prop('checked', false).change();//.uniform('refresh');
            }

        }
    });
    //blood type
    $("#bloodtype").live('change', function () {
        var del = $(this).val();
        if (del == 0) {
            $.post(hosturl + '/controllers/patients.php?ac=getallbloodtype', function (data) {
                $("#bloodtype").select2("val", "");
                $('#wifestatusmodel').html(data);
                $('#wifestatusmodel').modal('show');
            });
        }
    });

    $("#bloodtype").select2({
        width: '240px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn blue custombtnstyle'>إضافة جديد</a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
        /* add the new term */
        var bloodtype = $('#newTerm').val();
        var hosturl = $('#hosturl').val();
        $.post(hosturl + "/controllers/patients.php?ac=addbloodtype", {bloodtype: bloodtype, inline: patientId, type: 'w'}, function (data) {
            $('.bloodtype > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + bloodtype + '</option>');
            //$('<option value="' + Number(data) + '" >' + bloodtype + '</option>').appendTo('#bloodtype');
            $('#bloodtype').select2('val', Number(data)); // select the new term
            $("#bloodtype").select2('close'); // close the dropdown
            if (Number(data)) {
                var shortCutFunction = 'success';
                var msg = 'The blood type has been Added successfully';
                var title = 'Success';
                $('.todayvisit').html();
            } else {
                var shortCutFunction = 'error';
                var msg = 'Sorry , an error has been occured ';
                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);
        });
    });
    // blood type husband
    $("#bloodtypehus").live('change', function () {
        var del = $(this).val();
        if (del == 0) {
            $.post(hosturl + '/controllers/patients.php?ac=getallbloodtype', function (data) {
                $("#bloodtypehus").select2("val", "");
                $('#wifestatusmodel').html(data);
                $('#wifestatusmodel').modal('show');
            });
        }
    });

    $("#bloodtypehus").select2({
        width: '240px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn blue custombtnstyle'>إضافة جديد</a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
        /* add the new term */
        var bloodtype = $('#newTerm').val();
        var hosturl = $('#hosturl').val();
        $.post(hosturl + "/controllers/patients.php?ac=addbloodtype", {bloodtype: bloodtype, inline: patientId, type: 'h'}, function (data) {
            $('#bloodtypehus > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + bloodtype + '</option>');
            //$('<option value="' + Number(data) + '" >' + bloodtype + '</option>').appendTo('#bloodtypehus');
            $('#bloodtypehus').select2('val', Number(data)); // select the new term
            $("#bloodtypehus").select2('close'); // close the dropdown

            if (Number(data)) {
                var shortCutFunction = 'success';
                var msg = 'The blood type has been Added successfully';
                var title = 'Success';
                $('.todayvisit').html();
            } else {
                var shortCutFunction = 'error';
                var msg = 'Sorry , an error has been occured ';
                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);
        });
    });
    //
    //EDIT WIFE TYPE
    $("#selectWifeType").live('click', function ()
    {
        var id = $(this).attr('data-id');
        var name = $(this).text();
        $('#editwifetype_submit').removeAttr('disabled');
        $("#wifetype_name").val(name);
        $("#wifetype_id").val(id);
    });
    $("#editwifetype_submit").live('click', function () {
        var id = $(this).attr('data-id');
        var itr = $(this).attr('data-itr');
        var name = $("#wifetype_name" + itr).val();
        $.post(hosturl + '/controllers/patients.php?ac=updatewifetype', {id: id, name: name}, function (data) {
            $('#allWifeTypes').html(data);
            $('#wifetype').load(hosturl + '/controllers/patients.php?ac=wifetypeafterup');
        });
    });
    //EDIT Education
    $("#selectEducation").live('click', function ()
    {
        var id = $(this).attr('data-id');
        var name = $(this).text();
        $('#education_submit').removeAttr('disabled');
        $("#education_name").val(name);
        $("#education_id").val(id);
    });
    $("#education_submit").live('click', function () {



        var id = $(this).attr('data-id');
        var itr = $(this).attr('data-itr');
        var name = $("#wifetype_name" + itr).val();
        $.post(hosturl + '/controllers/patients.php?ac=updateeducation', {id: id, name: name}, function (data) {
            $('#allEducationUp').html(data);
            $('#education').load(hosturl + '/controllers/patients.php?ac=wifeteducationafterup');
            $('#educationhus').load(hosturl + '/controllers/patients.php?ac=wifeteducationafterup');
        });
    });
    //EDIT WifeJob
    $("#selectWifeJob").live('click', function ()
    {
        var id = $(this).attr('data-id');
        var name = $(this).text();
        $('#wifejob_submit').removeAttr('disabled');
        $("#wifejob_name").val(name);
        $("#wifejob_id").val(id);
    });
    $("#wifejob_submit").live('click', function () {



        var id = $(this).attr('data-id');
        var itr = $(this).attr('data-itr');
        var name = $("#wifejob_name" + itr).val();
        $.post(hosturl + '/controllers/patients.php?ac=updatewifejob', {id: id, name: name}, function (data) {
            $('#allWifeJobUpdate').html(data);
            $('#wifejob').load(hosturl + '/controllers/patients.php?ac=wifejobafterup');
            $('#wifestatus').load(hosturl + '/controllers/patients.php?ac=wifejobafterup');
        });
    });
    //EDIT WIFE STATUS
    $("#selectWifeStatus").live('click', function ()
    {
        bl_submit
        var id = $(this).attr('data-id');
        var name = $(this).text();
        $('#wifestatus_submit').removeAttr('disabled');
        $("#wifestatus_name").val(name);
        $("#wifestatus_id").val(id);
    });
    $("#wifestatus_submit").live('click', function () {


        var id = $(this).attr('data-id');
        var itr = $(this).attr('data-itr');
        var name = $("#wifestatus_name" + itr).val();
        $.post(hosturl + '/controllers/patients.php?ac=updatewifestatus', {id: id, name: name}, function (data) {
            $('#getWifeStatus').html(data);
            $('#wifestatus').load(hosturl + '/controllers/patients.php?ac=wifestatusafterup');
        });
    });
    //EDIT BLOOD TYPES
    $("#selectBL").live('click', function ()
    {
        var id = $(this).attr('data-id');
        var name = $(this).text();
        $('#bl_submit').removeAttr('disabled');
        $("#bl_name").val(name);
        $("#bl_id").val(id);
    });
    $("#bl_submit").live('click', function () {

        var id = $(this).attr('data-id');
        var itr = $(this).attr('data-itr');
        var name = $("#bl_name" + itr).val();
        $.post(hosturl + '/controllers/patients.php?ac=updatebl', {id: id, name: name}, function (data) {
            $('#getBloodTypes').html(data);
            $('#bloodtype').load(hosturl + '/controllers/patients.php?ac=bloodtypeafterup');
            $('#bloodtypehus').load(hosturl + '/controllers/patients.php?ac=bloodtypeafterup');
        });
    });
    //EDIT HUS TYPE
    $("#selectHusType").live('click', function ()
    {
        var id = $(this).attr('data-id');
        var name = $(this).text();
        $('#hustype_submit').removeAttr('disabled');
        $("#hustype_name").val(name);
        $("#hustype_id").val(id);
    });
    $("#hustype_submit").live('click', function () {


        var id = $(this).attr('data-id');
        var itr = $(this).attr('data-itr');
        var name = $("#hustype_name" + itr).val();
        $.post(hosturl + '/controllers/patients.php?ac=updatehus', {id: id, name: name}, function (data) {
            $('#husBandTypes').html(data);
            $('#husbandtype').load(hosturl + '/controllers/patients.php?ac=husbandtypeafterup');
        });
    });
    //EDIT HUS JOBS
    $("#selectHusJobs").live('click', function ()
    {
        var id = $(this).attr('data-id');
        var name = $(this).text();
        $('#husjob_submit').removeAttr('disabled');
        $("#husjob_name").val(name);
        $("#husjob_id").val(id);
    });
    $("#husjob_submit").live('click', function () {



        var id = $(this).attr('data-id');
        var itr = $(this).attr('data-itr');
        var name = $("#husjob_name" + itr).val();
        $.post(hosturl + '/controllers/patients.php?ac=updatehusjob', {id: id, name: name}, function (data) {
            $('#getHusbandJobs').html(data);
            $('#husbandjob').load(hosturl + '/controllers/patients.php?ac=husbandjobafterup');
        });
    });
    //## WIFE NICK NAME
    $("#wifetype").live('change', function () {
        var del = $(this).val();
        if (del == 0) {
            $.post(hosturl + '/controllers/patients.php?ac=getallwifetype', function (data) {
                $("#wifetype").select2("val", "");
                $('#wifetypedel').html(data);
                $('#wifetypedel').modal('show');
            });
        }
    });
    $("#wifetype").select2({
        width: '240px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn blue custombtnstyle'>إضافة جديد</a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
        /* add the new term */
        var wifetype = $('#newTerm').val();
        var hosturl = $('#hosturl').val();
        $.post(hosturl + "/controllers/patients.php?ac=addwifetype", {wifetype: wifetype, inline: patientId}, function (data) {
            $('#wifetype > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + wifetype + '</option>');
            //$('<option value="' + Number(data) + '" >' + wifetype + '</option>').appendTo('#wifetype');
            $('#wifetype').select2('val', Number(data)); // select the new term
            $("#wifetype").select2('close'); // close the dropdown

            if (Number(data)) {
                var shortCutFunction = 'success';
                var msg = 'The wife type has been Added successfully';
                var title = 'Success';
                $('.todayvisit').html();
            } else {
                var shortCutFunction = 'error';
                var msg = 'Sorry , an error has been occured ';
                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);
        });
    });
    $(".addwtRow").live('click', function () {
        var dtcount = $("#dtcount").val();
        var selectClass = $(this).attr('data-selectClass');
        var tablename = $(this).attr('data-tableName');
        var governorate = $('#governorate').val();
        if (tablename == 'governorate' || tablename == 'governorate_centers') {
            var colName = 'name';
        } else {
            var colName = 'title';
        }

        var fn = $(this).attr('data-fun');
        dtcount++;
        $.post(hosturl + "/controllers/patients.php?ac=addwtRow", {tablename: tablename, governorate: governorate}, function (data) {

            var dataid = Number(data);
            $('.' + selectClass + ' > .deleteoptincompo').before('<option value="' + dataid + '" ></option>');
            $(".ptAddTbl").prepend('<tr class="textcenter" >\
                            <td>\
                                <a class="deleteelement fa fa-times btn red fleft"  data-selectClass="' + selectClass + '"  data-select2="yes" data-id="' + dataid + '" data-link="patients"  data-fun="' + fn + '"></a>\
                            </td>\
                            <td style="width: 100%">\
                                <input type="text" class="form-control updateElementSelect" data-selectClass="' + selectClass + '"  data-select2="yes" data-id="' + dataid + '" data-colName="' + colName + '" data-tableName="' + tablename + '" value=""/>\
                            </td>\
                        </tr>');
        });
        $("#dtcount").val(dtcount);
    });
//HUSBAND TYPE
    $("#husbandtype").live('change', function () {
        var del = $(this).val();
        if (del == 0) {
            $.post(hosturl + '/controllers/patients.php?ac=getallhustype', function (data) {
                $("#husbandtype").select2("val", "");
                $('#husbandtypedel').html(data);
                $('#husbandtypedel').modal('show');
            });
        }
    });
    $("#husbandtype").select2({
        width: '240px',
        allowClear: true,
        formatNoMatches: function (term) {
            /* customize the no matches output */
            return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn blue custombtnstyle'>إضافة جديد</a>"
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
        /* add the new term */
        var husbandtype = $('#newTerm').val();
        var hosturl = $('#hosturl').val();
        $.post(hosturl + "/controllers/patients.php?ac=addhusbandtype", {husbandtype: husbandtype, inline: patientId}, function (data) {
            $('#husbandtype > .deleteoptincompo').before('<option value="' + Number(data) + '" >' + husbandtype + '</option>');
            //$('<option value="' + Number(data) + '" >' + husbandtype + '</option>').appendTo('#husbandtype');
            $('#husbandtype').select2('val', Number(data)); // select the new term
            $("#husbandtype").select2('close'); // close the dropdown

            if (Number(data)) {
                var shortCutFunction = 'success';
                var msg = 'The husband type has been Added successfully';
                var title = 'Success';
                $('.todayvisit').html();
            } else {
                var shortCutFunction = 'error';
                var msg = 'Sorry , an error has been occured ';
                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);
        });
    });
    var sortablebtn = function () {
        $("#sortable").sortable({
            update: function () {
                var datasorted = $("#sortable").sortable('serialize');
                $.ajax({
                    url: hosturl + '/controllers/index.php?ac=sortable',
                    type: "POST",
                    data: {datasorted: datasorted},
                    error: function () {
                        alert("There was an error while sortable.");
                    }
                });
            }
        });
    };
    var updatelastpatient = function () {

    }

    var ptfile = function () {
        $('.patientsfile').click(function () {


            var ptID = $('#patientid').val();
            $.ajax({
                url: hosturl + "/controllers/patients.php?ac=patientfiles",
                type: 'POST',
                data: {id: ptID},
                success: function (data) {
                    $('#ptfilemodel').modal('show');
                    $('#showdatapatientfiles').html(data);
                }

            });
        });
    }
    var filedownload = function () {
        $('#downloadfile').click(function () {


        });
    }
    var checkuser = function () {
        $(".checkpass").click(function () {

            var pass = $("#passforcheck").val();
            $.ajax({
                url: hosturl + "/controllers/setup.php?ac=checkpass",
                type: 'POST',
                data: {pass: pass},
                success: function (data) {
                    $('.dataokay').html(data);
                }

            });
        });
    }
    var visitviewed = function () {
        $('body').on('click', '.visitviewed', function () {
            var visitID = $(this).attr('data-id');
            var link = $(this).attr('data-link');
            $.ajax({
                url: hosturl + "/controllers/visits.php?ac=visitviewed",
                type: 'POST',
                data: {id: visitID},
                success: function (data) {
                    if (link == -1) {
                        $('#visitDoneRow' + visitID).addClass("visitDone");
                    }
                }
            });
        });
    }

    var cleantables = function () {
        $('.clntbls').click(function () {
            $('.clntbls').button('loading');
            var emptyalltables = $(this).attr('data-all');
            //alert(emptyalltables);
            $.ajax({
                url: hosturl + "/controllers/setup.php?ac=settingdatabase",
                type: 'POST',
                data: {emptyalltables: emptyalltables},
                success: function (data) {
                    setTimeout(function () {
                        $('.clntbls').button('reset');
                    });
                    if (data) {

                        var shortCutFunction = 'success';
                        var msg = 'The Tables has been Empty Successfully';
                        var title = 'Success';
                    } else {
                        var shortCutFunction = 'error';
                        var msg = 'Sorry , an error has been occured ';
                        var title = 'Error';
                    }
                    toastr.options = {
                        closeButton: $('#closeButton').prop('checked'),
                        debug: $('#debugInfo').prop('checked'),
                        positionClass: $('#positionGroup input:checked').val() || 'toast-top-left',
                        onclick: null
                    };
                    //var $toast = toastr[shortCutFunction](msg, title);
                }

            });
            //alert('why');
        });
    }
    var cleantablesdefault = function () {
        $('.clntblsdefault').click(function () {
            $('.clntblsdefault').button('loading');
            var emptyalltables = $(this).attr('data-all');
            //alert(emptyalltables);
            $.ajax({
                url: hosturl + "/controllers/setup.php?ac=settingdatabase",
                type: 'POST',
                data: {emptyalltables: emptyalltables},
                success: function (data) {
                    //alert(data);
                    setTimeout(function () {
                        $('.clntblsdefault').button('reset');
                    });
                    if (data) {
                        var shortCutFunction = 'success';
                        var msg = 'The Tables has been Empty Successfully';
                        var title = 'Success';
                    } else {
                        var shortCutFunction = 'error';
                        var msg = 'Sorry , an error has been occured ';
                        var title = 'Error';
                    }
                    toastr.options = {
                        closeButton: $('#closeButton').prop('checked'),
                        debug: $('#debugInfo').prop('checked'),
                        positionClass: $('#positionGroup input:checked').val() || 'toast-top-left',
                        onclick: null
                    };
                    //var $toast = toastr[shortCutFunction](msg, title);
                }

            });
            //alert('why');
        });
    }
    var erpDb = function () {
        jQuery.fn.forcepositivefloat = function () {

            return this.each(function () {
                $(this).keydown(function (e) {
                    var presedval = e.key;
                    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 ||
                            // pageup and pagedown
                            key == 33 || key == 34 ||
                            // left and right arrows
                            key == 37 || key == 39 ||
                            // Del and Ins
                            key == 46 || key == 45 ||
                            //dot or point  .  on keyboard  for one time
                                    (key == 110 && $(this).val().indexOf(".") < 0) ||
                                    (key == 190 && $(this).val().indexOf(".") < 0 && presedval == ".") ||
                                    (e.ctrlKey && (key == 67 || key == 86 || key == 65)))//allow copy && paste && ctrl+a)
                        return true;

                    return false;
                });
            });
        }


        $('#searchNotPayedBillsERP').live('click', function (e) {
            var patientid = $('#patientvisitid').val();
            var branch_id = $('#branch_id').val();

            if (patientid > 0 && branch_id > 0) {
                $('#clientIdForERP').val(patientid);
                $('#billsItr').val(0);
                $('#ErpBillBranchId').val(branch_id);
                $('#notPayedERPBillsTbody').html('');
                $.post(hosturl + '/controllers/visits.php?ac=notPayedERPBills', {clientid: patientid}, function (res) {
                    var html = '';
                    var billsItr = 0;
                    res = JSON.parse(res)
                    res['sell'].forEach(function (item, index) {
                        html += '<tr>' +
                                '<td>' + item.id + '</td>' +
                                '<td>' + item.date + '</td>' +
                                '<td>' + item.billtotal + '</td>' +
                                '<td>' + item.remain + '</td>' +
                                '<td>' + item.days + '</td>' +
                                '<td>' +
                                '   <label>كاش</label>' +
                                '   <input type="text" name="cashPay' + billsItr + '" id="cashPay' + billsItr + '" data-remain="' + item.remain + '" data-itr="' + billsItr + '" class="positivefloat billPayment" style="width:110px;" value="0">' +
                                '   <label>فيزا</label>' +
                                '   <input type="text" name="visaPay' + billsItr + '" id="visaPay' + billsItr + '" data-remain="' + item.remain + '" data-itr="' + billsItr + '" class="positivefloat billPayment" style="width:110px;" value="0">' +
                                '   <label>خصم</label>' +
                                '   <input type="text" name="billDis' + billsItr + '" id="billDis' + billsItr + '" data-remain="' + item.remain + '" data-itr="' + billsItr + '" class="positivefloat billPayment" style="width:110px;" value="0">' +
                                '   <label>ملاحظة</label>' +
                                '   <textarea rows="1" name="note' + billsItr + '" id="note' + billsItr + '" data-itr="' + billsItr + '" style="width: 200px; vertical-align: bottom;"></textarea>' +
                                '   <input type="hidden" name="billid' + billsItr + '" id="billid' + billsItr + '" value="' + item.id + '"></td>' +
                                '</tr>';
                        billsItr++;
                    });
                    $('#notPayedERPBillsTbody').html(html);
                    $('#billsItr').val(billsItr);


                    html = '';
                    billsItr = 0;
                    res['ret'].forEach(function (item, index) {
                        html += '<tr>' +
                                '<td>' + item.id + '</td>' +
                                '<td>' + item.date + '</td>' +
                                '<td>' + item.billtotal + '</td>' +
                                '<td>' + Math.abs(item.payed) + '</td>' +
                                '<td>' + item.days + '</td>' +
                                '<td>' +
                                '   <label>كاش</label>' +
                                '   <input type="text" name="cashPayRet' + billsItr + '" id="cashPayRet' + billsItr + '" data-payed="' + item.remain + '" data-itr="' + billsItr + '" class="positivefloat billPaymentRet" style="width:110px;" value="0">' +
                                '   <label>فيزا</label>' +
                                '   <input type="text" name="visaPayRet' + billsItr + '" id="visaPayRet' + billsItr + '" data-payed="' + item.remain + '" data-itr="' + billsItr + '" class="positivefloat billPaymentRet" style="width:110px;" value="0">' +
                                '   <label>خصم</label>' +
                                '   <input type="text" name="billDisRet' + billsItr + '" id="billDisRet' + billsItr + '" data-payed="' + item.remain + '" data-itr="' + billsItr + '" class="positivefloat billPaymentRet" style="width:110px;" value="0">' +
                                '   <label>ملاحظة</label>' +
                                '   <textarea rows="1" name="noteRet' + billsItr + '" id="noteRet' + billsItr + '" data-itr="' + billsItr + '" style="width: 200px; vertical-align: bottom;"></textarea>' +
                                '   <input type="hidden" name="billidRet' + billsItr + '" id="billidRet' + billsItr + '" value="' + item.id + '"></td>' +
                                '</tr>';
                        billsItr++;
                    });
                    $('#notPayedERPBillsRetTbody').html(html);
                    $('#billsItrRet').val(billsItr);


                    $('#notPayedERPBillsModal').modal('show');
                    $(".positivefloat").forcepositivefloat();
                });
            } else {
                alert('لابد من تحديد المريض والفرع أولا . ');
            }
        });



        $('.billPayment').live('keyup', function (e) {
            var itr = $(this).data('itr');
            var remain = Number($(this).data('remain'));
            var cashPay = Number($('#cashPay' + itr).val());
            var visaPay = Number($('#visaPay' + itr).val());
            var billDis = Number($('#billDis' + itr).val());

            var pay = cashPay + visaPay - billDis;

            if (pay > remain) {
                $('#cashPay' + itr).val(0);
                $('#visaPay' + itr).val(0);
                $('#billDis' + itr).val(0);
                $(this).val(remain)
            }
        });
        $('.billPaymentRet').live('keyup', function (e) {
            var itr = $(this).data('itr');
            var remain = Math.abs(Number($(this).data('payed')));
            var cashPay = Number($('#cashPayRet' + itr).val());
            var visaPay = Number($('#visaPayRet' + itr).val());
            var billDis = Number($('#billDisRet' + itr).val());

            var pay = cashPay + visaPay - billDis;

            if (pay > remain) {
                $('#cashPayRet' + itr).val(0);
                $('#visaPayRet' + itr).val(0);
                $('#billDisRet' + itr).val(0);
                $(this).val(remain)
            }
        });
        $('#payERPBills').live('click', function (e) {
            var thisBtn = $(this);
            if (!thisBtn.hasClass('processing...')) {
                thisBtn.addClass('processing...');
                $.post(hosturl + '/controllers/visits.php?ac=payERPBills', $("#notPayedERPBillsForm").serialize(), function (res) {
                    $('#notPayedERPBillsModal').modal('hide');
                    if (res != -1) {
                        console.log(res);
                        $("#printRDiv").html(res);
                        $.print("#printRDiv");
                        $("#printRDiv").html("");
                    }
                    thisBtn.removeClass('processing...');
                });
            }
        });


//DB
        $('.saveErpDB').click(function () {
            var erpDB = $('#erpDB').val();
//                    if (erpDB != "") {
            $('.saveErpDB').button('loading');
            $.ajax({
                url: hosturl + "/controllers/setup.php?ac=saveErpDB",
                type: 'POST',
                data: {erpDB: erpDB},
                success: function (data) {
                    if (erpDB == "") {
                        $("#erpDBSave").select2('data', {id: 0, text: ''});
                    }
                    setTimeout(function () {
                        $('.saveErpDB').button('reset');
                    });
                    if (data) {
                        var shortCutFunction = 'success';
                        var msg = ''; //'The Tables has been Empty Successfully';
                        var title = 'Success';
                    } else {
                        var shortCutFunction = 'error';
                        var msg = 'Sorry , an error has been occured ';
                        var title = 'Error';
                    }
                    toastr.options = {
                        closeButton: $('#closeButton').prop('checked'),
                        debug: $('#debugInfo').prop('checked'),
                        positionClass: $('#positionGroup input:checked').val() || 'toast-top-left',
                        onclick: null
                    };
                    //var $toast = toastr[shortCutFunction](msg, title);
                }

            });
//                    }
        });
        //save
        $("#erpDBSave").select2({
            placeholder: "Select save ...",
            allowClear: true,
            minimumInputLength: 0,
            //  minimumInputLength: 3,
            //quietMillis: 100,
            //width: '150px!important',
            ajax: {
                url: hosturl + "/controllers/setup.php?ac=getErpSave",
                dataType: 'json',
                data: function (term, page) {
                    //  alert(term);
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                    };
                },
                results: function (data) {

                    // alert(term);
                    return {results: data};
                }
            },
            formatResult: function (data) {
                return  data.text + '<span  style="text-align: left;  float: left;  width: 30%;">';
            },
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                //# to prevent add client .

                var data = {id: item[0], text: item[1]};
                callback(data);
            }
        }).on('change', function () {
            var erpdbsave = Number($("#erpDBSave").val());
            var erpdbsavename = '';
            if (erpdbsave > 0) {
                erpdbsavename = $("#erpDBSave").select2('data').text;
            }
            $('#erpdbsavename').val(erpdbsavename);
        });
        $('.saveErpSave').click(function () {
            var erpDBSave = $('#erpDBSave').val();
            if (erpDBSave != "") {
                $('.saveErpSave').button('loading');
                $.ajax({
                    url: hosturl + "/controllers/setup.php?ac=erpDBSave",
                    type: 'POST',
                    data: {erpDBSave: erpDBSave},
                    success: function (data) {
                        setTimeout(function () {
                            $('.saveErpSave').button('reset');
                        });
                        if (data) {
                            var shortCutFunction = 'success';
                            var msg = ''; //'The Tables has been Empty Successfully';
                            var title = 'Success';
                        } else {
                            var shortCutFunction = 'error';
                            var msg = 'Sorry , an error has been occured ';
                            var title = 'Error';
                        }
                        toastr.options = {
                            closeButton: $('#closeButton').prop('checked'),
                            debug: $('#debugInfo').prop('checked'),
                            positionClass: $('#positionGroup input:checked').val() || 'toast-top-left',
                            onclick: null
                        };
                        //var $toast = toastr[shortCutFunction](msg, title);
                    }

                });
            }
        });
        //visaaccount
        $("#erpDBVisaAccount").select2({
            placeholder: "اختر حساب الفيزا ",
            minimumInputLength: 0,
            //  minimumInputLength: 3,
            quietMillis: 100,
            width: '150px!important',
            ajax: {
                url: hosturl + "/controllers/setup.php?ac=geterpVisaAccounts",
                dataType: 'json',
                data: function (term, page) {
                    //  alert(term);
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                    };
                },
                results: function (data) {

                    // alert(term);
                    return {results: data};
                }
            },
            formatResult: function (data) {
                return  data.text + '<span  style="text-align: left;  float: left;  width: 30%;">';
            },
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                //# to prevent add client .

                var data = {id: item[0], text: item[1]};
                callback(data);
            }
        });
        $('.saveERPDBVisaAccount').click(function () {
            var erpDBVisaAccount = $('#erpDBVisaAccount').val();
            if (erpDBVisaAccount != "") {
                $('.saveERPDBVisaAccount').button('loading');
                $.ajax({
                    url: hosturl + "/controllers/setup.php?ac=saveERPDBVisaAccount",
                    type: 'POST',
                    data: {erpDBVisaAccount: erpDBVisaAccount},
                    success: function (data) {
                        setTimeout(function () {
                            $('.saveERPDBVisaAccount').button('reset');
                        });
                        if (data) {
                            var shortCutFunction = 'success';
                            var msg = ''; //'The Tables has been Empty Successfully';
                            var title = 'Success';
                        } else {
                            var shortCutFunction = 'error';
                            var msg = 'Sorry , an error has been occured ';
                            var title = 'Error';
                        }
                        toastr.options = {
                            closeButton: $('#closeButton').prop('checked'),
                            debug: $('#debugInfo').prop('checked'),
                            positionClass: $('#positionGroup input:checked').val() || 'toast-top-left',
                            onclick: null
                        };
                        //var $toast = toastr[shortCutFunction](msg, title);
                    }

                });
            }
        });

        //member save
        $(".erpDBSaveMem").select2({
            placeholder: "Select save ...",
            allowClear: true,
            minimumInputLength: 0,
            //  minimumInputLength: 3,
            //quietMillis: 100,
            //width: '150px!important',
            ajax: {
                url: hosturl + "/controllers/setup.php?ac=getErpSave",
                dataType: 'json',
                data: function (term, page) {
                    //  alert(term);
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                    };
                },
                results: function (data) {
                    // alert(term);
                    return {results: data};
                }
            },
            formatResult: function (data) {
                return  data.text + '<span  style="text-align: left;  float: left;  width: 30%;">';
            },
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                //# to prevent add client .

                var data = {id: item[0], text: item[1]};
                callback(data);
            }
        }).on('change', function () {
            var val = Number($(this).val());
            var memid = Number($(this).data('id'));
            if (val == 0) {
                var name = '';
            } else {
                var name = $('#erpDBSaveMem' + memid).select2('data').text;
            }

            if (memid > 0) {
                $.ajax({
                    url: hosturl + "/controllers/_member.php?ac=updateerpsaveid",
                    type: 'POST',
                    data: {memid: memid, val: val, name: name},
                    success: function (data) {
                        if (Number(data) > 0) {
                            var shortCutFunction = 'success';
                            var msg = ''; //'The Tables has been Empty Successfully';
                            var title = 'Success';
                        } else {
                            var shortCutFunction = 'error';
                            var msg = 'Sorry , an error has been occured ';
                            var title = 'Error';
                        }
                        toastr.options = {
                            closeButton: $('#closeButton').prop('checked'),
                            debug: $('#debugInfo').prop('checked'),
                            positionClass: $('#positionGroup input:checked').val() || 'toast-top-left',
                            onclick: null
                        };
                        var $toast = toastr[shortCutFunction](msg, title);
                    }

                });
            }
        });
        $(document).ready(function () {
            var erpdbsave = Number($('#save').val());
            var erpdbsavename = $('#erpdbsavename').val();
            if (erpdbsave > 0) {
                $("#erpDBSave").select2('data', {id: erpdbsave, text: erpdbsavename});
            }
//
            var erpDBVisaAccountId = Number($('#erpDBVisaAccountId').val());
            var erpDBVisaAccountName = $('#erpDBVisaAccountName').val();
            if (erpDBVisaAccountId > 0) {
                $("#erpDBVisaAccount").select2('data', {id: erpDBVisaAccountId, text: erpDBVisaAccountName});
            }

            $("input.erpDBSaveMem").each(function () {
                var memid = Number($(this).attr('data-id'));
                var saveid = Number($('#saveid' + memid).val());
                var savename = $('#savename' + memid).val();
                if (saveid > 0 && savename != "") {
                    $('#erpDBSaveMem' + memid).select2('data', {id: saveid, text: savename});
                }
            });
        });
        //sync patients to erp
        $('.syncPatientsToERP').click(function () {
            $('.syncPatientsToERP').button('loading');
            $.ajax({
                url: hosturl + "/controllers/patients.php?ac=addAllPatientsToERP",
                type: 'POST',
                success: function (data) {
                    setTimeout(function () {
                        $('.syncPatientsToERP').button('reset');
                    });
                    if (data) {
                        var shortCutFunction = 'success';
                        var msg = ''; //'The Tables has been Empty Successfully';
                        var title = 'Success';
                    } else {
                        var shortCutFunction = 'error';
                        var msg = 'Sorry , an error has been occured ';
                        var title = 'Error';
                    }
                    toastr.options = {
                        closeButton: $('#closeButton').prop('checked'),
                        debug: $('#debugInfo').prop('checked'),
                        positionClass: $('#positionGroup input:checked').val() || 'toast-top-left',
                        onclick: null
                    };
                    //var $toast = toastr[shortCutFunction](msg, title);
                }
            });
        });
        //sync detections to erp
        $('.syncDetectionsToERP').click(function () {
            $('.syncDetectionsToERP').button('loading');
            $.ajax({
                url: hosturl + "/controllers/visits.php?ac=addAllDetectionToERP",
                type: 'POST',
                success: function (data) {
                    setTimeout(function () {
                        $('.syncDetectionsToERP').button('reset');
                    });
                    if (data) {
                        var shortCutFunction = 'success';
                        var msg = ''; //'The Tables has been Empty Successfully';
                        var title = 'Success';
                    } else {
                        var shortCutFunction = 'error';
                        var msg = 'Sorry , an error has been occured ';
                        var title = 'Error';
                    }
                    toastr.options = {
                        closeButton: $('#closeButton').prop('checked'),
                        debug: $('#debugInfo').prop('checked'),
                        positionClass: $('#positionGroup input:checked').val() || 'toast-top-left',
                        onclick: null
                    };
                    //var $toast = toastr[shortCutFunction](msg, title);
                }
            });
        });
        //sync doctors to erp
        $('.syncDoctorsToERP').click(function () {
            $('.syncDoctorsToERP').button('loading');
            $.ajax({
                url: hosturl + "/controllers/_member.php?ac=addAllDoctorsToERP",
                type: 'POST',
                success: function (data) {
                    setTimeout(function () {
                        $('.syncDoctorsToERP').button('reset');
                    });
                    if (data) {
                        var shortCutFunction = 'success';
                        var msg = ''; //'The Tables has been Empty Successfully';
                        var title = 'Success';
                    } else {
                        var shortCutFunction = 'error';
                        var msg = 'Sorry , an error has been occured ';
                        var title = 'Error';
                    }
                    toastr.options = {
                        closeButton: $('#closeButton').prop('checked'),
                        debug: $('#debugInfo').prop('checked'),
                        positionClass: $('#positionGroup input:checked').val() || 'toast-top-left',
                        onclick: null
                    };
                    //var $toast = toastr[shortCutFunction](msg, title);
                }
            });
        });
        //sync doctors to erp
        $('.syncInvestigationsToERP').click(function () {
            $('.syncInvestigationsToERP').button('loading');
            $.ajax({
                url: hosturl + "/controllers/addinvestigation.php?ac=addAllInvestigationsToERP",
                type: 'POST',
                success: function (data) {
                    setTimeout(function () {
                        $('.syncInvestigationsToERP').button('reset');
                    });
                    if (data) {
                        var shortCutFunction = 'success';
                        var msg = ''; //'The Tables has been Empty Successfully';
                        var title = 'Success';
                    } else {
                        var shortCutFunction = 'error';
                        var msg = 'Sorry , an error has been occured ';
                        var title = 'Error';
                    }
                    toastr.options = {
                        closeButton: $('#closeButton').prop('checked'),
                        debug: $('#debugInfo').prop('checked'),
                        positionClass: $('#positionGroup input:checked').val() || 'toast-top-left',
                        onclick: null
                    };
                    //var $toast = toastr[shortCutFunction](msg, title);
                }
            });
        });
    }
    var publicjs = function () {
//called when key is pressed in textbox
        $(".digitsOnly").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                return false;
            }
        });
        /*$(".patientvisitidCheck").change(function () {
         var visitpid = $(this).val();
         var date = $('#visitdate').val();
         $.post(hosturl + '/controllers/visits.php?ac=checkvisipatient', {visitid: visitpid, date: date}, function (data) {
         if (Number(data) == 1) {
         $("#visitaddsubmit").attr('disabled', 'disabled');
         $("#checkvisitbefore").css('display', '');
         $("#checkvisitbefore").css('color', 'red');
         } else {
         $("#visitaddsubmit").removeAttr('disabled');
         $("#checkvisitbefore").css('display', 'none');
         $("#checkvisitbefore").css('color', '');
         }
         });
         });
         
         $(".patientvisitidCheckDate").change(function () {
         var visitpid = $('#patientvisitid').val();
         var date = $('#visitdate').val();
         $.post(hosturl + '/controllers/visits.php?ac=checkvisipatient', {visitid: visitpid, date: date}, function (data) {
         if (Number(data) == 1) {
         $("#visitaddsubmit").attr('disabled', 'disabled');
         $("#checkvisitbefore").css('display', '');
         $("#checkvisitbefore").css('color', 'red');
         } else {
         $("#visitaddsubmit").removeAttr('disabled');
         $("#checkvisitbefore").css('display', 'none');
         $("#checkvisitbefore").css('color', '');
         }
         });
         });*/


        $("#detectionadd_submit").click(function () {
            var detectiontype = $('#detectiontp').val();
            var detectionvl = $('#detectionvl').val();
            var doctorId = $('#for_doctor').val();
            var shareVersion = $('#shareVersion').val();
            if ((detectiontype) && (detectionvl))
            {
                $.post(hosturl + '/controllers/visits.php?ac=adddetectionpop', {doctorId: doctorId, shareVersion: shareVersion, detectiontype: detectiontype, detectionvl: detectionvl}, function (data) {
                    if (data) {
                        $('#detectiontp').val('');
                        $('#detectionvl').val('');
                        $("#sucssmsg").html();
                        $("#sucssmsg").css('display', '');
                        $("#sucssmsg").fadeOut(6000);
                        if (shareVersion == 2) {
                            $("#for_doctor").trigger('change');
                        } else {

                            $("#detectionid").html(data);
                        }
                    }
                });
            } else
            {
                alert("من فضلك أدخل البيانات");
            }
        });
        $("#editdetectiontype").live('click', function () {
            var dtID = $(this).attr('data-id');
            var itr = $(this).attr('data-itr');
            var dttitle = $('#detectiontitle' + itr).val();
            var dtvalue = $('#detectionvalue' + itr).val();
            $.post(hosturl + '/controllers/visits.php?ac=updatedetection', {id: dtID, title: dttitle, dtvalue: dtvalue}, function (data) {
                $('#loaddetectionnew').html(data);
                $("#detectionid").load(hosturl + '/controllers/visits.php?ac=loadalldtselected');
            });
        });
    }

    var dateMaskAndOther = function () {
//  $(".mask_date_new").inputmask("d-m-y");
        $(".mask_date_new").mask("99-99-9999", {placeholder: "0"});
    }

    var patientsBMI = function ()
    {
        $('body').on('click', '#patientsBMI', function ()
        {
            /* var WT = $(this).attr('data-WT');
             var HT = $(this).attr('data-HT');
             var bmi = $(this).attr('data-bmi');*/
            var examinationId = $(this).attr('data-id');
            var WT = $('#weight' + examinationId).val();
            var HT = $('#height' + examinationId).val();
            var bmi = $('#bmi' + examinationId).val();
            $('#examinationWeight').attr('data-id', examinationId);
            $('#examinationHeight').attr('data-id', examinationId);
            $('#examinationBMI').attr('data-id', examinationId);
            $('#examinationWeight').val(WT);
            $('#examinationHeight').val(HT);
            $('#examinationBMI').val(bmi);
            $("#showBmi").modal('show');
        });
        $('.examinationBMI').live('keyup', function ()
        {
            var id = $(this).attr('data-id');
            var wt = $('#examinationWeight').val();
            var ht = $('#examinationHeight').val();
            var patientid_me = $('#patientid').val();
            if (wt != '' && ht != '' && ht > 0) {
                var res = wt / (ht * ht);
                var newres = Math.ceil(res)
                $('#examinationBMI').val(newres);
                $('#patientsBMI').html('BMI : ' + newres);
                $("#bmi" + id).val(newres);
                $("#weight" + id).val(wt);
                $("#height" + id).val(ht);
                $.post(hosturl + '/controllers/gyna.php?ac=update', {id: id, value: newres, tableName: 'examination', colName: 'bmi', patientId: patientid_me}, function (res)
                {
                });
            }
//newres = $('#hidden_bmi').val();
        });
    }



    $('body').on('keyup', '.updatelastptIDtwice', function ()
    {
        var wifename = $("#wifename").val();
        var wifestatus = $("#statusno").val();
        var statusnoexist = $(this).attr('statusnoexist');
        var id = $(this).attr('data-id');
        $.ajax({
            url: hosturl + '/controllers/patients.php?ac=updateajaxtwice',
            type: 'POST',
            data: {wifename: wifename, wifestatus: wifestatus, statusnoexist: statusnoexist, id: id},
            success: function (data) {
                if (data) {
                    var shortCutFunction = 'success';
                    var msg = 'The element has been Added successfully';
                    var title = 'Success';
                    $('.todayvisit').html();
                } else {
                    var shortCutFunction = 'error';
                    var msg = 'Sorry , an error has been occured ';
                    var title = 'Error';
                }
                toastr.options = {
                    closeButton: $('#closeButton').prop('checked'),
                    debug: $('#debugInfo').prop('checked'),
                    positionClass: $('#positionGroup input:checked').val() || 'toast-top-left',
                    onclick: null
                };
                ////var $toast = toastr[shortCutFunction](msg, title);
            }
        });
    });
    $('body').on('change', '.updatelastptID', function () {
        var colname = $(this).attr('data-ptname');
        var id = $(this).attr('data-id');
        var valuenew = $(this).val();
        if (colname == "mirragefromy" || colname == "mirragefromm")
        {
            colname = "mirragefrom";
            var years = $('#mirragefromy').val();
            var month = $('#mirragefromm').val();
            if (years == '')
            {
                $('#mirragefromy').val(0);
            }
            if (month == '')
            {
                $('#mirragefromm').val(0);
            }

            valuenew = Number(years) + Number((month / 12));
        }

// update in database
        $.ajax({
            url: hosturl + '/controllers/patients.php?ac=updateajax',
            type: 'POST',
            data: {colname: colname, valuenew: valuenew, id: id},
            success: function (data)
            {
                console.log(data);
            }
        });
    });
/////////////////////////////////////Add in Edit Model

    $("#addRow").live('click', function () {

        var doctorId = $('#for_doctor').val();
        var shareVersion = $('#shareVersion').val();
        var dtcount = $("#dtcount").val();
        dtcount++;
        $.post(hosturl + "/controllers/visits.php?ac=adddetectionRow", {doctorId: doctorId, shareVersion: shareVersion}, function (data) {
            var dataid = Number(data);
            $('#detectionid > .deleteoptincompo').before('<option value="' + dataid + '" ></option>');
            if ($("#isHospital").val() == 1) {
                $("#dtAddTbl").prepend('<tr>\
                            <td style="width: 100%">\
                                <input type="text" class="form-control updateDetectionModel"  id="allnewitem_name' + dtcount + '" data-itr="' + dtcount + '" data-id="' + dataid + '" name="newamount_name" value="" >\
                            </td>\
                            <td>\
                                <a href="#" class="btn red fleft deleteelement" data-id="' + dataid + '" data-link="visits" data-fun="deldetection">\
                                    <i class="fa fa-times" ></i>\
                                </a>\
                            </td>\
                        </tr>');
            } else {

                if (shareVersion == 2) {
                    $("#dtAddTbl").prepend('<tr>\
                            <td style="width: 50%">\
                                <input type="text" class="form-control updateDetectionModel"  id="allnewitem_name' + dtcount + '" data-itr="' + dtcount + '" data-id="' + dataid + '" name="newamount_name" value="" >\
                            </td>\
                            <td style="width: 40%">\
                                <input type="text" class="form-control updateDetectionModel"  id="allnewitem_value' + dtcount + '" data-itr="' + dtcount + '" data-id="' + dataid + '" name="newamount_name" value="">\
                            </td>\
                            <td>\
                                <a href="#" class="btn red fleft deleteelement" data-id="' + dataid + '" data-link="visits" data-fun="deldetection" style="padding: 2px 0px;width: 100%">\
                                    <i class="fa fa-times" ></i>\
                                </a>\
                            </td>\
                         </tr>');
                } else if (shareVersion == 3) {
                    $("#dtAddTbl").prepend('<tr>'
                            + '<td>'
                            + '   <input type="checkbox" data-colName="for_customer" data-tableName="detections"   value="1"'
                            + '    class="form-control updateElementCheck" data-itr="' + dtcount + '" data-id="' + dataid + '" >'
                            + '</td>'
                            + '<td>'
                            + '<input type="checkbox"  data-colName="iserppayment" data-tableName="detections"   '
                            + '    value="1"     id="isERPPayment' + dtcount + '"'
                            + '  class="form-control updateDetectionModel" data-itr="' + dtcount + '"  data-id="' + dataid + '"   >'
                            + '</td>'
                            + ' <td>'
                            + ' <input type="text" class="form-control updateDetectionModel"  id="allnewitem_name' + dtcount + '" '
                            + '  data-itr="' + dtcount + '" data-id="' + dataid + '" name="newamount_name" value="" >'
                            + ' </td>'
                            + ' <td>'
                            + ' <input type="text" class="form-control updateDetectionModel"  id="allnewitem_value' + dtcount + '" '
                            + '    data-itr="' + dtcount + '" data-id="' + dataid + '" name="newamount_name" value="0" >'
                            + ' </td>'
                            + '  <td>'
                            + '<div class="md-radio-inline">'
                            + ' <div class="md-radio">'
                            + '    <input type="radio" data-colName="type" data-tableName="detections"   value="1" '
                            + '       name="type' + dtcount + '"  class="form-control updateElement" data-itr="' + dtcount + '"'
                            + '        data-id="' + dataid + '"  id="type1P' + dtcount + '"   checked >'
                            + '            <label for="type1P' + dtcount + '">'
                            + '         <span></span>'
                            + '         <span class="check"></span>'
                            + '    <span class="box"></span>'
                            + '     نبضات         </label>'
                            + '   </div>'

                            + '     <div class="md-radio">'
                            + '      <input type="radio" data-colName="type" data-tableName="detections"   value="2" '
                            + '      name="type' + dtcount + '" class="form-control updateElement" data-itr="' + dtcount + '" '
                            + '           data-id="' + dataid + '"   id="type2S' + dtcount + '"  >'
                            + '     <label for="type2S' + dtcount + '">'
                            + '      <span></span>'
                            + '       <span class="check"></span>'
                            + '      <span class="box"></span>'
                            + '  جلسات         </label>'
                            + '    </div>'
                            + '   </div>'
                            + '   </td>'

                            + ' <td>'
                            + '  <input type="text" class="form-control updateElement"  data-colName="units" '
                            + '      data-itr="' + dtcount + '" data-id="' + dataid + '" data-tableName="detections" value="0">'
                            + '  </td>'

                            + '  <td>'
                            + ' <input type="text" class="form-control updateElement"  data-colName="min_paid" '
                            + '       data-itr="' + dtcount + '" data-id="' + dataid + '" data-tableName="detections" value="0" >'
                            + '    </td>'

                            + ' <td>'
                            + '   <input type="text" class="form-control updateElement"  data-colName="max_session" '
                            + '          data-itr="' + dtcount + '" data-id="' + dataid + '" data-tableName="detections" value="0" >'
                            + '  </td>'

                            + '  <td>'
                            + '     <a href="#" class="btn red fleft deleteelement" data-id="' + dataid + '" data-link="visits" '
                            + '        data-fun="deldetection" style="padding: 2px 0px;width: 100%">'
                            + '          <i class="fa fa-times" ></i>'
                            + '        </a>'
                            + '     </td>'

                            + '</tr>');
                } else {
                    $("#dtAddTbl").prepend('<tr>\
                           <td>\
                                <input type="checkbox" data-colName="for_customer" data-tableName="detections"   value="1"\
                                 class="form-control updateElementCheck" data-itr="' + dtcount + '" data-id="' + dataid + '" >\
                           </td>\
                             <td>\
                                <input type="checkbox" data-colName="for_operation" data-tableName="detections"   value="1"\
                                 class="form-control updateElementCheck" data-itr="' + dtcount + '" data-id="' + dataid + '" >\
                           </td>\
                          <td style="width: 50%">\
                                <input type="text" class="form-control updateDetectionModel"  id="allnewitem_name' + dtcount + '" data-itr="' + dtcount + '" data-id="' + dataid + '" name="newamount_name" value="" >\
                            </td>\
                            <td style="width: 40%">\
                                <input type="text" class="form-control updateDetectionModel"  id="allnewitem_value' + dtcount + '" data-itr="' + dtcount + '" data-id="' + dataid + '" name="newamount_name" value="0">\
                            </td>\
                            <td>\
                                <a href="#" class="btn red fleft deleteelement" data-id="' + dataid + '" data-link="visits" data-fun="deldetection" style="padding: 2px 0px;width: 100%">\
                                    <i class="fa fa-times" ></i>\
                                </a>\
                            </td>\
                         </tr>');
                }
            }
        });
        $("#dtcount").val(dtcount);
    });
    return {
//main function to initiate the module
        init: function () {
//                    deleteelement();
            deletemsg();
//                    calcwifeage();
//                    calchusbandage();
//                    datadontdublicate();
//                    datadontdublicatenationalid();
//                    datadontdublicatenationalidhusband();
            searchresult();
            //  savevisits();
            deletemsgvisit();
//                    addnewinselect2();
            sortablebtn();
            updatelastpatient();
            ptfile();
            filedownload();
            checkuser();
            visitviewed();
            cleantables();
            cleantablesdefault();
            erpDb();
            //updatetwice();
            dateMaskAndOther();
//                    datadontdublicatestate();
            publicjs();
            patientsBMI();
        }

    };
}();
