// Takes the source element of the copy button and palces a copy after the source element
function handleElementCopy($this) {
    $this = jQuery($this);
    let clonedElement = $this.closest('.elements_added').clone();
    // paste the cloned element
    $this.closest('.elements_added').after(clonedElement);
    // take the checkbox type from the select tag, useful when copy is applied on the 'button/checkbox' element type
    let checkBoxType = $this.closest('.elements_added').find('select.fieldFormat').val();
    // initiate accordion inside the element box's open/close feature
    clonedElement.find('.styled-accordion').sccAccordion();
    // append 'copied' string to the title
    // clonedElement.find('input.input_pad:not([type=number])').val(function() {
    //     return this.value + ' ' + 'copied';
    // }).trigger('change');
    // apply checkbox value to the cloned element
    clonedElement.find('select.fieldFormat').val(checkBoxType);
    // remove the condition definition
    clonedElement.find('.scc_conditioned_dropdown').prop('checked', false).trigger('change');
    // add border effect
    clonedElement.css({border: '2px solid rgb(138, 153, 248)'}).delay(10000).queue(function(next){
        jQuery(this).css({border: 'unset'});
        next();
    });
}
// handles quote custom field setup form's delete button
function handleQuoteFieldDeletion($this) {
    $this = jQuery($this);
    let fieldKey = $this.data('fieldKey');
    // find the index of the fieldKey in the array
    let deletionCandidate = formFieldsArray.map(e => Object.keys(e)[0]).indexOf(fieldKey);
    // delete the key and the corresponding button
    let deletionStatus = delete formFieldsArray[deletionCandidate];
    if (deletionStatus) {
        jQuery('#formFieldSetupModal').modal('toggle');
        jQuery(`[data-field-key=${fieldKey}]`).remove();
    }
}

// Upload button click
var handleDropdownLogoSetup = function ($this ) {
    event.preventDefault();
    formField = jQuery($this);
    if ( window.hasOwnProperty('mediaUploader') ) {
        mediaUploader.open();
        return;
    }
    mediaUploader = wp.media.frames.file_frame = wp.media( {
        title: 'Choose Image',
        button: {
            text: 'Choose Image'
        }, multiple: false
    } );
    mediaUploader.on( "select", onMediaImageSelect );
    mediaUploader.open();
}
function removeDropdownImage($this) {
    $this = jQuery($this);
    var url = $this.prev().attr('src');
    var data = {
        action: "scc_handle_dropdown_logo",
        method: 'delete',
        data: url
    };
    var callback = (data) => {
        $this.prev().attr('src', data.link).data('hasImage', false).next().remove();
    }
    jQuery.post( ajaxurl, data, callback );
}
function resizeImage( url, callback ) {
    var data = {
        action: "scc_handle_dropdown_logo",
        data: url
    };
    
    jQuery.post( ajaxurl, data, callback );
}
/**
 * On media image select
 */
function onMediaImageSelect() {
    var attachment = mediaUploader.state().get('selection').first().toJSON()
    var field = formField;
    field.attr('src', attachment.sizes.thumbnail.url );
    resizeImage(attachment.sizes.thumbnail.url, (data) => {
        var element = field.attr('src', data.link ).data('hasImage', true);
        if (!element.next('span').length) element.after(jQuery('<span class="scc-dropdown-image-remove" onclick="removeDropdownImage(this)">x</span>'));
    });
}

// Functions to change the backend title while typing.
function changeElementTitleSlider($this){
    var changeBackendTitleElement = jQuery($this).closest(".slider-section-container").prev().find(".scc-element-title")
    var currentBackendInputTitle = truncateElementTitle(jQuery($this).val(),20)
    changeBackendTitleElement.text(currentBackendInputTitle)
}
function changeElementTitle($this){
    var changeBackendTitleElement = jQuery($this).closest(".elements_added").find(".scc-element-title")
    var currentBackendInputTitle = truncateElementTitle(jQuery($this).val(),20)
   
    changeBackendTitleElement.text(currentBackendInputTitle)
}
function changeElementTitleCustomMath($this) {
    var changeBackendTitleElement = jQuery($this).closest('.scc_custom_math').find('.scc-element-title')
    var currentBackendInputTitle = truncateElementTitle(jQuery($this).val(),20)

    changeBackendTitleElement.text(currentBackendInputTitle)
}
function truncateElementTitle(str, n){
  return (str.length > n) ? str.substr(0, n-1) + '..' : str;
};
