//VistaLoginControlScriptLib.js
//Contains variables and functions used by the VistaLoginControl.html page

//Static Variables
var vlc_UserSiteId = '';
var vlc_UserSiteNo = '';
var vlc_ViaLoginMinutes;

function setAppNameValue(value) {
    consumingApp.name = value;
    via_setCookie("viasessionappname", value, vlc_ViaLoginMinutes);
}
function setAppTokenValue(value) {
    consumingApp.token = value;
    via_setCookie("viasessionapptoken", value, vlc_ViaLoginMinutes);
}
function setAppPassValue(value) {
    consumingApp.password = value;
    via_setCookie("viasessionapppass", value, vlc_ViaLoginMinutes);
}
function setUrlValue(value) {
    consumingApp.url = value;
    via_setCookie("viasessionappurl", value, vlc_ViaLoginMinutes);
}
function setNoteTitleValue(value) {
    consumingApp.notetitleid = value;
    via_setCookie("viasessionnotetitleid", value, vlc_ViaLoginMinutes);
}
function setLoginCookies(value) {
    vlc_ViaLoginMinutes = value;
    getKeyValuePair("via_consumingapp_name", setAppNameValue);
    getKeyValuePair("via_consumingapp_token", setAppTokenValue);
    getKeyValuePair("via_consumingapp_pass", setAppPassValue);
    getKeyValuePair("via_endpoint", setUrlValue);
    getKeyValuePair("via_ncchvnotetitle_id", setNoteTitleValue);
}

function vlc_formLoad() {
    try {

        //Determine the status of the parent record
        if (parent.Xrm.Page.ui.getFormType() > 2) {  
            //The form is disabled, hide login section
            parent.Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_vistalogin").setVisible(false);
            return false;
        }

        ////Get VIA Login URL and other items needed for login
        //consumingApp = new AppInfo();
        //vlc_ViaLoginMinutes = 230;
        //consumingApp.name = "HRC_CRM";
        //consumingApp.token = "HRC_CRM_ID_5496";
        //consumingApp.password = "Bf5d2w!rQj";
        //consumingApp.url = "https://URL.DNS";
        //consumingApp.notetitleid = 1949;
        //getKeyValuePair("via_login_minutes", setLoginCookies); 

        var notetype = parent.Xrm.Page.getAttribute("vhacrm_notetype_code").getValue(); 
        if (notetype == null || notetype == 713770000) {
            // CRM Note Only
            return false;
        }
      
        if (via_checkUserLogIn()) {
            //Hide the login section
            parent.Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_vistalogin").setVisible(false);

            //Get Veteran Id from Vista facility
            var veteranId = parent.Xrm.Page.getAttribute("customerid").getValue();
            if (veteranId) {
                via_getVeteran(veteranId, getVeteran_Result);
            }

            //Populate dropdowns
            via_getLocations(getLocations_Result);

            return true;
        }
        else {
            //Show the login section
            parent.Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_vistalogin").setVisible(true);
            //Set focus to the login control
            parent.Xrm.Page.getControl("WebResource_VistaLoginControl").setFocus();
            return false;
        }
       
    }
    catch (err) {
        alert('VistA Login Control Web Resource Function Error(vlc_formLoad): ' + err.message);
    }
}

function vlc_vistaLogin() {
    try {
        //Get Login Field data
        var vlc_accessCode = $('#vlc_accessCode').val();
        var vlc_verifyCode = $('#vlc_verifyCode').val();
        //Verify that fields are not empty
        if (vlc_accessCode == null || vlc_accessCode == "") { alert("Please enter your Access Code!"); return false; }
        if (vlc_verifyCode == null || vlc_verifyCode == "") { alert("Please enter your Verify Code!"); return false; }

        //Disable login fields and button
        document.getElementById('vlc_accessCode').disabled = true;
        document.getElementById('vlc_verifyCode').disabled = true;
        document.getElementById('vlc_loginbuttonid').disabled = true;

        //Get the Site ID (Station Suffix)
        var vlc_UserSiteNo = parent.Xrm.Page.getAttribute("vhacrm_stationsuffix_text").getValue();
        vlc_UserSiteId = vlc_UserSiteNo.toString();

        VIAServices.loginVIA(vlc_UserSiteId, vlc_accessCode, vlc_verifyCode, vlc_vistaLogin_response);

    }
    catch (err) {
        alert('VistA Login Control Web Resource Function Error(vlc_vistaLogin): ' + err.message);
    }
}


function vlc_vistaLogin_response(returnUserTO) {
    userTO = returnUserTO;

    if (userTO.error !== "" && userTO.error !== null) {
        //Handle Errors
        alert(userTO.error + "\n" + userTO.fault);
        //Clear login fields
        document.getElementById('vlc_accessCode').disabled = false;
        document.getElementById('vlc_verifyCode').disabled = false;
        document.getElementById('vlc_loginbuttonid').disabled = false;
        return false;

    } else {
        //Success
        via_setCookie("viasessionlink", userTO, vlc_ViaLoginMinutes);

        alert("Login Successful \n" + userTO.greeting);

        //Clear login fields and hide control
        parent.Xrm.Page.ui.clearFormNotification("VIASERVICE");
        document.getElementById('vlc_accessCode').disabled = false;
        document.getElementById('vlc_verifyCode').disabled = false;
        document.getElementById('vlc_loginbuttonid').disabled = false;
        document.getElementById('vlc_accessCode').value = '';
        document.getElementById('vlc_verifyCode').value = '';
        parent.Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_vistalogin").setVisible(false);

        // Get Vista Facility Locations
        via_getLocations(getLocations_Result);

        // Get Vista Veteran Id
        var veteranId = parent.Xrm.Page.getAttribute("customerid").getValue();
        if (veteranId) {
            var vistaVeteranId = parent.Xrm.Page.getAttribute("vhacrm_vistaveteranid_text").getValue();
            if (vistaVeteranId == null) {
                via_getVeteranId(veteranId, getVeteran_Result);
            }
        }
        
    }    
}

function getVeteran_Result(serviceResult) {
    try {
        if (serviceResult) {
            if (serviceResult[0].error = "") {
                arrayPatientTO = serviceResult;
                patientTO = arrayPatientTO[0];
                // Set Vista Veteran fields
                parent.Xrm.Page.getAttribute("vhacrm_vistaveteranid_text").setValue(patientTO.localpid);
                parent.Xrm.Page.getAttribute("vhacrm_vistaveteranname_text").setValue(patientTO.patientname);
            }
        }
        else {
            alert("The Veteran is not registered with this facility.  A note cannot be written to VISTA.");
            return false;
        }
    } catch (err) {
        alert("getVeteran_Result: " + err.message);
    }
}

function getLocations_Result(serviceResult) {
    try {
        if (serviceResult.length > 0) {
            
            //Populate dropdown
            var ddLocations = parent.Xrm.Page.ui.controls.get('WebResource_VistaWriteNoteControl').getObject().contentWindow.document.getElementById('ddLocation');
            $.each(serviceResult, function (index, item) {
                if (item.error !== "" && item.error !== null) {
                    //Handle Errors
                    alert(item.error + "\n" + item.fault);
                } else {
                    //Success
                    ddLocations.add(new Option(item.name, item.id));
                }
            });

            //Set selected location
            var facilitylocation = parent.Xrm.Page.getAttribute("vhacrm_vistalocationid_text").getValue();
            if (facilitylocation) {
                ddLocations.val(facilitylocation);
            }
        }
    } catch (err) {
        alert("getLocations_Result: " + err.message);
    }
}

