//check for report page

var hosturl = $('#hosturl').val();
if ($('#reportPage').val() == 1)
{
    $(document).ready(function () {
        $(".bp_mask").inputmask("999/999", {
            autoUnmask: true});
    });
    var hosturl = $('#hosturl').val();
    var tdate = $("#tdate").val();
    var controllName = $("#controllName").val();
    ///////////////Expected Delivery
    $("#fromdate").live('change', function () {

        var fromdate = $(this).val();
        var todate = $("#todate").val();
        $.post(hosturl + '/controllers/' + controllName + '.php?ac=search', {fromdate: fromdate, todate: todate}, function (res)
        {
            $("#expectedDiv").html("");
            $("#expectedDiv").append(res);

        });

    });

    $("#todate").live('change', function () {

        var todate = $(this).val();
        var fromdate = $("#fromdate").val();
        $.post(hosturl + '/controllers/' + controllName + '.php?ac=search', {fromdate: fromdate, todate: todate}, function (res)
        {
            $("#expectedDiv").html("");
            $("#expectedDiv").append(res);

        });

    });

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

        var todate = $("#todate").val();
        var fromdate = $("#fromdate").val();
        $.post(hosturl + '/controllers/' + controllName + '.php?ac=showprint', {fromdate: fromdate, todate: todate}, function (res)
        {
            $("#expectedPrint").html(res);
            $.print("#expectedPrint");
            $("#expectedPrint").html('');

        });

    });

//////////////////////////Financial Report

    $('.searchFin').select2({
        width: '170px',
        allowClear: true,
        minimumInputLength: 3,
        formatNoMatches: function (term) {
            /* customize the no matches output */
        }
    }).parent().find('.select2-with-searchbox').on('click', '#addddNew', function () {
        var newitem = $('#newddTerm').val();

    });


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

        if (deptId > 0) {
            $.post(hosturl + '/controllers/visits.php?ac=getDoctor', {role_id: deptId}, function (data) {
                var obj = JSON.parse(data);
                if (obj.doctor_show == 1) {
                    $('#repDoctors').html(obj.doctors);
                    $('#repDoctors').select2();
                } else {
                    $('#repDoctors').html('<option value="">choose</option>');
                    $('#repDoctors').select2();
                }
            });

            if (deptId == 12) {
                $('#labDiv').show();
            } else {
                $('#labDiv').hide();
            }


        } else {
            $('#reserve_action_div').hide();
            $('#offersDiv').hide();
            $('#labDiv').hide();
        }
    });

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

        if (labType == 1) {
            $('#offersDiv').show();
        } else {
            $('#offersDiv').hide();
        }
    });

    $(".finSearch").live('change', function () {

        var fdate = $("#findate").val();
        var todate = $("#tofindate").val();
        var value = $("#patientName").val();
        var hvalue = $("#husband").val();
        var userId = $("#userId").val();
        var fordepartment = $("#fordepartment").val();
        var repDoctors = $("#repDoctors").val();

        var labType = $("#labType").val();
        var offerId = $("#offerId").val();


        if ($(this).attr('id') == "husband")
            value = '';
        $.post(hosturl + '/controllers/' + controllName + '.php?ac=search', {fdate: fdate, todate: todate
            , value: value, hvalue: hvalue, userId: userId, fordepartment: fordepartment
            , repDoctors: repDoctors, labType: labType, offerId: offerId}, function (res)
        {
            $("#financialDiv").html("");
            $("#financialDiv").append(res);

//            $('.operation_rslt').select2();
        });

    });

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

        var fdate = $("#findate").val();
        var todate = $("#tofindate").val();
        var value = $("#patientName").val();
        var hvalue = $("#husband").val();
        var userId = $("#userId").val();
        var fordepartment = $("#fordepartment").val();
        var repDoctors = $("#repDoctors").val();

        if ($(this).attr('id') == "husband")
            value = '';
        $.post(hosturl + '/controllers/' + controllName + '.php?ac=showprint', {fdate: fdate, todate: todate
            , value: value, hvalue: hvalue, userId: userId, fordepartment: fordepartment
            , repDoctors: repDoctors}, function (res)
        {
            $("#financialPrint").html(res);
            $.print("#financialPrint");
            $("#financialPrint").html('');

        });

    });

    $("#exportExcel").live('click', function () {
        var patientId = $('#patientid').val();
        if (patientId != 'undefined' && patientId != null && patientId != "")
        {
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=getexcel', {patientId: patientId}, function (res)
            {
                $("#filesExcel").html("");
                $("#filesExcel").html(res);
                $("#ExelSheetsD").modal('show');

            });
        } else
        {
            alert('Please Choose patient first ...........');
        }

    });

    /////////////////Complete Report
    $(".patientReport").live("change", function ()
    {
        var patientId = $(this).val();
        $("#patientid").val(patientId);
        $("#pNo").select2('val', patientId);
        $("#pName").select2('val', patientId);
        $.post(hosturl + '/controllers/' + controllName + '.php?ac=search', {patientId: patientId}, function (res)
        {
            $("#CompleteReportDiv").html("");
            $("#CompleteReportDiv").append(res);

            $(".bp_mask").inputmask("999/999", {
                autoUnmask: true});
            $("#printc").attr('data-id', patientId);
        });

    });

    $('.removeMsg').live('click', function () {
        $(this).parent().parent().remove();
    });

    $('#printc').live('click', function () {


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

        // window.location.href = hosturl + "/controllers/" + controllName + ".php?ac=showprint&id=" + id+"&patientid="+patientId;
        $.post(hosturl + '/controllers/' + controllName + '.php?ac=showprint', {patientid: patientId}, function (data)
        {
            $("#cprint").html(data);
            if ($("#reportNote").val() == "")
            {
                $("#pnotDiv").hide();
            } else
            {
                $("#preportNote").html($("#reportNote").val());
                $("#pnotDiv").show();
            }

            $.print("#cprint");
            $("#cprint").html('');
            $("#pnotDiv").show();
        });
    });

    $('#printCom').live('click', function () {
        var fage = $("#fromage").val();
        var toage = $("#toage").val();
        var diagnosis = new Array();
        var diagnosisant = new Array();
        var operation = $("#operation").val();
        var termination = $("#termination").val();

        $('#diagnosis :selected').each(function (i, selected) {
            diagnosis[i] = $(selected).val();
        });

        $('#diagnosisant :selected').each(function (i, selected) {
            diagnosisant[i] = $(selected).val();
        });
        if ($(this).attr("id") == "diagnosis" && $.inArray("0", diagnosis) != -1)
        {
            $("#diagnosis option:selected").removeAttr("selected");
            $("#diagnosis").select2();
        }
        if ($(this).attr("id") == "diagnosisant" && $.inArray("0", diagnosisant) != -1)
        {
            $("#diagnosisant option:selected").removeAttr("selected");
            $("#diagnosisant").select2();
        }
        $.post(hosturl + '/controllers/' + controllName + '.php?ac=showprint', {fage: fage, toage: toage, diagnosis: JSON.stringify(diagnosis), diagnosisant: JSON.stringify(diagnosisant), operation: operation, termination: termination}, function (res)
        {
            $("#comPrint").html(res);
            $.print("#comPrint");
            $("#comPrint").html('');
        });
    });

    $(".comSearch").live('change', function () {

        var fage = $("#fromage").val();
        var toage = $("#toage").val();
        var diagnosis = new Array();
        var diagnosisant = new Array();
        var operation = $("#operation").val();
        var termination = $("#termination").val();

        $('#diagnosis :selected').each(function (i, selected) {
            diagnosis[i] = $(selected).val();
        });

        $('#diagnosisant :selected').each(function (i, selected) {
            diagnosisant[i] = $(selected).val();
        });
        if ($(this).attr("id") == "diagnosis" && $.inArray("0", diagnosis) != -1)
        {
            $("#diagnosis option:selected").removeAttr("selected");
            $("#diagnosis").select2();
        }
        if ($(this).attr("id") == "diagnosisant" && $.inArray("0", diagnosisant) != -1)
        {
            $("#diagnosisant option:selected").removeAttr("selected");
            $("#diagnosisant").select2();
        }
        $.post(hosturl + '/controllers/' + controllName + '.php?ac=search', {fage: fage, toage: toage, diagnosis: JSON.stringify(diagnosis), diagnosisant: JSON.stringify(diagnosisant), operation: operation, termination: termination}, function (res)
        {
            $("#combinedDiv").html("");
            $("#combinedDiv").append(res);
        });

    });

    $('body').on('change', '.operation_attend', function () {

        if ($(this).is(':checked')) {
            var value = 1;
        } else {
            var value = 0;
        }

        var id = $(this).attr("data-id");
        var colName = $(this).attr("data-colName");
        var tableName = $(this).attr("data-tableName");


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

            if (value == 1) {
                $('#operationTr' + id).css("background-color", "#d8eac6");
            } else {
                $('#operationTr' + id).css("background-color", "");
            }

        });
    });



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

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

        var fdate = $("#findate").val();
        var todate = $("#tofindate").val();
        var value = $("#patientName").val();
        var hvalue = $("#husband").val();
        var userId = $("#userId").val();
        var fordepartment = $("#fordepartment").val();
        var repDoctors = $("#repDoctors").val();
        var detection = $("#detection").val();
        var referDrId = $("#referDrId").val();

        var labType = $("#labType").val();
        var offerId = $("#offerId").val();


        if ($(this).attr('id') == "husband")
            value = '';
        $.post(hosturl + '/controllers/' + controllName + '.php?ac=search', {fdate: fdate, todate: todate
            , value: value, hvalue: hvalue, userId: userId, fordepartment: fordepartment, referDrId: referDrId
            , repDoctors: repDoctors, labType: labType, offerId: offerId, detection: detection}, function (res)
        {
            $("#financialDiv").html("");
            $("#financialDiv").append(res);
            $('#talks-loading').hide();
        });

    });

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

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

        var value = $("#patientName").val();
        var hvalue = $("#husband").val();

        if (value > 0 || value > 0) {
            if ($(this).attr('id') == "husband")
                value = '';
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=rfcSearch', {value: value, hvalue: hvalue}, function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
                $('#talks-loading').hide();
            });
        } else {
            alert('choose patient first ..............');
            $('#talks-loading').hide();
        }

    });

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

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

        var fdate = $("#findate").val();
        var todate = $("#tofindate").val();
        var value = $("#patientName").val();
        var hvalue = $("#husband").val();
        var userId = $("#userId").val();
        var fordepartment = $("#fordepartment").val();
        var repDoctors = $("#repDoctors").val();



        if ($(this).attr('id') == "husband")
            value = '';
        $.post(hosturl + '/controllers/' + controllName + '.php?ac=packagesearch', {fdate: fdate, todate: todate
            , value: value, hvalue: hvalue, userId: userId, fordepartment: fordepartment
            , repDoctors: repDoctors}, function (res)
        {
            $("#financialDiv").html("");
            $("#financialDiv").append(res);
            $('#talks-loading').hide();
        });

    });

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

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

        var fdate = $("#findate").val();
        var todate = $("#tofindate").val();
        var repDoctors = $("#repDoctors").val();


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

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

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

        var value = $("#patientName").val();
        var hvalue = $("#husband").val();
        var userId = $("#userId").val();
        var findate = $("#findate").val();
        var todate = $("#tofindate").val();

        if (value > 0 || hvalue > 0 || userId > 0) {
            if ($(this).attr('id') == "husband")
                value = '';
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=visitSearch'
                    , {findate: findate, todate: todate, userId: userId, value: value, hvalue: hvalue}, function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
                $('#talks-loading').hide();
            });
        } else {
            alert('choose patient or user to search  ..............');
            $('#talks-loading').hide();
        }

    });

    $('body').on('click', '.visitUpdateDetails', function () {
        var visitId = $(this).attr("data-id");

        if (visitId > 0) {
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=visitUpdates', {visitId: visitId}, function (res) {
                $('#upVisitsDiv').html('');
                $('#upVisitsDiv').html(res);
                $("#upVisitsModel").modal('show');
            });
        }

    });

}


if ($('#terminationreport').val() == 1)
{
    $('#printf').live('click', function () {
        $("#printd").css('display', 'block');
        $.print("#printd");
        $("#printd").css('display', 'none');
    });
    var hosturl = $('#hosturl').val();
    var controllName = $("#controllName").val();
    $('.all').on('change', '#terminationType', function () {
        var value = $(this).val();
        $.post(hosturl + '/controllers/' + controllName + '.php?ac=search', {termtype: value}, function (res)
        {
            $("#expectedDiv").html("");
            $("#expectedDiv").append(res);

        });
    });
    //$('#repTable').dataTable();

}
if ($('#risktypePage').val() == 1)
{
    $('#printf').live('click', function () {
        var value = $('#risktype').val();
        $.post(hosturl + '/controllers/' + controllName + '.php?ac=showprint', {risktype: value}, function (res)
        {
            $("#riskPrint").html(res);
            $.print("#riskPrint");
            $("#riskPrint").html('');
        });
    });
    var hosturl = $('#hosturl').val();
    var controllName = $("#controllName").val();
    $('.all').on('change', '#risktype', function () {
        var value = $(this).val();
        $.post(hosturl + '/controllers/' + controllName + '.php?ac=search', {risktype: value}, function (res)
        {
            $("#expectedDiv").html("");
            $("#expectedDiv").append(res);

        });
    });
    //$('#repTable').dataTable();

}

var awcustomjs = function () {

    var initcontrolpropr = function () {

        var table = $('#controllpropr');

        // begin: third table
        table.dataTable({
            // Internationalisation. For more info refer to http://datatables.net/manual/i18n

            // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
            // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js).
            // So when dropdowns used the scrollable div should be removed.
            //"dom": "<'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",

            //"bStateSave": true, // save datatable state(pagination, sort, etc) in cookie.

            "lengthMenu": [
                [15, 20, -1],
                [15, 20, "All"] // change per page values here
            ],
            // set the initial value
            "pageLength": 15,
            "language": {
                "lengthMenu": " _MENU_",
                "aria": {
                    "sortAscending": ": Used to order Ascending",
                    "sortDescending": ": Used to order Descending"
                },
                "emptyTable": "NO data",
                "info": "Show _START_ From _END_ To _TOTAL_ item",
                "infoFiltered": "(Filter is _MAX_ from total)",
                "lengthMenu": "_MENU_",
                "search": "",
                "zeroRecords": "No search data"
            },
            "columnDefs": [{// set default column settings
                    'orderable': true,
                    'targets': [0]
                }],
            "order": [
                [4, "asc"]
            ] // set first column as a default sort by asc
        });
        var tableWrapper = jQuery('#controllprop_wrapper');

        tableWrapper.find('.dataTables_length select').select2(); // initialize select2 dropdown

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

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

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

                    });
                }
            });
            $("input.erpDBSaveMem").each(function () {
                var memid = Number($(this).attr('data-id'));
                var saveid = Number($('#saveid' + memid).val());
                var savename = $('#savename' + memid).val();
                if (saveid > 0 && savename != "") {
                    $('#erpDBSaveMem' + memid).select2('data', {id: saveid, text: savename});
                }
            });
        });
    }

    return {
        //main function to initiate the module
        init: function () {
            initcontrolpropr();
        }
    };
}();


if ($('#drReport').val() == 1)
{
    var controllName = $("#controllName").val();

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

        if (deptId > 0) {
            $.post(hosturl + '/controllers/visits.php?ac=getDoctor', {role_id: deptId}, function (data) {
                var obj = JSON.parse(data);
                $('#repDoctors').html(obj.doctors);
                $('#repDoctors').select2();
            });
        }
    });

    $(".finSearch").live('change', function () {
        var fdate = $("#findate").val();
        var todate = $("#tofindate").val();
        var repDoctors = $("#repDoctors").val();
        if (repDoctors > 0) {
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=drReportSearch', {fdate: fdate, todate: todate
                , repDoctors: repDoctors}, function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
            });
        }
    });

    $("#printfi").live('click', function () {
        var fdate = $("#findate").val();
        var todate = $("#tofindate").val();
        var repDoctors = $("#repDoctors").val();
        if (repDoctors > 0) {
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=drReportPrint', {fdate: fdate, todate: todate
                , repDoctors: repDoctors}, function (res)
            {
                $("#financialPrint").html(res);
                $.print("#financialPrint");
                $("#financialPrint").html('');
            });
        }
    });

    $(".orgSearch").live('change', function () {
        var fdate = $("#findate").val();
        var todate = $("#tofindate").val();
        var repDoctors = $("#repDoctors").val();
        var organization = $("#organization").val();

        if (repDoctors > 0) {
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=organizationReportSearch', {
                fdate: fdate, todate: todate, organization: organization
                , repDoctors: repDoctors}, function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
            });
        }
    });

    $("#printorg").live('click', function () {
        var fdate = $("#findate").val();
        var todate = $("#tofindate").val();
        var repDoctors = $("#repDoctors").val();
        var organization = $("#organization").val();

        if (repDoctors > 0 || organization > 0) {
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=organizationReportPrint', {
                fdate: fdate, todate: todate, organization: organization
                , repDoctors: repDoctors}, function (res)
            {
                $("#financialPrint").html(res);
                $.print("#financialPrint");
                $("#financialPrint").html('');
            });
        }
    });

    $("#orgSearchBtn").live('click', function () {
        var fdate = $("#findate").val();
        var todate = $("#tofindate").val();
        var repDoctors = $("#repDoctors").val();
        var organization = $("#organization").val();

        if (repDoctors > 0 || organization > 0) {
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=organizationReportSearch', {
                fdate: fdate, todate: todate, organization: organization
                , repDoctors: repDoctors}, function (res)
            {
                $("#financialDiv").html("");
                $("#financialDiv").append(res);
            });
        }
    });
}



if ($('#centerReport').val() == 1)
{
    var controllName = $("#controllName").val();

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

        if (deptId > 0) {
            $.post(hosturl + '/controllers/visits.php?ac=getDoctor', {role_id: deptId}, function (data) {
                var obj = JSON.parse(data);
                $('#repDoctors').html(obj.doctors);
                $('#repDoctors').select2();
            });
        }
    });

    $(".finSearch").live('change', function () {
        var fdate = $("#findate").val();
        var todate = $("#tofindate").val();
        var deptId = $('#fordepartment').val();
        var repDoctors = $("#repDoctors").val();

        $.post(hosturl + '/controllers/' + controllName + '.php?ac=centerReportSearch', {fdate: fdate, todate: todate
            , deptId: deptId, repDoctors: repDoctors}, function (res)
        {
            $("#financialDiv").html("");
            $("#financialDiv").append(res);
        });
    });

}


if ($('#controllName').val() == 'financialreport' || $('#controllName').val() == 'operationreport'
        || $('#trackingReport').val() == 1 || $('#externalLabReport').val() == 1 || $('#archiveReport').val() == 1) {
    var formatResultName = function (data) {
        return  data.name;
    }

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


    $("#patientName").select2({
        placeholder: "اختر ",
        minimumInputLength: 3,
        width: '100%',
        allowClear: true,
        quietMillis: 100,
        ajax: {
            url: hosturl + '/controllers/visits.php?ac=getWnames',
            dataType: 'json',
            data: function (term, page) {

                return {
                    term: term, //search term
                    page_limit: 10 // page size
                };
            },
            results: function (data) {
                //     alert(data);
                return {results: data};
            }
        },
        formatResult: formatResultName,
        formatSelection: formatSelectionName,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {
                id: item[0],
                name: item[1]
            };
            callback(data);
        }
    });

    $("#husband").select2({
        placeholder: "اختر ",
        minimumInputLength: 3,
        width: '100%',
        allowClear: true,
        quietMillis: 100,
        ajax: {
            url: hosturl + '/controllers/visits.php?ac=getHnames',
            dataType: 'json',
            data: function (term, page) {

                return {
                    term: term, //search term
                    page_limit: 10 // page size
                };
            },
            results: function (data) {
                //     alert(data);
                return {results: data};
            }
        },
        formatResult: formatResultName,
        formatSelection: formatSelectionName,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {
                id: item[0],
                name: item[1]
            };
            callback(data);
        }
    });

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


        var statusNo = $('#statusNoRemote').val();

        if (statusNo > 0) {
            $.post(hosturl + '/controllers/visits.php?ac=getnameswithstatus', {statusNo: statusNo}, function (res) {
                var obj = JSON.parse(res);

                // wife
                $('#patientName').val(null).empty();
                var option = new Option(obj.wifename, obj.id, true, true);
                $("#patientName").append(option);
                $('#patientName').select2("val", obj.id).trigger("change").trigger('select2:select');

                if ($('#trackingReport').val() == 1 || $('#externalLabReport').val() == 1 || $('#archiveReport').val() == 1) {
                    $('#husband').val(null).empty();
                    var option2 = new Option(obj.husdandname, obj.id, true, true);
                    $("#husband").append(option2);
                    $('#husband').select2("val", obj.id).trigger("change").trigger('select2:select');
                }

                if ($('#rfcSearch').val() == 1 || $('#visitSearchReport').val() == 1) {
                    $("#select2-chosen-1").html(obj.wifename);
                } else {
                    if ($('#controllName').val() == 'financialreport') {
                        $("#select2-chosen-2").html(obj.wifename);
                    } else if ($('#controllName').val() == 'operationreport') {
                        $("#select2-chosen-1").html(obj.wifename);
                    } else if ($('#trackingReport').val() == 1 || $('#externalLabReport').val() == 1 || $('#archiveReport').val() == 1) {
                        $("#select2-chosen-1").html(obj.wifename);
                        $("#select2-chosen-2").html(obj.husdandname);
                    }
                }

                if ($('#operationDataAll').val() == 1 && $('#opPatNo').val() > 0) {
                    $('#opSearchBtn').trigger('click');
                }


//                // husband
//                $('#husband').val(null).empty();
//                var option = new Option(obj.husdandname, obj.id, true, true);
//                $("#husband").append(option);
//                $('#husband').select2("val", obj.id).trigger("change").trigger('select2:select');
//                $("#select2-chosen-3").html(obj.husdandname);

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


if ($('#reserveReportPage').val() == 1)
{
    $('body').on('click', '#reserveSearch', function () {
        $.post(hosturl + '/controllers/operationreport.php?ac=reserveSearch', $("#reserveReportForm").serialize(), function (data) {
            $('#reserveDiv').html(data);
        });

    });
}


if ($('#center_reports').val() == 1)
{
    var controllName = $("#controllName").val();

    $("#centerReportsPrintBtn").live('click', function () {
        $('#talks-loading').show();
        var fromDate = $("#fromDate").val();
        var toDate = $("#toDate").val();
        var knownFrom = $("#knownFrom").val();
        var reportAc = $("#reportAc").val();

        $('#centerReportsSearchBtn').trigger('click');

        $.post(hosturl + '/controllers/' + controllName + '.php?ac=' + reportAc + 'Print', {
            fromDate: fromDate, toDate: toDate, knownFrom: knownFrom}, function (res) {
            $('#talks-loading').hide();
            $("#resultsPrintDiv").html(res);
            $.print("#resultsPrintDiv");
            $("#resultsPrintDiv").html('');

        });
    });

    $("#centerReportsSearchBtn").live('click', function () {
        $('#talks-loading').show();
        var fromDate = $("#fromDate").val();
        var toDate = $("#toDate").val();
        var knownFrom = $("#knownFrom").val();
        var reportAc = $("#reportAc").val();

        $.post(hosturl + '/controllers/' + controllName + '.php?ac=' + reportAc + 'Search', {
            fromDate: fromDate, toDate: toDate, knownFrom: knownFrom}, function (res) {
            $("#resultsDiv").html("");
            $("#resultsDiv").append(res);
            $('#talks-loading').hide();
        });
    });

    $('body').on('click', '.knownFromDetails', function () {
        var knownFromId = $(this).attr("data-id");
        var fromDate = $("#fromDate").val();
        var toDate = $("#toDate").val();

        if (knownFromId > 0) {
            $.post(hosturl + '/controllers/' + controllName + '.php?ac=knownFromDetails', {
                knownFromId: knownFromId, fromDate: fromDate, toDate: toDate}, function (res) {
                $('#knownPatDiv').html('');
                $('#knownPatDiv').html(res);
                $("#knownPatModel").modal('show');
            });
        }

    });

}