var index = {
    colors: ['#34495e', '#DC6A6A', '#d35400', '#4daf7c', '#336e7b', '#1ba39c'],
    settings: {
        userType: null,
        wsConnHost: null,
        wsConnSocket: null,
        dashboardCount_url: null,
        dashboardReportPreviewUrl : '',
    },
    ws: null,
    init: function() {
        this.dashboardContents();
        global.createModal('dashboard-appointment-modal', 'dashboard-appointment-modal-content', 'large');
        /*this.wsConnect();*/
    },
    openAppointmentModal: function(scheduleId){
        var requestName = 'dashboardAppointmentForm',
            modal = jQ('#dashboard-appointment-modal'),
            modalContent = jQ('#dashboard-appointment-modal-content');
        global.ajaxCancel(requestName);
        let settings = {
            url: global.settings.url + "/main/appointment/dashboard/form/u/" + scheduleId,
            type: 'GET',
            error: function(xhr, responseText) {
                if(responseText !== 'abort' && responseText !== 'error') {
                    alert(responseText);
                }
            },
            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');
                global.maskInput();
                global.bindFormSubmitted();
            }
        };
        global.ajax(settings, requestName);
    },
    dashboardContents: function() {
        if(jQ("#dashboard-counter").length > 0) {
            global.ajax({
                url: index.settings.dashboardCount_url,
                type: 'GET',
                success: function(json) {
                    if(index.settings.userType === "Clinician"){
                        index.listAppointmentDashboard(json);
                        index.listTicketDashboard(json);
                        index.listReminderDashboard(json);
                        index.listLetterDashboard(json);
                        index.listOverDueDashboard(json);
                        index.listInsurancePackageDashboard(json);
                      } else {
                        index.animateCount(jQ('#dashboard-counter-with-fax-no-encounter'),json.with_fax_no_encounters);
                        index.animateCount(jQ('#dashboard-counter-with-referral-no-encounter'),json.with_referral_no_encounters);
                        index.animateCount(jQ('#dashboard-counter-new-faxes'),json.new_faxes);
                        index.animateCount(jQ('#dashboard-counter-for-rebook'),json.for_rebookings);
                        index.animateCount(jQ('#dashboard-counter-initial-encounter'),json.init_encounters);
                        index.animateCount(jQ('#dashboard-counter-encounter-call'),json.encounter_calls);
                        index.animateCount(jQ('#dashboard-counter-seventy-two-hour-follow-up'),json.seventy_two_hour_followups);
                        index.animateCount(jQ('#dashboard-counter-three-month-follow-up'),json.three_months_followups);
                        index.animateCount(jQ('#dashboard-counter-6-month-follow-up'),json.six_months_followups);
                        index.animateCount(jQ('#dashboard-counter-appointment-notice'),json.appointment_notice);
                        index.animateCount(jQ('#dashboard-counter-my-task'),json.my_taks);
                        index.animateCount(jQ('#dashboard-counter-endorsed'),json.endorsed);
                        index.animateCount(jQ('#dashboard-counter-letters'),json.letters);
                        index.animateCount(jQ('#dashboard-counter-ar'),json.accountsReceivable);
                        index.animateCount(jQ('#dashboard-counter-reminder'),json.reminder);
                    }
                }
            }, 'dashboardCount');
        }
    },
    listReminderDashboard: function(json){
        index.animateCount(jQ("#reminder-ctr"),json.reminders.length);
        jQ('#dashboard-reminder-list').removeClass('has-loading');
        for(let i =0; i < json.reminders.length; i++){
            let reminder = json.reminders[i];
            let li = jQ('<li>').attr({
                    onclick: `global_reminder.form('u', ${reminder.id})`
                }),
                head = jQ('<div>').attr({
                    class: "list-head",
                }),
                headTitle = jQ('<span>').attr({
                    class: 'list-head-title'
                }).html(reminder.startDate + ': '),
                headSub = jQ('<span>').attr({
                    class: "list-head-subtitle",
                    title: "Category",
                }).html(reminder.reminderType_description),
                body = jQ('<div>').attr({
                    class: "list-body",
                    title: "Reminder note",
                }).html(reminder.note);

            headTitle.appendTo(head);
            headSub.appendTo(head);
            head.appendTo(li);
            body.appendTo(li);
            jQ('#dashboard-reminder-list').append(li);
        }
        if(json.reminders.length <= 0) jQ('#dashboard-reminder-list').html("<li><small style='color:grey; margin-left: 6px'>No reminders set.</small></li>")
    },
    listTicketDashboard: function(json){
        index.animateCount(jQ("#ticket-ctr"),json.tickets.length);
        jQ('#dashboard-ticket-list').removeClass('has-loading');
        for(let i =0; i < json.tickets.length; i++){
            let ticket = json.tickets[i];
            let li = jQ('<li>').attr({
                    onclick: `window.open('${global.settings.url}/main/ticket/form/u/${ticket.idEncoded}', '_blank')`
                }),
                head = jQ('<div>').attr({
                    class: "list-head",
                }),
                headTitle = jQ('<span>').attr({
                    class: 'list-head-title'
                }).html('ID: ' + ticket.id + ' '),
                headSub = jQ('<span>').attr({
                    class: "list-head-subtitle",
                    title: "Severity",
                }).html(ticket.severity),
                body = jQ('<div>').attr({
                    class: "list-body",
                    title: "Latest note",
                }).html(ticket.latestNote);

            headTitle.appendTo(head);
            headSub.appendTo(head);
            head.appendTo(li);
            body.appendTo(li);
            jQ('#dashboard-ticket-list').append(li);
        }
        if(json.tickets.length <= 0) jQ('#dashboard-ticket-list').html("<li><small style='color:grey; margin-left: 6px'>No tickets available.</small></li>")
    },
    listAppointmentDashboard: function(json){
        jQ('#dashboard-appointment-list').removeClass('has-loading');
        index.animateCount(jQ("#appointment-ctr"),json.appointments.length + json.appointments_pending_update.length);
        index.animateCount(jQ("#appointment-today-ctr"),json.appointments.length);
        for(let i =0; i < json.appointments.length; i++){
            let appointment = json.appointments[i];
            let li = jQ('<li>').attr({
                    onclick: `index.openAppointmentModal('${btoa(appointment.id)}')`
                }),
                head = jQ('<div>').attr({
                    class: "list-head",
                }),
                headTitle = jQ('<span>').attr({
                    class: 'list-head-title'
                }).html(appointment.start_time),
                headSub = jQ('<span>').attr({
                    class: "list-head-subtitle",
                    title: "Status",
                }).html(' ' + appointment.schedule_status),
                body = jQ('<div>').attr({
                    class: "list-body",
                    title: "",
                }).html(appointment.chartType + '<br>' + appointment.patient_fullName);
            headTitle.appendTo(head);
            headSub.appendTo(head);
            head.appendTo(li);
            body.appendTo(li);
            jQ('#dashboard-appointment-list').append(li);
        }
        if(json.appointments.length <= 0) jQ('#dashboard-appointment-list').html("<li><small style='color:grey; margin-left: 6px'>No appointments today.</small></li>")

        jQ('#dashboard-appointment-pending-update-list').removeClass('has-loading');
        index.animateCount(jQ("#appointment-pending-update-ctr"),json.appointments_pending_update.length);
        for(let i =0; i < json.appointments_pending_update.length; i++){
            let appointment = json.appointments_pending_update[i];
            let li = jQ('<li>').attr({
                    onclick: `index.openAppointmentModal('${btoa(appointment.id)}')`
                }),
                head = jQ('<div>').attr({
                    class: "list-head",
                }),
                headTitle = jQ('<span>').attr({
                    class: 'list-head-title'
                }).html(appointment.scheduleDT),
                headSub = jQ('<span>').attr({
                    class: "list-head-subtitle",
                    title: "Status",
                }).html(' ' + appointment.schedule_status),
                body = jQ('<div>').attr({
                    class: "list-body",
                    title: "",
                }).html(appointment.chartType + '<br>' + appointment.patient_fullName);
            headTitle.appendTo(head);
            headSub.appendTo(head);
            head.appendTo(li);
            body.appendTo(li);
            jQ('#dashboard-appointment-pending-update-list').append(li);
        }
        if(json.appointments_pending_update.length <= 0) jQ('#dashboard-appointment-pending-update-list').html("<li><small style='color:grey; margin-left: 6px'>No pending appointment updates.</small></li>")
    },
    listLetterDashboard: function(json){
        index.animateCount(jQ("#letter-ctr"),json.clinician_letters.length);
        jQ('#dashboard-clinician-letter-list').removeClass('has-loading');
        for(let i =0; i < json.clinician_letters.length; i++){
            let clinician_letters = json.clinician_letters[i];
            let li = jQ('<li>').attr({
                    onclick: `window.open('${global.settings.url}/main/patient/detail/${clinician_letters.patientIdEncoded}?tab=c', '_blank')`
                }),
                head = jQ('<div>').attr({
                    class: "list-head",
                }),
                headTitle = jQ('<span>').attr({
                    class: 'list-head-title'
                }).html('ID: ' + clinician_letters.id + ' '),
                headSub = jQ('<span>').attr({
                    class: "list-head-subtitle",
                    title: "Date",
                }).html(clinician_letters.createdAt),
                body = jQ('<div>').attr({
                    class: "list-body",
                    title: "Letter Type",
                }).html(clinician_letters.letter_type);

            headTitle.appendTo(head);
            headSub.appendTo(head);
            head.appendTo(li);
            body.appendTo(li);
            jQ('#dashboard-clinician-letter-list').append(li);
        }
        if(json.clinician_letters.length <= 0) jQ('#dashboard-clinician-letter-list').html("<li><small style='color:grey; margin-left: 6px'>No letters available.</small></li>")
    },
    listOverDueDashboard: function(json){
        index.animateCount(jQ("#overdue-ctr"),json.encounter_overdue.hri.length);
        jQ('#dashboard-encounter-overdue-list').removeClass('has-loading');
        for(let i =0; i < json.encounter_overdue.hri.length; i++){
            let encounter_overdue = json.encounter_overdue;
            let li = jQ('<li>').attr({
                    onclick: `window.open('${global.settings.url}/main/patient/detail/${encounter_overdue.hri[i].patientIdEncoded}?tab=c', '_blank')`
                }),
                head = jQ('<div>').attr({
                    class: "list-head",
                }),
                headTitle = jQ('<span>').attr({
                    class: 'list-head-title'
                }).html('Patient: ' + encounter_overdue.hri[i].patientName + '<br>'),
                headSub = jQ('<span>').attr({
                    class: "list-head-subtitle",
                    title: "Encounter Type",
                }).html('Encounter Type: HSAT Results Interpretation <br>'),
                body = jQ('<div>').attr({
                    class: "list-body",
                    title: "Overdue",
                }).html(encounter_overdue.hri[i].dayOverDue);

            headTitle.appendTo(head);
            headSub.appendTo(head);
            head.appendTo(li);
            body.appendTo(li);
            jQ('#dashboard-encounter-overdue-list').append(li);
        }
        for(let i =0; i < json.encounter_overdue.cs.length; i++){
            let encounter_overdue = json.encounter_overdue;
            let li = jQ('<li>').attr({
                    onclick: `window.open('${global.settings.url}/main/patient/detail/${encounter_overdue.cs[i].patientIdEncoded}?tab=c', '_blank')`
                }),
                head = jQ('<div>').attr({
                    class: "list-head",
                }),
                headTitle = jQ('<span>').attr({
                    class: 'list-head-title'
                }).html('Patient: ' + encounter_overdue.cs[i].patientName + '<br>'),
                headSub = jQ('<span>').attr({
                    class: "list-head-subtitle",
                    title: "Encounter Type",
                }).html('Encounter Type: CPAP Setup <br>'),
                body = jQ('<div>').attr({
                    class: "list-body",
                    title: "Overdue",
                }).html(encounter_overdue.cs[i].dayOverDue);

            headTitle.appendTo(head);
            headSub.appendTo(head);
            head.appendTo(li);
            body.appendTo(li);
            jQ('#dashboard-encounter-overdue-list').append(li);
        }
        for(let i =0; i < json.encounter_overdue.css.length; i++){
            let encounter_overdue = json.encounter_overdue;
            let li = jQ('<li>').attr({
                    onclick: `window.open('${global.settings.url}/main/patient/detail/${encounter_overdue.css[i].patientIdEncoded}?tab=c', '_blank')`
                }),
                head = jQ('<div>').attr({
                    class: "list-head",
                }),
                headTitle = jQ('<span>').attr({
                    class: 'list-head-title'
                }).html('Patient: ' + encounter_overdue.css[i].patientName + '<br>'),
                headSub = jQ('<span>').attr({
                    class: "list-head-subtitle",
                    title: "Encounter Type",
                }).html('Encounter Type: CPAP Setup Sold <br>'),
                body = jQ('<div>').attr({
                    class: "list-body",
                    title: "Overdue",
                }).html(encounter_overdue.css[i].dayOverDue);

            headTitle.appendTo(head);
            headSub.appendTo(head);
            head.appendTo(li);
            body.appendTo(li);
            jQ('#dashboard-encounter-overdue-list').append(li);
        }
        for(let i =0; i < json.encounter_overdue.ce.length; i++){
            let encounter_overdue = json.encounter_overdue;
            let li = jQ('<li>').attr({
                    onclick: `window.open('${global.settings.url}/main/patient/detail/${encounter_overdue.ce[i].patientIdEncoded}?tab=c', '_blank')`
                }),
                head = jQ('<div>').attr({
                    class: "list-head",
                }),
                headTitle = jQ('<span>').attr({
                    class: 'list-head-title'
                }).html('Patient: ' + encounter_overdue.ce[i].patientName + '<br>'),
                headSub = jQ('<span>').attr({
                    class: "list-head-subtitle",
                    title: "Encounter Type",
                }).html('Encounter Type: CPAP Eval <br>'),
                body = jQ('<div>').attr({
                    class: "list-body",
                    title: "Overdue",
                }).html(encounter_overdue.ce[i].dayOverDue);

            headTitle.appendTo(head);
            headSub.appendTo(head);
            head.appendTo(li);
            body.appendTo(li);
            jQ('#dashboard-encounter-overdue-list').append(li);
        }
        for(let i =0; i < json.encounter_overdue.cee.length; i++){
            let encounter_overdue = json.encounter_overdue;
            let li = jQ('<li>').attr({
                    onclick: `window.open('${global.settings.url}/main/patient/detail/${encounter_overdue.cee[i].patientIdEncoded}?tab=c', '_blank')`
                }),
                head = jQ('<div>').attr({
                    class: "list-head",
                }),
                headTitle = jQ('<span>').attr({
                    class: 'list-head-title'
                }).html('Patient: ' + encounter_overdue.cee[i].patientName + '<br>'),
                headSub = jQ('<span>').attr({
                    class: "list-head-subtitle",
                    title: "Encounter Type",
                }).html('Encounter Type: CPAP End Eval <br>'),
                body = jQ('<div>').attr({
                    class: "list-body",
                    title: "Overdue",
                }).html(encounter_overdue.cee[i].dayOverDue);

            headTitle.appendTo(head);
            headSub.appendTo(head);
            head.appendTo(li);
            body.appendTo(li);
            jQ('#dashboard-encounter-overdue-list').append(li);
        }
        if(json.encounter_overdue.hri.length <= 0 && json.encounter_overdue.cs.length <= 0 && json.encounter_overdue.css.length <= 0 && json.encounter_overdue.ce.length <= 0 && json.encounter_overdue.cee.length <= 0) jQ('#dashboard-encounter-overdue-list').html("<li><small style='color:grey; margin-left: 6px'>No overdue.</small></li>")
    },
    listInsurancePackageDashboard: function(json){
        index.animateCount(jQ("#insurance-package-ctr"),json.insurance_package.length);
        jQ('#dashboard-insurance-package-list').removeClass('has-loading');
        for(let i =0; i < json.insurance_package.length; i++){
            let insurance_package = json.insurance_package[i];
            let li = jQ('<li>').attr({
                    onclick: `window.open('${global.settings.url}/main/patient/detail/${insurance_package.patientIdEncoded}?tab=b', '_blank')`
                }),
                head = jQ('<div>').attr({
                    class: "list-head",
                }),
                headTitle = jQ('<span>').attr({
                    class: 'list-head-title'
                }).html('Invoice No.: ' + insurance_package.invoiceNo + ' '),
                headSub = jQ('<span>').attr({
                    class: "list-head-subtitle",
                    title: "Patient",
                }).html(insurance_package.patientName),
                body = jQ('<div>').attr({
                    class: "list-body",
                    title: "Billing Date",
                }).html(insurance_package.billingDate);

            headTitle.appendTo(head);
            headSub.appendTo(head);
            head.appendTo(li);
            body.appendTo(li);
            jQ('#dashboard-insurance-package-list').append(li);
        }
        if(json.insurance_package.length <= 0) jQ('#dashboard-insurance-package-list').html("<li><small style='color:grey; margin-left: 6px'>No invoice.</small></li>")
    },
    /*wsConnect: function() {
        this.ws = new WebSocket(this.settings.wsConnHost + ':' + this.settings.wsConnSocket);
        this.ws.onopen = function() {
            this.onmessage = function(msg) {
                if(msg.data !== undefined) {
                    var data = JSON.parse(msg.data);
                    if(data.dashboardReload !== undefined && data.dashboardReload) {
                        global.countNotif();
                        index.dashboardContents();
                    }
                }
            };
        };
    },*/
    animateCount: function(element, value){
        jQuery({ Counter: 0 }).animate({ Counter: value }, {
            duration: 1000,
            easing: 'swing',
            step: function () {
                element.text(Math.ceil(this.Counter));
            }
        });
    },
};