/**
 * funciones y eventos para el mostrado del svg del mapa y sus estilos
 */
document.addEventListener('DOMContentLoaded', function () {
    // Cache DOM elements that are used multiple times
    const countrySelect = document.getElementById('map_country');
    const mapId = document.getElementById('map_id').value;
    const mapColor = document.getElementById('map_color');
    const mapHoverColor = document.getElementById('map_color_mouse_over');
    const mapStrokeColor = document.getElementById('stroke_color');
    const mapStrokeWidth = document.getElementById('stroke_width');
    const pinShapeColor = document.getElementById('pines_shape_color');
    const pinNameColor = document.getElementById('pines_text_color');
    const pinSize = document.getElementById('pin_width');
    const pinTextSize = document.getElementById('pin_name_text');
    const svgMap = document.getElementById('svg-container');

    const un_id = mapId;
    const mapCountry = countrySelect.value;

    showMap(mapCountry, un_id);

    // Event listener for country selection change
    countrySelect.addEventListener('change', function () {
        showMap(this.value, un_id);
    });

    /**
     * Function to update map regions
     * @param {callback} updateFn 
     */
    function updateMapRegions(updateFn) {
        svgMap.querySelectorAll('path').forEach(updateFn);
    }

    /**
     * Function to update pin elements
     * @param {cssSelector} selector 
     * @param {callback} updateFn 
     */
    function updatePinElements(selector, updateFn) {
        svgMap.querySelectorAll(selector).forEach(updateFn);
    }

    // Map color change event
    mapColor.addEventListener('change', function () {
        const color = mapColor.value;
        updateMapRegions(mapRegion => {
            mapRegion.style.fill = color;
            mapRegion.addEventListener('mouseleave', function () {
                mapRegion.style.fill = color;
            });
        });
    });

    // Map hover color change event
    mapHoverColor.addEventListener('change', function () {
        const hoverColor = mapHoverColor.value;
        const color = mapColor.value;
        updateMapRegions(mapRegion => {
            mapRegion.addEventListener('mouseenter', function () {
                mapRegion.style.fill = hoverColor;
            });
            mapRegion.addEventListener('mouseleave', function () {
                mapRegion.style.fill = color;
            });
        });
    });

    // Map stroke color change event
    mapStrokeColor.addEventListener('change', function () {
        updateMapRegions(mapRegion => {
            mapRegion.style.stroke = mapStrokeColor.value;
        });
    });

    // Map stroke width change event
    mapStrokeWidth.addEventListener('change', function () {
        updateMapRegions(mapRegion => {
            mapRegion.style.strokeWidth = mapStrokeWidth.value;
        });
    });
    //inicio jo 30 jul
    // Pin shape color change event
    pinShapeColor.addEventListener('change', function () {
        updatePinElements('.xpin', pin => {
            pin.style.background = pinShapeColor.value;
        });
    });

    // Pin name color change event
    pinNameColor.addEventListener('change', function () {
        updatePinElements('.jo-pin-text', pinText => {
            pinText.style.color = pinNameColor.value;
        });
    });

    // Pin size change event
    pinSize.addEventListener('input', function () {
        const size = pinSize.value;
        const imgSize = Math.round(size / 1.33);
        updatePinElements('.xpin', pin => {
            pin.style.width = `${size}px`;
            pin.style.height = `${size}px`;
            const img = pin.querySelector('.imgempnext');
            img.style.width = `${imgSize}px`;
            img.style.height = `${imgSize}px`;
        });
    });

    // Pin text size change event
    pinTextSize.addEventListener('input', function () {
        const size = pinTextSize.value;
        updatePinElements('.jo-pin-text', pinText => {
            pinText.style.fontSize = `${size}px`;
        });
    });
    //fin jo 30 jul



    /***********************
     ***** FUNCTIONS ******
     *********************/
    function showMap(mapCountry, un_id){
        // Load SVG content using AJAX
		console.log("ServerData.pluginUrl", ServerData.pluginUrl + 'assets/svgs/' + mapCountry + '.svg');
        fetch( ServerData.pluginUrl + 'assets/svgs/' + mapCountry + '.svg')
            .then(response => response.text())
            .then(data => {
                // Parse the SVG content
                const parser = new DOMParser();
                const svgDoc = parser.parseFromString(data, 'image/svg+xml');
                const svgElement = svgDoc.querySelector('svg');

                if (svgElement) {
                    // Set new attributes
                    svgElement.setAttribute('id', 'mapaalemaniab_' + un_id);
                    svgElement.setAttribute('baseProfile', 'tiny');
                    svgElement.setAttribute('fill', '#7c7c7c');
                    svgElement.setAttribute('stroke', '#E7E2DF');
                    svgElement.setAttribute('stroke-linecap', 'round');
                    svgElement.setAttribute('stroke-linejoin', 'round');
                    svgElement.setAttribute('stroke-width', '2');
                    svgElement.setAttribute('version', '1.2');
                    svgElement.setAttribute('class', 'mapMain');

                    // Remove unwanted attributes if necessary
                    // svgElement.removeAttribute('xmlns');
                    // svgElement.removeAttribute('width');
                    // svgElement.removeAttribute('height');

                    // Convert the modified SVG element back to a string
                    const serializer = new XMLSerializer();
                    let svgString = serializer.serializeToString(svgElement);

                    // Inject the modified SVG into the DOM
                    document.getElementById('svg-container').innerHTML = svgString;
                    
                    /*****************/
                    /**** events ****/
                    /***************/
                    let mapColor =document.getElementById('map_color');
                    let mapHoverColor =document.getElementById('map_color_mouse_over');
                    let mapStrokeColor =document.getElementById('stroke_color');
                    let mapStrokeWidth = document.getElementById('stroke_width');
                    

                    let svgMap = document.getElementById('svg-container');
                    svgMap.querySelectorAll('path').forEach(function(mapRegion){
                        //establece color del mapa
                        mapRegion.style.fill = mapColor.value;
                        //color del stroke
                        mapRegion.style.stroke = mapStrokeColor.value;
                        mapRegion.style.strokeWidth = mapStrokeWidth.value;
                        
                        //color del mapa en enter mapRegion
                        mapRegion.addEventListener('mouseenter', function(){
                            mapRegion.style.fill=mapHoverColor.value;
                        });
                        //color del mapa en mouse leave mapRegion
                        mapRegion.addEventListener('mouseleave', function(){
                            mapRegion.style.fill=mapColor.value;
                        });
                    });

                    const myTimeout = setTimeout(mapSizeAdjust, 35);

                } else {
                    console.error('SVG element not found');
                    document.getElementById('svg-container').innerText = 'No SVG found in the file.';
                }
            })
            .catch(error => {
                console.error('Error loading SVG:', error);
                document.getElementById('svg-container').innerText = 'Error loading SVG.';
            });


    }
    //esta funcion no es necesaria pero se deja por si en algun momento es necesario interrumpir el evento 
    function myStopFunction() {
        clearTimeout(myTimeout);
    }
    function mapSizeAdjust(){
        var map_size_relation = 100;
        var percent = 1 + ((100 - map_size_relation) / 1000);

        var maxWidth = 0;
        var maxHeight = 0;

        var svg = document.querySelector('map svg');
        // console.log(svg);

        var paths = svg.querySelectorAll("path");
        paths.forEach(function (path) {
            var bbox = path.getBBox();
            var pathWidth = bbox.x + bbox.width;
            var pathHeight = bbox.y + bbox.height;

            console.log("percentpercentpercent", percent);
            maxWidth = Math.max(maxWidth, pathWidth);
            maxWidth = maxWidth * percent

            maxHeight = Math.max(maxHeight, pathHeight);
            maxHeight = maxHeight * percent
        });
        svg.setAttribute("viewBox", "0 0 " + maxWidth + " " + maxHeight);
    }
});

//jo 30 julio
/**
 * funcion para actualizar el color del texto, shape de los pines y la velocidad de animacion en la carga de la pagina
 */
document.addEventListener('DOMContentLoaded', function () {
    // Recuperar los colores guardados de PHP a JavaScript
    let pinesShapeColor = document.getElementById('pines_shape_color').value;
    let pinesTextColor = document.getElementById('pines_text_color').value;
    let animDuration = document.getElementById('bound_velocity').value;
    let pinTextSize = document.getElementById('pin_name_text').value;

    animDuration = animDuration/1000;
    // Crear una nueva hoja de estilos
    let styleSheet = document.createElement("style");
    document.head.appendChild(styleSheet);

    // Función para actualizar los colores en tiempo real
    function updateColors(shapeColor, textColor) {
        let cssRuleShape = `.xpin { background: ${shapeColor}; }`;
        let cssRuleText = `.jo-pin-text { color: ${textColor};font-size: ${pinTextSize}px }`;
        let cssRuleAnim = `.jo-animation { animation-duration: ${animDuration}s }`;
        if (styleSheet.styleSheet) {
            styleSheet.styleSheet.cssText = cssRuleShape + cssRuleText + cssRuleAnim; // IE
        } else {
            styleSheet.innerHTML = cssRuleShape + cssRuleText + cssRuleAnim; // Otros navegadores
        }
    }
    // Actualizar los colores con los valores guardados al cargar la página
    updateColors(pinesShapeColor, pinesTextColor);
});

let svgElementN = null;
var intervalID = null;

function esDispositivoMovil() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

/**
 * Funciones y metodos para el mostrado de pins en el mapa
 */
document.addEventListener('DOMContentLoaded', function () {
    let countrySelect = document.getElementById('map_country');
    let mapId = document.getElementById('map_id').value;

    const mapCountry = countrySelect.value; // Example country, you can set this dynamically
    const un_id = mapId; // Example ID, you can set this dynamically
    const newDivHtml = '<div  attrid="' + un_id + '" class="cardnc" style="z-index:10000;" id="cardn_' + un_id + '"><div class="close-btn" style="padding-top:10px !important; width:12px; position: absolute;top: -3px;right: 5px;cursor: pointer;color: black;font-weight:bold; padding: 1px;z-index: 11;"><img style="width:12px;" src="' + ServerData.pluginUrl +'/assets/img/Close_Icon_Black.svg" /> </div><div class="text" style="padding-top:10px; padding-left:10px;left:30%; width: 60%; position:absolute;top: 0;display: flex;flex-direction: column;justify-content: space-between;"><a id="aW_' + un_id + '" href=""><div style="text-align:left;line-height:1" class="name_style" id="nameW_' + un_id + '"></div><div class="position_style" style="text-align:left;line-height:1" id="positionW_' + un_id + '"></div></a><div class="cel_style" style="margin-top:10px; text-align:left;line-height:1" id="celW_' + un_id + '"></div><div class="email_style" style="text-align:left;line-height:1" id="emailW_' + un_id + '"></div></div><div class="imagecrd" style="height:100px; position: absolute; top: 0; left: 0; width:30%"></div></div><div class="popupnb_class" id="popupnb_' + un_id + '"></div>';

    function myCallback() {
        const svgContainer = document.getElementById('svg-container');
        svgElementN = svgContainer.querySelector('svg');
        if (svgElementN != null) {
            nahiro_init(un_id, newDivHtml);
            jQuery('#mapaalemaniab_' + un_id + ' circle').trigger('mouseenter');
            clearInterval(intervalID);
        }
    }

    intervalID = setInterval(myCallback, 100);
    //const pinsPreview = setTimeout( function(){
    console.log("auika")

    //nahiro_init(un_id,newDivHtml);
    //jQuery('#mapaalemaniab_'+un_id+' circle').trigger('mouseenter');
    //}, 240);

    function extractText(pattern) {
        const regex = /(\d)_([\d_]+)$/;
        const match = pattern.match(regex);

        if (match) {
            return `${match[1]}_${match[2]}`;
        } else {
            return "No match found";
        }
    }

    function hideDiv(buttonElement, widgetid) {
        //var pinesClicks = window['pinesClicks_' + widgetid];
        let attrid = jQuery(buttonElement.parent()).attr('attrid')
        let idEnd = jQuery(buttonElement.parent()).attr('id')[jQuery(buttonElement.parent()).attr('id').length - 1]
        console.log("pinesClicks", pinesClicks, idEnd + '_' + attrid, jQuery(buttonElement.parent()));
        let id = jQuery(buttonElement.parent()).attr('id')
        let codeCard = extractText(jQuery(buttonElement.parent()).attr('id'));
        let clicksNow = pinesClicks[codeCard].clicks
        clicksNow = clicksNow.filter(item => item !== '#' + id);
        console.log("clicksNow", clicksNow);

        var parentDiv = buttonElement.parent();
        //parentDiv.style.display = 'none';
        parentDiv.css({ "display": "none" });
        pinesClicks[codeCard].clicks = clicksNow
        console.log('pinesClicks', pinesClicks, clicksNow)
        if (clicksNow.length == 0) {
            const valor = pinesClicks[codeCard];
            let originalSrc = valor.url
            let originalSize = valor.size
            jQuery('img[id="' + idEnd + '_' + attrid + '"]').attr('src', originalSrc);
            jQuery('img[id="' + idEnd + '_' + attrid + '"]').css({
                width: originalSize.width,
                //height: originalSize.height
            });
            reboteInfinito(jQuery('img[id="' + idEnd + '_' + attrid + '"]'))

            //pinesClicks = pinesClicks.filter(item => {console.log("ujumllele::", item); item !== idEnd + '_'+ attrid));
            delete pinesClicks[codeCard];
            //window['pinesClicks_' + widgetid] = pinesClicks
            console.log('pinesClicks222', pinesClicks)
        }
    }

    function reboteInfinito(elemento, rebotIni = false) {
        // 2 may: jo: impide ejecucion de funcion rebote infinito sin interrumpir el flujo de codigo normal
        return;

    }

    const circles = [];
    function nahiro_init(un_id, newDivHtml) {
        jQuery('#svg-container').before(newDivHtml);

        const svgContainer = document.getElementById('svg-container');
        console.log("auika333", svgContainer)
        svgElementN = svgContainer.querySelector('svg');
        console.log("auika444", svgElementN)
        const pinItems = document.querySelectorAll('.pin-item');


        pinItems.forEach((pinItem, index) => {
            const cxInput = pinItem.querySelector('input[name^="circle_coordinates"][name$="[cx]"]');
            const cyInput = pinItem.querySelector('input[name^="circle_coordinates"][name$="[cy]"]');
            const nameInput = pinItem.querySelector('input[name^="circle_coordinates"][name$="[circle_name]"]');
            const colorInput = pinItem.querySelector('input[name^="circle_coordinates"][name$="[circle_color]"]');
            const ratioInput = pinItem.querySelector('input[name^="circle_coordinates"][name$="[circle_ratio]"]');
            //jo
            const imgInput = pinItem.querySelector('input[name^="circle_coordinates"][name$="[circle_image][url]"]');
            //edward 30 jul
            const circleHideSelect = pinItem.querySelector('select[name^="circle_coordinates"][name$="[circle_hide]"]');
            const selectedValue = circleHideSelect.value;

            if (cxInput && cyInput && nameInput && colorInput && ratioInput) {
                const circleX = cxInput.value;
                const circleY = cyInput.value;
                const circleName = nameInput.value;
                const circleColor = colorInput.value;
                const circleRadius = ratioInput.value;
                //jo 
                const circleImage = imgInput.value;

                const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
                //edward 30 jul
                circle.setAttribute('style', 'stroke:none; color:transparent; fill: transparent;');
                circle.setAttribute('id', `${index}_${un_id}`);
                circle.setAttribute('cx', circleX);
                circle.setAttribute('cy', circleY);
                circle.setAttribute('r', circleRadius);
                circle.setAttribute('fill', circleColor);
                circle.setAttribute('data-name', circleName);

                svgElementN.appendChild(circle);

                const cardItems = pinItem.querySelectorAll('.card-item');
                const cards = [];

                cardItems.forEach((cardItem, indexC) => {
                    const personName = cardItem.querySelector('input[name^="circle_coordinates"][name$="[person_name]"]').value;
                    const personPosition = cardItem.querySelector('input[name^="circle_coordinates"][name$="[person_position]"]').value;
                    const personPhone = cardItem.querySelector('input[name^="circle_coordinates"][name$="[person_phone]"]').value;
                    const personEmail = cardItem.querySelector('input[name^="circle_coordinates"][name$="[person_email]"]').value;
                    const personImg = cardItem.querySelector('input[name^="circle_coordinates"][name$="[person_image][url]"]').value;

                    console.log("personImgpersonImgpersonImg", personImg);



                    cards.push({
                        id: `${indexC}`,
                        personName,
                        personPosition,
                        personPhone,
                        personEmail,
                        personImg
                    });
                });

                circles.push({
                    id: `${index}_${un_id}`,
                    name: circleName,
                    cx: circleX,
                    cy: circleY,
                    hide: selectedValue,
                    radius: circleRadius,
                    color: circleColor,
                    image: circleImage,
                    cards: cards
                });
            }
        });


        jQuery('#mapaalemaniab_' + un_id + ' circle').off().on('mouseenter', function (e) {
            console.log("ujummm circle");
            var position = jQuery(this).offset();
            console.log("original", jQuery(this).css("top"), jQuery(this).css("position"));
            var width = jQuery(this).width();
            var height = jQuery(this).height();
            var elementorIds = [un_id + 'a', un_id + 'b', un_id + 'c'];


            var region = jQuery(this).attr('id');  // Asegúrate de que cada `path` tiene un id correspondiente a una clave en `pinesPorRegion`
            console.log("regionregionregion", region);
            //$('#' + region + 'x').css('fill', '#e5dfd9'); // Cambia el color a rojo al pasar el mouse
            var pines = circles.find(circle => circle.id === region);
            console.log("pinespines", pines);
            if (!pines) return;  // Si no hay pines para esta región, no hacemos nada


            var pinSize = document.getElementById('pin_width').value;
            var imgSize = pinSize / 1.33;

            var popupnContent = '<img id="' + region + '" attrid="' + region + '" class="imgempn_' + un_id + ' imgempnext"  src="' + pines.image + '' + '" alt="' + pines.name + '" style="border-radius:100%;width:' + imgSize + 'px;height:' + imgSize + 'px;">';
            var topPin = 0;
            var fontW = "";
            if (esDispositivoMovil()) {
                topPin = pines.cy - 15;
                fontW = "14";

            } else {
                topPin = pines.cy;
                fontW = "18";
            }
            // topPin = 70;

            if (mapMargin == null || offsetMargin == null) {
                var mapMargin = document.getElementById("svg-container");
                //console.table(pines);
                console.log("mapMargin", mapMargin);
                var offsetMargin = window.getComputedStyle(mapMargin).marginLeft; //out: ejm: '800px'
                offsetMargin = offsetMargin.split("px"); //out ejm: ['800','px']
                offsetMargin = Number(offsetMargin[0]); //out ejem: 800
                console.log("offsetMargin", offsetMargin, window.getComputedStyle(mapMargin).top, window.getComputedStyle(mapMargin).height);
            }
            //console.log("voy1");
            var pinWidthHeightRule = `width:${pinSize}px;height: ${pinSize}px;`;
            //inicio edward 30 jul
            popupnContent = "<div class='jo-animation reboteInfinito' style='display:flex; flex-direction:row'><div class='xpin " + "" + "' style='" + pinWidthHeightRule + "' >" + popupnContent + "</div></div><div style='position:absolute; width:100%; text-align:center; font-weight:light; /*font-family:\"Lato\";*/ line-height:1; top:" + "78" + "px; left:" + "0" + "px' class='jo-pin-text circle-dinamic-"+region+"'>" + pines.name + "</div>";
            if (pines.hide == 'no') {
                // alert('ok');
               var cssRule = '.circle-dinamic-'+region+'::before { content: ""; width: '+ pines.radius +'px; height: '+ pines.radius +'px; border-radius: 50%; background-color: '+ pines.color +'; display: block; position: absolute; left: calc(50% - 3px); top: 15px; z-index: -1; }';
                jQuery('head').append('<style>' + cssRule + '</style>');
            }
            //fin edward 30 jul
            //var newParentDiv = $('<div id="parent_"+uniqueId+"' + region +'" class="parentall" style="width:100%; height:100%">');
            var popupClonado = jQuery('#popupnb_' + un_id + '').clone();
            popupClonado.attr('id', 'popupClonb_' + un_id + '' + region);
            //jo 6 may
            //console.log(elementorIds);
            popupClonado.addClass('elementor-repeater-item-' + elementorIds[0]);


            console.log("popupClonado", popupClonado, jQuery('#popupnb_' + un_id + ''))
            jQuery('#svg-container').append(popupClonado);
            //jQuery('#popupnb_'+un_id+'').parent().append(popupClonado);
            //$('#popupnb_'+uniqueId+'').parent().append(newParentDiv);
            //newParentDiv.append(popupClonado);

            widthParent = e.target.getBoundingClientRect().width
            console.log("ujum", position, jQuery(this).parent().offset(), jQuery(this).offset());

            const topPosition = position.top - jQuery(this).parent().parent().offset().top
            console.log("topPosition", topPosition, jQuery(this));
            jQuery('#popupClonb_' + un_id + '' + region).css({
                'top': (position.top - jQuery(this).parent().offset().top - /*100*/ 85) + 'px',
                'position': 'absolute',
                //jo 7 may +offset
                'left': (position.left - jQuery(this).parent().offset().left /*- 34*/ - 32 + offsetMargin) + 'px'
            });


            console.log("popupnContent", popupnContent, jQuery('#popupClonb_' + un_id + '' + region));
            jQuery('#popupClonb_' + un_id + '' + region).html(popupnContent);
            jQuery('#popupClonb_' + un_id + '' + region).show();


        });



        jQuery('#map_country').off().on('change', function () {
            //alert('change');
            console.table('change okay');
            const svgElementN = svgContainer.querySelector('svg');
            //intervalID = setInterval(myCallback, 100);
            setTimeout(selectInitialize, 200);

        });



        function selectInitialize() {
            setTimeout(function () {
                nahiro_init(un_id);
                jQuery('#mapaalemaniab_' + un_id + ' circle').trigger('mouseenter');
            }, 220);
        }

        jQuery('#nahiroimap_map_preview-meta_box #svg-container').click(function (e) {
            var posX = jQuery(this).offset().left, posY = jQuery(this).offset().top;
            //alert((e.pageX - posX)*2 + ' , ' + (e.pageY - posY)*2);
            jQuery('#pin-position-popup_x').text('Horizontal: ' + Math.round((e.pageX - posX) * 2));
            jQuery('#pin-position-popup_y').text('Vertical: ' + Math.round((e.pageY - posY) * 2));

        });

    }


    const myPinsTimeout = setTimeout(pines_init, 230);

    var pinesClicks = {};
    const option_card = "opcionE";
    function clickPin(un_id) {
        jQuery(document).on('click', 'img.imgempn_' + un_id + '', function (e1) {
            //jo 01/06 stop event propagation, solve bug element executing click event twice when clicked once
            e1.stopPropagation();
            e1.stopImmediatePropagation();
            //fin jo 01/06

            var makeclick = false;
            var attrid = jQuery(this).attr('attrid');

            console.log("attrid", attrid, makeclick, jQuery(this));
            if (pinesClicks.hasOwnProperty(attrid)) {
                console.log("por el if")
                makeclick = true;
                originalSrc = pinesClicks[jQuery(this).attr('attrid')].url
                //delete pinesClicks[$(this).attr('attrid')];
            } else {
                console.log("por el else")
                pinesClicks[attrid] = { "url": jQuery(this).attr('src') }
                console.log("en el else 1", pinesClicks);
            }
            console.log("pinesClicks 1", pinesClicks);

            if (!makeclick) {
                //if (!$(this).data('original-src')) {
                originalSrc = jQuery(this).attr('src');

                originalSize = {
                    width: jQuery(this).width(),
                    height: jQuery(this).height()
                };

                pinesClicks[jQuery(this).attr('attrid')].size = originalSize

                jQuery(this).data('original-src', jQuery(this).attr('src'));
                //        }

                jQuery(this).css({
                    //width: originalSize.width - 10,
                    //height: originalSize.height - 10
                    //jo
                    width: originalSize.width,
                    //height: originalSize.height + 5
                });
                //jo 3 may, si se comenta la siguiente linea, se elimina el efecto de imagen cuando se hace click
                //    $(this).attr('src', 'https://somelink-removebg-preview.png');
                jQuery(this).stop(true, false);

                //originalSrc = $(this).attr('src');


                var imgid = jQuery(this).attr('id');
                var regid = jQuery(this).attr('attrid');
                var position2 = jQuery(this).offset();


                var pines = circles.find(circle => circle.id === regid);
                console.log("circles pines", circles, regid, pines)
                //var enc = pines.cards.find(pin => pin.id === imgid);
                pines.cards.map((pin, ipin) => {

                    if (pinesClicks.hasOwnProperty(jQuery(this).attr('attrid'))) {
                        let arrayClicks = pinesClicks[jQuery(this).attr('attrid')].clicks
                        if (typeof arrayClicks === "undefined") {
                            arrayClicks = []
                        }
                        arrayClicks.push("#card_" + un_id + "" + pin.id + pines.id)
                        pinesClicks[jQuery(this).attr('attrid')].clicks = arrayClicks
                    }

                    var cardClon = jQuery('#cardn_' + un_id + '').clone();

                    let newh = 0
                    if (window.innerWidth <= 768) {
                        let neww = (window.innerWidth * 250) / 1366 + 70
                        let newp = (neww * 100) / 250
                        newh = (newp / 100) * 100 + 20
                        jQuery(cardClon).css({
                            width: neww,
                            height: newh,
                            padding: 1,
                        });
                    }

                    cardClon.attr('id', 'card_' + un_id + '' + pin.id + pines.id);
                    console.log("option_cardoption_cardoption_card", option_card, cardClon);
                    if (option_card != 'opcionD' && option_card != 'opcionE') {
                        jQuery('#' + 'card_' + un_id + '' + pin.id + pines.id + ' .close-btn').remove();
                    } else {

                    }
                    //cardClon.attr('attrid', regid);

                    //jQuery('#cardn_'+un_id+'').parent().append(cardClon);
                    jQuery('#svg-container').append(cardClon);

                    console.log("aquika close button", jQuery('.close-btn'));
                    jQuery('.close-btn').click(function (event) {
                        hideDiv(jQuery(this), un_id);
                    });

                    console.log("por aqui", "#card_" + un_id + "" + pin.id + pines.id, jQuery("#card_" + un_id + "" + pin.id + pines.id));

                    jQuery("#card_" + un_id + "" + pin.id + pines.id + " .imagecrd").css('background', 'url(' + pin.personImg + ') center/cover no-repeat');
                    if (window.innerWidth <= 768) {
                        jQuery("#card_" + un_id + "" + pin.id + pines.id + " .imagecrd").css('height', newh);

                    }
                    if (pin.url !== "") {
                        jQuery("#card_" + un_id + "" + pin.id + pines.id + " #aW_" + un_id + "").attr('href', pin.url);
                    } else {
                        jQuery("#card_" + un_id + "" + pin.id + pines.id + " #aW_" + un_id + "").click(function (event) {
                            event.preventDefault();
                        });
                    }
                    jQuery("#card_" + un_id + "" + pin.id + pines.id + " #nameW_" + un_id + "").text(pin.personName);
                    if (window.innerWidth <= 768) {
                        jQuery("#card_" + un_id + "" + pin.id + pines.id + " #nameW_" + un_id + "").css({
                            //fontSize: 11,
                        });
                    }
                    jQuery("#card_" + un_id + "" + pin.id + pines.id + " #positionW_" + un_id + "").text(pin.personPosition);
                    if (window.innerWidth <= 768) {
                        jQuery("#card_" + un_id + "" + pin.id + pines.id + " #positionW_" + un_id + "").css({
                            //fontSize: 9,
                        });
                        jQuery("#card_" + un_id + "" + pin.id + pines.id + " #positionW_" + un_id + "").parent().parent().css({
                            paddingLeft: 5,
                        });
                        jQuery("#card_" + un_id + "" + pin.id + pines.id + " #positionW_" + un_id + "").parent().parent().css({
                            paddingTop: 5,
                        });
                    }
                    //$("#card_"+uniqueId+""+pin.id+pines.id+" #celW_"+uniqueId+"").text(pin.phone);
                    jQuery("#card_" + un_id + "" + pin.id + pines.id + " #celW_" + un_id + "").empty();
                    jQuery("#card_" + un_id + "" + pin.id + pines.id + " #celW_" + un_id + "").append('<a style="" href="tel:' + pin.personPhone + '">' + pin.personPhone + '</a>');
                    if (window.innerWidth <= 768) {
                        jQuery("#card_" + un_id + "" + pin.id + pines.id + " #celW_" + un_id + "").css({
                            marginTop: 8,
                            // fontSize: 14,
                        });

                        jQuery("#card_" + un_id + "" + pin.id + pines.id + " #celW_" + un_id + " a").css({
                            //  fontSize: 14,
                        });
                    }
                    jQuery("#card_" + un_id + "" + pin.id + pines.id + " #emailW_" + un_id + "").empty();
                    jQuery("#card_" + un_id + "" + pin.id + pines.id + " #emailW_" + un_id + "").append('<a style="" href = "mailto: ' + pin.personEmail + '">' + pin.personEmail + '</a>');
                    if (window.innerWidth <= 768) {
                        jQuery("#card_" + un_id + "" + pin.id + pines.id + " #emailW_" + un_id + "").css({
                            marginTop: 1,
                            // fontSize: 14,
                        });

                        jQuery("#card_" + un_id + "" + pin.id + pines.id + " #emailW_" + un_id + " a").css({
                            //fontSize: 9,
                        });
                    }
                    //.text(pin.email);
                    if (window.innerWidth <= 768) {
                        jQuery("#card_" + un_id + "" + pin.id + pines.id).css({
                            'top': (jQuery(this).parent().parent().parent()[0].offsetTop - jQuery(this).parent().parent().parent()[0].offsetHeight - (ipin * 85) + 15) + 'px',
                            'left': (e1.pageX - jQuery(this).parent().parent().parent().offset().left - (jQuery(this).parent().parent().parent()[0].offsetWidth / 2) - 20) + 'px'
                        });
                    } else {
                        var $componentA = jQuery(this);
                        var $componentB = jQuery(cardClon);

                        var rectA = $componentA[0].getBoundingClientRect();
                        console.log('rectA');
                        var pinPos = $componentA.parent().parent().parent()[0].offsetTop;
                        // Position componentB above componentA and centered
                        $componentB.css({
                            top: pinPos - 100 - (ipin * 130),
                            //top: `${rectA.top - $componentB.outerHeight() - 100 - (ipin * 130)}px`,
                            left: `${rectA.left + (rectA.width / 2) - $componentB.outerWidth() - 30}px`,
                            //display: 'block'
                        });
                        /*jQuery("#card_"+un_id+"" + pin.id + pines.id).css({
                            'top': (jQuery(this).parent().parent().parent()[0].offsetTop - jQuery(this).parent().parent().parent()[0].offsetHeight - (ipin * 105) - 40) + 'px',
                            'left': (e1.pageX - jQuery(this).parent().parent().parent().parent().offset().left - (jQuery(this).parent().parent().parent()[0].offsetWidth / 2) - 83) + 'px'
                        });*/
                    }
                    console.log("finalizando");
                    jQuery("#card_" + un_id + "" + pin.id + pines.id).show();

                });
            } else {
                let arrayClicks = pinesClicks[jQuery(this).attr('attrid')].clicks

                if (option_card == 'opcionA' || option_card == 'opcionE') {
                    arrayClicks.map((item, iitem) => {
                        jQuery(item).hide();
                    })

                    jQuery(this).attr('src', originalSrc);
                    jQuery(this).css({
                        width: originalSize.width,
                        //height: originalSize.height
                        //height: originalSize.height + 5
                    });
                    reboteInfinito(jQuery(this))
                    delete pinesClicks[jQuery(this).attr('attrid')];
                }
            }
            console.log("pinesClicks 2", pinesClicks);
        });
    }

    function pines_init() {
        //invocacion
        jQuery('#mapaalemaniab_' + un_id + ' circle').trigger('mouseenter');
        clickPin(un_id);
    }


});
