var gl_elDrag = null;
var gl_iPos = -1;

function _fillNewForm(fPrivate, strSubst, iListId) {
  const elForm=document.getElementById("check-item-list__form-new");
  const aelInput=elForm.getElementsByTagName("input");

  aelInput[0].checked = fPrivate; // 'Private' checkbox
  aelInput[1].value = strSubst; // Mask text
  aelInput[2].value = iListId; // 'list-id' hidden input
  aelInput[1].focus();
}

function _btnEdit() {
  const strSubst = document.getElementById("subst-"+this.dataset.id).textContent;

  document.getElementById("check-item-list__new-cb").checked = true;
  _fillNewForm(this.dataset.private == "1", strSubst, this.dataset.id);
}


function _dragPos() { return [].indexOf.call( gl_elDrag.parentNode.children, gl_elDrag ); }

function _dragBegin(elBtn) {
  if (!gl_elDrag) {
    gl_elDrag = elBtn.parentNode;
    gl_elDrag.classList.add("check-item-list__row--drag");
    gl_iPos = _dragPos();
    document.getElementsByTagName("body")[0].style.userSelect = "none";
  }
}

function _dragEnd() {
  if (gl_elDrag) {
    const iPos = _dragPos();
    if (gl_iPos != iPos)
      document.location="?prop=subst&amp;id="+gl_elDrag.dataset.id+"&amp;to="+iPos;
    else {
      gl_elDrag.classList.remove("check-item-list__row--drag");
      gl_elDrag = null;
      document.getElementsByTagName("body")[0].style.userSelect = null;
    }
  }
}

function _dragMove(el) {
  if (gl_elDrag) {
    while(!el.classList.contains("check-item-list__row")) {
      el = el.parenNode;
      if (!el) return;
    }
    if ( !el.getElementsByClassName("row__drag-btn").length ) return;

    el.parentNode.insertBefore(gl_elDrag,
           (el === gl_elDrag.nextElementSibling) ? el.nextElementSibling : el);
  }
}


window.addEventListener("load", function() {
  const elNewCB=document.getElementById("check-item-list__new-cb");
  const aelEdit=document.getElementsByClassName("row__edit-btn");

  elNewCB.addEventListener("click", function() { _fillNewForm(true,"",0); } );

  for(elEdit of aelEdit)
    elEdit.onclick=_btnEdit;

  const aelDragBtn=document.getElementsByClassName("row__drag-btn");
  for(elBtn of aelDragBtn)
  {
    elBtn.addEventListener( "mousedown", function(e) {
      _dragBegin( e.currentTarget );
    });
    elBtn.addEventListener( "touchstart", function(e) {
      _dragBegin( e.touches[0].target );
      if (gl_elDrag)
        e.preventDefault();
    });
  }

  document.addEventListener( "mousemove", function(e) {
    _dragMove( document.elementFromPoint( e.clientX, e.clientY ) );
  });
  document.addEventListener( "mouseup", _dragEnd );

  document.addEventListener( "touchmove", function(e) {
    _dragMove( document.elementFromPoint( e.touches[0].clientX, e.touches[0].clientY ) );
  });
  document.addEventListener( "touchend", _dragEnd );
  document.addEventListener( "touchcancel", _dragEnd );

} );
