

var builder;

function saveForm() {
  
  $.ajax({
    type: "POST",
    url: "",
    data: JSON.stringify(builder.instance.schema, null, 4),
		headers: {"content-id": "form"},
    contentType: "application/json",
    success: function(res) {
      alert("Saved")
    },
    error: function (request, status, error) {
      alert(request.responseText + status + error);
    }
  });
  
  
  
  /*
  Save HTML
  var formElement = document.getElementById('form');
  Formio.createForm(formElement, builder.instance.form);

  
  $.ajax({
    type: "POST",
    url: "",
    data: $("#form").children().first().prop('outerHTML'),
		headers: {"content-id": "htmlform"},
    contentType: "text/plain",
    success: function(res) {
      alert("Saved")
    },
    error: function (request, status, error) {
      alert(request.responseText + status + error);
    }
  });
  */
  
}

  
  
$(document).ready(function(){
  var jsonElement = document.getElementById('json');
  var subJSON = document.getElementById('subjson');

  var onForm = function(form) {
    form.on('change', function() {
      subJSON.innerHTML = '';
      subJSON.appendChild(document.createTextNode(JSON.stringify(form.submission, null, 4)));
    });
  };

  var onBuild = function(build) {
    jsonElement.innerHTML = '';
    jsonElement.appendChild(document.createTextNode(JSON.stringify(builder.instance.schema, null, 4)));
  };

  var onReady = function() {
    var jsonElement = document.getElementById('json');
    var formElement = document.getElementById('formio');
    builder.instance.on('change', onBuild);
  };

  var setDisplay = function(display) {
    builder.setDisplay(display).then(onReady);
  };


  
  
  $.ajax({
    type: "GET",
    url: "../json",
    dataType: "json",
    success: function(json) {
        builder = new Formio.FormBuilder(document.getElementById("builder"), json);
        builder.instance.ready.then(onReady);
        builder.instance.ready.then(onBuild);
    },
    error: function (request, status, error) {
    
      builder = new Formio.FormBuilder(document.getElementById("builder"), {
        display: 'form',
        components: []
        }, {
        baseUrl: 'https://examples.form.io'
        });
      builder.instance.ready.then(onReady);
    }
  });

});
