var BlockImageForm = function(){};

/***
 * Initialise le formulaire
 * @returns {undefined}
 */
BlockImageForm.Init = function(){
    Event.AddById("btnSaveBlockImage", "click", BlockImageForm.SaveBlockImage);
    Library.Init(BlockImageForm.ImageSelected);
};


/***
 * Ajout de l'image dans le content edita current
 */
BlockImageForm.InitAdd = function(){
    Library.Init(BlockImageForm.ImageSelected);
    Event.AddById("btnSaveBlockImage", "click", BlockImageForm.AppendImageToContent);
};

/***
 * Seelct image on the library
 */
BlockImageForm.ImageSelected = function(e){
   
    let currentImg = document.querySelector(".cmsLibrary .col-md-3.selected");
    if(currentImg){
        currentImg.className = "imgContainer col-md-3";
    }

    let img = e.srcElement;
    img.parentNode.className = "imgContainer col-md-3 selected";

    let imgSrc = Dom.GetById("imgSrc");
    imgSrc.value = img.src;

};

/***
* Obtient l'id de l'item courant 
*/
BlockImageForm.GetId = function(){
    return Form.GetId("BlockImageForm");
};

/*
* Sauvegare l'itineraire
*/
BlockImageForm.SaveBlockImage = function(e){
   
    if(Form.IsValid("BlockImageForm"))
    {

    let data = "Class=Cms&Methode=SaveBlockImage&App=Cms";
        data +=  Form.Serialize("BlockImageForm");

        Request.Post("Ajax.php", data).then(data => {

            data = JSON.parse(data);

            if(data.statut == "Error"){
                Form.RenderError("BlockImageForm", data.message);
            } else {

                //Form.SetId("BlockImageForm", data.data.Id);
                Dialog.Close();
                
                Cms.RefreshTool();
            }
        });
    }
};

/***
 * Ajout de l'image dans le content
 */
BlockImageForm.AppendImageToContent = function(){

 let imgSrc = Form.GetValue("BlockImageForm", "imgSrc");
 let width = Form.GetValue("BlockImageForm", "Width");

 let data = "Class=Cms&Methode=UplodImageToLibrary&App=Cms";
     data +=  Form.Serialize("BlockImageForm");

         
        Request.Post("Ajax.php", data).then(data => {
         
         if(data != ""){
             imgSrc = data;
         }
        
         Dashboard.currentEditor.appendImage(imgSrc, width);
         Dialog.Close();              
   
        });
        
   
};