var SF_MULTI_PICKLIST_DELIMITER = ';';
var BLANK_VALUE = '';
var SELECTED_ATTRIBUTE = 'selected';

/**
 * Converts the selected value(s) of an HTML <select> element to a delimited String stored in a hidden field.
 * @param {string} hiddenValueFieldId - The Id of the field which will ultimately store the delimited value.
 * @param {string} sendingField - The field sending the onchange event which contains the selected value(s).
 */
function setHiddenFieldToVisibleValue(hiddenValueFieldId, sendingField) {
    var hiddenValueField = $(document.getElementById(hiddenValueFieldId));
    var visibleMultiPicklist = $(sendingField);

    var selectedOptions = visibleMultiPicklist.val();

    if (selectedOptions === null || selectedOptions.length <= 0) {
        $(hiddenValueField).val(BLANK_VALUE);
        return;
    }

    // Join array on delimiter.
    var joinedValue = selectedOptions.join(SF_MULTI_PICKLIST_DELIMITER);

    // Assign the joined value to the hidden field.
    $(hiddenValueField).val(joinedValue);
}

/**
 * Intended to pre-select a delimited String list of values in a hidden field in a visible HTML <select> element.
 * @param {string} hiddenValueFieldId - The Id of the field which contains the delimited String to select.
 * @param {string} visibleMultiPicklistId - The Id of the field to pre-select items from the hidden field.
 */
function preSelectHiddenPicklistValues(hiddenValueFieldId, visibleMultiPicklistId) {
    var hiddenValueField = $(document.getElementById(hiddenValueFieldId));
    var visibleMultiPicklist = $(document.getElementById(visibleMultiPicklistId));
    var hiddenValue = hiddenValueField.val();

    if (hiddenValue === null || hiddenValue.length <= 0) {
        return;
    }

    // Loop through each item in the split hidden field value.
    $.each(hiddenValue.split(SF_MULTI_PICKLIST_DELIMITER), function(itemIndex, itemValue) {
        // Find the multi picklist item matching the current value, mark it as selected.
        visibleMultiPicklist.find('option[value=\'' + itemValue + '\']').prop(SELECTED_ATTRIBUTE, true);
    });
}