var hosturle = $('#hosturl').val();
var pathe = $('#path').val();
var controllname = $("#controllname").val();

$(document).ready(function () {
    $('body').on('click', '.resetdate', function () {
        $(".eedlmp").each(function () {
            $(this).val("").trigger('change');
        });

    });
    if (controllname == "gynasheet" || controllname == "ancsheet") {
        // getymt();
    }

    function getymt() {
        $(".getymt").each(function () {

            var sdt = $(this).val();
            if (sdt) {
                var id = $(this).attr("data-id");
                var templmp = sdt.split('-');
                lmp = templmp[2] + '-' + templmp[1] + '-' + templmp[0];
                var sdt2 = new Date(lmp);
                var difdt = new Date(new Date() - sdt2);
                var texx = (difdt.toISOString().slice(0, 4) - 1970) + "Y " + (difdt.getMonth()) + "M ";
                var table = "awifep";
                var name = "wifeage";
                $.post(hosturle + '/controllers/infertilitysheet.php?ac=Add', {
                    table: table,
                    name: name,
                    value: texx,
                    id: id
                });
                $('#awifepmonth_' + id).html(texx);
            }
        });
    }

    $("#completesreport").live('change', function () {
        var patientid = $(this).val();
        $.post(hosturle + '/controllers/completesreport.php?ac=search', {patientid: patientid}, function (res)
        {
            $("#expectedDiv").html("");
            $("#expectedDiv").append(res);

        });
    });

    $('body').on('change', '.getymt', function () {
        var sdt = $(this).val();
        var id = $(this).attr("data-id");
        var templmp = sdt.split('-');
        lmp = templmp[2] + '-' + templmp[1] + '-' + templmp[0];
        var sdt2 = new Date(lmp);
        var difdt = new Date(new Date() - sdt2);
        var texx = (difdt.toISOString().slice(0, 4) - 1970) + "Y " + (difdt.getMonth()) + "M ";
        var table = "awifep";
        var name = "wifeage";
        /*   $.post(hosturle + '/controllers/infertilitysheet.php?ac=Add', {
         table: table,
         name: name,
         value: texx,
         id: id
         });*/
        $('#awifepmonth_' + id).html(texx);
    });

    $(".bp_mask").inputmask("999/999", {
        autoUnmask: true
    });

    if (controllname == "ancsheet" || controllname == "infertilitysheet" || controllname == "gynasheet") {
        // $(".aw_green").hide();
        obstetric();
    }
    var cat = localStorage.getItem('perient');
    if (cat == 1) {
        $(".history2").toggle();
        localStorage.removeItem('perient');
        $('html, body').animate({
            scrollTop: $("#historyshow").offset().top
        }, 1000);
    }

    $('.historys').click(function () {
        if (confirm(" ؟ هل  انت متاكد  ")) {

            var patientid = $('#patientId').val();
            var kind = $(this).attr("data-kind");
            $.post(hosturle + '/controllers/' + controllname + '.php?ac=endpreg', {
                patientid: patientid,
                kind: kind
            }, function (data) {
                if (data == 1) {
                    $("#awifeplocal").click();
                    $("#awifepclocal").click();
                    localStorage.setItem('perient', 1);
                    window.location = hosturle + '/controllers/ancsheet.php?ac=index&patientid=' + patientid;
                } else {
                    window.location = hosturle + '/controllers/infertilitysheet.php?ac=index&patientid=' + patientid + '#icsi';
                }
            });
        } else {
            return false;
        }

    });

    selectRefresh();

    function selectRefresh() {
        $(".getselectajax").each(function () {
            var tablep = $(this).attr("data-table");
            var celtable = $(this).attr("data-celtable");
            var name = $(this).attr('name');
            var selid = $(this).attr('data-selid');
            var id = $("#id").val();
            var kind = $(this).attr('data-kind');
            $.post(hosturle + '/controllers/' + controllname + '.php?ac=getselect', {
                selid: selid,
                tablep: tablep,
                celtable: celtable,
                id: id,
                name: name,
                kind: kind
            }, function (result) {
                $('#' + celtable + selid).html(result);
                $('#' + celtable + selid).trigger('change');

            });

        });

    }
    popoverhover();

    function popoverhover() {
        $(".amrpop,input,textarea,select").hover(function () {
            var pop_value = $(this).val();
            $(this).attr({
                "html": true,
                "data-toggle": "popover",
                "data-trigger": "hover",
                "data-placement": "bottom",
                "data-container": "body",
                "data-content": pop_value
            });
            $(this).popover("show");
        });


    }

    function selectRefresh2() {
        $("select.getselectajax2").each(function () {
            var tablep = $(this).attr("data-table");
            var celtable = $(this).attr("data-celtable");
            var name = $(this).attr('name');
            var selid = $(this).attr('data-selid');
            var id = $("#id").val();
            var kind = $(this).attr('data-kind');
            $.post(hosturle + '/controllers/' + controllname + '.php?ac=getselect', {
                selid: selid,
                tablep: tablep,
                celtable: celtable,
                id: id,
                name: name,
                kind: kind
            }, function (result) {
                $('#' + celtable + selid).html(result);
                $('#' + celtable + selid).trigger('change');
                getselectajax2();
                $('#' + celtable + selid).addClass('getselectajax').removeClass('getselectajax2');

            });

        });


        $(".datepicker").datepicker({
            todayBtn: "linked",
            autoclose: true,
            todayHighlight: true,
            format: 'dd/mm/yy',
            isRTL: true
        });
        $(".bp_mask").inputmask("999/999", {
            autoUnmask: true
        });

    }

    $('.datepicker').on('click', function (e) {
        e.preventDefault();
        $(this).attr("autocomplete", "off");
    });

    getselectajax2();

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

    getselectajax();

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

    $(window).load(function () {
        if (controllname == "ancsheet" || controllname == "infertilitysheet" || controllname == "gynasheet" || controllname == "ivfsheet") {

            $('body').on('change', 'select', function () {
                var tablep = $(this).attr("data-table");
                var celtable = $(this).attr("data-celtable");
                var name = $(this).attr('name');
                var selid = $(this).attr('data-selid');
                var id = $(this).attr('data-id');
                var kind = $(this).attr('data-kind');
                var value = $(this).val();
                var newterm = $(this).attr('data-new');
                var values = String($(this).val());
                $.post(hosturle + '/controllers/' + controllname + '.php?ac=Add', {
                    table: tablep,
                    name: name,
                    value: values,
                    id: id
                });
                if ($.inArray('-1', value) > -1 || value == -1) {
                    $("#" + celtable + selid + " option[value='-1']").prop("selected", false);
                    $.post(hosturle + '/controllers/' + controllname + '.php?ac=getselectajax', {
                        newterm: newterm,
                        celtable: celtable,
                        selid: selid
                    }, function (data) {
                        $('#' + celtable + selid + ' > .adddataselect').before('<option value="' + Number(data) + '" >' + newterm + '</option>');
                        $('#' + celtable + selid + ' option[value="' + Number(data) + '"]').attr('selected', true);
                        $('#' + celtable + selid).trigger('change');
                    });
                } else if (value == -2 || $.inArray('-2', value) > -1) {
                    $.post(hosturle + '/controllers/' + controllname + '.php?ac=getselect', {
                        selid: selid,
                        tablep: tablep,
                        celtable: celtable,
                        id: id,
                        name: name
                    }, function (result) {
                        $('#' + celtable + selid).html(result);
                        $('#' + celtable + selid).trigger('change');
                    });

                    $("#" + celtable + selid + " option[value='-2']").prop("selected", false);
                    $('#' + celtable + selid).trigger('change');


                    $.post(hosturle + '/controllers/' + controllname + '.php?ac=getdataselect', {
                        celtable: celtable
                    }, function (result) {
                        if (result != 0) {
                            $("#allgetdataselect").html(result);
                            $("#getdataselect").modal('show');

                        }

                    });
                }
            });
        }
    });

    $('body').on('click', '.deleteselect', function () {
        var table = $(this).attr("data-table");
        var id = $(this).attr('data-id');
        $.post(hosturle + '/controllers/' + controllname + '.php?ac=deldataselect', {
            id: id,
            table: table
        }, function (result) {
            if (result > 0) {
                $("#remove_" + id).remove();
            }

        });

        if (controllname != 'operations') {
            $("select[data-celtable=" + table + "]").each(function () {
                var tablep = $(this).attr("data-table");
                var celtable = $(this).attr("data-celtable");
                var name = $(this).attr('name');
                var selid = $(this).attr('data-selid');
                var id = $("#id").val();
                var kind = $(this).attr('data-kind');
                $.post(hosturle + '/controllers/' + controllname + '.php?ac=getselect', {
                    selid: selid,
                    tablep: tablep,
                    celtable: celtable,
                    id: id,
                    name: name,
                    kind: kind
                }, function (result) {
                    $('#' + celtable + selid).html(result);
                    $('#' + celtable + selid).trigger('change');

                });
            });
        } else {
            $("#" + table + "W option[value='" + id + "']").remove();
            $('#' + table + 'W').trigger('change');
        }
    });

    $('body').on('click', '.checkbox', function () {
        if (!$(this).is(':checked')) {
            $(this).val('0');
        } else {
            $(this).val('1');
        }
    });

    if (controllname == "ancsheet" || controllname == "infertilitysheet" || controllname == "gynasheet" || controllname == "ivfsheet") {
        $('body').on('change', 'input, textarea', function () {

            if ($(this).hasClass('dontSave')) {
            } else {
                var table = $(this).attr('data-table');
                var id = $(this).attr('data-id');
                var name = $(this).attr('name');
                var value = $(this).val().toString();

                $.post(hosturle + '/controllers/' + controllname + '.php?ac=Add', {
                    table: table,
                    name: name,
                    value: value,
                    id: id
                }, function (data) {
                    console.log(data);
                });
            }
        });
    }

    if (controllname == "operations" || controllname == "epc" || controllname == "Deliveries") {

        $('body').on('change', 'input, textarea', function () {

            if ($(this).hasClass('dontSave')) {
            } else {
                var table = $(this).attr('data-table');
                var id = $(this).attr('data-id');
                var name = $(this).attr('name');
                var value = $(this).val().toString();

                $.post(hosturle + '/controllers/infertilitysheet.php?ac=Add', {
                    table: table,
                    name: name,
                    value: value,
                    id: id
                }, function (data) {
                    if ((table == 'operation' || table == 'four_d') && name == 'title') {
                        $('#' + table + 'W  option[value="' + id + '"]').text(value);
                    }
                });
            }
        });
    }

    $('body').on('change', '.eedlmp', function () {
        var table = $(this).attr('data-table');
        var id = $(this).attr('data-id');
        var name = $(this).attr('name');
        var value = $(this).val();
        if (value == '') {
            return false;
        }

        $.post(hosturle + '/controllers/' + controllname + '.php?ac=eedlmp', {
            table: table,
            name: name,
            value: value,
            id: id
        }, function (res) {
            res = res.split(",");
            $('#edd').val(res[0]);
            $('#lmp').val(res[1]);
        });


    });

    $('body').on('change', '.vdate2', function () {
        var lmp = $('#lmp').val();
        var templmp = lmp.split('-');
        lmp = templmp[2] + '-' + templmp[1] + '-' + templmp[0];
        var firstDate = new Date(lmp);
        var newvisitwid = $(this).attr('data-id');
        var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
        var thisval = $(this).val();
        var tempthisval = thisval.split('-');
        thisval = tempthisval[2] + '-' + tempthisval[1] + '-' + tempthisval[0];
        var secondDate = new Date(thisval);
        var diffDays = Math.floor(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
        var diffInWeeks = Math.floor(diffDays / 7) + 'W ' + (diffDays % 7) + 'D';
        $('#newvisitw_' + newvisitwid).val(diffInWeeks);
        //   $('#newvisitw_' + newvisitwid).trigger("change");
        $('label[data-id=' + $(this).attr('data-id') + ']').text(diffInWeeks);
        if (secondDate < firstDate) {
            $('label[data-id=' + $(this).attr('data-id') + ']').css('color', 'red');
            $('label[data-id=' + $(this).attr('data-id') + ']').css('font-weight', 'bold');
        } else {
            $('label[data-id=' + $(this).attr('data-id') + ']').css('color', 'maroon');
            $('label[data-id=' + $(this).attr('data-id') + ']').css('font-weight', 'bolder');
        }
    });

    function vdate() {
        var lmp = $('#lmp').val();
        var templmp = lmp.split('-');
        lmp = templmp[2] + '-' + templmp[1] + '-' + templmp[0];
        var firstDate = new Date(lmp);
        $('.vdate2').each(function () {
            var newvisitwid = $(this).attr('data-id');
            var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
            var thisval = $(this).val();
            var tempthisval = thisval.split('-');
            thisval = tempthisval[2] + '-' + tempthisval[1] + '-' + tempthisval[0];
            var secondDate = new Date(thisval);
            var diffDays = Math.floor(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
            var diffInWeeks = Math.floor(diffDays / 7) + 'W ' + (diffDays % 7) + 'D';

            $('#newvisitw_' + newvisitwid).val(diffInWeeks);
            $('#newvisitw_' + newvisitwid).trigger("change")
            $('label[data-id=' + $(this).attr('data-id') + ']').text(diffInWeeks);
            if (secondDate < firstDate) {
                $('label[data-id=' + $(this).attr('data-id') + ']').css('color', 'red');
                $('label[data-id=' + $(this).attr('data-id') + ']').css('font-weight', 'bold');
            } else {
                $('label[data-id=' + $(this).attr('data-id') + ']').css('color', 'maroon');
                $('label[data-id=' + $(this).attr('data-id') + ']').css('font-weight', 'bolder');
            }

        });
    }

    $('body').on('click', '.addappend', function () {
        var tablep = $(this).attr('data-table');
        var tablename = $(this).attr('data-add');
        var id = $(this).attr('data-id');
        $.post(hosturle + '/controllers/' + controllname + '.php?ac=append', {
            tablename: tablename,
            tablep: tablep,
            id: id
        }, function (result) {
            $('#' + tablename).append(result);
            selectRefresh2();
            popoverhover();

        });



    });

    $('body').on('change', '.cd', function () {
        var id = $(this).attr('data-id');
        var value = Number($(this).val()) - 1;
        var infertilitysheetid = Number($('#infertilitysheetid').val());
        $.post(hosturle + '/controllers/' + controllname + '.php?ac=folliculom', {
            id: id,
            value: value,
            infertilitysheetid: infertilitysheetid
        }, function (result) {
            $("#date_" + id).val(result);
            $("#date_" + id).trigger('change');

        });

    });

    $('body').on('change', '.lmpfresh2', function () {
        $('.newcd').each(function () {
            var lmpfresh = $(".lmpfresh").val();
            var id = $(this).attr('data-id');
            var table = $(this).attr('data-table');
            var datename = $(this).attr('data-datename');
            var name = $(this).attr('name');
            var value = Number($(this).val() - 1);
            if (value != -1) {
                $.post(hosturle + '/controllers/' + controllname + '.php?ac=newcd', {
                    id: id,
                    lmpf: lmpfresh,
                    value: value,
                    datename: datename,
                    name: name,
                    table: table
                }, function (result) {
                    $("#" + datename + "_" + id).val(result);
                    $("#" + datename + "_" + id).trigger('change');
                });
            }
        });
    });

    $('body').on('change', '.lmpfrozen2', function () {
        $('.newcd2').each(function () {
            var lmpfrozen = $(".lmpfrozen").val();
            var id = $(this).attr('data-id');
            var table = $(this).attr('data-table');
            var datename = $(this).attr('data-datename');
            var name = $(this).attr('name');
            var value = Number($(this).val() - 1);
            if (value != -1) {
                $.post(hosturle + '/controllers/' + controllname + '.php?ac=newcd', {
                    id: id,
                    lmpf: lmpfrozen,
                    value: value,
                    datename: datename,
                    name: name,
                    table: table
                }, function (result) {
                    $("#" + datename + "_" + id).val(result);
                    $("#" + datename + "_" + id).trigger('change');

                });
            }
        });
    });

    $('body').on('change', '.newcd', function () {
        var lmpfresh = $(".lmpfresh").val();
        var id = $(this).attr('data-id');
        var table = $(this).attr('data-table');
        var datename = $(this).attr('data-datename');
        var name = $(this).attr('name');
        var value = Number($(this).val() - 1);
        $.post(hosturle + '/controllers/' + controllname + '.php?ac=newcd', {
            id: id,
            lmpf: lmpfresh,
            value: value,
            datename: datename,
            name: name,
            table: table
        }, function (result) {
            $("#" + datename + "_" + id).val(result);
            $("#" + datename + "_" + id).trigger('change');
        });
    });

    $('body').on('change', '.newcd2', function () {
        var lmpfrozen = $(".lmpfrozen").val();
        var id = $(this).attr('data-id');
        var table = $(this).attr('data-table');
        var datename = $(this).attr('data-datename');
        var name = $(this).attr('name');
        var value = Number($(this).val() - 1);
        $.post(hosturle + '/controllers/' + controllname + '.php?ac=newcd', {
            id: id,
            lmpf: lmpfrozen,
            value: value,
            datename: datename,
            name: name,
            table: table
        }, function (result) {
            $("#" + datename + "_" + id).val(result);
            $("#" + datename + "_" + id).trigger('change');
        });
    });

    $('body').on('click', '.toggle', function () {
        var tablename = $(this).attr('data-show');
        $("." + tablename).toggle();
    });

    $('body').on('click', '.fresh2', function () {
        $(".frozen").hide();
    });

    $('body').on('click', '.frozen2', function () {
        $(".fresh").hide();
    });

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

        var tablep = $(this).attr('data-table');
        var id = $(this).attr('data-id');
        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(hosturle + '/controllers/' + controllname + '.php?ac=deleterow', {
                            tablep: tablep,
                            id: id
                        }, function (result) {
                            if (result > 0) {
                                $('.row' + tablep + id).remove();
                            }
                        });

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

    $('body').on('click', '.chekdeleterow', function () {
        var tablep = $(this).attr('data-table');
        var id = $(this).attr('data-id');
        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(hosturle + '/controllers/' + controllname + '.php?ac=deleterow', {
                            tablep: tablep,
                            id: id
                        }, function (result) {
                            if (result > 0) {
                                $('.row' + tablep + id).remove();

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



    function obstetric() {
        var id = $('#infertilitysheetid').val();
        $.post(hosturle + '/controllers/infertilitysheet.php?ac=obstetric', {
            id: id
        }, function (result) {
            result = result.split(",");
            $('#obstg').text(result[0]);
            $('#obstp').text(result[1]);
            $('#obstft').text(result[2]);
            $('#obstpt').text(result[3]);
            $('#obstepc').text(result[4]);
            $('#obstliving').text(result[5]);

            $('#obstgv').text(result[0]);
            $('#obstpv').text(result[1]);
            $('#obstepcv').text(result[4]);
        });
    }
    ;



    $('body').on('change', '.usvsdtv', function () {
        var table = $(this).attr('data-table');
        var id = $(this).attr('data-id');
        var name = "usvsdtv";
        var value = $(this).val().toString();
        $.post(hosturle + '/controllers/' + controllname + '.php?ac=Add', {
            table: table,
            name: name,
            value: value,
            id: id
        });

    });


});
