/*
 * @category   Bespoke Software
 * @author     Bespoke.ws Ltd
 * @copyright  Copyright (c) 2019. Bespoke.ws Ltd, All Rights Reserved
 * @link       https://bespokeuk.com
 */

/**
 * Format slug
 *
 * @param input
 * @returns {string}
 */
function formatSlug(input) {
    return input
        .replace(/\s+/g, '-')
        .replace(/([^\w\d-])/g, '')
        .toLowerCase();
}

/**
 * Handle the name field
 */
$(document).on('blur', '[name=name]', function (e) {
    let slugField = $('[name=slug]');
    let metaTitleField = $('[name=meta_title]');
    let metaDescriptionField = $('[name=meta_description]');

    if (slugField.length && ! slugField.val()) {
        slugField.val(formatSlug($(this).val()));
    }
    if (metaTitleField.length && ! metaTitleField.val()) {
        metaTitleField.val($(this).val());
    }
    if (metaDescriptionField.length && ! metaDescriptionField.val()) {
        metaDescriptionField.val($(this).val());
    }
});

/**
 * Handle the slug field
 */
$(document).on('keyup paste', '[name=slug]', function (e) {
    $(this).val(formatSlug($(this).val()));
});
