{if $product['status'] == "auto-draft"}
    <p style="width: 100%;color: #555;font-size: 13px;line-height: 24px;">{$t::getTraduction( "Cree_produit_pour_utilise_ds4")}</p>
{else}
	<script>
            // When the user clicks on div, open the popup
		
            function showHideDS4Popup(id)
            {
                var allPopups = document.getElementsByClassName("ds4_popuptext");
		for (let i = 0; i < allPopups.length; i++)
                {
                    if (allPopups[i].id != "myPopup" + id) allPopups[i].classList.remove("show");
                }
                var popup = document.getElementById("myPopup" + id);
		popup.classList.toggle("show");
            }
		
	</script>
        <!--{$form_nonce}-->
    <div style="border-bottom: 1px solid rgba(128, 128, 128, 0.24);color: #555;font-size: 15px;line-height: 1.5;"
         id="affichage_des_gabarits">

        
        <p style="width: 100%;color: #555;font-size: 15px;line-height: 1.5;">{$t::getTraduction( "Choix_gabarit")}</p>

        <div id="DigitalSignage4_liste_des_gabarits">

            <div class="gabarit_carrousel">

                {foreach from=$gabarits item=gabarit}
					{if  $gabarit->getIsUsable() == 1}
						<div onclick="selectGabarit({$gabarit->getId()} , this)" class="DigitalSignage4_gabarit_card"
							 style="position: relative"
							 id="gabarit_{$gabarit->getId()}">

							<p style="text-align: left; text-transform:uppercase;margin:0;color: #555;font-size: 12px;line-height: 24px;">{$gabarit->getNom()}</p>

							{*                    <span onclick="reloadGabrit({$gabarit->getId()} , this)" class="reloadIcon">*}
							{*                          <i class="DigitalSignage4_material-icons">loop</i>*}
							{*                    </span>*}

							<video id="{$gabarit->getId()}" controls
								   class="video_gabarit_displayer" loop
								   width="250" height="142" preload="metadata" muted="muted">
								<source src="{$gabarit->getLienVideoExemple()}" type="video/mp4">
							</video>

							<div style="position: absolute;width: 100%;height: calc( 100% - 85px ); top: 0; left: 0; z-index: 1000">

							</div>


						</div>
					{/if}
                {/foreach}


                

            </div>

        </div>
        <!--p style="width: 100%;color: #555;font-size: 15px;line-height: 1.5;">{$t::getTraduction( "Gabarit_not_usable")}</p-->

        <div id="liste_des_gabarits_not_usable">

            <div class="gabarit_carrousel">

                {foreach from=$gabarits item=gabarit}
					{if  $gabarit->getIsUsable() == 0}
						<div onclick="showHideDS4Popup({$gabarit->getId()})" class="DigitalSignage4_gabarit_card ds4_popup"
							 style="position: relative"
							 id="gabarit_{$gabarit->getId()}">
							 <span class="ds4_popuptext" id="myPopup{$gabarit->getId()}">
								{
									//$t::getTraduction( "Gabarit_not_usable_popup",$toolsDS4::getAcaciaRedirectionPageUrl("getgabarit"))
								}
							</span>

							<p style="text-align: left; text-transform:uppercase;margin:0;color: #555;font-size: 12px;line-height: 24px;">{$gabarit->getNom()}</p>

							{*                    <span onclick="reloadGabrit({$gabarit->getId()} , this)" class="reloadIcon">*}
							{*                          <i class="DigitalSignage4_material-icons">loop</i>*}
							{*                    </span>*}

							<video id="{$gabarit->getId()}" controls
								   class="video_gabarit_displayer" loop
								   width="250" preload="metadata" muted="muted">
								<source src="{$gabarit->getLienVideoExemple()}" type="video/mp4">
							</video>

							<div style="position: absolute;width: 100%;height: calc( 100% - 85px ); top: 0; left: 0; z-index: 1000">

							</div>


						</div>
					{/if}
                {/foreach}


                <script>
					let videos_displayers = document.querySelectorAll(".video_gabarit_displayer");
                    videos_displayers.forEach((videoContainer) => {
                            videoContainer.currentTime = 2;

                        }
                    )
					
					
                    
                </script>

            </div>

        </div>
    </div>
    <div style="display: none; padding-bottom: 20px" id="gabarit_elements">


        <div style="
        border-bottom: 1px solid #8080803d;
        padding-top: 30px !important;
        padding-bottom: 30px"
             class="DigitalSignage4_champs_section DigitalSignage4_creation_box DigitalSignage4_topless">

            <div id="DigitalSignage4_champs"></div>

            <div id="imgs"></div>
			
            <div class="send_video_creation"
                 style="margin-bottom: 0px !important;display: flex;height: 100px;align-items: center;">

                {if  $NbrActiveVideo > -100}
				<input type='button' id="bouton_send_video" onclick="sendVideoToApi();"
                        {*                       class="btn btn-primary save uppercase ml-3" *}
                       class="button button-primary button-large"
                       disabled="disabled"
                       value="{$t::getTraduction( "Create_the_video")}"/>

                <div id="DigitalSignage4_loading_gif">
                </div>

			{else}
			{/if}
            </div>
            <div id="errors_section">

            </div>

        </div>


    </div>
    <div id="video_produit">

        <h2 style="padding: 40px 0 0.5em 0;width: 100%;color: #555;font-size: 15px;line-height: 1.5;">{$t::getTraduction( "Historique_video_produit")}</h2>

        <div id="DigitalSignage4_videoDispo">

            {if  !$currentHistoriqueHtml}
                <p id="no_video_dispo">{$t::getTraduction( "Historique_vide")}</p>
            {else}
                {$currentHistoriqueHtml}
            {/if}

        </div>

        <br><input type='button' onclick="document.location.href='{$urlVideos}'"
                {*                   class="btn btn-primary save uppercase ml-3"*}
                   class="button button-primary button-large"
                   value="{$t::getTraduction( "Lien_videotheque")}"/>

    </div>
    <div id="vu"></div>
    <script>

        // Récuperation des gabarit dans une variable JS
        var gabarits = getGabarits();

        // Gabrit actuel
        var gabarit = null;

        // Valeurs du produit actif
        var produit = {$product|json_encode};

        console.log(produit);

        // Récupération des images du produit
        var images = {$product_img|json_encode};
        var image_nb = 1;


        function DigitalSignage4_showSuccessMessageSpecial(message, autoDistroy = true) {
            document.getElementById('errors_section').prepend(stringToHTMLForNotice('<div style="font-size: 1.2em" class="updated notice is-dismissible auto-dismiss"><p>' + message + '</p></div>', autoDistroy));
            resizeSizeFromContent();
        }

        function DigitalSignage4_showErrorMessageSpecial(message, autoDistroy = true) {
            document.getElementById('errors_section').prepend(stringToHTMLForNotice('<div style="font-size: 1.2em" class="updated error is-dismissible auto-dismiss"><p>' + message + '</div>', autoDistroy));
            resizeSizeFromContent();
        }


        /**
         * Envois du formulaire en AJAX
         */
        function sendVideoToApi() {

            document.getElementById('errors_section').innerHTML = "";

            document.getElementById('bouton_send_video').style.display = "none";
            document.getElementById('DigitalSignage4_loading_gif').style.display = "block";

            var data = getFormData();

            data.append('gabarit', gabarit['id']);
            data.append('product_id', produit.id);

            var now = new Date();
            data.append('date_demande', now.getDate() + "/" + (now.getMonth() + 1) + "/" + now.getFullYear());

            var xhr = new XMLHttpRequest();
            xhr.open('POST', '{$urlAjax}?action=AddVideoAjaxHandler&nonce={$ajax_nonce}', true);
            xhr.onload = function () {

                try {

                    console.log(this.responseText);

                    let tmpResponse = JSON.parse(this.responseText);
                    let response = JSON.parse(tmpResponse.data.message);

                    if (response) {

                        if (response.statut === 'ko') {

                            let errorFound = false;

                            response.error.map((message) => {
                                errorFound = true;
                                DigitalSignage4_showErrorMessageSpecial(message);
                            }, true);

                            response.data.map((id) => {
                                let input = document.querySelector("#" + id);
                                if (input)
                                    input.classList.add('inputError');
                            }, true);

                            if (!errorFound) {
                                DigitalSignage4_showErrorMessageSpecial("{$t::getTraduction( "Creation_impossible")}");
                            }

                            document.getElementById('bouton_send_video').style.display = "block";
                            document.getElementById('DigitalSignage4_loading_gif').style.display = "none";

                        } else {

                            DigitalSignage4_showSuccessMessageSpecial("{$t::getTraduction( "Video_cours_creation")}");
                            document.getElementById('bouton_send_video').style.display = "block";
                            document.getElementById('DigitalSignage4_loading_gif').style.display = "none";
                            addWaitingVideo(data.get("produit_libelle"), data.get("date_demande"), response.data);

                        }

                    } else {
                        DigitalSignage4_showErrorMessageSpecial("{$t::getTraduction( "pas_reponse_serveur")}");
                    }

                } catch (e) {

                    console.log(e);

                    DigitalSignage4_showErrorMessageSpecial("{$t::getTraduction( "Erreur_retour_api")}");
                    //      console.error(e);
                    document.getElementById('bouton_send_video').style.display = "block";
                    document.getElementById('DigitalSignage4_loading_gif').style.display = "none";

                }


            };

            xhr.send(data);

        }

        /**
         *  Affichage des images du produit
         */
		let number_display_product_img = 1;
        function display_product_img(name, label, isRequired, imgs, loading = false, contain = document.createElement("div")) {

            let imagesView = document.getElementById("imgs");
            let isAlreadyCreated = contain.innerHTML !== "";

            if (loading) {
                imgs = [{
                    url: "{$urlLoadingImg}",
                    path: ""
                }]
            }

            if (!isAlreadyCreated) {

                contain.classList.add("DigitalSignage4_image_line", "DigitalSignage4_creation_box");

                contain.style.margin = "0px";
                contain.style.paddingLeft = "0px";

                let span = document.createElement("span");
                span.innerHTML = addStarToLabelIfRequired(label, isRequired) + "<br>";
                span.style.marginBottom = "8px";


                span.style.color = "#555";
                span.style.fontWeight = "400";
                span.style.width = "100%";
                span.style.paddingRight = "0px";
                span.style.fontSize = "14px";
                span.style.lineHeight = "24px";
                span.style.cursor = "default";

                contain.appendChild(span);
                imagesView.appendChild(contain);

            } else {
                contain.removeChild(contain.lastElementChild);
            }

            let number = 0;

            for (const imge in imgs) {

                let image = imgs[imge];

                let image_url = image['url'];
                let image_path = image['path'];
                let div = document.createElement("div");

                if (image_url) {

                    let radio = document.createElement("input");
                    radio.type = "radio";
                    radio.name = name;
                    radio.value = image_path;
                    radio.style.margin = "0px";

					number = number + 1 ;
                    if (number == number_display_product_img || imgs.length == 1) {
                        radio.checked = true;
                    }


                    div.classList.add("image");
                    div.style.backgroundImage = "url(" + image_url + ")";
                    div.style.backgroundRepeat = "no-repeat";
                    div.style.backgroundSize = "95%";
                    div.style.backgroundPosition = "center";
                    div.style.backgroundColor = "white";
                    div.appendChild(radio);

                } else {

                    let label = document.createElement("label");
                    label.id = name;
                    label.style.width = "200px";
                    label.style.height = "200px";
                    label.style.backgroundColor = "white";
                    label.style.border = "1px solid grey";
                    label.style.display = "flex";
                    label.style.textAlign = "center";
                    label.style.alignItems = "center";
                    label.style.justifyContent = "center";
                    label.style.fontSize = "25px";
                    label.style.lineHeight = "1em";
                    label.innerText = "{$t::getTraduction( "no_image_dispo")}";
                    div.appendChild(label);

                }


                contain.appendChild(div);

            }
			
			number_display_product_img = number_display_product_img + 1;
			if (number_display_product_img > number)
			{
				number_display_product_img = 1;
			}

            return contain;

        }

        /**
         * Restart a video with a loader indication
         */
        function reloadGabrit(id, loader) {

            let video = document.getElementById(id);
            video.currentTime = 0;
            video.play();

            loader.classList.toggle('rotate_icon');

            setTimeout(() => {
                loader.classList.toggle('rotate_icon');
            }, 1000);

        }

        function stringToHTMLForNotice(str, $autoRemove = true) {
            var dom = document.createElement('div');
            dom.innerHTML = str;

            let el = dom.firstChild

            if ($autoRemove) {
                setTimeout(
                    () => {
                        el.parentElement.removeChild(el);
                        resizeSizeFromContent();
                    }, 50_000
                );
            }

            return el;
        }


        /**
         * Enregistre les information du formululaire dans un FormData pour l'envois en AJAX
         */
        function getFormData() {

            var data = new FormData();

            let champs = gabarit['champs'];

            for (const champ in champs) {

                let champs_gabarit = champs[champ];

                let element = document.getElementById(champs_gabarit['name']);

                if (champs_gabarit['type'] !== 'picture') {
                    data.append(champs_gabarit['name'], element.value);
                } else { // Récuperation de l'image coché via le nom du champ input

                    element = document.getElementsByName(champs_gabarit['name']);

                    for (var i = 0, length = element.length; i < length; i++) {
                        if (element[i].checked) {
                            // do whatever you want with the checked radio
                            data.append(champs_gabarit['name'], element[i].value);
							//alert("ici:"+champs_gabarit['name']+"|"+element[i].value);

                            // only one radio can be logically checked, don't check the rest
                            break;
                        }
                    }

                }

            }

            return data;

        }

        /**
         * Récuperation des gabarits depuis une variable PHP
         * @returns Array
         */
        function getGabarits() {
            return {

                {foreach from=$gabarits item=gabarit}
                {$gabarit->getId()} :
                    {
                        "champs": {$gabarit->getChamps()|json_encode},
                        "name":
                            '{$gabarit->getNom()}'
                    }
                ,
                {/foreach}
            }
                ;

        }
		
		function getNbrActiveVideo()
		{
			return {$NbrActiveVideo};
		}

        /**
         * Affiche un gabarit selectionné
         * @param id
         * @param e
         */
        function selectGabarit(id, e) {

            document.getElementById("bouton_send_video").disabled = "disabled";

            let element = document.querySelector(".DigitalSignage4_gabarit_card.selected");
            if (element)
                element.classList.remove("selected");

            document.querySelector(".DigitalSignage4_creation_box").style.transitionDuration = "0.1s";
            document.querySelector(".DigitalSignage4_creation_box").style.padding = "150%";
            document.querySelector(".DigitalSignage4_creation_box").style.height = "0px";

            if (id === -1) {
                gabaritNormal();
                return false;
            }

            gabarit = gabarits[id];
            gabarit['id'] = id;

            e.classList.add("selected");
            gabaritNormal();

            setGabaritChamps(gabarit);

            setTimeout(
                () => {
                    document.querySelector(".DigitalSignage4_creation_box").style.padding = "30px 10px 10px 10px";
                    document.querySelector(".DigitalSignage4_creation_box").style.transitionDuration = "3s";
                    resizeSizeFromContent();
                },
                100
            )

            document.getElementById('gabarit_elements').style.display = "block";
        }

        function resizeSizeFromContent() {

            document.querySelector(".DigitalSignage4_creation_box").style.height =
                (
                    document.querySelector(".DigitalSignage4_creation_box.DigitalSignage4_champs_section #DigitalSignage4_champs").scrollHeight +
                    document.querySelector(".DigitalSignage4_creation_box.DigitalSignage4_champs_section #imgs").scrollHeight +
                    document.querySelector(".DigitalSignage4_creation_box.DigitalSignage4_champs_section .send_video_creation").scrollHeight +
                    document.querySelector(".DigitalSignage4_creation_box.DigitalSignage4_champs_section #errors_section").scrollHeight + 50
                ) + "px"

        }


        /**
         * Ajout des champs dynamiquement du gabarit
         * @param gabarit
         */
        function setGabaritChamps(gabarit) {

            let champs = gabarit['champs'];
            let champView = document.getElementById("DigitalSignage4_champs");

            //vide le contenu
            champView.innerHTML = "";

            image_nb = 1;
            document.getElementById("imgs").innerHTML = "";

            let haveSpecialData = false;

            for (const champ in champs) {

                
                var xhr = new XMLHttpRequest();

                let champs_gabarit = champs[champ];
                let champName = champs_gabarit['wordpress_champ_name'];
                let isRequered = ('' + champs_gabarit['canBeNull'] === "0");
				
				console.log('champName:'+champName+' champs_gabarit_name :'+champs_gabarit['name']);
				//debug 
				/*
				if (champName=='description') {
					//champName='IA_description';
					champs_gabarit['name']='IA_description';
					
				}
				*/
				
				
                if (champs_gabarit['type'] !== 'picture') {

                    let value = getValueProduct(produit, champName);
                    let isHide = ('' + champs_gabarit['hide'] === "1");

                    let divContent = document.createElement('div');
					
                    divContent.style.display = "flex";
                    divContent.appendChild(createElement(champs_gabarit['name'], champs_gabarit['label'], champs_gabarit['name'], value, champs_gabarit['type'], champs_gabarit['default'], isHide, isRequered));
                    champView.appendChild(divContent);

                    if (value === "" && champName) {

                        let champ = divContent.lastElementChild.lastElementChild;

                        if (!isHide)
                            insertAfter(champ, getLoadingImgBalise());

                        haveSpecialData = true;
						//alert('champName:'+champName+' champs_gabarit_name :'+champs_gabarit['name']);
						if (champName=='IA_description') {
							//alert('IA_description'+'{$urlSpecialData}' + champName+'&ia_question='+encodeURIComponent(champs_gabarit['ia_question'])+'&id_product='+produit.id);
							xhr.open('POST', '{$urlSpecialData}?action=CreationVideoSpecialDataProviderAjaxHandler&nonce={$ajax_nonce}&digitalSignageSpecialData=' + champName+'&ia_question='+encodeURIComponent(champs_gabarit['ia_question'])+'&id_product='+produit.id, true);
						} else {
							xhr.open('POST', '{$urlSpecialData}?action=CreationVideoSpecialDataProviderAjaxHandler&nonce={$ajax_nonce}&digitalSignageSpecialData=' + champName, true);
						}
                        xhr.onload = function () {

                            if (!isHide) {
                                champ.parentElement.removeChild(champ.nextElementSibling);
                                resizeSizeFromContent();
                            }

                            if (this.responseText)
                            {
                                returnJSON = JSON.parse(this.responseText);
                                champ.value = returnJSON.data.message;
                            }

                            if (document.querySelectorAll(".loader_img").length === 0)
                                document.getElementById("bouton_send_video").disabled = "";

                        }
                        xhr.onerror = function () {
                            if (!isHide)
                                champ.parentElement.removeChild(champ.nextElementSibling);
                        }
                        var params = 'action=CreationVideoSpecialDataProviderAjaxHandler';
                        xhr.send(params);

                    }


                } else {

                    //Pour une image contenant pictureurl, on laisse quand même le choix
                    if (champName && champName.indexOf("PictureUrl") === -1) {

                        haveSpecialData = true;
						
						

                        let imageChamp = display_product_img(champs_gabarit['name'], champs_gabarit['label'], isRequered, null, true);
						//alert('ICI: '+'{$urlSpecialData}' + champName);
                        //xhr.open('POST', '{$urlSpecialData}?digitalSignageSpecialData=' + champName, true);
                        xhr.open('POST', '{$urlSpecialData}?action=CreationVideoSpecialDataProviderAjaxHandler&nonce={$ajax_nonce}&digitalSignageSpecialData=' + champName, true);
                        xhr.onload = function () {

                            if (this.responseText) {
                                returnJSON = JSON.parse(this.responseText);
                                let responsexhr = returnJSON.data.message;
            console.log(champName+'retour :'+this.responseText);
								console.log("champName:"+champName+" gabarit_name:"+champs_gabarit['name']+" gabarit_label:"+champs_gabarit['label']);
								console.log("retour image :"+responsexhr);
                                let datas = responsexhr.split(';');
								let imageSpecial = [];
								if (datas.length>=2) {
									imageSpecial = [{
										url: datas[0],
										path: datas[1]
									}];
								} else {
									//detecter l'indice de l'image par rapport a son nom
									imageSpecial = [{
										url: responsexhr,
										path: responsexhr
									}];
									let indice_image =0;
									switch(champName) {
									  case "product01PictureUrl01":
										indice_image=0;
										break;
									  case "product02PictureUrl01":
										indice_image=1;
										break;
									  case "product03PictureUrl01":
										indice_image=2;
										break;
									  case "product04PictureUrl01":
										indice_image=3;
										break;
									  case "product05PictureUrl01":
										indice_image=4;
										break;
									  case "product06PictureUrl01":
										indice_image=5;
										break;
									  case "product07PictureUrl01":
										indice_image=6;
										break;
									  case "product08PictureUrl01":
										indice_image=7;
										break;
									  case "product09PictureUrl01":
										indice_image=8;
										break;
									  case "product10PictureUrl01":
										indice_image=9;
										break;
									  default:
										indice_image=0;
									}
									
									
									
									let compteur_image_ =0;
									for (const imge in images) {
										if (compteur_image_==indice_image) {
											let image = images[imge];
											let image_url = image['url'];
											let image_path = image['path'];
											console.log("tab images :"+image_url+" "+image_path);
											imageSpecial = [{
												url: image_url,
												path: image_path
											}];
											break;
										}
										compteur_image_++;
										
										
										
									}
								
									
								}
								
								
								
                                display_product_img(champs_gabarit['name'], champs_gabarit['label'], isRequered, imageSpecial, false, imageChamp, isRequered);

                                if (document.querySelectorAll(".loader_img").length === 0)
                                    document.getElementById("bouton_send_video").disabled = "";

                            }

                        }
                        xhr.send(params);

                    } else {
						//alert('La name:' + champs_gabarit['name']+ ' label:'+champs_gabarit['label']);
						//console.log("NON image :"+champs_gabarit['name']+ ' label:'+champs_gabarit['label']);
                        display_product_img(champs_gabarit['name'], champs_gabarit['label'], isRequered, images);
                    }

                }

            }


        }

        function insertAfter(referenceNode, newNode) {
            referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
        }

        function getLoadingImgBalise() {
            let img = document.createElement("img");
            img.classList.add("loader_img");
            img.src = "{$urlLoadingImg}";
            img.style.height = "20px";
            img.style.marginLeft = "10px";
            return img;
        }

        /**
         * Recuperation de la valeur du champ du produit sans les erreur de champs vide
         * @param produit
         * @param champsGabaritElement
         * @returns string
         */
        function getValueProduct(produit, champsGabaritElement) {
            let value = getProductValue(produit, champsGabaritElement);

            if (value === undefined) {
                return "";
            }
            return value;
        }

        /**
         * Recuperation de la valeur du champ du produit
         * @param produit
         * @param champsGabaritElement
         * @returns string
         */
        function getProductValue(produit, champsGabaritElement) {

            let value = produit[champsGabaritElement];

            if (typeof value === 'object' && value !== null) {
                return value[1].replace(/(<([^>]+)>)/gi, "");
            }

            if (value) {
                return value.replace(/(<([^>]+)>)/gi, "")
            }

            return value;

        }

        function addWaitingVideo(videoN, date, id) {

            let videos = document.getElementById("DigitalSignage4_videoDispo");
            let containMain = document.createElement("div");
            let contain = document.createElement("div");
            contain.classList.add("DigitalSignage4_creation_box", "DigitalSignage4_video_dispo");
            contain.setAttribute("data-ds-id", id);
            contain.setAttribute("data-ds-flag", "pending");
            containMain.appendChild(contain);
            videos.appendChild(containMain);

            try {
                document.getElementById("no_video_dispo").style.display = "none";
            } catch (e) {

            }

            updateVideohistorique(contain, true);
        }

        function addStarToLabelIfRequired(elementLabel, required) {
            return elementLabel + ((required) ? "<span style='color:red'> *</span>" : "");
        }

        /**
         * Création d'une element du DOM pour l'insertion dans la page d'inputs dynamiques
         * @param elementId
         * @param elementLabel
         * @param elementName
         * @param elementValue
         * @param elementType
         * @param elementDefault
         * @param hide
         * @param required
         * @returns HTMLLabelElement
         */
        function createElement(elementId, elementLabel, elementName, elementValue, elementType, elementDefault, hide, required) {

            let container = document.createElement("div");
            container.style.width = "100%";
            container.style.padding = "5px 20px 5px 162px !important";
            container.style.margin = "9px 0";
            container.style.fontStyle = "14px";
            container.style.lineHeight = "24px";
            container.style.color = "#555";
            container.style.fontWeight = "400";
            container.style.display = "flex";

            let input;

            let label = document.createElement('label');
            label.htmlFor = elementId;
            label.style.width = "200px";
            label.style.marginRight = "10px";
            label.style.marginTop = "5px";
            label.style.marginBottom = "0";
            label.style.paddingRight = "0px";
            label.style.float = "left";


            let span = document.createElement('span');
            span.style.fontSize = "14px";
            span.style.lineHeight = "24px";
            span.innerHTML = addStarToLabelIfRequired(elementLabel, required);

            if (elementType === "textarea") {

                input = document.createElement('textarea');
                input.style.minHeight = "20ch";
                input.addEventListener("keypress", function (el) {
                    el.target.classList.remove("inputError");
                })
                input.id = elementId;
                input.name = elementName;
                input.innerHTML = (elementValue === "") ? elementDefault : elementValue;

            } else {

                input = document.createElement('input');
                input.style.height = "24px";
                input.addEventListener("keypress", function (el) {
                    el.target.classList.remove("inputError");
                })
                input.id = elementId;

                input.addEventListener("keydown", (el) => {
                    if (el.key === "Enter")
                        el.preventDefault()
                });

                input.name = elementName;
                input.value = (elementValue === "") ? elementDefault : elementValue;
                input.type = elementType;
            }

            input.style.width = "50%";
            input.style.height = "32px";
            input.style.border = "1px solid #ddd";
            input.style.boxShadow = "inset 0 1px 2px rgba(0,0,0,.07)";
            input.style.backgroundColor = "#fff";
            input.style.color = "#32373c";
            input.style.outline = "0";
            input.style.overflow = "visible";
            input.style.padding = "3px 5px";


            if (hide) {
                container.style.opacity = "0";
                container.style.position = "fixed";
                container.style.top = "-200%";
            }

            label.appendChild(span);

            container.appendChild(label)
            container.appendChild(input)

            return container

        }

        /**
         * Reset l'affichage d'un gabarit
         */
        function gabaritNormal() {
            document.getElementById('gabarit_elements').style.display = "none";
        }

        updateVideoDispo();

        //update de l'etat des videos
        function updateVideoDispo() {

            let videos = document.querySelectorAll('#DigitalSignage4_videoDispo .DigitalSignage4_creation_box');

            videos.forEach(function (videoContainer) {

                videoContainer.addEventListener("mouseenter", () => {
                    let video = videoContainer.querySelector('video');
                    if (video) {
                        video.play();
                    }
                });

                videoContainer.addEventListener("mouseleave", () => {
                    let video = videoContainer.querySelector('video');
                    if (video) {
                        video.pause();
                        video.currentTime = 0;
                    }
                });

                updateVideohistorique(videoContainer, true);
            });
        }

        function updateVideohistorique(videoContainer, withTimeout = false) {

            if (videoContainer !== null && videoContainer.getAttribute("data-ds-flag") !== 'completed' && videoContainer.getAttribute("data-ds-flag") !== null && videoContainer.getAttribute("data-ds-id") !== null) {
                let url = "{$urlAjax}?action=UpdateVideoAjaxHandler&nonce={$ajax_nonce}&demande_items=true&product_id=" + produit.id + "&demande_id=" + videoContainer.getAttribute("data-ds-id") + "&demande_flag=" + videoContainer.getAttribute("data-ds-flag");
                let xhr = new XMLHttpRequest();
                xhr.open('POST', url, true);
                xhr.onload = function () {
                    returnJSON = JSON.parse(this.responseText);
                    let response = returnJSON.data.message;
                    if (response) {

                        let div = document.createElement("div");
                        div.innerHTML = response;
                        response = div.firstElementChild;

                        if (response.firstElementChild.getAttribute("data-ds-flag") !== videoContainer.getAttribute("data-ds-flag")) {
                            withTimeout = response.firstElementChild.getAttribute("data-ds-flag") !== "completed";
                            if (videoContainer.parentElement) {
                                videoContainer.parentElement.parentElement.replaceChild(response, videoContainer.parentElement);
                                videoContainer = response.firstElementChild;

                                if (response.firstElementChild.getAttribute("data-ds-flag") === "completed") {

                                    let currentVideo = videoContainer.querySelector("video");
                                    if (currentVideo) {
                                        currentVideo.addEventListener("mouseenter", () => {
                                            let video = videoContainer.querySelector('video');
                                            if (video) {
                                                video.play();
                                            }
                                        });
                                        currentVideo.addEventListener("mouseleave", () => {
                                            let video = videoContainer.querySelector('video');
                                            if (video) {
                                                video.pause();
                                                video.currentTime = 0;
                                            }
                                        });
                                    }

                                    updateDisplayedVideo(response.firstElementChild.getAttribute("data-ds-id"), produit.id);

                                }


                            }
                        }

                        // setDisplayedVideoTextValidInHistorique();

                        if (withTimeout) {
                            setTimeout(
                                function () {
                                    updateVideohistorique(videoContainer, true);
                                },
                                10_000
                            )
                        }

                    }
                };
                xhr.send();
            }
        }

        let currentDisplayerChecked = null;
        setDisplayedVideoTextValidInHistorique();

        function setDisplayedVideoTextValidInHistorique() {

            let divContainer = document.createElement("div");
            divContainer.classList.add("valid");

            let text = document.createElement("span");
            text.innerHTML = "{$t::getTraduction( "Video_displayed")}";


            let valid = document.createElement("span");
            valid.style.marginLeft = "10px";
            valid.style.marginRight = "5px";
            valid.innerHTML = "✓";
            valid.style.color = "green";

            let p = document.createElement("p");
            p.style.textAlign = "center";
            p.style.marginBottom = "3px";
            p.appendChild(valid);
            p.appendChild(text);

            divContainer.appendChild(p);

            let inputs = document.querySelectorAll("#DigitalSignage4_videoDispo>div>div>input[type='radio']");
            inputs.forEach((input) => {
                if (input.checked) {

                    currentDisplayerChecked = input;

                    let valid = input.parentElement.parentElement.querySelector('.valid');
                    if (!valid)
                        input.parentElement.parentElement.appendChild(divContainer);

                    input.parentElement.parentElement.style.backgroundColor = "rgba(62, 238, 32, 0.16)";
                    input.parentElement.style.backgroundColor = "rgba(62, 238, 32, 0)";
                } else {
                    let valid = input.parentElement.parentElement.querySelector('.valid');
                    if (valid)
                        input.parentElement.parentElement.removeChild(valid);
                    input.parentElement.parentElement.style.backgroundColor = "rgba(62, 238, 32, 0)";
                    input.parentElement.style.backgroundColor = "rgba(62, 238, 32, 0.16)";
                }
            });

        }

        function updateDisplayedVideo(idVideo, idProduct) {

            let url = "{$urlAjax}?action=DisplayedVideoProductAjaxHandler&nonce={$ajax_nonce}&idDemande=" + idVideo + "&idProduct=" + idProduct;
            let xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.onload = function () {
                returnJSON = JSON.parse(this.responseText);
                let response = returnJSON.data.message;
                if (this.responseText && response === "ok") {
                    setDisplayedVideoTextValidInHistorique();
                } else {
                    if (currentDisplayerChecked) {
                        currentDisplayerChecked.checked = true;
                    }
                }
            };
            xhr.send();
        }

    </script>
{/if}
