
var patientcustom = function () {
//global hosturlf
    var hosturl = $('#hosturl').val();
    var path = $('#path').val();
    var patientId = $('#ptntid').val();


    var deleteelement = function () {
        //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();
            var tr2 = $(this).parent().parent().parent();

            bootbox.dialog({
                message: "Do you want to delete this item?",
                title: "Delete confirmation",
                buttons: {
                    danger: {
                        label: "Cancel",
                        className: "btn-primary"
                    },
                    main: {
                        label: "Delete",
                        className: "btn-danger",
                        callback: function () {


                            $.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 == 'delwifejob') {
                                    $("#wifejob").html(data);
                                } else if (fun == 'delstatus') {
                                    $("#wifestatus").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 (fun == 'deldetection') {

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

                                if (tableName == 'gynainfertilityplan') {
                                    tr2.remove();
                                } else {
                                    tr.remove();
                                }
                            });

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

        });
    }


    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');
        })
    }
    var calcwifeage = function () {
        $(".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);
                        });
                    }
                }
            });
        });
    }
    var calchusbandage = function () {
        $(".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);
        });
    });


    var datadontdublicate = function () {
        $('#wifename').live('keyup', function () {
            var wifename = $(this).val();
            var patientId = $(this).attr('data-id');
            $.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";
                    $('#patient_submit').attr('disabled', 'disabled');
                    $('#patient_submit').css('opacity', '0.3');
                } 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 ($('#lb_ckstatusno:visible').length == 0 && $('#lb_ckhusdandname:visible').length == 0 && $('#lb_ckphone:visible').length == 0 && $('#lb_ckmobile:visible').length == 0 && $('#lb_ckwifenationalid:visible').length == 0 && $('#lb_ckhusbandnationalid:visible').length == 0)
                    {
                        $("#patient_submit").removeAttr('disabled');
                        $('#patient_submit').css('opacity', '1');
                    }
                }
            });
        });

        $('.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";
                        $('#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 {
                        $('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', '');
                        if ($('#lb_ckstatusno:visible').length == 0 && $('#lb_ckwifename:visible').length == 0 && $('#lb_ckhusdandname:visible').length == 0 && $('#lb_ckphone:visible').length == 0 && $('#lb_ckmobile:visible').length == 0 && $('#lb_ckwifenationalid:visible').length == 0 && $('#lb_ckhusbandnationalid:visible').length == 0)
                        {
                            $("#patient_submit").removeAttr('disabled');
                            $('#patient_submit').css('opacity', '1');

                            $("#patient_submit_v").removeAttr('disabled');
                            $('#patient_submit_v').css('opacity', '1');


                        }
                    }
                });
            }


        });


    }
    var datadontdublicatestate = function () {
        $('#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";
                    $('#patient_submit').attr('disabled', 'disabled');
                    $('#patient_submit').css('opacity', '0.3');
                } 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', '');
                    if ($('#lb_ckstatusno:visible').length == 0 && $('#lb_ckhusdandname:visible').length == 0 && $('#lb_ckphone:visible').length == 0 && $('#lb_ckmobile:visible').length == 0 && $('#lb_ckwifenationalid:visible').length == 0 && $('#lb_ckhusbandnationalid:visible').length == 0)
                    {
                        $("#patient_submit").removeAttr('disabled');
                        $('#patient_submit').css('opacity', '1');
                    }
                }
            });
        });
    }
    var datadontdublicatenationalid = function () {
        $('#wifenationalid').live('change', function ()
        {
            var wifenationalid = $(this).val();
            var patientId = $(this).attr('data-id');
            var colname = $(this).attr('data-ptname');
            var id = $(this).attr('data-id');
            var treeId = $("#treeId").val();
            $.post(hosturl + '/controllers/patients.php?ac=updateajax', {colname: colname, valuenew: wifenationalid, id: id, treeId: treeId}, function (res1)
            {
                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);
                    var treeId = $("#treeId").val();
                    $.post(hosturl + '/controllers/patients.php?ac=updateajax', {colname: 'dateofbirth', valuenew: bDate, id: id, treeId: treeId}, function (res)
                    {
                    });
                    calcDate('w');
                }
            });

        });


    }

    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;
        }
    }
    var datadontdublicatenationalidhusband = function () {
        $('#husbandnationalid').live('change', function () {
            var husbandnationalid = $(this).val();
            var patientId = $(this).attr('data-id');
            var colname = $(this).attr('data-ptname');
            var id = $(this).attr('data-id');
            var treeId = $("#treeId").val();

            $.post(hosturl + '/controllers/patients.php?ac=updateajax', {colname: colname, valuenew: husbandnationalid, id: id, treeId: treeId}, function (res1)
            {
                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);
                    var treeId = $("#treeId").val();
                    $.post(hosturl + '/controllers/patients.php?ac=updateajax', {colname: 'husbanddateofbirth', valuenew: bDate, id: id, treeId: treeId}, 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]);

        if (day <= 9) {
            day = '0' + day;
        }

        if (month <= 9) {
            month = '0' + month;
        }



        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 jobtitleًW = $('#jobtitleًW').val();
            var age = $('#age').val();
            var phone = $('#phone').val();
            var mobile = $('#mobile').val();
            var nationalid = $('#nationalid').val();
            var detectionSearch = $('#detectionSearch').val();
            if (search == '' && husbandname == '' && address == '' && jobtitle == '' && jobtitleًW == '' && age == '' && phone == '' && mobile == '' && nationalid == '' && detectionSearch == '') {
                $('#ermsg').css('display', 'block');
                $('.success').html('');
            } else {
                $.post($('form').attr('action'), {jobtitleًW: jobtitleًW, 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 {
//$('.faild').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');
                });
            }
        });
    }
    var savevisits = function () {
        $('.btnsve').click(function () {
            var patientid = $('#patientvisitid').val();
            var visitdate = $('#visitdate').val();
            var visitPeriod = $('#visitPeriod').val();
            var cardStatusNo = $('#cardStatusNo').val();
            var add = 1;
            var cash = $('#detectionvalue_cash').val();
            var printserial = $('#printserial').val();
            var visitBranch = $('#visitBranch').val();

            $('.btnsve').attr('disabled', true);

            if (visitPeriod == 1 && $('#visit_period').val() < 1) {
                add = 0;
            }

            if (visitBranch == 1 && $('#branchId').val() < 1) {
                add = 0;
            }

            if (patientid != '' && visitdate != '' && add == 1) {
                $.post(hosturl + '/controllers/visits.php?ac=add', $("#myvisitform").serialize(), function (visitId) {
                    //alert(data);
                    if (Number(visitId) == -1) {
                        $("#visitaddsubmit").attr('disabled', 'disabled');
                        $("#checkvisitbefore").css('display', '');
                        $("#checkvisitbefore").css('color', 'red');
                        $('.btnsve').attr('disabled', false);
                    }
                    if (visitId && Number(visitId) != -1) {
                        $('#cardStatusNo').val('');
                        var shortCutFunction = 'success';
                        var msg = 'تم الإضافة ........';
                        var title = 'Success';


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

//                        $('#visitNew').html(data);
                        if ($('#detectionid').val() == -99)
                        {
                            $.post(hosturl + '/controllers/visits.php?ac=gettotalbalance', {
                                patientId: patientid
                            }, function (res) {
                                console.log(res);
                                $("#balance").val(res);
                            });
                        }

                        $("#visitaddsubmit").removeAttr('disabled');
                        $("#checkvisitbefore").css('display', 'none');
                        $("#checkvisitbefore").css('color', '');

                        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 date_from = $('#date_from').val();
                        var date_to = $('#date_to').val();
                        var patientId = $('#patientIdRemote').val();

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

                            //        $("#visit_period").trigger('change');
                            $("#patientvisitidNo").select2("val", "");
                            $("#patientvisitid").select2("val", "");
                            $("#detectionid").select2("val", "");
                            $('#visit_period').select2().trigger('change');
                            $("#detectionvalue_cash").val(0);
                            $("#detectionvalue_visa").val(0);
                            $("#restdetectionvalue").val(0);
                            $("#totaldetectionvalue").val(0);
                            $("#discount").val(0);
                            $("#notes").val('');

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

                            $('#lastVisitDetails').html('');
                            $('#restDiv').html('');
                            $('.btnsve').attr('disabled', false);
                        });
                    }
                });
            } else {
                $('.btnsve').attr('disabled', false);
            }
            return false;
        });

        $('body').on('change', '.searchvisitIndex', function () {
            var date_from = $('#date_from').val();
            var date_to = $('#date_to').val();
            var patientId = $('#patientIdRemote').val();
            var cardStatusNo = $('#cardStatusNo').val();

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

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

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

        function getLastVisit(patientId)
        {
            $.post(hosturl + '/controllers/visits.php?ac=getlastvisit', {
                patientId: patientId
            }, function (res) {
                console.log(res);
                var obj = JSON.parse(res);
                $('#detectionid').select2("val", obj.detectionId).trigger("change");

                //     $('#detectionvalue').val(obj.detectionValue);
            });

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

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

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

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

    };
    var addnewinselect2 = function () {
        $('.select2me_aw').select2({language: "ar"});
        // ADD WIFE JOB


        $("#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');
                });
            }
        });
        $("#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);
            });
        });
        //ADD EDUCATION HUSBAND
        $("#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) {
                $('.hiddenforsng').css('display', 'none');
                $('.displaynot').css('display', 'none');
            } else if (del == 3) {
                $('.hiddenforsng').css('display', 'none');
                $('.displaynot').css('display', 'block');
                $('#husbandLive').html('  منذ');
            } else if (del == 2) {
                $('.hiddenforsng').css('display', '');
                $('.displaynot').css('display', '');
                $('#husbandLive').html('  منذ');
            } else if (del == 4) {
                $('.hiddenforsng').css('display', 'none');
                $('.displaynot').css('display', '');
                $('#husbandLive').html('  منذ');
            } else
            {
                $('.hiddenforsng').css('display', '');
                $('.displaynot').css('display', '');
                $('#husbandLive').html('  منذ');
            }
        });
        $("#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);
            });
        });

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

        $("#detectionid").live('change', 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();
            if (myvalue == -1) {
                $("#detectionid").val('');
                $('#detectionadd').html();
                $('#detectionadd').modal('show');
            } else {
                if (myvalue == 0) {
                    $("#detectionid").val('');
                    $("#detectionid").select2();
                    $("#detectionvalue").val('');
                    $.post(hosturl + '/controllers/visits.php?ac=editselect', {tableName: maintableName, colName: colName, patientid: patientId, mainId: id}, function (data) {

                        $("#detectionforview").html(data);
                        $("#edit_detectionforview").modal('show');
                    });
                } else {
                    $.post(hosturl + '/controllers/visits.php?ac=getdtprice', {dtID: myvalue}, function (data) {
                        //      $("#detectionvalue").val(data);
                        $("#detectionvalue_cash").val(data);
                        $("#detectionvalue_visa").val(0);
                        $("#restdetectionvalue").val(0);
                        $("#totaldetectionvalue").val(data);
                        $('#discount').val(0);
                    });
                }

            }
        });


        $(".updateDetectionModel").live('change', 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 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}, 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").val('');
                            $("#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);
                        });
                    });
                });
            }
        });
        //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 fn = $(this).attr('data-fun');
            dtcount++;
            $.post(hosturl + "/controllers/patients.php?ac=addwtRow", {tablename: tablename}, 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="title" 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 () {
        $('.updatelastptID').change(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));
            }
            var treeId = $("#treeId").val();
            // update in database
            $.ajax({
                url: hosturl + '/controllers/patients.php?ac=updateajax',
                type: 'POST',
                data: {colname: colname, valuenew: valuenew, id: id, treeId: treeId},
                success: function (data)
                {
                    //alert(data);
                }
            });



        });
    }

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

            });
        });
        $('[name="mobile"]').keyup(function () {
            $('#uName').val($(this).val());
        });
    }
    var visitviewed = function () {
        $('body').on('click', '.visitviewed', function () {
            var visitID = $(this).attr('data-id');
            $.ajax({
                url: hosturl + "/controllers/visits.php?ac=visitviewed",
                type: 'POST',
                data: {id: visitID},
                success: function (data) {

                }
            });
        });
    }

    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 () {
        //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: "اختر خزنة ",
            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);


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

                });
            }
        });
        $(document).ready(function () {
            var erpdbsave = Number($('#save').val());
            var erpdbsavename = $('#erpdbsavename').val();
            if (erpdbsave > 0) {
                $("#erpDBSave").select2('data', {id: erpdbsave, text: erpdbsavename});
            }
        });
        //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);
                }
            });
        });
    }
    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();
            if ((detectiontype) && (detectionvl))
            {
                $.post(hosturl + '/controllers/visits.php?ac=adddetectionpop', {detectiontype: detectiontype, detectionvl: detectionvl}, function (data) {
                    if (data) {
                        $('#detectiontp').val('');
                        $('#detectionvl').val('');
                        $("#sucssmsg").html();
                        $("#sucssmsg").css('display', '');
                        $("#sucssmsg").fadeOut(6000);
                        $("#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);


                $.post(hosturl + '/controllers/gyna.php?ac=updatePatBmi',
                        {wt: wt, ht: ht, bmi: newres, 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');
        var treeId = $("#treeId").val();
        $.ajax({
            url: hosturl + '/controllers/patients.php?ac=updateajaxtwice',
            type: 'POST',
            data: {wifename: wifename, wifestatus: wifestatus, statusnoexist: statusnoexist, id: id, treeId: treeId},
            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);
            }
        });
    });

/////////////////////////////////////Add in Edit Model

    $("#addRow").live('click', function () {
        var dtcount = $("#dtcount").val();
        dtcount++;
        $.post(hosturl + "/controllers/visits.php?ac=adddetectionRow", 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
            {


                $("#dtAddTbl").prepend('<tr>\
                            <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="">\
                            </td>\
                            <td>\
                                <a href="#" class="btn red fleft deleteelement wds100 " data-id="' + dataid + '" data-link="visits" data-fun="deldetection">\
                                    <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();
        }

    };
}();
