/* ########## Tell (copyright e2see.de) ##########
<script>
$(document).ready(function(){
    
});
</script>
*/

function tell_connect(element) {
    if (!element || !element.hasAttribute || !element.hasAttribute('data-tell-name')) return;

    if (!element._tellHandlers) element._tellHandlers = [];

    var mainElem = element,
        name = mainElem.getAttribute('data-tell-name'),
        container = mainElem.closest('form') || document.body;

    if (mainElem.hasAttribute('data-tell-value')) {
        var value = mainElem.getAttribute('data-tell-value'),
            nameArr = name.split('|'),
            valueArr = value.split('|');

        var clickHandler = function() {
            nameArr.forEach(function(iName, i) {
                var targets = container.querySelectorAll('input[name="' + iName + '"], select[name="' + iName + '"]');
                targets.forEach(function(target) {
                    var targetValue = valueArr[i] || '';
                    if (target.tagName === 'SELECT') {
                        var option = target.querySelector('option[value="' + targetValue + '"]');
                        if (option) {
                            target.value = targetValue;
                            target.dispatchEvent(new Event('change', { bubbles: true }));
                            target.dispatchEvent(new CustomEvent('tell.set', { bubbles: true }));
                        }
                    } else if (target.type === 'checkbox' || target.type === 'radio') {
                        if (target.value == targetValue) {
                            target.checked = true;
                            target.dispatchEvent(new Event('change', { bubbles: true }));
                            target.dispatchEvent(new CustomEvent('tell.set', { bubbles: true }));
                        }
                    } else {
                        target.value = targetValue;
                        target.dispatchEvent(new Event('change', { bubbles: true }));
                        target.dispatchEvent(new CustomEvent('tell.set', { bubbles: true }));
                    }
                });
            });
        };

        mainElem.addEventListener('click', clickHandler);
        mainElem._tellHandlers.push({
            type: 'click',
            handler: clickHandler
        });

    } else {
        mainElem.setAttribute('data-tell-content', 'clear');

        var formElements = container.querySelectorAll('input[name="' + name + '"], select[name="' + name + '"], textarea[name="' + name + '"]');

        setTimeout(function() {
            if (formElements.length > 0) {
                tell_initText(formElements[formElements.length - 1], mainElem, container);
            }
        }, 20);

        formElements.forEach(function(formElem) {
            if (!formElem._tellHandlers) formElem._tellHandlers = [];

            var changeHandler = function() {
                tell_initText(formElem, mainElem, container);
            };

            formElem.addEventListener('change', changeHandler);
            formElem._tellHandlers.push({
                type: 'change',
                handler: changeHandler,
                textElement: mainElem
            });

            // Zusätzlich für Radio-Buttons: Click-Handler
            if (formElem.type === 'radio' || formElem.type === 'checkbox') {
                var clickHandler = function() {
                    tell_initText(formElem, mainElem, container);
                };
                formElem.addEventListener('click', clickHandler);
                formElem._tellHandlers.push({
                    type: 'click',
                    handler: clickHandler,
                    textElement: mainElem
                });
            }
        });
    }

    mainElem.setAttribute('data-tell-connected', 'true');
}

function tell_initText(formElem, textElem, container) {
    var formElemName = formElem.getAttribute('name');

    var previewBoxes = container.querySelectorAll('.tell[data-tell-preview="' + formElemName + '"]');
    var previewBox = previewBoxes.length > 0 ? previewBoxes[0] : null;

    if (previewBox) {
        previewBox.innerHTML = '';
    }

    var formElemList;
    if (formElemName && formElemName.endsWith('[]')) {
        formElemList = container.querySelectorAll('input[name="' + formElemName + '"], select[name="' + formElemName + '"], textarea[name="' + formElemName + '"]');
    } else {
        formElemList = [formElem];
    }

    var arrTxt = [];
    var arrFileCount = [];
    var arrFileSize = [];
    var arrFileList = [];

    formElemList.forEach(function(elem) {
        if (elem.tagName === 'SELECT') {
            var selectedOption = Array.from(elem.options).find(opt => opt.value === elem.value);
            if (selectedOption) {
                arrTxt.push(selectedOption.hasAttribute('data-tell') ?
                    selectedOption.getAttribute('data-tell') : selectedOption.textContent);
            }
        }
        else if (elem.type === 'checkbox' || elem.type === 'radio') {
            if (elem.checked) {
                if (elem.hasAttribute('data-tell')) {
                    arrTxt.push(elem.getAttribute('data-tell'));
                } else if (elem.parentElement && elem.parentElement.tagName === 'LABEL') {
                    arrTxt.push(elem.parentElement.textContent.trim());
                } else {
                    arrTxt.push(elem.value);
                }
            }
        }
        else if (elem.type === 'range') {
            arrTxt.push(elem.value || '0');
        }
        else if (elem.type === 'file') {
            if (elem.files.length > 0) {
                arrFileCount.push(elem.files.length);

                Array.from(elem.files).forEach(function(fl) {
                    arrFileSize.push(fl.size);
                    arrFileList.push(fl.name);

                    if (previewBox) {
                        var thmb = document.createElement('span');
                        thmb.className = 'tell-loading';
                        thmb.title = fl.name;
                        thmb.setAttribute('data-tell-type', fl.type);

                        if (fl.type.match('image.*')) {
                            var reader = new FileReader();
                            reader.readAsDataURL(fl);
                            previewBox.appendChild(thmb);

                            reader.addEventListener('load', function() {
                                thmb.classList.remove('tell-loading');
                                thmb.style.backgroundImage = 'url(' + reader.result + ')';
                                thmb.style.display = 'inline-block';
                                thmb.style.width = '50px';
                                thmb.style.height = '50px';
                                thmb.style.backgroundSize = 'cover';
                                thmb.textContent = '';
                            });
                        } else {
                            thmb.classList.remove('tell-loading');
                            thmb.textContent = fl.name;
                            previewBox.appendChild(thmb);
                        }
                    }
                });
            }
        }
        else if (elem.value !== '') {
            arrTxt.push(elem.value);
        }
    });

    if (formElem.type === 'file') {
        var completeCount = arrFileCount.reduce(function(a, b) { return a + b; }, 0);
        var completeSize = arrFileSize.reduce(function(a, b) { return a + b; }, 0);

        var sizeText;
        if (completeSize > 1000000000) {
            sizeText = (completeSize / 1000000000).toFixed(2) + ' GB';
        } else if (completeSize > 1000000) {
            sizeText = (completeSize / 1000000).toFixed(2) + ' MB';
        } else {
            sizeText = (completeSize / 1000).toFixed(2) + ' KB';
        }

        var endText = completeCount === 1 ? '' : 'en';

        if (completeCount === 0) {
            textElem.setAttribute('data-tell-content', 'clear');
            textElem.textContent = '';
            textElem.dispatchEvent(new CustomEvent('tell.clear', { bubbles: true }));
        } else {
            textElem.setAttribute('data-tell-content', 'set');
            textElem.textContent = completeCount + ' Datei' + endText + ' / ' + sizeText;
            textElem.dispatchEvent(new CustomEvent('tell.set', {
                bubbles: true,
                detail: {
                    text: completeCount + ' Datei' + endText + ' / ' + sizeText,
                    count: completeCount,
                    size: completeSize,
                    fileList: arrFileList
                }
            }));
        }
    } else {
        var completeTxt = arrTxt.join(', ');
        textElem.textContent = completeTxt;

        if (completeTxt === '') {
            textElem.setAttribute('data-tell-content', 'clear');
            textElem.dispatchEvent(new CustomEvent('tell.clear', { bubbles: true }));
        } else {
            textElem.setAttribute('data-tell-content', 'set');
            textElem.dispatchEvent(new CustomEvent('tell.set', {
                bubbles: true,
                detail: {
                    text: completeTxt,
                    textList: arrTxt
                }
            }));
        }
    }
}

function tell_disconnect(element) {
    if (!element) return;

    if (element._tellHandlers) {
        element._tellHandlers.forEach(function(item) {
            element.removeEventListener(item.type, item.handler);
        });
        delete element._tellHandlers;
    }

    var container = element.closest('form') || document.body;
    var allElements = container.querySelectorAll('[data-tell-name]');

    allElements.forEach(function(otherElem) {
        if (otherElem._tellHandlers && otherElem !== element) {
            var remainingHandlers = otherElem._tellHandlers.filter(function(item) {
                if (item.textElement === element) {
                    otherElem.removeEventListener(item.type, item.handler);
                    return false;
                }
                return true;
            });

            if (remainingHandlers.length === 0) {
                delete otherElem._tellHandlers;
            } else {
                otherElem._tellHandlers = remainingHandlers;
            }
        }
    });

    element.removeAttribute('data-tell-connected');
}

function tell_refresh(container) {
    container = container || document.body;

    var tellElements = container.querySelectorAll('[data-tell-name]');

    tellElements.forEach(function(el) {
        if (el.getAttribute('data-tell-connected') === 'true') {
            tell_disconnect(el);
        }
    });

    tellElements.forEach(function(el) {
        tell_connect(el);
    });
}





/* cdn 1ms */