<?php

function wysiwyg_ckeditor_nice_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['editor']['name'] != 'ckeditor' || !isset($settings['toolbar'][0])) {
    return;
  }

  $tools = array_flip($settings['toolbar'][0]);
  $tools2 = $tools;

  $tools['-'] = 42;
  $map = _wysiwyg_ckeditor_nice_plugin_map();
  $items = 0;

  foreach ($map as $key => $toolgroup) {
    if ($toolgroup == '/') {
      // When there have been no items in this row
      // remove the seperator
      if ($items == 0) {
        unset($map[$key]);
      }

      $items = 0;
      continue;
    }

    if (!is_array($toolgroup)) {
      continue;
    }

    foreach ($toolgroup as $k => $tool) {
      if (!isset($tools[$tool])) {
        unset($map[$key][$k]);
      }
      else {
        unset($tools2[$tool]);
        $items++;
      }
    }

    if (count($map[$key]) == 0) {
      unset($map[$key]);
    }
    else {
      $map[$key] = array_values($map[$key]);
    }
  }

  // Unset excess separators
  foreach ($map as $row_key => $row) {
    $prev = '-';
    foreach ($row as $item_key => $item) {
      if ($item == '-' && $prev == '-') {
        unset($row[$item_key]);
      } else {
        $prev = $item;
      }
    }
    if (!empty($row) && end($row) == '-') {
      array_pop($row);
    }
    $row = array_values($row);
    if (empty($row)) {
      unset($map[$row_key]);
    } else {
      $map[$row_key] = $row;
    }
  }

  // Renumber
  $map[] = array_values(array_flip($tools2));
  $map = array_values($map);

  $settings['toolbar'] = $map;

  // Set language
  global $language;
  $settings['language'] = $language->language;
}

function _wysiwyg_ckeditor_nice_plugin_map() {
  $map = array(
    array('Source', '-', 'Save', 'NewPage', 'Preview', '-', 'Templates'),
    array('Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Print', 'SpellChecker', 'Scayt'),
    array('Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'),
    array('Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'),
    array('Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript'),
    array('NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote', 'CreateDiv'),
    array('JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'),
    array('Link', 'Unlink', 'Anchor'),
    array('Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'),
    array('Styles'),
    array('Format'),
    array('Font'),
    array( 'FontSize'),
    array('TextColor', 'BGColor'),
    array('Maximize', 'ShowBlocks', '-', 'About'),
  );

  return $map;
}
