var Base64 = { _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function (e) { var t = ""; var n, r, i, s, o, u, a; var f = 0; e = Base64._utf8_encode(e); while (f < e.length) { n = e.charCodeAt(f++); r = e.charCodeAt(f++); i = e.charCodeAt(f++); s = n >> 2; o = (n & 3) << 4 | r >> 4; u = (r & 15) << 2 | i >> 6; a = i & 63; if (isNaN(r)) { u = a = 64 } else if (isNaN(i)) { a = 64 } t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a) } return t }, decode: function (e) { var t = ""; var n, r, i; var s, o, u, a; var f = 0; e = e.replace(/[^A-Za-z0-9+/=]/g, ""); while (f < e.length) { s = this._keyStr.indexOf(e.charAt(f++)); o = this._keyStr.indexOf(e.charAt(f++)); u = this._keyStr.indexOf(e.charAt(f++)); a = this._keyStr.indexOf(e.charAt(f++)); n = s << 2 | o >> 4; r = (o & 15) << 4 | u >> 2; i = (u & 3) << 6 | a; t = t + String.fromCharCode(n); if (u != 64) { t = t + String.fromCharCode(r) } if (a != 64) { t = t + String.fromCharCode(i) } } t = Base64._utf8_decode(t); return t }, _utf8_encode: function (e) { e = e.replace(/rn/g, "n"); var t = ""; for (var n = 0; n < e.length; n++) { var r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r) } else if (r > 127 && r < 2048) { t += String.fromCharCode(r >> 6 | 192); t += String.fromCharCode(r & 63 | 128) } else { t += String.fromCharCode(r >> 12 | 224); t += String.fromCharCode(r >> 6 & 63 | 128); t += String.fromCharCode(r & 63 | 128) } } return t }, _utf8_decode: function (e) { var t = ""; var n = 0; var r = c1 = c2 = 0; while (n < e.length) { r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r); n++ } else if (r > 191 && r < 224) { c2 = e.charCodeAt(n + 1); t += String.fromCharCode((r & 31) << 6 | c2 & 63); n += 2 } else { c2 = e.charCodeAt(n + 1); c3 = e.charCodeAt(n + 2); t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63); n += 3 } } return t } }


/* --- E D I T O R  S P E C I F I C  F E A T U R ES ---*/

var dragOverColor = "rgb(64, 114, 207)";
var outlineselection = "1px solid rgba(64, 114, 207,0.8)";
var outlineUnselected = "1px dotted rgba(220,220,220,0.3)";



function isdarkmode() {
  if (document.documentElement.classList.contains("dark")==true ) {
    return "1"
  } else {
    return "0"
  }
}


function setColorTheme (color) {
  if (color) {
    app.setColorTheme(color);
  }
}


function setStyle (color) {
  if (color) {
      document.documentElement.style.setProperty('--f7-theme-color', color);
  }
}


function windowsFallBack(s) {
  return;
  if (s) {
    document.title = encodeURIComponent(s);
  } else {
    document.title = '';
  }
}


function zoomIn(z) {
  document.body.style.zoom=z+"%";
}

function resizeSelection() {
  var handle = $("#objecthandle");
  if (handle.css('display') == "none") { return; }
  var p = getObjectAttribute("objecthandle", "data-parent");
  var o = document.getElementById(p);
  if (!(o)) { return; }
  var br = o.getBoundingClientRect();
  var innerWidth = $('#sortable').width();
  var mst = $('#maincontents').scrollTop() || 0;
  var pst = $('.page').scrollTop() || 0;

  var actualInnerWidth = $("body").prop("scrollWidth"); //clientWidth

  //Handles Position
  var w = Math.min(br.width, actualInnerWidth);
  var t = br.top || 0;
  var l = br.left || 0;
  var h = br.height || 0;
  handle.css({ top: t, left: l, height: h, width: w });

  //Crumb Position
  var ol = $("#object-label");
  var tp = t-20 ; //- 22
  if (tp < 20) { 
    tp = 2; //br.top + br.height; 
  }
  var topPos = tp + mst + pst-5 ; //- 5
  if (topPos <= 0) { topPos = 0; }
  ol.css({ top: topPos });
  var oll = br.left+8;
  if (oll >= (innerWidth - 315)) { oll = innerWidth - 315; }; //Min Width
  ol.css({ left: oll });
  ol.css({ display: "block" });
}

/* clear previous selection */
function clearSelection() {
  $("#objecthandle").css({ display: 'none' });
  $("#object-label").css({ display: 'none' });
}

window.onerror = function (errorMsg, url, lineNumber) {
  window.status = "Editor Error: " + errorMsg + " on Line " + lineNumber + " at url " + url;
};

/* Generic Functions */
var guid = function () {
  return Math.random().toString(36).substr(2, 9);
};

function reload() {
  location.reload(true);
}
function showZoom() {
  //Silent function in Editor;
}

function setDirection(d) {
  if (d == 0) {
    document.body.style.direction = "ltr";
  }
  else if (d == 1) {
    document.body.style.direction = "rtl";
  }
}

function setBodyFont(f) {
  if ((f) && (f.length > 0)) {
    document.body.style.fontFamily = f;
    windowsFallBack(document.body.style.fontFamily);
    return document.body.style.fontFamily;
  }
  else {
    document.body.style.fontFamily = null;
    document.body.removeAttribute('font-family');
    windowsFallBack("remove");
    return "remove";
  }
}

/* Load a Google font by its name. */
var loadFont = function (font) {
  WebFont.load({
    google: {
      families: [font]
    }
  });
};

/*-- J Q V M A P  --*/
function initJQVMap(id, map, bg, bc, ez, sc, sr, st, dc, fc, tc, dl) {
  var values;
  var links;
  if (dc) { values = JSON.parse(dc); sr = null; }
  if (dl) { links = JSON.parse(dl); }
  var srj;
  if (sr) {
    srj = JSON.parse("[" + sr.replace(/'/g, '"') + "]");
  }
  var themap = $('#' + id);
  if (themap) {
    themap.vectorMap({
      map: map,
      enableZoom: ez,
      hoverOpacity: 0.8,
      hoverColor: false,
      borderColor: bc,
      borderOpacity: 0.25,
      borderWidth: 0.2,
      backgroundColor: bg,
      normalizeFunction: 'polynomial',
      selectedColor: sc,
      color: fc,
      scaleColors: [fc, tc],
      showLabels: false,
      showTooltip: st,
      selectedRegions: srj,
      values: values,
      onLabelShow: function (event, label, code) {
        if (values) {
          if (values[code]) {
            var value = values[code];
            var c = label[0].textContent;
            if (value) {
              label.html('<div class="map-tooltip">' + c + ': ' + value + '</div>');
            }
          }
        };
      },
      onRegionOver: function (event, code, region) {
      },
      onRegionClick: function (event, code, region) {
        event.preventDefault();
        if (links) {
          if (links[code]) {
            var lnk = links[code];
            if (JSON.stringify(lnk)) {
              window.location = lnk;
            }
          }
        }
      }
    });
    windowsFallBack("1");
    return 1;
  } else {
    windowsFallBack("0");
    return 0;
  }
}


/* replaceAll Implementation */
function replaceAll(str, find, replace) {
  var s = str.replace(new RegExp(find, 'g'), replace);
  windowsFallBack(s);
  return s;
}

/* code id random attribution */
function setcodeguids(str) {
  var intIndexOfMatch = str.indexOf(":uid");
  while (intIndexOfMatch != -1) {
    str = str.replace(":uid", guid());
    intIndexOfMatch = str.indexOf(":uid");
  }
  windowsFallBack(str);
  return str;
}

function setallIDsByID(p) {
  var x = document.getElementById(p);
  var t = x.innerHTML;
  x.innerHTML = setcodeguids(t);
  return;
}

function objectExists(p) {
  if ($("#" + p).length > 0) {
    windowsFallBack('true');
    return 'true';
  } else {
    windowsFallBack('false');
    return 'false';
  }
}

function changeCSSTheme(cssFile) {
  var t = document.getElementById('csstheme');
  t.setAttribute("href", cssFile);
}

var scriptStatus=null;

function getScriptStatus() {
  return scriptStatus;
}

function AddCustomCssLink(path) {
  var cssId = 'customcss';  
  if (document.getElementById(cssId)) {
    el.remove();
  }  
  if (!document.getElementById(cssId)) {
    var head = document.getElementsByTagName('head')[0];
    var link = document.createElement('link');
    link.id = cssId;
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.href = path;
    link.media = 'all';
    head.appendChild(link);
  }
}

function addScript(src) {
  scriptStatus = null;
  var tag = document.querySelector('script[src*="' + src + '"]');
  if (tag) {
    scriptStatus = "loaded";
  } else {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = src;
    script.onload = function () {
      scriptStatus = "loaded";
    };
    script.onerror = function () {
      scriptStatus = "error";
    };
    document.body.appendChild(script);
  }
}

function addCssClass(classSource) {
  var style = document.createElement('style');
  style.type = 'text/css';
  style.innerHTML = classSource;
  document.getElementsByTagName('head')[0].appendChild(style);
}  

function getGooglemapStatus() {
  var r = ((typeof google) == 'object');
  windowsFallBack(r);
  return r;
}

function changeMainGoogleFont(fontName) {
  var t = document.getElementById('mainfont');
  t.setAttribute("href", fontName);
}

/* add a class to an object*/
function addClass(p, c) {
  var o=null;
  if (p=="html") {
    o=document.documentElement;
  } else if (p=="body") {
    o=document.body;
  } else {
    o=document.getElementById(p);
  }
  if (!(o)) {
    windowsFallBack('none');
    return 'none';
  }
  if (!(o.classList.contains(c))) { o.classList.add(c); }
  windowsFallBack(o.className);
  return o.className;
}

/* remove one classe from  an object*/
function removeClass(p, c) {
  var o=null;
  if (p=="html") {
    o=document.documentElement;
  } else if (p=="body") {
    o=document.body;
  } else {
    o=document.getElementById(p);
  }
  if (!(o)) {
    windowsFallBack('none');
    return 'none';
  }
  if (o.classList.contains(c)) { 
    o.classList.remove(c); 
  }
  windowsFallBack(o.className);
  return o.className;
}

/* remove classes from  an object*/
function removeAllClasses(p) {
  var o = document.getElementById(p);
  if (!(o)) { windowsFallBack('none'); return 'none'; }
  o.removeAttribute("class")
}

/* remove one attribute from  an object*/
function removeObjectAttribute(p, c) {
  var o = document.getElementById(p);
  if (!(o)) { windowsFallBack('0'); return 0; }
  if (!(c)) { windowsFallBack('0'); return 0; }
  if (o.hasAttribute(c)) { o.removeAttribute(c); }
  windowsFallBack('1');
  return 1;
}

/* remove All attributes by name for an object including childs*/
function removeAllAttributes(p, c) {
  var i;
  var $target = $("#" + p);
  if (!$target) { return; }
  $target.removeAttr(c);
  return;
};


function removeAllAttrs() {
  var b = document.body;
  for (var i = b.attributes.length; i-- > 0;)
    element.removeAttributeNode(element.attributes[i]);
}


/* set object style for given Object id and style name */
function setObjectProperty(p, pstyle, pvalue) {
  var o = document.getElementById(p);
  if (!(o)) { return 'none'; }
  if ((pstyle == "font-family") && (pvalue.length > 0)) {
    $('#' + p).css(pstyle, "'" + pvalue + "'");
  } else {
    $('#' + p).css(pstyle, pvalue);
  }
  return 1;
}

/* get object custom styles list for given id  */
function getObjectProperties(p, style) {
  var elm = document.getElementById(p);
  if (elm) {
    var computedStyle;
    if (typeof elm.currentStyle != "undefined") {
      computedStyle = elm.currentStyle;
    }
    else {
      computedStyle = document.defaultView.getComputedStyle(elm, null);
    }
    windowsFallBack(computedStyle[style]);
    return computedStyle[style];
  } else {
    windowsFallBack('0');
    return 0;
  }
}

/* inner HTML */
function getObjectInnerHTML(p) {
  var o = document.getElementById(p);
  if (o) {
    var x = o.firstChild;
    if (x) {
      return $("#" + p).html();
    } else { return ""; }
  } else { return ""; }
}

function setObjectInnerHTML(p, h) {
  var o = document.getElementById(p);
  if (o) {
    o.innerHTML = h;
  } else { return 0; }
}

/* outer HTML */
function GetobjectOuterHTML(p) {
  var o = document.getElementById(p);
  if (o) {
    return o.outerHTML;
  } else return;
}
function setObjectOuterHTML(p, h) {
  var o = document.getElementById(p);
  if (o) {
    o.outerHTML = h;
  } else { return false; }
}

/* all HTML */
function GetPageHTML() {
  var s = document.documentElement.outerHTML;
  windowsFallBack(s);
  return s;
}

function setPageCode(c) {
  var s = document.getElementById("sortable");
  if (s) {
    clearSelection();
    s.innerHTML = decodeURIComponent(c);
    return 1;
  } else { windowsFallBack('0'); return 0; }
}

function getPageCode() {
  var s = document.getElementById("sortable");
  if (s) {
    windowsFallBack(s.innerHTML);
    return s.innerHTML;
  } else { return; }
}

function InsertBodyCode(c) {
  document.body.innerHTML = decodeURIComponent(c) + document.body.innerHTML;
  windowsFallBack(document.body.innerHTML);
  return document.body.innerHTML;
}
/* END Generic Functions */

/* Block Functions */
function getBlockUnderMouse(x, y) {
  var o = document.elementFromPoint(x, y);
  if (!(o)) { return; }
  var cn = getclassname(o.id);
  var isfound = false;
  while (isfound == false) {
    if (cn == "block") {
      isfound = true;
      windowsFallBack(o.id);
      return o.id;
    }
    o = o.parentElement;
    if (o) { cn = getclassname(o.id); }
    else {
      isfound = false;
      return;
    }
  }
}

//Set Title
function resetTitle() {
  windowsFallBack('');
}


/* Reset Drop Borders */
function resetBlockDropBorders() {
  var xl = document.getElementsByClassName("block");
  var i;
  for (i = 0; i < xl.length; i++) {
    xl[i].style.setProperty("border-top", "1px dashed transparent", "important");
    xl[i].style.setProperty("border-bottom", "1px dashed transparent", "important");
  }
 // document.body.style.setProperty("border-top", "1px dashed transparent", "important");
  var dp = document.getElementById("object-dropper");
  dp.style.display = "none";
}

/* dragOver get parent Block ID from Mouse Position */
function getParentBlockID(x, y) {
  var co = "2px solid " + dragOverColor;
  var wh = "1px dashed transparent";
  var op;
  var id = null;
  var o = document.elementFromPoint(x, y);
  if (!(o)) { windowsFallBack("xxxy"); return "xxxy"; }
  /* Test if drag over block*/
  if (o.className == "block") {
    id = o.id;
    op = o;
  } else { /* else drag over object*/
    op = o.parentElement;
    if (!(op)) { return; }
    while (op) {
      if (op.className == "block") { id = op.id; break; }
      op = op.parentElement;
    }
  }
  /* Remove line of others block */
  resetBlockDropBorders();
  if (!(id)) { /* drag over body */
    if (o.tagName = "BODY") {
      var xl = document.getElementsByClassName("block");
      if (xl.length == 0) {
    //    document.body.style.setProperty("border-top", co, "important");
      }
      else {
        xl[xl.length - 1].style.setProperty("border-bottom", co, "important")
      }
    } else { return; }
  }
  /* drag over block */
  /* Adding line of current block */
  if (!(op)) { return "xxx"; }
  var rect = op.getBoundingClientRect();
  var midpos = (rect.top + (op.offsetHeight / 2));
  if (y < midpos) {
    op.style.setProperty("border-top", co, "important");
    op.style.setProperty("border-bottom", wh, "important");
  }
  else {
    op.style.setProperty("border-top", wh, "important");
    op.style.setProperty("border-bottom", co, "important");
  }
  /* Return id of current block */
  windowsFallBack(id);
  return id;
}

/* Boolean Function: DropBloc at Pos + html code */
function dropBlockatPos(x, y, c) {
  var op;
  var id = null;
  resetBlockDropBorders();
  var o = document.elementFromPoint(x, y);
  if (!(o)) { windowsFallBack("0"); return 0; }
  if (o.className == "block") { /*drop on block*/
    op = o;
    id = o.id;
  }
  else {
    op = o.parentElement;
    if (!(op)) { windowsFallBack("0"); return 0; }
    while (op) {
      if (op.className == "block") { id = op.id; break; }
      op = op.parentElement;
    }
  }
  if (!(id)) { /* dropped on body */
    if (o.tagName = "BODY") {
      var s = document.getElementById("sortable");
      if (s) { s.innerHTML = s.innerHTML + c; return 1; } else { return 0; }
    } else { windowsFallBack("0"); return 0; }
  }
  /* dropped on block */
  /* Remove line of others block */
  resetBlockDropBorders();
  /* Adding line of current block */
  var rect = op.getBoundingClientRect();
  var midpos = (rect.top + (op.offsetHeight / 2));
  if (y < midpos) { op.outerHTML = c + op.outerHTML; windowsFallBack("1"); return 1; }
  else { op.outerHTML = op.outerHTML + c; windowsFallBack("1"); return 1; }
}


/* Select Block By ID : Boolean*/
function selectBlockFromID(p) {
  if (!(p)) { windowsFallBack("0"); return 0; }
  var o = document.getElementById(p);
  if (!(o)) { windowsFallBack("0"); return 0; }
  windowsFallBack(p);
  var x = document.getElementsByClassName("block");
  if (x) {
    for (i = 0; i < x.length; i++) {
      x[i].style.setProperty("border-color", "rgb(200,200,200)", "important");
      x[i].style.setProperty("border-size", "1px", "important");
    }
  }
  o.style.setProperty("border-color", "rgb(87,171,229)", "important");
  o.style.setProperty("border-size", "1px", "important");

  var l = document.getElementById("object-label");
  var br = o.getBoundingClientRect();
  var ct = document.getElementById("maincontents");
  var w = o.offsetWidth;
  var h = o.offsetHeight;
  /* label */
  var tp = br.top + document.body.scrollTop + h;
  if (tp < 1) { tp = 1; }
  l.style.top = tp + "px";
  l.style.left = br.left + "px";
  l.style.height="22px";
  document.getElementById("object-label-text").innerHTML = "block - id: " + p + " size=" + w + "x" + h + " px";
  l.style.display = "block";
  windowsFallBack("1");
  return 1;
}

function hideInfoWindow() {
  var l = document.getElementById("object-label");
  l.style.display = "none";
}
/* End Block Functions */

/* Object Functions */

/* get clicked Object DIV data-x="object"*/
function objectClassAtPoint(x, y) {
  var o = document.elementFromPoint(x, y);
  if (!(o)) { return; }
  windowsFallBack(o.className);
  return o.className;
}

function objectElementAtPoint(x, y) {
  var o = document.elementFromPoint(x, y);
  if (!(o)) { return; }
  windowsFallBack(o.tagName);
  return o.tagName;
}

function getFirstElementByClassName(c) {
  var elements = document.getElementsByClassName(c);
  if (!(elements)) { return ""; }
  var o = elements[0];
  if (!(o)) { return ""; }
  windowsFallBack(o.id);
  return o.id;
}

function mouseDownAtPoint(x, y) {
  unSelectObjects();
  var o = document.elementFromPoint(x, y);
  if (!(o)) { return; }
  if (o.className == "block") { windowsFallBack(o.id); return o.id; }
  var attr = getObjectAttribute(o.id, "data-x");
  var isfound = false;
  while (isfound == false) {
    if (attr == "object") {
      isfound = true;
      windowsFallBack(o.id);
      return o.id;
    }
    o = o.parentElement;
    if (o) { attr = getObjectAttribute(o.id, "data-x"); }
    else {
      isfound = false;
      return;
    }
  }
}

function initSortable() {
//Nada
}


function getScrollTop() {
  var ct = $("#maincontents");
  var st=null;
  if (ct) { st = ct.scrollTop(); } else { ct = 0; }
  windowsFallBack(st);
  return st;
}

var TimeOutVar

/* select an object */
function selectObject(p) {
  if (!(p)) { return 0; }
  var o = document.getElementById(p);
  if (!(o)) { return 0; }
  unSelectObjects();
  o.style.setProperty("outline", outlineselection);
  windowsFallBack(p);
  if (TimeOutVar) { clearTimeout(TimeOutVar); }
  var br = o.getBoundingClientRect();
  var ct = $("#maincontents");
  var st = 0;
  if (ct) { st = ct.scrollTop() || 0; }
  var tp = br.top + st; //-20
  if (tp < 4) { tp = 4; }
  var type;
  if (o.className == "block") { type = "block"; }
  else { type = getObjectAttribute(p, "data-widget"); }
  if (type) { type = type.toLowerCase(); } else { type = o.tagName.toLowerCase(); }
  var w = o.offsetWidth || 0;
  var h = o.offsetHeight || 0;
  var lbl = document.getElementById("object-label-text");
  lbl.innerHTML =type + " [" + o.tagName.toLowerCase() + "] - size: " + w + "x" + h + " px";
  $("#object-label").show();
  setObjectAttribute("objecthandle", "data-parent", p);
  $("#objecthandle").css({ display: 'block' });
  resizeSelection();
  setTimeout(function () {resizeSelection(); }, 50);
  setTimeout(function () {resizeSelection(); }, 500);
  return p;
}

function setAllDefaultOutline() {
  var x = $('[data-x]');
  var i;
  for (i = 0; i < x.length; i++) {
    x[i].style.setProperty("outline", outlineUnselected); /*, "important"*/
  }
}


function unSelectObjects() {
  var x = $('[data-x]');
  var i;
  for (i = 0; i < x.length; i++) {
    x[i].style.setProperty("outline", outlineUnselected); /*, "important"*/
  }
  /*-- bloc --s*/
  var y = document.getElementsByClassName("block");
  for (i = 0; i < y.length; i++) {
    y[i].style.setProperty("outline", outlineUnselected); /* , "important"*/
  }
  clearSelection();
  setObjectAttribute("objecthandle", "data-parent", "");
  var dp = $("#object-dropper");
  dp.css({ display: "none" });
}

/* object attribute.. */
function getObjectAttribute(p, attr) {
  var o = document.getElementById(p);
  if (o) {
    if (o.hasAttribute(attr)) {
      var r = o.getAttribute(attr);
      if (r) {
        windowsFallBack(r);
        return r;
      }
    }
  }
}

function setObjectAttribute(id, att, val) {
  var t = document.getElementById(id);
  if (!(t)) { return; }
  t.setAttribute(att, val);
}
/* object attribute by tagname eg body.. */
function getBodyAttribute(attr) {
  var r = document.body;
  var computedStyle = getComputedStyle(r).getPropertyValue(attr);
  windowsFallBack(computedStyle);
  return computedStyle;
}


/* object get text content.. */
function getObjectText(p) {
  try {
    if (!p) { return; }
    var o = $("#" + p);
    if (!o) { return; }
    if (!o.children()) { return; }
    var r = o
      .clone()    //clone the element
      .children() //select all the children
      .remove()   //remove all the children
      .end()  //again go back to selected element
      .text();    //get the text of element

    windowsFallBack(r);
    return r;
  }
  catch (err) {
    return;
  }
}

function getObjectTextExt(id) {
  if (!id) { return; }
  var element=document.getElementById(id);
  if (!element) { return; }
  if (element.childElementCount > 0) {
      var text="";
      for (var i = 0; i < element.childNodes.length; ++i) {
          var selt=element.childNodes[i];
          if (selt.nodeType === Node.TEXT_NODE) {
              text += element.childNodes[i].textContent; 
          }
      }
      return text;
  } else {
      return element.textContent;
  }
}

function setObjectTextExt(id,text) {
  if (!id) { return; }
  var element=document.getElementById(id);
  if (!element) { return; }
  if (element.childElementCount > 0) {
      for (var i = 0; i < element.childNodes.length; ++i) {
          var selt=element.childNodes[i];
          if (selt.nodeType === Node.TEXT_NODE) {
            element.childNodes[i].textContent= text; 
            break;
          }
      }
  } else {
      element.textContent=text;
  }
}


function getObjectInnerText(p) {
  try {
    if (!p) { return; }
    var o = document.getElementById(p);
    if (!o) { return; }
    const r = o.innerText;
    return r;
  }
  catch (err) {
    return;
  }
}


/* object set text content.. */
function setObjectText(p, t) {
  var o = document.getElementById(p);
  if (!o) { return; }
  var cache = $("#" + p).children();

  $("#" + p).html(t).append(cache);
  windowsFallBack(o.textContent);
  return o.textContent;
}

/*Get Closest item of class */
function getClosestElement(id,selector) {
  var element = document.getElementById(id);
  if (element) {
    var closestElement = element.closest(selector);
    if (closestElement) {
      return closestElement.id;
    }
  }
}

/*Find item of class in page--*/
function findElementWithClass(cln) {
  var cl= $(cln);
  if (cl) {
    if (cl.length>0) {
    return cl[0].id;
   }
  }
}

/* -- get object id at pos --- */
function getElementIDAtPos(x, y) {
  var o = document.elementFromPoint(x, y);
  if (o instanceof HTMLIFrameElement)
    o = o.contentWindow.document.elementFromPoint(x, y);
  if (o) {
    windowsFallBack(o.id);
    return o.id;
  }
}

/*-- get the first element id undermouse with attribute data-x=[object] --*/
function getObjectIdAtPos(x, y) {
  var o = document.elementFromPoint(x, y);
  if (!(o)) { return; }
  var attr = getObjectAttribute(o.id, "data-x");
  var isfound = false;
  while (isfound == false) {
    if (attr == "object") {
      isfound = true;
      windowsFallBack(o.id);
      return o.id;
    }
    o = o.parentElement;
    if (o) { attr = getObjectAttribute(o.id, "data-x"); }
    else {
      isfound = false;
      return;
    }
  }
}

var targetContainer;
var targetPosition = 0;

/* get dropable object id from mouse coordinates */
function getDroppableObjectIDFromPoint(x, y) {
  /*-- vars --*/
  var dp = $("#object-dropper");
  dp.css({ display: "none" });
  var status = 0; /*-- 0=none 1=inside 2=top 3=bottom --*/

  /*-- get object under mouse and attributes --*/
  var id = getObjectIdAtPos(x, y);

  var o = document.getElementById(id);
  if (!id) {
    dp.css({ display: "none" });
    windowsFallBack('none');
    return "none";
  }
  var attr = getObjectAttribute(id, "data-acceptdrop");
  var rect = o.getBoundingClientRect();
  var atx = getObjectAttribute(id, "data-x");

  /*-- check position on object --*/
  var d = 4;
  if ((o.offsetHeight >= 10) && (attr != "true")) { d = o.offsetHeight / 2; }
  if (y <= (rect.top + d)) { status = 2; }
  else if (y >= (rect.top + rect.height - d)) { status = 3; }
  else { status = 1; }
  /*-- check object sub-elements with data-acceptdrop attribute--*/
  var sid = getElementIDAtPos(x, y);
  if (sid != id) {
    var sattr = getObjectAttribute(sid, "data-acceptdrop");
    if (sattr == "true") {
      id = sid;
      var so = document.getElementById(sid);
      rect = so.getBoundingClientRect();
      o = so;
      status = 1;
      attr = "true";
    }
  }

  dp.css({ left: rect.left });
  dp.css({ height: 3 });
  dp.css({ border: '0px' });
  dp.css({ width: o.offsetWidth });
  dp.css({ backgroundColor: 'transparent' });
  dp.css({ opacity: '1' });

  var u = "2px solid " + dragOverColor;
  if (status == 2) { //Drop top
    dp.css({ top: rect.top + document.body.scrollTop - 5 });
    dp.css({ borderBottom: u });
    dp.css({ display: 'block' });
  }
  else if (status == 3) { /* drop bottom */
    dp.css({ top: rect.top + o.offsetHeight + document.body.scrollTop });
    dp.css({ borderBottom: u });
    dp.css({ display: 'block' });
  }
  else if ((status == 1) && (attr == "true")) {
    /* drop inside allowed */
    u = "1px solid " + dragOverColor;
    dp.css({ left: rect.left });
    dp.css({ top: rect.top + document.body.scrollTop });
    dp.css({ width: o.offsetWidth });
    dp.css({ height: o.offsetHeight });
    dp.css({ border: u });
    dp.css({ backgroundImage: 'linear-gradient(rgba(179, 213, 239, 0.2), rgba(51, 122, 183, 0.5))' });
    dp.css({ opacity: '0.5' });
    dp.css({ display: 'block' });
  }
  targetContainer = o;
  targetPosition = status;
  windowsFallBack(id);
  return id;
}

/* called when mouse drop an object droponobject(id,code) */
function droponobject(p, c, x, y) {
  /*-- vars --*/
  var t2 = setcodeguids(c);
  var dp = document.getElementById("object-dropper");
  dp.style.display = "none";
  /*-- set HTM --*/
  if (targetPosition == 2) { /* top */
    targetContainer.outerHTML = t2 + targetContainer.outerHTML;
  }
  else if (targetPosition == 3) { /* bottom */
    targetContainer.outerHTML = targetContainer.outerHTML + t2;
  }
  else if (targetPosition == 1) { /* inside */
    targetContainer.innerHTML = targetContainer.innerHTML + t2
  }
  targetContainer = null;
  targetPosition = 0;
  windowsFallBack('1');
  return 1;
}


/* End Object Functions */

/* DOM List Functions */
function getDOMList(p) {
  var x;
  if (p) { x = document.getElementById(p).children; }
  else { x = document.getElementsByClassName("block"); }
  var i;
  var r = '';
  for (i = 0; i < x.length; i++) {
    if (x[i]) {
      var n = x[i].className;
      if (n.length == 0) n = x[i].tagName;
      var id = x[i].id;
      if (id.length > 0) {
        id=id.replace("#","");
        var z = $('#' + id + ' [data-x]').length;
        var attr = getObjectAttribute(id, "data-x");
        var type;
        if (x[i].className == "block") { type = "block"; }
        else { type = x[i].tagName; }
        if (!(type)) { type = x[i].tagName; }

        var w = x[i].className;
        if (x[i].id != p) {
          r = r + x[i].id + "|" + type + "|" + z + "|" + w + ",";
        }
      }
    }
  }
  windowsFallBack(r);
  return r;
}

function searchChildDOMList(p, c) {
  if (!p) { return; }
  var x = document.getElementById(p).children;
  var i;
  var type = '';
  var r = '';
  for (i = 0; i < x.length; i++) {
    if (x[i]) {
      if ((x[i].className) && (x[i].className.length > 0)) {
        type = x[i].className.trim();
      }
      if (type.length == 0) { type = x[i].tagName };
      if (type.length == 0) { type = x[i].nodeType() };
      var id = x[i].id;
      var z = 0;
      type = type.toLowerCase();
      if (id.length > 0) { z = $('#' + id).children.length; }
      if (x[i].id != p) {
        r = r + x[i].id + "|" + type + "|" + z + ",";
      }
    }
  }
  windowsFallBack(r);
  return r;
}
function getTranlatableElements(p) {
  var x;
  if (p) { x = document.getElementById(p).children; }
  else { x = document.getElementsByClassName("block");} 
  var i;
  var r = '';
  for (i = 0; i < x.length; i++) {
    if (x[i]) {
      var n = x[i].className;
      if (n.length == 0) n = x[i].tagName;
      var id = x[i].id;
      if (id.length > 0) {
        var z = $('#' + id).length;
        var type;
        if (x[i].className == "block") { type = "block"; }
        else { type = x[i].tagName; }
        if (!(type)) { type = x[i].tagName; }

        var w = x[i].className;
        if (x[i].id != p) {
          r = r + x[i].id + "|" + type + "|" + z + "|" + w + ",";
        }
      }
    }
  }
  return r;
}


/* END DOM List Functions */


/* insertBlock(id,html)  */
function insertBlock(p, c) {
  var o = document.getElementById(p);
  if (o) {
    var d = document.getElementsByClassName("block");
    var index = d.length + 1;
    s = o.parentNode;
    var t = s.outerHTML + c;
    var t2 = replaceAll(t, ":uid", index);
    s.outerHTML = t2;
    windowsFallBack(index);
    return index;
  } else { //drop on Body
    var s = document.getElementById("sortable");
    if (s) { s.innerHTML = s.innerHTML + c; return 1; } else { return 0; }
  }
}


/* JS CALLBACK FUNCTIONS */
/* Add HTML content h for and object by ID p */
function setHTMLContent(p, h) {
  var currobj = document.getElementById(p);
  if (currobj) {
    currobj.outerHTML = currobj.outerHTML + h;
    windowsFallBack('1');
    return 1;
  } else { windowsFallBack('0'); return 0; }
}

/* delete Block for a given id ID p */
function deleteBlock(p) {
  var currobj = document.getElementById(p);
  if (currobj) {
    currobj.outerHTML = '';
    clearSelection();
    windowsFallBack('1');
    return 1;
  } else { windowsFallBack('0'); return 0; }
}
/* delete object for a given id ID p */
function deleteObject(p) {
  var currobj = document.getElementById(p);
  if (currobj) {
    currobj.outerHTML = '';
    clearSelection();
    windowsFallBack('1');
    return 1;
  } else { windowsFallBack('0'); return 0; }
}

/* delete elements for a given classname p */
function deleteElementsFromClass(p) {
  var c = document.getElementById(p);
  if (!(c)) { windowsFallBack('0'); return 0; }
  if (c.length > 0) { c.remove(); }
  windowsFallBack('1');
  return 1;
}
/* delete child elements for a given classname p */
function RemoveAllChildsOfClass(id, p) {
  var c = $('#' + id);
  if (!(c)) { windowsFallBack('0'); return 0; }
  if (c.length > 0) { c.children("." + p).remove(); }
  windowsFallBack('1');
  return 1;
}

/* insertObject(id,html)  */
function insertObject(p, c) {
  var o = document.getElementById(p);
  if (o) {
    var i = guid;
    var cm = replaceAll(c, ":uid", i);
    o.innerHTML = o.innerHTML + cm;
    windowsFallBack('1');
    return i;
  }
  else { windowsFallBack('0'); return 0; }
}


/* object classname */
function getclassname(p) {
  var o = document.getElementById(p);
  if (o) {
    var c = o.className;
    windowsFallBack(c);
    return c;
  }
}

/* object tagName eg. DIV, P, etc... */
function gettagname(p) {
  var o = document.getElementById(p);
  if (o) {
    var r = o.tagName.toLowerCase();
    windowsFallBack(r);
    return r;
  }
}

/* object parent ID */
function getParentId(id) {
  var o = document.getElementById(id);
  if (!o) { return; }
  var op = o.parentElement;
  if (op) {
    windowsFallBack(op.id);
    return op.id;
  }
}


function findParentForm(id) {
	var formRef=document.querySelector('#'+id).closest(".form");
	if (formRef) {
    return formRef.id;
  } else {
    return;
  }
}
function findParentWithClassName(id,classname) {
	var formRef=document.querySelector('#'+id).closest("."+classname);
	if (formRef) {
    return formRef.id;
  } else {
    return;
  }
}

/* object style for given style name */
function getcsspropertyvalue(p, pstyle) {
  var o = document.getElementById(p);
  if (o) {
    var myreturn = window.getComputedStyle(o, null).getPropertyValue(pstyle);
    windowsFallBack(myreturn);
    return myreturn;
  }
}

/* block sub-object style for given style name */
function getblockcsspropertyvalue(p, pstyle) {
  var o = document.getElementById(p);
  if (o) {
    var x = o.firstElementChild;
    var myreturn = window.getComputedStyle(x, null).getPropertyValue(pstyle);
    windowsFallBack(myreturn);
    return myreturn;
  } else { windowsFallBack('0'); return 0; }
}

/* block sub-object style for given block id and style name */
function getFirstChildClassName(p) {
  var o = document.getElementById(p);
  if (!(o)) { return; }
  var x = o.children;
  var i;
  for (i = 0; i < x.length; i++) {
    var m = x[i].className;
    if (m != "handle") {
      windowsFallBack(m);
      return m;
    }
  }
}

function getFirstChildIdent(p) {
  var o = document.getElementById(p);
  if (!(o)) { return; }
  var x = o.children;
  if (!(x)) { return; }
  if (x.length == 0) { windowsFallBack('oups'); return "oups"; }
  windowsFallBack(x[0].id);
  return x[0].id;
}

/* get object element type from data-element custom attribute */
function getObjectElementType(p) {
  var o = document.getElementById(p);
  if (o) {
    var attr = getObjectAttribute(p, "data-element");
    windowsFallBack(attr);
    return attr;
  } else return;
}

/* set sub-object style for given block id and style name */
function setblockcsspropertyvalue(p, pstyle, pvalue) {
  var o = document.getElementById(p);
  if (o) {
    var x = o.firstElementChild;
    if (x) {
      x.style.marginBottom = pvalue;
      windowsFallBack(x.style.marginBottom);
      return x.style.marginBottom;
    } else { windowsFallBack('0'); return 0; }
  } else { windowsFallBack('0'); return 0; }
}

/* display drop line under UI object */
function showdropline(p) {
  var dp = document.getElementById("object-dropper");
  if (!p) {
    dp.style.display = "none";
    return;
  }
  var o = document.getElementById(p);
  if (o) {
    var rect = o.getBoundingClientRect();
    dp.style.left = rect.left;
    dp.style.top = rect.top + document.body.scrollTop;
    dp.style.width = o.offsetWidth;
    dp.style.height = o.offsetHeight;
    dp.style.display = "block";

  } else dp.style.display = "none";
}

/* called when mouse over object in edit mode */
function dragoverobject(p) {
  var dp = document.getElementById("object-dropper");
  var o = document.getElementById(p);
  if (o) {
    if (o.id == "sortable") { dp.style.display = "none"; return; }
    var pid = getParentID(p);
    if (pid == "sortable") { dp.style.display = "none"; return; }
    showdropline(p);
  }
}


/* get id from mouse coordinates */
function getElementIDFromPoint(x, y) {
  var o = document.elementFromPoint(x, y);
  if (o) {
    windowsFallBack(o.id);
    return o.id;
  } else { return ""; }
}

/* get tag of object under mouse */
function myTagNameFromPoint(x, y) {
  var o = document.elementFromPoint(x, y);
  if (o) {
    var tn = gettagname(o.id);
    windowsFallBack(tn);
    return tn;
  } else { return ""; }
}


/* get object absolute left from id */
function getOffsetLeft(p) {
  var o = document.getElementById(p);
  if (o) {
    var rect = o.getBoundingClientRect();
    windowsFallBack(rect.left);
    return rect.left;
  }
}
/* get object absolute top from id */
function getOffsetTop(p) {
  var o = document.getElementById(p);
  if (o) {
    var rect = o.getBoundingClientRect();
    windowsFallBack(rect.top);
    return rect.top;
  }
}
/* get object width from id */
function getWidth(p) {
  var o = document.getElementById(p);
  if (o) {
    windowsFallBack(o.offsetWidth);
    return o.offsetWidth;
  }
}
/* get object height from id */
function getHeight(p) {
  var o = document.getElementById(p);
  if (o) {
    windowsFallBack(o.offsetHeight);
    return o.offsetHeight;
  }
}

/* END JS CALLBACK FUNCTIONS */



/* object list */
function getnodelist() {
  ni = document.createNodeIterator(document.documentElement, NodeFilter.SHOW_ELEMENT);
  var mytext
  while (currentNode = ni.nextNode()) {
    mytext = mytext + " " + currentNode.nodeName + " " + currentNode.id;
  }
  windowsFallBack(mytext);
  return mytext;
}


/* drag&drop objects */
function objondragstart(ev) {
  var d=document.getElementById(ev.target.id);
  if (d) {
    var dg=d.getAttribute("draggable");
    var dobj=d.getAttribute("data-x");
    if ((dg && dg=="false") && (dobj && dobj=="object")) {
      ev.preventDefault();
      ev.stopImmediatePropagation();
      return;
    }
    var href=d.getAttribute("href");
    if (href && href.length>0) {
      return false;
    }

  } 
  if (ev.target.id!=ev.currentTarget.id) {
    var t=ev.target.getAttribute("data-x");
    if (t!="object") {
      var dragableparent=ev.target.closest("* [draggable='true']");
      if (!dragableparent) {
        ev.preventDefault();
        ev.stopImmediatePropagation();
        return;
      } 
      ev.dataTransfer.clearData();
      return;
    }
  }
  ev.dataTransfer.clearData();
  ev.dataTransfer.setData("text/plain", "[id=" + ev.target.id + "]");
  ev.dataTransfer.effectAllowed = 'move'
  ev.dataTransfer.dropEffect = 'move';
}

/* drag&drop from outside */
function objondragover(ev) {
  ev.preventDefault();
  // Set the dropEffect to move
  ev.dataTransfer.dropEffect = "move";
  windowsFallBack('false');
  return false;
}
function objdragenter(ev) {
}
function objdrop(ev) {
}

function classAugmentation(p, pn, v) {
  $("." + p).css(pn, v);
  windowsFallBack('1');
  return 1;
}
function getClassProperty(p, pn) {
  var r = $("." + (p)).css(pn);
  windowsFallBack(r);
  return r;
}

/* WIDGET SPECIFIC JS */
function getWidgetFirstChildHTML(p) {
  var c = document.getElementById(p).firstElementChild;
  if (c) {
    windowsFallBack(c.innerHTML);
    return c.innerHTML;
  } else { return ""; }
}
function setBlockQuoteContent(p, text, footerHTML) {
  $("#" + p).html(text + footerHTML);
}
function getBlockquoteText(p) {
  var t = $("#" + p + " p").html();
  if (t) {
    windowsFallBack(encodeURIComponent(t));
    return encodeURIComponent(t);
  } else { return ""; }
}
function getBlockquoteFooterText(p) {
  var r = $("#" + p + " footer").clone().children().remove().end().text();
  windowsFallBack(r);
  return r;
}

function getBlockquoteFooterSource(p) {
  var r = $("#" + p + " cite").clone().children().remove().end().text();
  windowsFallBack(r);
  return r;
}

function decodeString(encodedStr) {
  var parser = new DOMParser;
  var dom = parser.parseFromString(
    '<!doctype html><body>' + encodedStr,
    'text/html');
  var r = dom.body.textContent;
  if (r) {
    windowsFallBack(dom.body.textContent);
    return dom.body.textContent;
  }
  else {
    windowsFallBack('-1');
    return "-1";
  }

}

/* -- F7 styles -- */
var root = document.documentElement;
function setColor(o, c) {
  if (root) {
    root.style.setProperty(o, c);
    windowsFallBack('1');
    return 1;
  } else {
    windowsFallBack('0');
    return 0;
  }
}

function getCssVar(v) {
  var r = getComputedStyle(document.documentElement).getPropertyValue(v);
  windowsFallBack(r);
  return r
}

function setVLHeight() {
  $(".templaterow").each(function (idx, field) {
    var tag = field.tagName.toLowerCase();
    var h = field.offsetHeight;
    if (h > 0) {
      var h2 = field.getAttribute("data-template-height");
      if (h2 != h) {
        field.setAttribute("data-template-height", h);
      }
    }
  });
}

function fixBlankPage() {
  //Fix initial Blank page structure issue
  var obj = document.getElementById("app");
  if (obj) {
    var hasPageClass=obj.classList.contains("page");
    if (hasPageClass==true) {
      const viewMain=document.getElementById("view-main");
      if (viewMain) {
        var html=viewMain.innerHTML;
        const sortable=document.getElementById("sortable");
        if (sortable) {
          sortable.innerHTML=html;
          return "true";
        } else {
          return 3;
        }
      } else {
        return 1;
      }

    }
  } else {
    return 2;
  }
  return "false";
}

function getDuplicatedIDs() {
  var allElements = document.getElementsByTagName("*"), allIds = {}, dupIDs = [];
  for (var i = 0, n = allElements.length; i < n; ++i) {
    var el = allElements[i];
    if (el.id) {
      if (allIds[el.id] !== undefined) dupIDs.push(el.id);
      allIds[el.id] = el.name || el.id;
    }
  }
  if (dupIDs.length) {
    return dupIDs.toString();
  }
}

var focusHandler = function(event) {
  event.target.blur();
}


var widgets = {
  initall: function() {
    widgets.gauge.init();
    widgets.areaChart.init();
    widgets.pieChart.init();
    widgets.progressBar.init();
  },
  progressBar : {
    init : function() {
      var x = document.querySelectorAll(".progressbar");
      for (var i = 0; i < x.length; i++) {
        var elt = x[i];
        var progress=elt.getAttribute("data-progress")||50;
        app.progressbar.set(elt, progress);
      }
    }
  },
  gauge : {
    init : function() {
      var x = document.querySelectorAll(".gauge");
      for (var i = 0; i < x.length; i++) {
        var elt = x[i];
        elt.innerHTML="";
        var inst=app.gauge.get(elt);
        if (inst) {
          app.gauge.destroy(elt);
        }
        inst = app.gauge.create({
          el: elt,
          type: elt.getAttribute("data-gauge-type")||'circle',
          value: elt.getAttribute("data-gauge-value")||"0.5",
          size: elt.getAttribute("data-gauge-size")||"250",
          borderColor: elt.getAttribute("data-border-color")||'#2196f3',
          borderWidth: elt.getAttribute("data-border-width")||10,
          valueText: elt.getAttribute("data-value-text")||'50%',
          valueFontSize: elt.getAttribute("data-value-font-size")||41,
          borderBgColor: elt.getAttribute("data-border-bg-color")||'#2196f3',
          valueFontWeight: elt.getAttribute("data-value-font-weight")||'500',
          labelText: elt.getAttribute("data-label-text")||'',
          valueTextColor: elt.getAttribute("data-value-text-color")||'#000000', 
          labelFontSize: elt.getAttribute("data-label-font-size")||'14',
          labelFontWeight: elt.getAttribute("data-label-font-weight")||'400',
          labelTextColor: elt.getAttribute(" data-label-text-color")||'#888888',
          on: {
            beforeDestroy: function () {
              
            }
          }
        })
      }
    }
  },
  pieChart : {
    init : function() {
      var x = document.querySelectorAll(".pie-chart");
      for (var i = 0; i < x.length; i++) {
        var elt = x[i];
        elt.innerHTML="";
        var inst=app.pieChart.get(elt);
        if (inst) {
          app.pieChart.destroy(elt);
        }
        inst = app.pieChart.create({
          el: elt,
          tooltip: true,
          datasets: [
            {
              label: 'JavaScript',
              value: 150,
              color: '#ff0',
            },
            {
              label: 'Vue.js',
              value: 150,
              color: '#0f0',
            },
            {
              label: 'TypeScript',
              value: 400,
              color: '#00f',
            },
          ]
        })
      }
    }
  },
  areaChart: {
    init : function() {
      const dates = [];
      const today = new Date();
      const year = today.getFullYear();
      const month = today.getMonth();
      for (let i = 0; i < 4; i += 1) {
        dates.push(new Date(year, month - (3 - i)))
      }
      const axisDateFormat = Intl.DateTimeFormat(undefined, { month: 'short', year: 'numeric' });
      const tooltipDateFormat = Intl.DateTimeFormat(undefined, { month: 'long', year: 'numeric' });
      var x = document.querySelectorAll(".area-chart");
      for (var i = 0; i < x.length; i++) {
        var elt = x[i];
        elt.innerHTML="";
        var inst=app.areaChart.get(elt);
        if (inst) {
          app.areaChart.destroy(elt);
        }
        inst = app.areaChart.create({
          el: elt,
          tooltip: true,
          axis: true,
          axisLabels: dates,
          legend: true,
          toggleDatasets: true,
          lineChart: true,
          formatAxisLabel(date) {
            return axisDateFormat.format(date);
          },
          formatTooltipAxisLabel(date) {
            return tooltipDateFormat.format(date);
          },
          datasets: [
            {
              label: 'Red data',
              color: '#f00',
              values: [0, 300, 127, 47]
            },
            {
              label: 'Blue data',
              color: '#00f',
              values: [0, 75, 133, 237]
            },
            {
              label: 'Green data',
              color: '#0f0',
              values: [0, 100, 250, 307]
            },
          ]
        });
      }
    }
  },
}


$(window).on('load', function (e) {
  clearSelection();
  window.addEventListener("resize", resizeSelection);
  window.addEventListener("scroll", resizeSelection);
  window.addEventListener("wheel", resizeSelection);
  $('#maincontents').on('scroll wheel resize', function (event) {
    resizeSelection();
  });
  $('#sortable').on('scroll resize', function (event) {
    resizeSelection();
  });
  widgets.initall();
  document.body.addEventListener('focus', focusHandler, true); 
  window.status = "ready";
});


