<script src="https://editor.unlayer.com/embed.js"></script>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin=""></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin=""></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>

<style>
#myDevEditControl_html_test iframe {
  min-width: 700px !important;
}
.images{flex-wrap:wrap;display:flex}
.images .image{cursor:pointer;margin:5px}
.images .image img{max-width:90px;width:90px;height:90px}

.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

.modal-title {
  font-size: 14px;
}

button.close {
    padding: 0;
    background-color: transparent;
    border: 0;
    float: right;
    font-size: 1.5rem;
    font-weight: 700;
    line-height: 1;
    color: #000;
    text-shadow: 0 1px 0 #fff;
    opacity: .5;
}

/* Modal Content/Box */
.modal-content {
  background-color: #fefefe;
  margin: 5% auto; /* 15% from the top and centered */
  padding: 15px;
  border: 1px solid #888;
  width: 60%; /* Could be more or less, depending on screen size */
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}
.box{
  display: contents;
  flex-direction: column;
  place-content: center;
  align-items: center;
}

.mole {
  width: 10rem;
  height: 10rem;
  margin-bottom: 1rem;
}
</style>

<div id="{$editor.ElementId}_test" style="overflow: hidden; resize: both; height:{$editor.Height}px; width:{$editor.Width}"  class="InterspireEditor" ></div>

<textarea rows="0" id="{$editor.ElementId}"  name="{$editor.ElementId}" hidden="hidden">
{$editor.HtmlContent}
</textarea>   

<textarea rows="0" id="jsondata_{$editor.ElementId}"  name="json_{$editor.ElementId}" hidden="hidden">
{$editor.JSONContent}
</textarea>
 
<script type="text/javascript">
 editor{$editor.ElementId} = unlayer.createEditor({
  id: '{$editor.ElementId}_test',
  width : "{$editor.Width}", 
  displayMode: 'email',  
  mergeTagsConfig: {
    sort: false
  },
  locale: 'en-US',
    translations: {
    'en-US': {
    "labels.merge_tags": "Dynamic Contents"
    } 
  },
  features: {
    smartMergeTags: false
  },
  mergeTags: {
    insert_unsubscribe_link: {
      name: "Insert Unsubscribe link",
      value: " <a href='http://%%unsubscribelink%%/'>Unsubscribe me from this list</a> ",
    }, 
    custom_fields: {
      name: "Insert Custom Field",
      mergeTags: {
        street_1: {
          name: "Contact List Name",
          value: "%%listname%%"
        },
        street_2: {
          name: "Contacts Email Address",
          value: "%%emailaddress%%"
        },
        city: {
          name: "Email Confirmation Link",
          value: "%%confirmlink%%"
        },
        state: {
          name: "Subscribe Date",
          value: "%%subscribedate%%"
        },
        state: {
          name: "Todays Date",
          value: "%%todaysdate%%"
        },
        state: {
          name: "Link to Web Version of this Email",
          value: "%%webversion%%"
        },
        state: {
          name: "Company Name",
          value: "%%companyname%%"
        },
        state: {
          name: "Company Address",
          value: "%%companyaddress%%"
        },
        state: {
          name: "Company Phone Number",
          value: "%%companyphone%%"
        },
        zip: {
          name: "Contact's IP Address",
          value: "%%ipaddress%%"
        }
      }
    },
    insert_contact_customfields: {
      name: "Contact Lists[Custom Fields]",
      mergeTags: {
        {$editor.CfData}
      }
    }, 

	{if $editor.SurveyData}
    insert_survey_link: {
      name: "Insert Survey link",
      mergeTags: {
       {$editor.SurveyData}
      }
      
    }, 
    insert_dct: {
      name: "Insert a Dynamic Content Tag",
      mergeTags: {
       {$editor.DctData}
      }
      
    }
	{/if}
  }
});

var template =  {$editor.JSONContent} === 0 ? 0 : {$editor.JSONContent};

var userid =   {$editor.LoggedInUserId}  ;
var type =   '{$editor.ImageDirType}';
var ImageDirTypeId =   '{$editor.ImageDirTypeId}';
if(template !== 0){ 

  editor{$editor.ElementId}.loadDesign(template);
}
  
editor{$editor.ElementId}.addEventListener('design:updated', function(updates) {
  // Design is updated by the user
  
  editor{$editor.ElementId}.exportHtml(function(data) {
		var json = data.design; // design json
		var html = data.html; // design html
	 
	document.getElementById("{$editor.ElementId}").value = (data.html);
	document.getElementById("jsondata_{$editor.ElementId}").value = JSON.stringify(json);
    // Save the json, or html here
  })
 
});
editor{$editor.ElementId}.addEventListener('design:loaded', function(data) {
   editor{$editor.ElementId}.exportHtml(function(data) {
    var json = data.design; // design json
    var html = data.html; // design html
	 
	document.getElementById("{$editor.ElementId}").value = (data.html);
	document.getElementById("jsondata_{$editor.ElementId}").value = JSON.stringify(json);
    // Save the json, or html here
  })
  
})

editor{$editor.ElementId}.registerCallback('block:added', function (newBlock, done) {
  console.log('block:added', newBlock);
  
  // Save the block to your database here
  // and pass the object to done callback.
  // Each block should have it's own unique id

  done(block);
});
////////////////

 editor{$editor.ElementId}.registerCallback('selectImage', function (data, done) {
  // Open the modal
  $('#mediaLibrary').modal();

  $('#mediaLibrary .images img').bind('click', function (e) {
    // User has clicked on an image
    // This is where we will call Unlayer's "done" callback function
    // We will pass the image URL so Unlayer knows what image is added
    done({ url: $(e.target).attr('src') });

    // Close the modal
    $('#mediaLibrary').modal('hide');
  });
});

 
// We will unbind any previous image click events when modal opens to avoid duplicate events
$(document).ready(function () {
  $('#mediaLibrary').on('show.bs.modal', function () {
    $('#mediaLibrary .images img').unbind('click');
  });
  
  
  

const fileInput = document.getElementById('imageInput');

const images =  document.querySelectorAll('.mole');

fileInput.addEventListener('change', (e) =>{
    const file = e.target.files[0];
	var data = new FormData()
  data.append('file', e.target.files[0])
  data.append('app_url', "{$editor.AppUrl}")
  data.append('id',userid)
  data.append('type',type)
  data.append('ImageDirTypeId',ImageDirTypeId)
  data.append('what','uploadUnlayerImage')

  fetch('remote.php', {
    method: 'POST',
    headers: {
      'Accept': 'application/json'
    },
    body: data
  }).then(response => {
    // Make sure the response was valid
    if (response.status >= 200 && response.status < 300) {
      return response
    } else {
      var error = new Error(response.statusText)
      error.response = response
      throw error
    }
  }).then(response => {
    return response.json()
  }).then(data => {
    // Pass the URL back to Unlayer to mark this upload as completed
    //done({ progress: 100, url: data.filelink })
     images[0].setAttribute('src', data.filelink );
  })
   /* let fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    fileReader.onload = function (){
        images[0].setAttribute('src', fileReader.result);
        // images[0].setAttribute('style', `background-image: url('${fileReader.result}')`);
    }*/
})


 
});
    
</script>


<div id="mediaLibrary" class="modal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
     <button
          type="button"
          class="close"
          data-dismiss="modal"
          aria-label="Close"
        >
          <span aria-hidden="true">&times;</span>
        </button>
      <div class="modal-header">
        <h5 class="modal-title">My Media Library</h5>
    
      </div>
	  
  
  <label class="blockbuilder-label-right">
   <p><strong>Upload an image</strong></p>
     <label for="img"> 
   <input type="file" id="imageInput" />
	  <div class="blockbuilder-widget-label">
   </label>  

  <div class="box">
   
    <div class="images">
	<div class="image">
      <img class="mole" />
      </div>

    </div>
  </div>
 

  </label>
</div>
      <div class="modal-body">
        <p><strong>Choose an image from Image Gallery</strong></p>
        <div class="images">
			 %%GLOBAL_dirImages%%
          
        </div>
      </div>
    </div>
  </div>
</div>
