//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
            via_getVeteranId();

            //Populate dropdowns
            via_getLocations();

            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
        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 = '';

        // 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) {
    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);
}

function getLocations_Result(serviceResult) {
    try {
        if (serviceResult.length > 0) {
            var ddLocations = parent.Xrm.Page.getcontrol('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
                    //$('#ddLocation').append($("<option />").val(item.id).text(item.name));
                    ddLocations.add(new Option(item.name, item.id));
                }
            });
        }
    } catch (err) {
        alert("getLocations_Result: " + err.message);
    }
}

function selectLocation(selectObject) {
    parent.Xrm.Page.getAttribute("vhacrm_vistalocationid_text").setValue(selectObject.value);
    parent.Xrm.Page.getAttribute("vhacrm_vistalocationname_text").setValue(selectObject.text);
}

