	<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">
		<h2>{$t::getTraduction( "perso_modele_titre")}</h2>
		
		<p style="width: 100%;color: #555;font-size: 15px;line-height: 1.5;">{$t::getTraduction( "perso_modele_description")}</p>
        
        <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}
						<script>
						   var tab_ia_modele_question_{$gabarit->getId()} ={$gabarit->getIamodelequestion()|@json_encode};
						</script>
						<div class="DigitalSignage4_gabarit_card"
							 style="position: relative"
							 id="gabarit_{$gabarit->getId()}">

							<p onclick="selectGabarit({$gabarit->getId()} , this,tab_ia_modele_question_{$gabarit->getId()})" 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 onclick="selectGabarit({$gabarit->getId()} , this,tab_ia_modele_question_{$gabarit->getId()})" style="position: absolute;width: 100%;height: calc( 100% - 85px ); top: 0; left: 0; z-index: 1000">

							</div>


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


                

            </div>

        </div>
        
    </div>
    <script>
        //On met toutes les vidéos à 2s pour retirer le gros bouton play dans firefox
        let videos_displayers = document.querySelectorAll(".video_gabarit_displayer");
        videos_displayers.forEach((videoContainer) => {
                videoContainer.currentTime = 2;

            }
        )
    </script>
    <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;">

                
				<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="Enregistrer"/>

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

			
            </div>
            <div id="errors_section">

            </div>

        </div>


    </div>
    
    <script>

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

        // Gabrit actuel
        var gabarit = null;

        // Valeurs du produit actif
       

        // Récupération des images du produit
     
        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() {
			//alert("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']);
           

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

                try {

                    console.log(this.responseText);
                    document.getElementById('bouton_send_video').style.display = "block";
                    document.getElementById('DigitalSignage4_loading_gif').style.display = "none";
					//alert("ici");
					/*
                    let response = JSON.parse(this.responseText);

                    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.id = name;
                    radio.value = image_url+';'+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+"?a="+Math.random() + ")";
                    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);
					
					//ia_question
					if (element.value=='IA_description') {
						data.append(champs_gabarit['name']+'_ia_question', element.ia_question);
						
					}
                } else { // Récuperation de l'image coché via le nom du champ input
					if (element != null) {
					   //alert('getFormData:'+champs_gabarit['name']+'='+element.value);
					   data.append(champs_gabarit['name'], element.value);
					}
					//data.append(champs_gabarit['name'], element.value);
					/* ancienne methode
                    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);

                            // 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
		 -gabarit->getChamps
         */
        function getGabarits() {
            return {

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

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

            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.parentElement.classList.add("selected");
            gabaritNormal();
			
			
			gabarit['ia_modele_question']=ia_modele_question;

            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";
        }
		
		/**
         * 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");

                if (champs_gabarit['type'] !== 'picture') {

                    let value = "";
                    let isHide = ('' + champs_gabarit['hide'] === "1");

                    let divContent = document.createElement('div');
					
					if (champs_gabarit['default']==="") {
						champs_gabarit['default']=champs_gabarit['wordpress_champ_name'];
					}

                    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);
					
					let champ_ = divContent.lastElementChild.lastElementChild;
					insertAfter(champ_,getselecteur_champ(champs_gabarit['id'],champs_gabarit['name'],champs_gabarit['default'],champs_gabarit['ia_question'],gabarit['ia_modele_question']));
					document.getElementById("selecteur_"+champs_gabarit['id']).addEventListener("change", click_selecteur);
					document.getElementById("selecteur_"+champs_gabarit['id']).addEventListener("click", click_selecteur);
					document.getElementById("selecteur_"+champs_gabarit['id']).click();
					

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

                        let champ_ = divContent.lastElementChild.lastElementChild;

                       
						//insertAfter(champ,getselecteur_champ(champs_gabarit['id'],champs_gabarit['name'],champs_gabarit['default']));
						//document.getElementById("selecteur_"+champs_gabarit['id']).addEventListener("change", click_selecteur);
						//document.getElementById("selecteur_"+champs_gabarit['id']).addEventListener("click", click_selecteur);
                        haveSpecialData = true;
						
						//document.getElementById("selecteur_"+champs_gabarit['id']).click();
						
						
						/*
                        xhr.open('POST', '{$urlSpecialData}' + champName, true);
                        xhr.onload = function () {

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

                            if (this.responseText)
                                champ.value = this.responseText;

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

                        }
                        xhr.onerror = function () {
                            if (!isHide)
                                champ.parentElement.removeChild(champ.nextElementSibling);
                        }
                        xhr.send();
						*/
						document.getElementById("bouton_send_video").disabled = "";

                    }


                } else {

                    if ((champName) && (champs_gabarit['name']=="websiteLogoUrl")) {
						
						
                        haveSpecialData = true;

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

                            if (this.responseText) {
                                returnJSON = JSON.parse(this.responseText);
                                let datas = returnJSON.data.message.split(';');
                                let imageSpecial = [{
                                    url: datas[0],
                                    path: datas[1]
                                }];
                                display_product_img(champs_gabarit['name'], champs_gabarit['label'], isRequered, imageSpecial, false, imageChamp, isRequered);
								
								
								if (champs_gabarit['default']==="") {
									champs_gabarit['default']=champs_gabarit['wordpress_champ_name'];
								}
								
								
								
								insertAfter(imageChamp.lastElementChild,getselecteur_champ_picture(champs_gabarit['id'],champs_gabarit['name'],champs_gabarit['default']));
								
								
								document.getElementById("selecteur_picture_"+champs_gabarit['id']).addEventListener("change", click_selecteur_picture);
                                document.getElementById("selecteur_picture_"+champs_gabarit['id']).style.height = "fit-content";
																//document.getElementById("selecteur_picture_"+champs_gabarit['id']).addEventListener("click", click_selecteur_picture);
								
								//alert("click1 "+ "selecteur_picture_"+champs_gabarit['id']);
								
								let champView_picture = document.getElementById("selecteur_picture_"+champs_gabarit['id']);
								//console.log("ici "+champView_picture.name);
								//champView_picture.click();
								//console.log("la");
                                if (document.querySelectorAll(".loader_img").length === 0)
                                    document.getElementById("bouton_send_video").disabled = "";
								

                            }

                        }
                        xhr.send();
						

                    } else {
						//alert('La name:' + champs_gabarit['name']+ ' label:'+champs_gabarit['label']);
                        let value = "";
						
						if (champs_gabarit['default']==="") {
							champs_gabarit['default']=champs_gabarit['wordpress_champ_name'];
						}
					
						let isHide = ('' + champs_gabarit['hide'] === "1");

						let divContent = document.createElement('div');

						divContent.style.display = "flex";
						let image_champ = createElement(champs_gabarit['name'], champs_gabarit['label'], champs_gabarit['name'], value, champs_gabarit['type'], champs_gabarit['default'], isHide, false);
						divContent.appendChild(image_champ);
						
						//image_champ.lastElementChild.style.display = "none";
						console.log("default "+champs_gabarit['default']);
						if (champs_gabarit['default']==="") {
							champs_gabarit['default']=champs_gabarit['wordpress_champ_name'];
						}
						if (champs_gabarit['wordpress_champ_name']==="") {
							if (champs_gabarit['default']==="") {
								champs_gabarit['default']=champs_gabarit['name'];
							}
						}
						
						//console.log("wordpress_champ_name "+champs_gabarit['wordpress_champ_name']);
						insertAfter(image_champ.lastElementChild,getselecteur_champ_picture_produit(champs_gabarit['id'],champs_gabarit['name'],champs_gabarit['default']));
						
						let imagesView = document.getElementById("imgs");
						imagesView.appendChild(divContent);
						
						let champView_picture = document.getElementById("selecteur_picture_"+champs_gabarit['id']);
						champView_picture.addEventListener("change", click_selecteur_produit_picture);
						//champView_picture.addEventListener("click", click_selecteur_produit_picture);
						//alert("click2 "+ "selecteur_picture_"+champs_gabarit['id']);
						//console.log("ici "+champView_picture.name);
						//champView_picture.click();
					}
					
					

                }

            }


        }

        function resizeSizeFromContent() {

            document.querySelector(".DigitalSignage4_creation_box").style.height = "max-content";

        }


        

        function insertAfter(referenceNode, newNode) {
            referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
        }
		
		function click_selecteur_produit_picture(){
			let champView = document.getElementById(this.chp_source_id);
			//champView.value = this.value;
			//alert("click_selecteur_produit_picture "+champView.name+" "+this.value+" "+this.options[this.selectedIndex].text);
			
			//champView.style.display = "none";
			
			if (this.options[this.selectedIndex].text=="Autre image") {
				var input = document.createElement('input');
				input.type = 'file';
				input.name = 'picture_button';
				input.id = 'picture_button';
				input.chp_source_id = this.chp_source_id;

				input.onchange = e => { 
				   var file = e.target.files[0]; 
				   //alert(file.name+" "+this.chp_source_id);
				   sendfile(file,this.chp_source_id,true);
				    //pousser dans champView.value url;path
				}

				input.click();
			
			}
			
			if ((this.options[this.selectedIndex].text=="Logo de mon site") || 
				(this.options[this.selectedIndex].text=="Image 1 du produit") || 
				(this.options[this.selectedIndex].text=="Image 2 du produit") || 
				(this.options[this.selectedIndex].text=="Image 3 du produit") || 
				(this.options[this.selectedIndex].text=="Image 4 du produit") || 
				(this.options[this.selectedIndex].text=="Image 5 du produit")  
				) {
				champView.value = this.value;
				
				
			}
			
			if (this.options[this.selectedIndex].text=="Aucune image") {
				//champView.value ="{$urlnoImg}"+";"+"{$pathnoImg|escape:urlpathinfo}";
				champView.value ="{$urlnoImg}"+";"+"{$pathnoImg}";
			}
			
				
		}
		
		function click_selecteur_picture(){
			let champView = document.getElementById(this.chp_source_id);
			//champView.value = this.value;
			//alert("click_selecteur_picture "+champView.name+" "+this.value+" "+this.options[this.selectedIndex].text);
			
			//champView.style.display = "none";
			
			if (this.options[this.selectedIndex].text=="Autre image") {
				var input = document.createElement('input');
				input.type = 'file';
				input.name = 'picture_button';
				input.id = 'picture_button';
				input.chp_source_id = this.chp_source_id;

				input.onchange = e => { 
				   var file = e.target.files[0]; 
				   //alert(file.name+" "+this.chp_source_id);
				   //let champView = document.getElementById(this.chp_source_id);
				   //champView.value = file.name;
				   
				   sendfile(file,this.chp_source_id,false);
				    //pousser dans champView.value url;path
				}

				input.click();
			
			}
			
			if (this.options[this.selectedIndex].text=="Logo de mon site") {
				champView.value = this.value;
				champView.parentElement.style.backgroundImage = "url(" + "{$logosite}" + "?a="+Math.random()+")";
				
                champView.parentElement.style.backgroundRepeat = "no-repeat";
                champView.parentElement.style.backgroundSize = "95%";
                champView.parentElement.style.backgroundPosition = "center";
                champView.parentElement.style.backgroundColor = "white";
				champView.parentElement.innerHTML.reload;
				
			}
			
			if (this.options[this.selectedIndex].text=="Aucune image") {
				
				champView.value ="{$urlnoImg}"+";"+"{$pathnoImg}";
				
				
				champView.parentElement.style.backgroundImage = "url(" + "{$urlnoImg}" + "?a="+Math.random()+")";
				
                champView.parentElement.style.backgroundRepeat = "no-repeat";
                champView.parentElement.style.backgroundSize = "95%";
                champView.parentElement.style.backgroundPosition = "center";
                champView.parentElement.style.backgroundColor = "white";
				champView.parentElement.innerHTML.reload;
			}
			
			//champView.value = this.value;
			
		}
		
		function sendfile(file,dest,mode_picture_produit){
			//alert('sendfile '+file.name+' '+dest);
			//var data = new FormData();
			//data.append(dest, element[i].value);
			document.getElementById('bouton_send_video').style.display = "none";
			
			let formData = new FormData();           
			formData.append("file", file);
			formData.append("destination", dest);
			formData.append('id_gabarit', gabarit['id']);
	
			var xhr = new XMLHttpRequest();
            xhr.open('POST', '{$urlAjax}?action=AddGabaritCustomizeAjaxHandler&nonce={$ajax_nonce}', true);
			xhr.onload = function () {

                try {
					let champView = document.getElementById(dest);
					//alert("dest:"+dest);
                    //alert("reussi:"+this.responseText);
					///il faut pousser url;path dans le champ
					
					returnJSON = JSON.parse(this.responseText);
					let response = JSON.parse(returnJSON.data.message);

                    if (response) {
					   //alert("reussi2:"+response);
					   champView.value = response;
					   
					   let datas = response.split(';');
						let imageSpecial = [{
							url: datas[0],
							path: datas[1]
						}];
							
						if (!mode_picture_produit) {	
							champView.parentElement.style.backgroundImage = "url(" + datas[0] + "?a="+Math.random()+")";
							champView.parentElement.style.backgroundRepeat = "no-repeat";
							champView.parentElement.style.backgroundSize = "95%";
							champView.parentElement.style.backgroundPosition = "center";
							champView.parentElement.style.backgroundColor = "white";
							champView.parentElement.innerHTML.reload;
						}
					
                        //display_product_img(dest, dest, false, imageSpecial, false, champView.parentElement, false);
					}
					
					
					
					
					document.getElementById('bouton_send_video').style.display = "block";

                } catch (e) {
					document.getElementById('bouton_send_video').style.display = "block";
                    alert("erreur:"+e);

                }
			};
			xhr.send(formData);
			
			
			
		}
		
		function click_selecteur(){
			let champView = document.getElementById(this.chp_source_id);
			champView.value = this.value;
			champView.ia_question = this.options[this.selectedIndex].ia_question;
			//alert(this.value+" "+this.options[this.selectedIndex].text);
			if (this.options[this.selectedIndex].text=="Texte libre") {
				champView.disabled = "";
				champView.style.display = "block";
			} else {
				champView.disabled = "disabled";
				champView.style.display = "none";
			}
			
			
		}
		
		
		function getselecteur_champ_picture_produit(id,source,nom_chp){
			//alert("getselecteur_champ_picture_produit"+nom_chp);
			var img_produit_select = false;
			let selecteur = document.createElement("select");
			selecteur.name = "selecteur_picture_"+id;
			selecteur.id = "selecteur_picture_"+id;
			selecteur.chp_source_id = source
			
            //selecteur.src = "{$urlLoadingImg}";
            //selecteur.style.height = "20px";
            //selecteur.style.marginLeft = "10px";
			var option3 = document.createElement("option");
			option3.value = "product01PictureUrl01";
			option3.text = "Image 1 du produit";
			if (nom_chp==option3.value) {
				img_produit_select = true;
				option3.selected = true;
			}
			selecteur.appendChild(option3);
			
			var option3 = document.createElement("option");
			option3.value = "product02PictureUrl01";
			option3.text = "Image 2 du produit";
			if (nom_chp==option3.value) {
				img_produit_select = true;
				option3.selected = true;
			}
			selecteur.appendChild(option3);
			
			var option3 = document.createElement("option");
			option3.value = "product03PictureUrl01";
			option3.text = "Image 3 du produit";
			if (nom_chp==option3.value) {
				option3.selected = true;
				img_produit_select = true;
			}
			selecteur.appendChild(option3);
			
			var option3 = document.createElement("option");
			option3.value = "product04PictureUrl01";
			option3.text = "Image 4 du produit";
			if (nom_chp==option3.value) {
				option3.selected = true;
				img_produit_select = true;
			}
			selecteur.appendChild(option3);
			
			var option3 = document.createElement("option");
			option3.value = "product05PictureUrl01";
			option3.text = "Image 5 du produit";
			if (nom_chp==option3.value) {
				option3.selected = true;
				img_produit_select = true;
			}
			selecteur.appendChild(option3);
			
			
			
			
			var option2 = document.createElement("option");
			option2.value = "";
			option2.text = "Autre image";
			
			
			var option = document.createElement("option");
			option.value = "";
			option.text = "Aucune image";
			//if (nom_chp==option.value) {
			
			if (nom_chp.includes("no.png")) {
				option.selected = true;
			} else {
				if (!img_produit_select) {
					option2.selected = true;
				}
			}
			
			selecteur.appendChild(option2);
			selecteur.appendChild(option);
					
			


	
            return selecteur;
		}
		
		function getselecteur_champ_picture(id,source,nom_chp){
			//alert(nom_chp);
			let selecteur = document.createElement("select");
			selecteur.name = "selecteur_picture_"+id;
			selecteur.id = "selecteur_picture_"+id;
			selecteur.chp_source_id = source
			
            //selecteur.src = "{$urlLoadingImg}";
            //selecteur.style.height = "20px";
            //selecteur.style.marginLeft = "10px";
			var option3 = document.createElement("option");
			option3.value = "siteLogo";
			option3.text = "Logo de mon site";
			if (nom_chp==option3.value) {
				option3.selected = true;
			}
			selecteur.appendChild(option3);
			
			
			var option2 = document.createElement("option");
			option2.value = "";
			option2.text = "Autre image";
			
			
			var option = document.createElement("option");
			option.value = "";
			option.text = "Aucune image";
			//if (nom_chp==option.value) {
			if (nom_chp.includes("no.png")) {
				option.selected = true;
			} else {
				if (nom_chp!=option3.value) {
					option2.selected = true;
				}
			}
			selecteur.appendChild(option2);
			selecteur.appendChild(option);
					
			


	
            return selecteur;
		}
		
		function getselecteur_champ(id,source,nom_chp,ia_question,ia_modele_question){
			let selecteur = document.createElement("select");
			selecteur.name = "selecteur_"+id;
			selecteur.id = "selecteur_"+id;
			selecteur.chp_source_id = source
			
            //selecteur.src = "{$urlLoadingImg}";
            //selecteur.style.height = "20px";
            //selecteur.style.marginLeft = "10px";
			var option = document.createElement("option");
			if (nom_chp=="") {
				nom_chp="Veuillez saisir votre texte ici.";
			}
			option.value = nom_chp;
			option.text = "Texte libre";
			selecteur.appendChild(option);
			
			for (const elt in ia_modele_question) {
				
				var option = document.createElement("option");
				option.value = "IA_description";
				option.text = ia_modele_question[elt]['libelle'];
				option.ia_question = ia_modele_question[elt]['question'];
									  
				if (ia_question==option.ia_question) {
					option.selected = true;
				}
				selecteur.appendChild(option);
			}
			
						
			
			var option = document.createElement("option");
			option.value = "siteUrl";
			option.text = "Url du site";
			if (nom_chp==option.value) {
				option.selected = true;
			}
			selecteur.appendChild(option);
			var option = document.createElement("option");
			option.value = "siteName";
			option.text = "Nom du site";
			if (nom_chp==option.value) {
				option.selected = true;
			}
			selecteur.appendChild(option);
			var option = document.createElement("option");
			option.value = "name";
			option.text = "Nom du produit";
			if (nom_chp==option.value) {
				option.selected = true;
			}
			selecteur.appendChild(option);
			var option = document.createElement("option");
			option.value = "description";
			option.text = "Description du produit";
			if (nom_chp==option.value) {
				option.selected = true;
			}
			selecteur.appendChild(option);
			var option = document.createElement("option");
			option.value = "price";
			option.text = "Prix du produit";
			if (nom_chp==option.value) {
				option.selected = true;
			}
			selecteur.appendChild(option);
			var option = document.createElement("option");
			option.value = "regular_price";
			option.text = "Prix du produit avant réduction";
			if (nom_chp==option.value) {
				option.selected = true;
			}
			selecteur.appendChild(option);
			var option = document.createElement("option");
			option.value = "devise";
			option.text = "Devise";
			if (nom_chp==option.value) {
				option.selected = true;
			}
			selecteur.appendChild(option);
			
			var option = document.createElement("option");
			option.value = "first_category";
			option.text = "Première catégorie du produit";
			if (nom_chp==option.value) {
				option.selected = true;
			}
			selecteur.appendChild(option);
			
			var option = document.createElement("option");
			option.value = "permalink";
			option.text = "Permalien du produit";
			if (nom_chp==option.value) {
				option.selected = true;
			}
			selecteur.appendChild(option);
			
			var option = document.createElement("option");
			option.value = "pourcent_reduc";
			option.text = "Pourcentage de réduction du prix du produit";
			if (nom_chp==option.value) {
				option.selected = true;
			}
			selecteur.appendChild(option);
			
			
	
            return selecteur;
		}

        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;
        }

        

        

        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;
				
				if (input.value=== "") {
					input.value=elementName;
				}
				
                input.type = elementType;
				if (elementType=='picture') {
					input.type = "hidden";
				}
				//console.log("elementType:"+elementType+" elementName:"+elementName);
				//input.type = "hidden";
            }

            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";
        }

        

        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)";
                }
            });

        }

        

    </script>

