var calendar = {
    settings: {
        scheduleViewUrl: '',
        calendar_formUrl: '',
        calendar_formActionUrl: '',
        referring_health_facility_autocomplete_url: '',
        referring_provider_autocomplete_url: '',
        marketing_staff_autocomplete_url: '',
        health_facility_autocomplete_url: '',
        scheduleStatus_autocomplete_url: '',
        note_template_data_url: '',
        note_template_autocomplete_url: '',
        chartType_autocomplete_url: '',
        patientChartCheck_healthFacility_url: '',
        healthFacilityAjaxUrl: '',
        healthFacilitiesData: '',
        displayDistance_i: 0,
        displayDistance_i2: -1,
        noteTemplateAccess: '',
    },
    currentAjaxName: null,
    scheduleForm: {
        map: null,
        pMarker: null,
        hfMarker: null
    },
    init: function() {
        calendar.initElements();
        calendar.scheduleView();
        calendar.bindScheduleCalendarForm();
    },
    initMap: function(){
        var latLong = new google.maps.LatLng(53.5564402,-113.7368218); // Edmonton, Canada
        calendar.scheduleForm.map  = new google.maps.Map(document.getElementById('map-canvas'), {
            center: latLong,
            zoom: 5,
            gestureHandling: 'greedy',
            //scaleControl: false,
            streetViewControl: false,
            //rotateControl: false,
            fullscreenControl: false,
            // mapTypeControl: false,
            controlSize: 26,
            mapTypeControlOptions: {
                mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain']
            }
        });
    },
    initElements: function() {
        jQ('#schedule-facility-id').unbind('change').bind('change', calendar.scheduleView);
        jQ('.date-picker').mask('99/99/9999').datepicker({
            changeMonth: true,
            changeYear: true,
            'onSelect': calendar.scheduleView
        });
        jQ(window).scroll(function(){
            if(jQ(window).scrollTop() > 100) {
                let width = 'calc(100% - 10px)';
                if(!(jQ('#main-side-menu-container').css('margin-left') === '-222px')) {
                    width = 'calc(100% - 222px)';
                }
                jQ('#calendar-filter-container').css({'position': 'fixed', 'top' : '0', 'width' : width});
            } else {
                jQ('#calendar-filter-container').css({'position': 'initial', 'width' : 'auto'});
            }
        });
        jQ('#modal').on('closed.zf.reveal', function () {
            global.ajaxCancel(calendar.currentAjaxName);
            if(calendar.scheduleForm.hfMarker !== null){
                calendar.scheduleForm.hfMarker.setMap(null);
                calendar.scheduleForm.hfMarker = null;
            }
            if(calendar.scheduleForm.pMarker !== null){
                calendar.scheduleForm.pMarker.setMap(null);
                calendar.scheduleForm.pMarker = null;
            }

            let
                txtName = jQ('<span>').text(''),
                txtBirthDate = jQ('<span>').text(''),
                txtPHN = jQ('<span>').text(''),
                txtAddress = jQ('<span>').text(''),
                txtMobileNos = jQ('<span>').text(''),
                txtPhoneNos = jQ('<span>').text(''),
                insurances = jQ('<span>').text(''),
                chartStatus = jQ('<span>').text(''),
                chartType = jQ('<span>').text(''),
                chartDate = jQ('<span>').text(''),
                healthFacility = jQ('<span>').text(''),
                provider = jQ('<span>').text('');
            jQ('#patient-detail-name').html('');
            jQ('#patient-detail-birthDate').html('');
            jQ('#patient-detail-address').html('');
            jQ('#patient-detail-phn').html('');
            jQ('#patient-detail-mobile').html('');
            jQ('#patient-detail-phone').html('');
            jQ('#patient-detail-insurance').html('');
            jQ('#patient-detail-referring-health-facility').html('');
            jQ('#patient-detail-referring-provider').html('');
            jQ('#chart-detail-provider').html('');
            jQ('#chart-detail-health-facility').html('');
            jQ('#chart-detail-chart-type').html('');
            jQ('#chart-detail-chart-status').html('');
            jQ('#chart-detail-chart-date').html('');
            jQ('#patient-detail').html('');
            jQ('#chart-latest').html('');
            //txtId.appendTo(jQ('#patient-detail-id'));
            txtName.appendTo(jQ('#patient-detail-name'));
            txtBirthDate.appendTo('#patient-detail-birthDate');
            txtAddress.appendTo('#patient-detail-address');
            txtPHN.appendTo('#patient-detail-phn');
            txtMobileNos.appendTo('#patient-detail-mobile');
            txtPhoneNos.appendTo('#patient-detail-phone');
            insurances.appendTo('#patient-detail-insurance');
            provider.appendTo('#chart-detail-provider');
            healthFacility.appendTo('#chart-detail-health-facility');
            chartType.appendTo('#chart-detail-chart-type');
            chartStatus.appendTo('#chart-detail-chart-status');
            chartDate.appendTo('#chart-detail-chart-date');
            jQ('#schedule_patient_city_id').val('');
            jQ('#city-warning').css({'display': 'none'});
            jQ('#patient-chart-warning').css({'display': 'none'});
            calendar.closeTbody();
            global.formSubmittedReverse();
        });
    },
    scheduleView: function () {
        global.ajax({
            'url': calendar.settings.scheduleViewUrl,
            'type': 'GET',
            'data':{
                'healthFacility_id': jQ('#schedule-facility-id').val(),
                'date': jQ('#calendar-appoinment-date').val()
            },
            beforeSend: function(){
                jQ('#calendar-container').html('').addClass('has-loading');

            },
            success: function (data) {
                jQ('#calendar-container').removeClass('has-loading').html(data.html);
                calendar.bindScheduleCalendarForm();
                if(jQ('#calendar-datalist').length) {
                    jQ('#calendar-datalist').floatThead({
                        position: 'fixed',
                        zIndex: 0,
                        top: 65
                    });
                }
            }
        });
    },
    bindScheduleCalendarForm: function() {
        if(jQ('.schedule-calendar').length > 0) {
            jQ('.schedule-calendar').unbind('click').bind('click', function(){
                var requestName = 'scheduleCalendarForm',
                    modal = jQ('#modal'),
                    modalContent = jQ('#modal-form-container');
                calendar.currentAjaxName = requestName;
                global.ajaxCancel(requestName);

                var cityChecker = function () {
                        if(jQ('#schedule_patient_city_id').val() !== '' && jQ('#schedule_health_facility_city_id').val() !== '' && jQ('#schedule_health_facility_city_id').val() !== jQ('#schedule_patient_city_id').val()){
                            jQ('#city-warning').slideDown();
                        }else{
                            jQ('#city-warning').slideUp();
                        }
                    },
                    displayDistance =  function(batch_origins, batch_destinations, latLongDetails, howManyTimes) {
                        var loadingTd = jQ("<td>").attr({
                            style: 'padding: 0px; margin: 0px; white-space: nowrap',
                            colspan: '3',
                            class: 'has-loading temp-loading'
                        });
                        var service = new google.maps.DistanceMatrixService();
                        service.getDistanceMatrix({
                            origins: batch_origins[calendar.settings.displayDistance_i],
                            destinations: batch_destinations[calendar.settings.displayDistance_i],
                            travelMode: 'DRIVING'
                        }, function (response, status) {
                            if (status !== 'OK') {
                                alert('Google Error: ' + calendar.settings.displayDistance_i + status);
                                return;
                            }
                            let results = [];
                            for(let i = 0 ; i<response.rows.length; i++){
                                calendar.settings.displayDistance_i2 += 1;
                                console.log(calendar.settings.displayDistance_i2);
                                results.push({
                                    description : latLongDetails[calendar.settings.displayDistance_i2]['description'],
                                    result : response.rows[i]['elements'][i]
                                });
                            }
                            results = results.sort(function (a, b) {
                                return a.result.duration.value - b.result.duration.value;
                            });
                            jQ('#tbody-distance-table .temp-loading').remove();
                            for(let j =0 ; j<results.length; j++){
                                var element = results[j].result,
                                    tr = jQ('<tr>'),
                                    td1 = jQ('<td>').attr({
                                        style: 'padding: 0px; margin: 0px; white-space: nowrap'
                                    }),
                                    td2 = jQ('<td>').attr({
                                        style: 'padding: 0px; margin: 0px; white-space: nowrap; text-align:center;'
                                    }),
                                    td3 = jQ('<td>').attr({
                                        style: 'padding: 0px; margin: 0px; white-space: nowrap; text-align:center;'
                                    }),
                                    distance = jQ('<span>').text(element.distance.text),
                                    duration = jQ('<span>').text(element.duration.text),
                                    destination = jQ('<span>').text(results[j]['description']);
                                destination.appendTo(td1);
                                distance.appendTo(td2);
                                duration.appendTo(td3);
                                td1.appendTo(tr);
                                td2.appendTo(tr);
                                td3.appendTo(tr);
                                tr.appendTo('#tbody-distance-table');
                                loadingTd.appendTo('#tbody-distance-table');
                                if( calendar.settings.displayDistance_i < howManyTimes ){
                                } else {
                                    jQ('#tbody-distance-table .temp-loading').remove();
                                }
                            }
                        });
                        calendar.settings.displayDistance_i += 1;
                        if( calendar.settings.displayDistance_i < howManyTimes ){
                            setTimeout( function () {
                                displayDistance(batch_origins, batch_destinations, latLongDetails, howManyTimes);
                            }, 10000 );
                        } else {
                            setTimeout(function () {
                                jQ('#tbody-distance-table .temp-loading').remove();
                            }, 10000);
                        }
                    },
                    latLngChecker = function () {
                        var hfGeoLat = jQ('#schedule_health_facility_geoLat').val(),
                            hfGeolong =  jQ('#schedule_health_facility_geoLong').val();

                        if(hfGeoLat !== '' && hfGeolong !== ''){
                            if(calendar.scheduleForm.hfMarker === null){
                                calendar.scheduleForm.hfMarker = new google.maps.Marker({
                                    map: calendar.scheduleForm.map,
                                    position : new google.maps.LatLng(hfGeoLat, hfGeolong),
                                    icon:'/bundles/rxconnexion/admin/images/map-icon/HF.png'
                                });
                            }else{
                                calendar.scheduleForm.hfMarker.setPosition(new google.maps.LatLng(hfGeoLat, hfGeolong));
                            }
                        }

                        var pGeoLat = jQ('#schedule_patient_geoLat').val(),
                            pGeolong =  jQ('#schedule_patient_geoLong').val();

                        if(calendar.scheduleForm.hfMarker !== null && calendar.scheduleForm.pMarker !== null){
                            let latLngBounds = new google.maps.LatLngBounds();
                            latLngBounds.extend(calendar.scheduleForm.pMarker.getPosition());
                            latLngBounds.extend(calendar.scheduleForm.hfMarker.getPosition());
                            calendar.scheduleForm.map.fitBounds(latLngBounds);
                        }
                        if(pGeoLat !== '' && pGeoLat !== null && pGeolong !== '' && pGeolong != null){
                            if(calendar.scheduleForm.pMarker === null){
                                calendar.scheduleForm.pMarker = new google.maps.Marker({
                                    map: calendar.scheduleForm.map,
                                    position : new google.maps.LatLng(pGeoLat, pGeolong),
                                });
                            }else{
                                calendar.scheduleForm.pMarker.setPosition(new google.maps.LatLng(pGeoLat, pGeolong));
                            }
                            var latLongDetails = JSON.parse(calendar.settings.healthFacilitiesData),
                                origin = new google.maps.LatLng(pGeoLat, pGeolong);
                            /*    thead = jQ('<thead onclick="calendar.closeTbody()">').attr({
                                    id : 'thead-distance-table'
                                }),
                                th1 = jQ('<th class="open-tbody">').text('Branch'),
                                th2 = jQ('<th nowrap class="open-tbody">').text('Distance'),
                                th3 = jQ('<th class="open-tbody">').text('Duration');
                            th1.appendTo(thead);
                            th2.appendTo(thead);
                            th3.appendTo(thead);
                            thead.appendTo('#distance-table');*/
                            let origins = [],
                                destinations = [],
                                batch_origins = [],
                                batch_destinations = [],
                                batch_idx = -1;
                            for(let x=0; x<latLongDetails.length; x++){
                                if(x % 9 === 0){
                                    batch_idx += 1;
                                    batch_origins.push([origin]);
                                    batch_destinations.push([latLongDetails[x]['latLng']]);
                                } else {
                                    batch_origins[batch_idx].push(origin);
                                    batch_destinations[batch_idx].push(latLongDetails[x]['latLng']);
                                }
                                /*if((origins.length + destinations.length) < 20){
                                    origins.push(origin);
                                    destinations.push(latLongDetails[x]['latLng']);
                                }*/
                            }

                            jQ('#view-details').unbind('click').bind('click', function () {
                                jQ('#tbody-distance-table').empty();
                                calendar.settings.displayDistance_i2 = -1;
                                calendar.settings.displayDistance_i = 0;
                                displayDistance(batch_origins, batch_destinations, latLongDetails, batch_origins.length);
                                /*var service = new google.maps.DistanceMatrixService();
                                service.getDistanceMatrix({
                                    origins: origins,
                                    destinations: destinations,
                                    travelMode: 'DRIVING'
                                }, function (response, status) {
                                    if (status !== 'OK') {
                                        alert('Google Error: ' + status)
                                        return;
                                    }
                                    let results = [];
                                    for(let i=0 ; i<response.rows.length; i++){
                                        results.push({
                                            description : latLongDetails[i]['description'],
                                            result : response.rows[i]['elements'][i]
                                        });
                                    }
                                    results = results.sort(function (a, b) {
                                        return a.result.duration.value - b.result.duration.value;
                                    });
                                    for(let j =0 ; j<results.length; j++){
                                        var element = results[j].result,
                                            tr = jQ('<tr>'),
                                            td1 = jQ('<td>').attr({
                                                style: 'padding: 0px; margin: 0px; white-space: nowrap'
                                            }),
                                            td2 = jQ('<td>').attr({
                                                style: 'padding: 0px; margin: 0px; white-space: nowrap; text-align:center;'
                                            }),
                                            td3 = jQ('<td>').attr({
                                                style: 'padding: 0px; margin: 0px; white-space: nowrap; text-align:center;'
                                            }),
                                            distance = jQ('<span>').text(element.distance.text),
                                            duration = jQ('<span>').text(element.duration.text),
                                            destination = jQ('<span>').text(results[j]['description']);
                                        destination.appendTo(td1);
                                        distance.appendTo(td2);
                                        duration.appendTo(td3);
                                        td1.appendTo(tr);
                                        td2.appendTo(tr);
                                        td3.appendTo(tr);
                                        tr.appendTo('#tbody-distance-table');
                                    }
                                });*/
                                jQ('#distance-table').removeClass('hide');
                                jQ('#view-details').addClass('hide');
                            });
                        }else{
                            jQ('#view-details').unbind('click').bind('click', function () {
                                alert('Patient has no location details. Please update patient information.');
                            });
                        }
                    };
                var settings = {
                    url: calendar.settings.calendar_formUrl,
                    type: 'GET',
                    data: {
                        'healthFacility_id': jQ('#schedule-facility-id').val(),
                        'date': jQ('#calendar-appoinment-date').val(),
                        'marketing_staff_id': jQ(this).data('provider'),
                        'start_time': jQ(this).data('time'),
                        'action': jQ(this).data('action'),
                        'id': jQ(this).data('id')
                    },
                    beforeSend: function() {
                        modalContent.html('').addClass('has-loading');
                        modal.foundation('open');
                    },
                    success: function(json) {
                        modal.foundation('close');
                        modalContent.removeClass('has-loading').html(json.html);
                        modal.foundation('open');
                        /*jQ(this).data('provider');*/
                        let action =  json.action,
                            branchDetails = json.branchDetails,
                            branchAddress = jQ('<span>').text(branchDetails.address),
                            mobileNos = jQ('<span>').text(branchDetails.mobileNos),
                            phoneNos = jQ('<span>').text(branchDetails.phoneNos);
                        jQ('#save-action').val(action);
                        jQ('#delete-action').val(action);
                        jQ('#save-action').data('axn', action);
                        if(action === 'u') {
                            /*if(json.latestPatientChartDetails !== undefined && json.latestPatientChartDetails !== null){
                                let
                                    patientChartDetails = json.latestPatientChartDetails,
                                    chartStatus = jQ('<span>').text(patientChartDetails.chartStatus),
                                    chartType = jQ('<span>').text(patientChartDetails.chartType),
                                    chartDate = jQ('<span>').text(patientChartDetails.chartDate),
                                    healthFacility = jQ('<span>').text(patientChartDetails.healthFacility),
                                    provider = jQ('<span>').text(patientChartDetails.provider);

                                provider.appendTo('#chart-detail-provider');
                                healthFacility.appendTo(jQ('#chart-detail-health-facility'));
                                chartType.appendTo('#chart-detail-chart-type');
                                chartStatus.appendTo('#chart-detail-chart-status');
                                chartDate.appendTo('#chart-detail-chart-date');
                            }*/

                            let
                                patientDetails = json.patientDetails,
                                txtName = jQ('<span>').html(patientDetails.patientName),
                                txtBirthDate = jQ('<span>').text(patientDetails.birthDate),
                                txtPHN = jQ('<span>').text(patientDetails.personalHealthNo),
                                txtAddress = jQ('<span>').text(patientDetails.address),
                                txtMobileNos = jQ('<span>').text(patientDetails.mobileNos),
                                txtPhoneNos = jQ('<span>').text(patientDetails.phoneNos),
                                insurances = jQ('<span>').text(patientDetails.insurances);

                            jQ('#patient-detail-name').html('<strong>Full Name: </strong>');
                            jQ('#patient-detail-birthDate').html('<strong>Birth Date: </strong>');
                            jQ('#patient-detail-address').html('<strong>Address: </strong>');
                            jQ('#patient-detail-phn').html('<strong>PHN: </strong>');
                            jQ('#patient-detail-mobile').html('<strong>Mobile No(s): </strong>');
                            jQ('#patient-detail-phone').html('<strong>Phone No(s): </strong>');
                            jQ('#patient-detail-insurance').html('<strong>Insurance(s): </strong>');
                            jQ('#chart-detail-provider').html('<strong>Clinician: </strong>');
                            jQ('#chart-detail-health-facility').html('<strong>Branch: </strong>');
                            jQ('#chart-detail-chart-type').html('<strong>Chart Type: </strong>');
                            jQ('#chart-detail-chart-status').html('<strong>Chart Status: </strong>');
                            jQ('#chart-detail-chart-date').html('<strong>Chart Date: </strong>');
                            jQ('#patient-detail').html('<h5>Patient Details </h5>');
                            jQ('#chart-latest').html('<h5>Latest Chart </h5>');
                            jQ('#branch-detail-address').html('<strong>Address: </strong>');
                            jQ('#branch-detail-mobileNos').html('<strong>Fax No(s): </strong>');
                            jQ('#branch-detail-phoneNos').html('<strong>Phone No(s): </strong>');
                            txtName.appendTo(jQ('#patient-detail-name'));
                            txtBirthDate.appendTo('#patient-detail-birthDate');
                            txtAddress.appendTo('#patient-detail-address');
                            txtPHN.appendTo('#patient-detail-phn');
                            txtMobileNos.appendTo('#patient-detail-mobile');
                            txtPhoneNos.appendTo('#patient-detail-phone');
                            insurances.appendTo('#patient-detail-insurance');
                            branchAddress.appendTo('#branch-detail-address');
                            mobileNos.appendTo('#branch-detail-mobileNos');
                            phoneNos.appendTo('#branch-detail-phoneNos');
                            latLngChecker();
                            jQ('#save-action').addClass('ask-continue');
                            jQ('#save-action').removeClass('just-continue');
                            jQ('#delete-action').removeClass('hide');

                            if(json.latestPatientChartDetails !== undefined && json.latestPatientChartDetails !== null){
                                let
                                    patientChartDetails = json.latestPatientChartDetails,
                                    chartStatus = jQ('<span>').text(patientChartDetails.chartStatus),
                                    chartType = jQ('<span>').text(patientChartDetails.chartType),
                                    chartDate = jQ('<span>').text(patientChartDetails.chartDate),
                                    healthFacility = jQ('<span>').text(patientChartDetails.healthFacility),
                                    provider = jQ('<span>').text(patientChartDetails.provider);

                                provider.appendTo('#chart-detail-provider');
                                healthFacility.appendTo(jQ('#chart-detail-health-facility'));
                                chartType.appendTo('#chart-detail-chart-type');
                                chartStatus.appendTo('#chart-detail-chart-status');
                                chartDate.appendTo('#chart-detail-chart-date');
                            }
                        }else{
                            jQ('#branch-detail-address').html('<strong>Address: </strong>');
                            jQ('#branch-detail-mobileNos').html('<strong>Fax No(s): </strong>');
                            jQ('#branch-detail-phoneNos').html('<strong>Phone No(s): </strong>');
                            branchAddress.appendTo('#branch-detail-address');
                            mobileNos.appendTo('#branch-detail-mobileNos');
                            phoneNos.appendTo('#branch-detail-phoneNos');
                            latLngChecker();
                            jQ('#save-action').removeClass('ask-continue');
                            jQ('#save-action').addClass('just-continue');
                            jQ('#delete-action').addClass('hide');
                        }
                        
                        global.autocomplete.bind(calendar.settings.referring_health_facility_autocomplete_url, '#marketingStaffScheduleForCalendar_referringHealthFacility_desc', '#marketingStaffScheduleForCalendar_referringHealthFacility',{
                            onSelect: function (e) {
                                calendar.closeTbody();
                                // if((e.geoLat === null && e.geoLat === '') || (e.geoLong === null || e.geoLong === '')){
                                //     const geocoder = new google.maps.Geocoder();
                                //     geocoder.geocode(
                                //         {
                                //             'address': e.address,
                                //             'country': 'CA'
                                //         }, function (results, status) {
                                //             if (status === google.maps.GeocoderStatus.OK) {
                                //                 jQ('#schedule_patient_geoLat').val(results[0].geometry.location.lat());
                                //                 jQ('#schedule_patient_geoLong').val(results[0].geometry.location.lng());
                                //                 latLngChecker();
                                //             } else {
                                //                 if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                                //                     wait = true;
                                //                     setTimeout("wait = true", 2000);
                                //                 }else{
                                //                     //Error handling
                                //                     alert('Geocode was not successful for the following reason: ' + status);
                                //                 }
                                //             }
                                //         });
                                // }else{
                                //     jQ('#marketingStaffScheduleForCalendar_patient_geoLat').val(e.geoLat);
                                //     jQ('#marketingStaffScheduleForCalendar_patient_geoLong').val(e.geoLong);
                                //     latLngChecker();
                                // }
                                if(e.patientChartDetails.length){
                                    var
                                        chartDetail = e.patientChartDetails.split('|'),
                                        chartStatus = jQ('<span>').text(chartDetail[1]),
                                        chartType = jQ('<span>').text(chartDetail[2]),
                                        chartDate = jQ('<span>').text(chartDetail[3]),
                                        healthFacility = jQ('<span>').text(chartDetail[4]),
                                        provider = jQ('<span>').text(chartDetail[5]);
                                }
                                var
                                    //txtId = jQ('<span>').text(e.id),
                                    txtName = jQ('<span>').text(e.data),
                                    txtBirthDate = jQ('<span>').text(e.birthDate),
                                    txtPHN = jQ('<span>').text(e.personal_health_no),
                                    txtAddress = jQ('<span>').text(e.address),
                                    txtMobileNos = jQ('<span>').text(e.mobileNos),
                                    txtPhoneNos = jQ('<span>').text(e.phoneNos),
                                    insurances = jQ('<span>').text(e.insurances),
                                    rhf = jQ('<span>').text(e.referringHealthFacilities),
                                    rp = jQ('<span>').text(e.referringProviders);


                                /*if(e.geoLat !== '' && e.geoLat !== null && e.geoLong !== '' && e.geoLong != null){
                                    var latLongDetails = JSON.parse(calendar.settings.healthFacilitiesData),
                                        origin = new google.maps.LatLng(e.geoLat, e.geoLong),
                                        service = new google.maps.DistanceMatrixService();

                                    jQ('#tbody-distance-table').empty();
                                    for(let x=0; x<latLongDetails.length; x++){
                                        service.getDistanceMatrix({
                                            origins: [origin],
                                            destinations: [latLongDetails[x]['latLng']],
                                            travelMode: 'DRIVING'
                                        }, function (response, status) {
                                            if (status === 'OK') {
                                                var origins = response.originAddresses;
                                                for (let i = 0; i < origins.length; i++) {
                                                    var results = response.rows[i].elements;
                                                    for (let j = 0; j < results.length; j++) {
                                                        var element = results[j],
                                                            tr = jQ('<tr>'),
                                                            td1 = jQ('<td>').attr({
                                                                style: 'padding: 0px; margin: 0px; white-space: nowrap'
                                                            }),
                                                            td2 = jQ('<td>').attr({
                                                                style: 'padding: 0px; margin: 0px; white-space: nowrap; text-align:center;'
                                                            }),
                                                            td3 = jQ('<td>').attr({
                                                                style: 'padding: 0px; margin: 0px; white-space: nowrap; text-align:center;'
                                                            }),
                                                            distance = jQ('<span>').text(element.distance.text),
                                                            duration = jQ('<span>').text(element.duration.text),
                                                            destination = jQ('<span>').text(latLongDetails[x]['description']);
                                                        destination.appendTo(td1);
                                                        distance.appendTo(td2);
                                                        duration.appendTo(td3);
                                                        td1.appendTo(tr);
                                                        td2.appendTo(tr);
                                                        td3.appendTo(tr);
                                                        tr.appendTo('#tbody-distance-table');
                                                    }
                                                }
                                            }
                                        });
                                    }
                                }*/

                                //jQ('#patient-detail-id').html('<strong>ID: </strong>');
                                jQ('#patient-detail-name').html('<strong>Full Name: </strong>');
                                jQ('#patient-detail-birthDate').html('<strong>Birth Date: </strong>');
                                jQ('#patient-detail-address').html('<strong>Address: </strong>');
                                jQ('#patient-detail-phn').html('<strong>PHN: </strong>');
                                jQ('#patient-detail-mobile').html('<strong>Mobile No(s): </strong>');
                                jQ('#patient-detail-phone').html('<strong>Phone No(s): </strong>');
                                jQ('#patient-detail-insurance').html('<strong>Insurance(s): </strong>');
                                jQ('#patient-detail-referring-health-facility').html('<strong>Referring Health Facility: </strong>');
                                jQ('#patient-detail-referring-provider').html('<strong>Referring Physician: </strong>');
                                jQ('#chart-detail-provider').html('<strong>Marketing Staff: </strong>');
                                jQ('#chart-detail-health-facility').html('<strong>Branch: </strong>');
                                jQ('#chart-detail-chart-type').html('<strong>Chart Type: </strong>');
                                jQ('#chart-detail-chart-status').html('<strong>Chart Status: </strong>');
                                jQ('#chart-detail-chart-date').html('<strong>Chart Date: </strong>');
                                jQ('#patient-detail').html('<h5>Patient Details </h5>');
                                jQ('#chart-latest').html('<h5>Latest Chart </h5>');
                                //txtId.appendTo(jQ('#patient-detail-id'));
                                txtName.appendTo(jQ('#patient-detail-name'));
                                txtBirthDate.appendTo('#patient-detail-birthDate');
                                txtAddress.appendTo('#patient-detail-address');
                                txtPHN.appendTo('#patient-detail-phn');
                                txtMobileNos.appendTo('#patient-detail-mobile');
                                txtPhoneNos.appendTo('#patient-detail-phone');
                                insurances.appendTo('#patient-detail-insurance');
                                rhf.appendTo('#patient-detail-referring-health-facility');
                                rp.appendTo('#patient-detail-referring-provider');
                                if(provider !== undefined) provider.appendTo('#chart-detail-provider');
                                if(healthFacility !== undefined) healthFacility.appendTo('#chart-detail-health-facility');
                                if(chartType !== undefined) chartType.appendTo('#chart-detail-chart-type');
                                if(chartStatus !== undefined) chartStatus.appendTo('#chart-detail-chart-status');
                                if(chartDate !== undefined) chartDate.appendTo('#chart-detail-chart-date');
                                jQ('#schedule_patient_city_id').val(e.city_id);
                                cityChecker();
                            }
                        });
                        global.autocomplete.bind(calendar.settings.referring_provider_autocomplete_url, '#marketingStaffScheduleForCalendar_referringProvider_fullName', '#marketingStaffScheduleForCalendar_referringProvider',{
                            onSelect: function (e) {
                                calendar.closeTbody();
                                // if((e.geoLat === null && e.geoLat === '') || (e.geoLong === null || e.geoLong === '')){
                                //     const geocoder = new google.maps.Geocoder();
                                //     geocoder.geocode(
                                //         {
                                //             'address': e.address,
                                //             'country': 'CA'
                                //         }, function (results, status) {
                                //             if (status === google.maps.GeocoderStatus.OK) {
                                //                 jQ('#schedule_patient_geoLat').val(results[0].geometry.location.lat());
                                //                 jQ('#schedule_patient_geoLong').val(results[0].geometry.location.lng());
                                //                 latLngChecker();
                                //             } else {
                                //                 if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                                //                     wait = true;
                                //                     setTimeout("wait = true", 2000);
                                //                 }else{
                                //                     //Error handling
                                //                     alert('Geocode was not successful for the following reason: ' + status);
                                //                 }
                                //             }
                                //         });
                                // }else{
                                //     jQ('#marketingStaffScheduleForCalendar_patient_geoLat').val(e.geoLat);
                                //     jQ('#marketingStaffScheduleForCalendar_patient_geoLong').val(e.geoLong);
                                //     latLngChecker();
                                // }
                                if(e.patientChartDetails.length){
                                    var
                                        chartDetail = e.patientChartDetails.split('|'),
                                        chartStatus = jQ('<span>').text(chartDetail[1]),
                                        chartType = jQ('<span>').text(chartDetail[2]),
                                        chartDate = jQ('<span>').text(chartDetail[3]),
                                        healthFacility = jQ('<span>').text(chartDetail[4]),
                                        provider = jQ('<span>').text(chartDetail[5]);
                                }
                                var
                                    //txtId = jQ('<span>').text(e.id),
                                    txtName = jQ('<span>').text(e.data),
                                    txtBirthDate = jQ('<span>').text(e.birthDate),
                                    txtPHN = jQ('<span>').text(e.personal_health_no),
                                    txtAddress = jQ('<span>').text(e.address),
                                    txtMobileNos = jQ('<span>').text(e.mobileNos),
                                    txtPhoneNos = jQ('<span>').text(e.phoneNos),
                                    insurances = jQ('<span>').text(e.insurances),
                                    rhf = jQ('<span>').text(e.referringHealthFacilities),
                                    rp = jQ('<span>').text(e.referringProviders);


                                /*if(e.geoLat !== '' && e.geoLat !== null && e.geoLong !== '' && e.geoLong != null){
                                    var latLongDetails = JSON.parse(calendar.settings.healthFacilitiesData),
                                        origin = new google.maps.LatLng(e.geoLat, e.geoLong),
                                        service = new google.maps.DistanceMatrixService();

                                    jQ('#tbody-distance-table').empty();
                                    for(let x=0; x<latLongDetails.length; x++){
                                        service.getDistanceMatrix({
                                            origins: [origin],
                                            destinations: [latLongDetails[x]['latLng']],
                                            travelMode: 'DRIVING'
                                        }, function (response, status) {
                                            if (status === 'OK') {
                                                var origins = response.originAddresses;
                                                for (let i = 0; i < origins.length; i++) {
                                                    var results = response.rows[i].elements;
                                                    for (let j = 0; j < results.length; j++) {
                                                        var element = results[j],
                                                            tr = jQ('<tr>'),
                                                            td1 = jQ('<td>').attr({
                                                                style: 'padding: 0px; margin: 0px; white-space: nowrap'
                                                            }),
                                                            td2 = jQ('<td>').attr({
                                                                style: 'padding: 0px; margin: 0px; white-space: nowrap; text-align:center;'
                                                            }),
                                                            td3 = jQ('<td>').attr({
                                                                style: 'padding: 0px; margin: 0px; white-space: nowrap; text-align:center;'
                                                            }),
                                                            distance = jQ('<span>').text(element.distance.text),
                                                            duration = jQ('<span>').text(element.duration.text),
                                                            destination = jQ('<span>').text(latLongDetails[x]['description']);
                                                        destination.appendTo(td1);
                                                        distance.appendTo(td2);
                                                        duration.appendTo(td3);
                                                        td1.appendTo(tr);
                                                        td2.appendTo(tr);
                                                        td3.appendTo(tr);
                                                        tr.appendTo('#tbody-distance-table');
                                                    }
                                                }
                                            }
                                        });
                                    }
                                }*/

                                //jQ('#patient-detail-id').html('<strong>ID: </strong>');
                                jQ('#patient-detail-name').html('<strong>Full Name: </strong>');
                                jQ('#patient-detail-birthDate').html('<strong>Birth Date: </strong>');
                                jQ('#patient-detail-address').html('<strong>Address: </strong>');
                                jQ('#patient-detail-phn').html('<strong>PHN: </strong>');
                                jQ('#patient-detail-mobile').html('<strong>Mobile No(s): </strong>');
                                jQ('#patient-detail-phone').html('<strong>Phone No(s): </strong>');
                                jQ('#patient-detail-insurance').html('<strong>Insurance(s): </strong>');
                                jQ('#patient-detail-referring-health-facility').html('<strong>Referring Health Facility: </strong>');
                                jQ('#patient-detail-referring-provider').html('<strong>Referring Physician: </strong>');
                                jQ('#chart-detail-provider').html('<strong>Marketing Staff: </strong>');
                                jQ('#chart-detail-health-facility').html('<strong>Branch: </strong>');
                                jQ('#chart-detail-chart-type').html('<strong>Chart Type: </strong>');
                                jQ('#chart-detail-chart-status').html('<strong>Chart Status: </strong>');
                                jQ('#chart-detail-chart-date').html('<strong>Chart Date: </strong>');
                                jQ('#patient-detail').html('<h5>Patient Details </h5>');
                                jQ('#chart-latest').html('<h5>Latest Chart </h5>');
                                //txtId.appendTo(jQ('#patient-detail-id'));
                                txtName.appendTo(jQ('#patient-detail-name'));
                                txtBirthDate.appendTo('#patient-detail-birthDate');
                                txtAddress.appendTo('#patient-detail-address');
                                txtPHN.appendTo('#patient-detail-phn');
                                txtMobileNos.appendTo('#patient-detail-mobile');
                                txtPhoneNos.appendTo('#patient-detail-phone');
                                insurances.appendTo('#patient-detail-insurance');
                                rhf.appendTo('#patient-detail-referring-health-facility');
                                rp.appendTo('#patient-detail-referring-provider');
                                if(provider !== undefined) provider.appendTo('#chart-detail-provider');
                                if(healthFacility !== undefined) healthFacility.appendTo('#chart-detail-health-facility');
                                if(chartType !== undefined) chartType.appendTo('#chart-detail-chart-type');
                                if(chartStatus !== undefined) chartStatus.appendTo('#chart-detail-chart-status');
                                if(chartDate !== undefined) chartDate.appendTo('#chart-detail-chart-date');
                                jQ('#schedule_patient_city_id').val(e.city_id);
                                cityChecker();
                            }
                        });
                        global.autocomplete.bind(calendar.settings.marketing_staff_autocomplete_url, '#marketingStaffScheduleForCalendar_marketingStaff_fullName', '#marketingStaffScheduleForCalendar_marketingStaff');
                        global.autocomplete.bind(calendar.settings.chartType_autocomplete_url, '#marketingStaffScheduleForCalendar_chartType_desc', '#marketingStaffScheduleForCalendar_chartType', {
                            onSelect: function () {
                                var params = {
                                    chartType_id : jQ('#marketingStaffScheduleForCalendar_chartType').val() !== '' ? jQ('#marketingStaffScheduleForCalendar_chartType').val() : '',
                                };

                                jQ('#marketingStaffScheduleForCalendar_scheduleStatus_desc').devbridgeAutocomplete('setOptions', {params: params});
                            }
                        });
                        global.autocomplete.bind(calendar.settings.health_facility_autocomplete_url, '#marketingStaffScheduleForCalendar_health_facility_desc', '#marketingStaffScheduleForCalendar_health_facility',{
                            onSelect: function (e) {
                                jQ('#schedule_health_facility_city_id').val(e.city_id);
                                jQ('#schedule_health_facility_geoLat').val(e.geoLat);
                                jQ('#schedule_health_facility_geoLong').val(e.geoLong);
                                cityChecker();
                                latLngChecker();

                                calendar.patientChartCheck(jQ('#marketingStaffScheduleForCalendar_patient').val());

                                var
                                    txtAddress = jQ('<span>').text(e.address),
                                    txtMobileNos = jQ('<span>').text(e.mobileNos),
                                    txtPhoneNos = jQ('<span>').text(e.phoneNos);

                                jQ('#branch-detail-address').html('<strong>Address: </strong>');
                                jQ('#branch-detail-mobileNos').html('<strong>Mobile No(s): </strong>');
                                jQ('#branch-detail-phoneNos').html('<strong>Phone No(s): </strong>');
                                txtAddress.appendTo('#branch-detail-address');
                                txtMobileNos.appendTo('#branch-detail-mobileNos');
                                txtPhoneNos.appendTo('#branch-detail-phoneNos');
                            }
                        });

                        global.autocomplete.bind(calendar.settings.scheduleStatus_autocomplete_url, '#marketingStaffScheduleForCalendar_scheduleStatus_desc', '#marketingStaffScheduleForCalendar_scheduleStatus');

                        global.autocomplete.bind(calendar.settings.scheduleStatus_autocomplete_url, '#schedule_scheduleStatus_desc', '#schedule_scheduleStatus');

                        jQ('#marketingStaffScheduleForCalendar_note_type').unbind('change').bind('change', function () {
                            if (jQ(this).val() == 'Template') {
                                jQ('#marketingStaffScheduleForCalendar_note_template_description').removeClass('hide');
                            } else {
                                jQ('#marketingStaffScheduleForCalendar_note_template_description').addClass('hide');
                            }
                        });

                        if(calendar.settings.noteTemplateAccess == false) {
                            jQ('#marketingStaffScheduleForCalendar_note_type').children('option[value=Template]').addClass('hide');
                        }

                        global.autocomplete.bind(calendar.settings.note_template_autocomplete_url, '#marketingStaffScheduleForCalendar_note_template_description', '#marketingStaffScheduleForCalendar_noteTemplate', {
                            onSelect: function (d) {
                                global.ajax({
                                    url: calendar.settings.note_template_data_url+'/'+d.noteTemplate_description,
                                    type: 'GET',
                                    beforeSend: function() {
                                        jQ('#marketingStaffScheduleForCalendar_note').val('');
                                    },
                                    success: function(json) {
                                        jQ('#marketingStaffScheduleForCalendar_note').val(json.note);
                                    },
                                });
                            }
                        });


                        /*calendar.scheduleForm.map.addListenerOnce('idle', function(){
                            latLngChecker();
                        });*/
                        /*google.maps.event.addListenerOnce(calendar.scheduleForm.map, 'idle', function(){
                            latLngChecker();
                        });*/
                        global.bindFormSubmitted();
                        calendar.bindScheduleCalendarFormAction();
                    }
                };

                global.ajax(settings, requestName);
            });
            jQ('.patient_info').click(function(e) {
                e.stopPropagation();
            });
        }
    },

    bindScheduleCalendarFormAction: function() {

        jQ('.href-schedule-calendar-action').unbind('click.scheduleCalendarFormAction').bind('click.scheduleCalendarFormAction', function () {

            var requestName = 'scheduleCalendarFormAction',
                _form = jQ('#form-scheduleCalendar'),
                modal = jQ('#modal'),
                axn = jQ(this).data('axn');
            _form.find('.form-action').val(axn);

            global.formSubmitted();
            global.ajaxCancel(requestName);

            var settings = {
                url: calendar.settings.calendar_formActionUrl,
                type: 'POST',
                data: _form.serialize(),
                success: function (json) {
                    if (json.success) {
                        modal.foundation('close');
                        global.parseFlashMessages('#flash-messages-content-page', 'success', json.successMessages);
                        calendar.scheduleView();
                    } else {
                        global.formSubmittedReverse();
                        global.parseFlashMessages('#flash-messages-content-modal', 'alert', json.errorMessages);
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },
    closeTbody: function () {
        jQ('#distance-table').addClass('hide');
        jQ('#view-details').removeClass('hide')
    },
    patientChartCheck: function (patient_id) {
        jQ('#patient-chart-warning').css('display', 'none');

        var data = {};
        data['patient'] = patient_id;

        jQ.post(calendar.settings.patientChartCheck_healthFacility_url, data, function(response) {
            console.log(jQ('#schedule_health_facility').val());

            if (response.health_facility_id != jQ('#schedule_health_facility').val()) {
                jQ('#patient-chart-warning').css('display', 'block');
            }
        }, 'json');
    }
};