/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * draggable.js
 *
 * Manages behaviors for draggable table lines
 *
 * LICENSE: This source file is subject to version 1.0 of the OpenFlyers
 * license that is available through the world-wide-web at the following
 * URI: https://openflyers.com/fr/entreprise/conditions-generales. If you did not receive a
 * copy of the OpenFlyers License and are unable to obtain it through the
 * web, please send a note to contact@openflyers.com so we can mail you
 * a copy immediately.
 *
 * @category    Javascript
 * @package     OpenFlyers
 * @author      Antoine VACHÉ <antoine.vache@openflyers.com>
 * @copyright   2008 OPENFLYERS S.A.R.L. <contact@openflyers.com>
 * @license     https://openflyers.com/fr/entreprise/conditions-generales  OpenFlyers License
 * @since       Thu Feb 14 2023
 */

/** Init global variables */
var isRowsEqual;
var row;
var rowId;
var trChildren;

/**
 * dragEnd
 * 
 * This method called with the attribute ondragend
 * When the dragged data is dropped, a dragend event occurs
 * 
 * @param {*} ajaxActionName, the name of the ajax script
 * @return void
 */
function dragEnd(ajaxActionName) {
    row.attributes[0].value = 'draggableRow';
    if ( isRowsEqual ) {
        var previousRowId = row.previousElementSibling.getAttribute('data-id');
        ajaxAction(ajaxActionName, onSuccessDraggableFunction, null, null, 'json', null, {'rowId' : rowId, 'previousRowId' : previousRowId});
    }
}

/**
 * dragOver
 *
 * This method called with the attribute ondragover
 * specifies where the dragged data can be dropped
 * 
 * @return void
 */
function dragOver() {
    event.preventDefault();
    if ((window.innerHeight - event.y) < (window.innerHeight/6)) window.scrollBy(0, 5);
    trChildren  = Array.from(event.target.parentNode.closest('tr').parentNode.children);
    isRowsEqual = event.target.parentNode.closest('tr').isEqualNode(row);

    if ((row !== undefined) && (row.getAttribute('class') !== undefined) && (trChildren.indexOf(event.target.parentNode.closest('tr')) !== 0) && !isRowsEqual) {
        if (trChildren.indexOf(event.target.parentNode.closest('tr')) > trChildren.indexOf(row)) {
            event.target.parentNode.closest('tr').after(row);
            row.attributes[0].value = 'draggableRow isDraggable';
        }
        else {
            event.target.parentNode.closest('tr').before(row);
            row.attributes[0].value = 'draggableRow isDraggable';
        }
    }
}

/**
 * dragStart
 *
 * This method called with the attribute ondragstart
 * specifies what data to be dragged.
 *
 * @return void
 */
function dragStart() {
    if (event.target.localName === 'tr') row = event.target;
    rowId = row.getAttribute('data-id');
}
