/**
 * Remove video.
 */
function spider_video_player_remove_row(id) {
  tr = document.getElementById(id);
  tr.parentNode.removeChild(tr);
  spider_video_player_refresh();
}

/**
 * Move up videos.
 */
function spider_video_player_up_row(id) {
  // Current div wich must be moved.
  var cur_node = document.getElementById(id);
  // Current div's parent div.
  var parent_node = cur_node.parentNode;
  spider_video_player_remove_spaces(parent_node);
  // Parent div's childs array.
  var child_nodes = parent_node.childNodes;
  for (var i = 1; i < child_nodes.length; i++) {
    if (child_nodes[i] == cur_node) {
      // Current div's previous div.
      var previous_node = child_nodes[i - 1];
    }
  }
  // Insert current div before previous div.
  if (previous_node) {
    parent_node.insertBefore(cur_node, previous_node);
  }
  spider_video_player_refresh();
}

/**
 * Move down videos.
 */
function spider_video_player_down_row(id) {
  // Current div wich must be moved.
  var cur_node = document.getElementById(id);
  // Current div's parent div.
  var parent_node = cur_node.parentNode;
  spider_video_player_remove_spaces(parent_node);
  // Parent div's childs array.
  var child_nodes = parent_node.childNodes;
  for (var i = 0; i < child_nodes.length - 1; i++) {
    if (child_nodes[i] == cur_node) {
      // Current div's next div.
      var next_node = child_nodes[i + 1];
    }
  }
  // Insert next div before current div.
  if (next_node) {
    parent_node.insertBefore(next_node, cur_node);
  }
  spider_video_player_refresh();
}

/**
 * Set videos sequence.
 */
function spider_video_player_refresh() {
  var tbody = document.getElementById('video_list');
  var tox = '';
  for (var x = 0; x < tbody.childNodes.length; x++) {
    tr = tbody.childNodes[x];
    if (tbody.childNodes[x].innerHTML) {
      tox = tox + tr.getAttribute('video_id') + ',';
    }
  }
  document.getElementById('added_videos').value = tox;
}

/**
 * Remove witespaces from childNodes.
 */
function spider_video_player_remove_spaces(parent) {
  if (!parent) {
    parent = document;
  }
  var children = parent.childNodes;
  for (var i = children.length - 1; i >= 0; i--) {
    var child = children[i];
    if (child.nodeType == 3) {
      if (child.data.match(/^\s+$/)) {
        parent.removeChild(child);
      }
    }
    else {
      spider_video_player_remove_spaces(child);
    }
  }
}
