//--------------------------------------------------//
//                  CONFIGS PAGE                    //
//------------------------------- ------------------//





(function() {
  "use strict";

  var configform = document.getElementById('config-form');

  if (configform) {

    // Theme color
    var themecolor = document.getElementById('themecolor'),
      themecolor2 = document.getElementById('themecolor2');

    themecolor.addEventListener('keyup', function (e) {
      themecolor2.value = this.value;
    }, false);

    themecolor2.addEventListener('change', function (e) {
      themecolor.value = this.value;
    }, false);


    // Icon preview
    var themeicon = document.getElementById('themeicon');
    themeicon.addEventListener('change', function (e) {
      var file = e.target.files[0],
        img = document.getElementById('themeicon-preview'),
        reader = new FileReader();
      reader.onload = (function (aImg) {
        return function (e) {
          aImg.src = e.target.result;
        };
      })(img);
      reader.readAsDataURL(file);
    }, false);


    // Logo preview
    var themelogo = document.getElementById('themelogo');
    themelogo.addEventListener('change', function (e) {
      var file = e.target.files[0],
        img = document.getElementById('themelogo-preview'),
        reader = new FileReader();
      reader.onload = (function (aImg) {
        return function (e) {
          aImg.src = e.target.result;
        };
      })(img);
      reader.readAsDataURL(file);
    }, false);


    // Caption enable/disable
    var caption = document.getElementById('caption-enabled');
    caption.addEventListener('change', function (e) {
      var els = document.getElementsByClassName('qrcode');
      if (this.checked) {
        for (let i = 0; i < els.length; i++) {
          els[i].hidden = false;
        }
      } else {
        for (let i = 0; i < els.length; i++) {
          els[i].hidden = true;
        }
      }
    }, false);


    // QR Code preview
    var qrcodepreview = document.getElementById('qrcode-preview'),
      qrcodebaseurl = (qrcodepreview.src).slice(0, (qrcodepreview.src).indexOf('?')),
      captiontext = document.getElementById('caption-text'),
      captionfont = document.getElementById('caption-font');

    captiontext.addEventListener('keyup', function (e) {
      qrcodepreview.src = qrcodebaseurl + '?caption=' + encodeURIComponent(this.value);
      qrcodepreview.src += '&fontsize=' + parseInt(captionfont.value, 10);
    }, false);

    captionfont.addEventListener('change', function (e) {
      qrcodepreview.src = qrcodebaseurl + '?caption=' + encodeURIComponent(captiontext.value);
      qrcodepreview.src += '&fontsize=' + parseInt(this.value, 10);
    }, false);
  }

})();





//--------------------------------------------------//
//               CREATE SCENE PAGE                  //
//------------------------------- ------------------//





(function ($) {
  "use strict";

  if ($('#scene-page').length) {

    // ------  Start Page -------- //

    // Get Entities and attach to scene and form
    // Get Marker or create one
    var scene_id = $('#scene_id').val();
    axios({
      method: 'get',
      url: '/scenes/' + scene_id,
      headers: {
        'Accept': 'application/json'
      },
    }).then(function (response) {

      var scene = response.data.scene;

      // ------ ENTITIES ------ //

      // Get Entities and attach to scene and form
      if (scene.entities.length) {
        var entities = scene.entities,
          response_data = {};
        for (var i = 0; i < entities.length; i++) {

          response_data.entity = entities[i];

          // Create Entity Object of Scene and Attach to scene
          var entityObj = createEntityObject(response_data);

          // Create Entity Form and Attach events to Entity Obj
          createEntityForm(entityObj, response_data);
        }
      }

      // ------ MARKER ------ //

      // Get Marker or create one
      if (!scene.marker) {
        // Create one
        axios({
          method: 'post',
          url: '/markers',
          headers: {
            'Accept': 'application/json'
          },
          data: {
            scene_code: $('#scene_code').val(),
            scene_id: $('#scene_id').val()
          }
        }).then(function (response) {
          setMarker(response.data.marker);
        }).catch(function (error) {
          console.log(error);
        });

      } else {
        setMarker(scene.marker);
      }

    }).catch(function (error) {
      if (error.response) {
        showErrors(error);
      }
    });

    // ------ End Start Page -------- //


    // MARKER EVENTS

    // Marker input radio buttons
    var qpr = $('#qrcode_print_row');
    $('#download_type_png').on('change', function () {
      qpr.prop('hidden', true);
    });

    var dpdf = $('#download_type_pdf');
    dpdf.on('change', function () {
      qpr.prop('hidden', false);
    });

    $('#qrcode_caption').on('input', function () {
      axios({
        method: 'post',
        url: '/markers/' + $('#marker_id').val() + '?timestamp=' + ((new Date).getTime()),
        headers: {
          'Accept': 'application/json'
        },
        data: {
          _method: 'PUT',
          scene_code: $('#scene_code').val(),
          scene_id: $('#scene_id').val(),
          qrcode_caption: $('#qrcode_caption').val(),
          qrcode_fontsize: $('#qrcode_fontsize').val()
        }
      }).then(function (response) {
        setMarker(response.data.marker);
      }).catch(function (error) {
        console.log(error);
      });
    });

    $('#qrcode_fontsize').on('input', function () {
      axios({
        method: 'post',
        url: '/markers/' + $('#marker_id').val() + '?timestamp=' + ((new Date).getTime()),
        headers: {
          'Accept': 'application/json'
        },
        data: {
          _method: 'PUT',
          scene_code: $('#scene_code').val(),
          scene_id: $('#scene_id').val(),
          qrcode_caption: $('#qrcode_caption').val(),
          qrcode_fontsize: $('#qrcode_fontsize').val()
        }
      }).then(function (response) {
        setMarker(response.data.marker);
      }).catch(function (error) {
        console.log(error);
      });
    });


    $('#qrcode_preview').on('click', function (e) {
      var marker_id = $('#marker_id').val(),
        download_type = $('#download_type_pdf').prop('checked') ? 'pdf' : 'png',
        baseURL = document.head.querySelector('meta[name="app-url"]').content,
        href = baseURL + '/markers/' + marker_id + '/download?preview=1&download_type=' + download_type;

      if (download_type == 'pdf') {
        var quantity_markers = $('#quantity_markers').val(),
          marker_size = $('#marker_size').val();
        href += '&quantity_markers=' + quantity_markers + '&marker_size=' + marker_size;
      }

      window.open(href);
      e.preventDefault();
    });


    $('#qrcode_download').on('click', function (e) {
      var marker_id = $('#marker_id').val(),
        download_type = $('#download_type_pdf').prop('checked') ? 'pdf' : 'png',
        baseURL = document.head.querySelector('meta[name="app-url"]').content,
        href = baseURL + '/markers/' + marker_id + '/download?preview=0&download_type=' + download_type;

      if (download_type == 'pdf') {
        var quantity_markers = $('#quantity_markers').val(),
          marker_size = $('#marker_size').val();
        href += '&quantity_markers=' + quantity_markers + '&marker_size=' + marker_size;
      }

      window.open(href);
      e.preventDefault();
    });


    // ------ END MARKER EVENTS ------ //


    // Add Entity on Click (Dropdown button)

    var entTypes = $('.dropdown-item');
    entTypes.each(function (index, elem) {

      $(elem).on('click', function (e) {

        var type = this.dataset.type,
          accept = this.dataset.accept,
          inputFile = $('<input type="file">');

        inputFile[0].accept = accept;
        inputFile[0].click();

        inputFile.on('change', function () {
          addEntity(this.files[0], type);
        });
        e.preventDefault();
      });
    });



    // SAVE SCENE AND ENTITIES
    $('#save-scene').on('click', function (e) {
      saveScene();
      e.preventDefault();
    });



    // ------------ FUNCTIONS ----------- //


    function addEntity(file, type) {
      var scene_id = $('#scene_id').val();
      var formData = new FormData();
      formData.append('name', file.name);
      formData.append('scene_id', scene_id);
      formData.append('props_asset_size', file.size);
      formData.append('props_asset_file', file);

      switch (type) {
        case 'image':
          var img = new Image();
          img.onload = function () {
            formData.append('type', 'a-image');
            formData.append('props_asset_width', img.naturalWidth);
            formData.append('props_asset_height', img.naturalHeight);
            formData.append('props_asset_type', 'img');
            var fileData = {
              width: img.naturalWidth,
              height: img.naturalHeight,
              size: file.size
            };
            var res = validateFile(fileData);
            if (res === true) {
              submitEntity(formData);
            } else {
              showErrors(res);
            }
          }
          var reader = new FileReader();
          reader.onload = (function (aImg) {
            return function (e) {
              aImg.src = e.target.result;
            };
          })(img);
          reader.readAsDataURL(file);
          break;

        case 'video':
          var video = document.createElement('video');
          video.onloadedmetadata = function () {
            formData.append('type', 'a-video');
            formData.append('props_asset_type', 'video');
            formData.append('props_asset_width', this.videoWidth);
            formData.append('props_asset_height', this.videoHeight);
            formData.append('props_asset_duration', Math.floor(this.duration));
            formData.append('props_asset_loop', 'false');
            formData.append('props_asset_preload', 'none');
            formData.append('props_asset_autoplay', 'false');
            var fileData = {
              width: this.videoWidth,
              height: this.videoHeight,
              duration: Math.floor(this.duration),
              size: file.size
            };
            var res = validateFile(fileData);
            if (res === true) {
              submitEntity(formData);
            } else {
              showErrors(res);
            }
          }
          var reader = new FileReader();
          reader.onload = (function (aVid) {
            return function (e) {
              aVid.src = e.target.result;
            };
          })(video);
          reader.readAsDataURL(file);
          break;

        case 'audio':
          var audio = document.createElement('audio');
          audio.onloadedmetadata = function () {
            formData.append('type', 'a-sound');
            formData.append('props_asset_type', 'audio');
            formData.append('props_asset_duration', Math.floor(this.duration));
            formData.append('props_asset_loop', 'false');
            formData.append('props_asset_preload', 'none');
            formData.append('props_asset_autoplay', 'false');
            var fileData = {
              duration: Math.floor(this.duration),
              size: file.size
            };
            var res = validateFile(fileData);
            if (res === true) {
              submitEntity(formData);
            } else {
              showErrors(res);
            }
          }
          var reader = new FileReader();
          reader.onload = (function (aAud) {
            return function (e) {
              aAud.src = e.target.result;
            };
          })(audio);
          reader.readAsDataURL(file);
          break;

        case 'model':
          var reader = new FileReader();
          reader.onload = function (e) {
            validator.validateBytes(new Uint8Array(e.target.result))
              .then((report) => {
                formData.append('type', 'a-gltf-model');
                formData.append('props_asset_type', 'model');
                var fileData = {
                  size: file.size
                };
                var res = validateFile(fileData);
                if (res === true) {
                  submitEntity(formData);
                } else {
                  showErrors(res);
                }
              })
              .catch((error) => {
                console.error('Validation failed: ', error);
              });
          };
          reader.readAsArrayBuffer(file);
          break;
      }

    }



    function validateFile(data) {
      var error = {},
        msgs = [],
        fv = $('#file-validation')[0],
        maxwidth = fv.dataset.maxwidth,
        maxwidthmsg = fv.dataset.maxwidthmsg,
        maxheight = fv.dataset.maxheight,
        maxheightmsg = fv.dataset.maxheightmsg,
        maxsize = fv.dataset.maxsize,
        maxsizemsg = fv.dataset.maxsizemsg,
        maxduration = fv.dataset.maxduration,
        maxdurationmsg = fv.dataset.maxdurationmsg;

      for (var prop in data) {
        switch (prop) {
          case 'width':
            if (data[prop] > maxwidth) msgs.push(maxwidthmsg);
            break;
          case 'height':
            if (data[prop] > maxheight) msgs.push(maxheightmsg);
            break;
          case 'size':
            if (data[prop] > maxsize) msgs.push(maxsizemsg);
            break;
          case 'duration':
            if (data[prop] > maxduration) msgs.push(maxdurationmsg);
            break;
        }
      }
      if (msgs.length === 0) {
        return true;
      } else {
        error = {
          response: {
            data: {
              errors: {}
            }
          }
        };
        error.response.data.errors.messages = msgs;
        return error;
      }
    }



    function submitEntity(formData) {

      // start progress bar
      $('#progress-bar-container')[0].hidden = false;

      axios({
        method: 'post',
        url: '/entities',
        headers: {
          'Content-Type': 'multipart/form-data',
          'Accept': 'application/json'
        },
        data: formData,
        onUploadProgress: function (progressEvent) {
          var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          var pb = $('#progress-bar');
          pb.attr('style', 'width: ' + percentCompleted + '%;');
          pb.attr('aria-valuenow', percentCompleted);
          pb.text(percentCompleted + '%');
        },
      }).then(function (response) {

        // finish progress bar
        $('#progress-bar-container')[0].hidden = true;

        // Create Entity Object of Scene and Attach to scene
        var entityObj = createEntityObject(response.data);

        // Create Entity Form and Attach events to Entity Obj
        createEntityForm(entityObj, response.data);

      }).catch(function (error) {
        // finish progress bar
        $('#progress-bar-container')[0].hidden = true;

        if (error.response) {
          showErrors(error);
        }
      });
    }



    function createEntityObject(data) {

      var sceneEl = document.getElementById('scene'),
        assetsEl = document.querySelector('a-assets'),
        assetType = data.entity.props.asset.type, // img, video, audio, model
        entityEl = document.createElement(data.entity.type), // a-image, a-video, a-sound, a-gltf-model
        entityProps = data.entity.props.entity;

      // Prepare asset of scene
      // Prevent media autoplay

      assetType = (assetType == 'model') ? 'a-asset-item' : assetType;
      var asset = document.createElement(assetType);
      asset.setAttribute('id', 'asset-' + data.entity.id);
      asset.setAttribute('src', data.entity.props.entity.src);
      if (assetType == 'video' || assetType == 'audio') {
        asset.classList.add('media');
      }
      assetsEl.appendChild(asset);

      // Prepare entity of scene

      for (var prop in entityProps) {
        if (prop == 'position' || prop == 'rotation' || prop == 'scale') {
          var x = parseFloat(entityProps[prop].x),
            y = parseFloat(entityProps[prop].y),
            z = parseFloat(entityProps[prop].z);
          switch (prop) {
            case 'position':
              entityEl.object3D.position.set(x, y + 1.5, z - 1.5);
              break;
            case 'rotation':
              entityEl.object3D.rotation.x = THREE.Math.degToRad(x);
              entityEl.object3D.rotation.y = THREE.Math.degToRad(y);
              entityEl.object3D.rotation.z = THREE.Math.degToRad(z);
              break;
            case 'scale':
              entityEl.object3D.scale.set(x, y, z);
              break;
          }
        } else if (prop == 'src') {
          var src = '#asset-' + data.entity.id;

          // a-sound
          if (data.entity.type == 'a-sound') {
            src = 'src: ' + src;
          }

          entityEl.setAttribute(prop, src);

        } else {
          entityEl.setAttribute(prop, entityProps[prop]);
        }
      }

      // Set animation of model
      if (data.entity.type == 'a-gltf-model') {
        entityEl.setAttribute('animation-mixer', '');
      }

      if (data.entity.type == 'a-image' && data.entity.props.asset.ext == 'gif') {
        entityEl.setAttribute('shader', 'gif');
      }

      if (data.entity.type == 'a-video' || data.entity.type == 'a-sound') {
        setMediaControls();
      }

      entityEl.setAttribute("id", 'entity-obj-' + data.entity.id);
      sceneEl.appendChild(entityEl);
      return entityEl;
    }



    function createEntityForm(entityObj, data) {

      var details,
        entityForm,
        type = data.entity.type,
        entitiesDiv = $('#entities');

      switch (type) {
        case 'a-image':
        case 'a-video':
          details = $('#matrix details:first-child');
          break;

        case 'a-sound':
          details = $('#matrix details').eq(2);
          break;

        case 'a-gltf-model':
          details = $('#matrix details').eq(1);
          break;
      }

      var newDetails = details.clone();
      newDetails[0].hidden = false;
      newDetails.prependTo(entitiesDiv);

      entityForm = $('#entities form').eq(0);

      // id
      var id = $("input[name='id']", entityForm);
      id.val(data.entity.id);

      // type
      var entityType = $("input[name='type']", entityForm);
      entityType.val(type);

      // scene_id
      var sceneId = $("input[name='scene_id']", entityForm);
      sceneId.val(data.entity.scene_id);

      // Name
      var name = $("input[name='name']", entityForm);
      name.val(data.entity.name);
      $('summary', entityForm.parent()).text(data.entity.name);
      name.on('input', function () {
        var newName = $(this).val();
        $('summary', entityForm.parent()).text(newName);
      });

      // Width and Height
      var width = $("input[name='entity[width]']", entityForm),
        height = $("input[name='entity[height]']", entityForm),
        ratio = data.entity.props.asset.ratio;

      width.val(entityObj.getAttribute('width'));
      width.on('change', function () {
        var newWidth = $(this).val(),
          newHeight = newWidth / ratio;
        newHeight = parseFloat(Math.round(newHeight * 100) / 100).toFixed(2);
        height.val(newHeight);
        entityObj.setAttribute('width', newWidth);
        entityObj.setAttribute('height', newHeight);
      });

      height.val(entityObj.getAttribute('height'));
      height.on('change', function () {
        var newHeight = $(this).val(),
          newWidth = newHeight * ratio;
        newWidth = parseFloat(Math.round(newWidth * 100) / 100).toFixed(2);
        width.val(newWidth);
        entityObj.setAttribute('height', newHeight);
        entityObj.setAttribute('width', newWidth);
      });

      // position
      var positionX = $("input[name='entity[components][position][x]']", entityForm),
        positionY = $("input[name='entity[components][position][y]']", entityForm),
        positionZ = $("input[name='entity[components][position][z]']", entityForm),
        position = entityObj.getAttribute('position');

      positionX.val(position.x);
      positionX.on('input', function () {
        var x = $(this).val(),
          y = positionY.val(),
          z = positionZ.val();
        entityObj.object3D.position.set(x, y, z);
      });

      positionY.val(position.y);
      positionY.on('input', function () {
        var x = positionX.val(),
          y = $(this).val(),
          z = positionZ.val();
        entityObj.object3D.position.set(x, y, z);
      });

      positionZ.val(position.z);
      positionZ.on('input', function () {
        var x = positionX.val(),
          y = positionY.val(),
          z = $(this).val();
        entityObj.object3D.position.set(x, y, z);
      });

      // rotation
      var rotationX = $("input[name='entity[components][rotation][x]']", entityForm),
        rotationY = $("input[name='entity[components][rotation][y]']", entityForm),
        rotationZ = $("input[name='entity[components][rotation][z]']", entityForm),
        rotation = entityObj.getAttribute('rotation');

      rotationX.val(rotation.x);
      rotationX.on('input', function () {
        var x = $(this).val();
        entityObj.object3D.rotation.x = THREE.Math.degToRad(x);
      });

      rotationY.val(rotation.y);
      rotationY.on('input', function () {
        var y = $(this).val();
        entityObj.object3D.rotation.y = THREE.Math.degToRad(y);
      });

      rotationZ.val(rotation.z);
      rotationZ.on('input', function () {
        var z = $(this).val();
        entityObj.object3D.rotation.z = THREE.Math.degToRad(z);
      });

      // scale
      var scaleX = $("input[name='entity[components][scale][x]']", entityForm),
        scaleY = $("input[name='entity[components][scale][y]']", entityForm),
        scaleZ = $("input[name='entity[components][scale][z]']", entityForm),
        scale = entityObj.getAttribute('scale');

      scaleX.val(scale.x);
      scaleX.on('input', function () {
        var x = $(this).val(),
          y = scaleY.val(),
          z = scaleZ.val();
        entityObj.object3D.scale.set(x, y, z);
      });

      scaleY.val(scale.y);
      scaleY.on('input', function () {
        var x = scaleX.val(),
          y = $(this).val(),
          z = scaleZ.val();
        entityObj.object3D.scale.set(x, y, z);
      });

      scaleZ.val(scale.z);
      scaleZ.on('input', function () {
        var x = scaleX.val(),
          y = scaleY.val(),
          z = $(this).val();
        entityObj.object3D.scale.set(x, y, z);
      });

      // opacity
      var opacity = $("input[name='entity[opacity]']", entityForm),
        defaultOpacity = entityObj.getAttribute('opacity');
      defaultOpacity = defaultOpacity ? defaultOpacity : 1;
      opacity.val(defaultOpacity);
      opacity.on('input', function () {
        var newValue = $(this).val();
        entityObj.setAttribute('opacity', newValue);
      });

      // a-sound
      // volume
      var loop = $("#inputSoundLoop", entityForm),
        entLoop = entityObj.getAttribute('loop');

      if (entLoop == 'true') {
        loop.prop('checked', true);
        loop.val('true');
      } else {
        loop.prop('checked', false);
        loop.val('false');
      }
      loop.on('change', function () {
        var isChecked = $(this).prop('checked');
        if (isChecked) {
          $(this).val('true');
        } else {
          $(this).val('false');
        }
        entityObj.setAttribute('loop', isChecked);
      });

      // Delete Button
      var btnDelete = $("a:last", entityForm);
      btnDelete.on('click', function (e) {
        var id = $("input[name='id']", entityForm);
        newDetails.hide(200, function () {
          newDetails[0].parentNode.removeChild(newDetails[0]);
        });
        deleteEntity(id.val());
        e.preventDefault();
      });
    }



    function deleteEntity(id) {
      var formData = new FormData();
      formData.append('_method', 'DELETE');
      formData.append('id', id);
      axios({
        method: 'post',
        url: '/entities/' + id,
        headers: {
          'Content-Type': 'multipart/form-data',
          'Accept': 'application/json'
        },
        data: formData,
      }).then(function (response) {
        var entityEl = $('#entity-obj-' + id)[0];
        entityEl.parentNode.removeChild(entityEl);

        var assetEl = $('#asset-' + id)[0];
        assetEl.parentNode.removeChild(assetEl);
        if ($('a-assets .media').length == 0) {
          $('#btn-play-pause').prop('hidden', true);
        }

      }).catch(function (error) {
        if (error.response) {
          showErrors(error);
        }
      });
    }



    function setMarker(marker) {
      //id, file, props(qrcode_value, caption_text, caption_fontsize)
      $('#marker_id').val(marker.id);
      $('#qrcode_image').attr('src', marker.file + '?timestamp=' + ((new Date).getTime()));
      $('#qrcode_value').text(marker.props.qrcode_value);
      if ($('#qrcode_caption_row')) {
        $('#qrcode_caption').val(marker.props.caption_text);
        $('#qrcode_fontsize').val(marker.props.caption_fontsize);
      }

    }



    function saveScene() {

      startSpinner();

      // ---- Scene ---- //
      // title, description, preload_assets, status, editable, published_at
      var scene = {
        title: $('#title').val(),
        description: $('#description').val(),
        preload_assets: $('#preload_assets').prop('checked') ? 0 : 1,
        status: $('#status').val(),
        published_at: $('#published_at').val()
      };

      // admin
      var editable = $('#editable');
      if (editable) {
        if (editable.checked) {
          scene.editable = 0;
        } else {
          scene.editable = 1;
        }
      }

      // Publishing
      if (scene.status == 1 && !scene.published_at) {
        var dt = new Date(),
          Y = dt.getFullYear(),
          m = dt.getMonth() + 1,
          d = dt.getDate(),
          H = dt.getHours(),
          i = dt.getMinutes(),
          s = dt.getSeconds();
        if (m < 10) m = `0${m}`;
        if (d < 10) d = `0${d}`;
        if (H < 10) H = `0${H}`;
        if (i < 10) i = `0${i}`;
        if (s < 10) s = `0${s}`;

        scene.published_at = `${Y}-${m}-${d} ${H}:${i}:${s}`;
        $('#published_at').val(scene.published_at);
      }

      scene._method = 'put';

      axios({
        method: 'post',
        url: '/scenes/' + $('#scene_id').val(),
        headers: {
          'Accept': 'application/json'
        },
        data: scene
      }).then(function (response) {

        var _scene = response.data.scene,
          status = $('#info-status'),
          published = $('#info-published');

        switch (_scene.status) {
          case '0':
            status.text(status[0].dataset.draft);
            break;
          case '1':
            status.text(status[0].dataset.published);
            break;
          case '2':
            status.text(status[0].dataset.archived);
            break;
        }

        if (_scene.published_at) {
          var pubDate = _scene.published_at.slice(0, 16);
          published.text(pubDate);
        }

        // ---- Entities ---- //
        var entitiesForm = $('#entities form');
        if (entitiesForm.length) {
          entitiesForm.each(function (index, form) {
            var entityFormData = new FormData(form);
            entityFormData.append('_method', 'PUT');
            if (entityFormData.get("type") != 'a-sound') {
              var positionY = parseFloat(entityFormData.get("entity[components][position][y]")) - 1.5,
                positionZ = parseFloat(entityFormData.get("entity[components][position][z]")) + 1.5;
              entityFormData.set("entity[components][position][y]", positionY);
              entityFormData.set("entity[components][position][z]", positionZ);
            }
            axios({
              method: 'post',
              url: '/entities/' + entityFormData.get('id'),
              headers: {
                'Accept': 'application/json'
              },
              data: entityFormData
            }).then(function (response) {
              endSpinner();
              showSave();
            }).catch(function (error) {
              showErrors(error);
              endSpinner();
            });
          });
        } else {
          endSpinner();
          showSave();
        }

      }).catch(function (error) {
        showErrors(error);
        endSpinner();
      });

    }



    function showErrors(error) {

      var modal = $('#modalMessage'),
        modalBody = $('#modalMessage .modal-body').first(),
        errors = error.response.data.errors;

      modalBody.text('');

      for (var prop in errors) {
        var arrErrors = errors[prop];
        for (var i = 0; i < arrErrors.length; i++) {
          var msg = $(`<div class="alert alert-danger" role="alert">${arrErrors[i]}</div>`);
          modalBody.append(msg);
        }
      }
      modal.modal('show');
    }



    function setMediaControls() {

      var btnPlayPause = $('#btn-play-pause');
      btnPlayPause.prop('hidden', false);

      btnPlayPause.on('click', function (e) {
        $('a-assets .media').each(function (index, mediaEl) {
          if (mediaEl.paused || mediaEl.ended) {
            mediaEl.play();
          } else {
            mediaEl.pause();
          }
        });
      });
    }



    function startSpinner() {
      $('#save-scene').prop('disabled', true);
      $('#spinner').prop('hidden', false);
    }



    function endSpinner() {
      $('#save-scene').prop('disabled', false);
      $('#spinner').prop('hidden', true);
    }



    function showSave() {
      $('#saved-ok').prop('hidden', false);
      setTimeout(function () {
        $('#saved-ok').hide(300);
      }, 1000);
    }


  }
})(jQuery);





//--------------------------------------------------//
//                      GENERAL                     //
//------------------------------- ------------------//





(function($) {
  "use strict";

  // Logout modal
  $('#btn-logout').on('click', function(e) {
    $('#logout-form')[0].submit();
    e.preventDefault();
  });

  // Delete scene
  $('#form-delete-scene').on('submit', function(e) {
    return confirm(this.dataset.message);
  });

  // Delete user
  $('form#form-delete-user').on('submit', function(e) {
    return confirm(this.dataset.message);
  });

})(jQuery);