<?php

/**
 * @file
 * Implements the necessary hooks for the editor to work properly.
 */

/**
 * Implementation of hook_menu().
 */
function bueditor_menu() {
  $items = array();
  $path = 'admin/settings/bueditor';
  $common = array('access arguments' => array('administer bueditor(execute PHP)'), 'file' => 'admin/bueditor.admin.inc');
  $form = array('page callback' => 'drupal_get_form', 'type' => MENU_CALLBACK) + $common;
  $items[$path] = $common + array(
    'title' => 'BUEditor',
    'description' => 'Customize your text editor.',
    'page callback' => 'bueditor_admin',
  );
  $items[$path .'/new'] = $form + array(
    'title' => 'Add new editor',
    'page arguments' => array('bueditor_editor_form'),
  );
  $items[$path .'/import'] = $form + array(
    'title' => 'Import editor',
    'page arguments' => array('bueditor_editor_import_form'),
  );
  $items[$path .'/%bueditor_editor'] = $form + array(
    'title' => 'Editor settings',
    'page arguments' => array('bueditor_editor_form', 3),
  );
  $items[$path .'/%bueditor_editor/delete'] = $form + array(
    'title' => 'Delete editor',
    'page arguments' => array('bueditor_delete_form', 3),
  );
  return $items;
}

/**
 * Implementation of hook_perm().
 */
function bueditor_perm() {
  return array('administer bueditor(execute PHP)');
}

/**
 * Implementation of hook_theme().
 */
function bueditor_theme() {
  $theme['bueditor_admin']['function'] = 'bueditor_admin_theme';
  $theme['bueditor_editor']['function'] = 'bueditor_editor_theme';
  return $theme;
}

/**
 * Implementation of hook_elements().
 */
function bueditor_elements() {
  return array('textarea' => array('#process' => array('bueditor_textarea')));
}

/**
 * Integrate the editor into textareas.
 */
function bueditor_textarea($element) {
  bueditor_inc();
  return _bueditor_textarea($element);
}

/**
 * Include necessary js and css files for editor settlement.
 */
function bueditor_settle($editor) {
  bueditor_inc();
  return _bueditor_settle($editor);
}

/**
 * load editor by id. used by menu system
 */
function bueditor_editor_load($eid) {
  return db_fetch_object(db_query("SELECT * FROM {bueditor_editors} WHERE eid = %d", $eid));
}

/**
 * Implementation of hook_file_download().
 */
function bueditor_file_download($file) {
  if (strpos($file, variable_get('bueditor_sprites_dir', 'bueditor-sprites') . '/') === 0) {
    $path = file_create_path($file);
    return array('Content-type: '. file_get_mimetype($path), 'Content-Length: '. filesize($path));
  }
}

/**
 * Load bueditor.inc file
 */
function bueditor_inc() {
  static $loaded;
  if (!isset($loaded)) {
    include_once './' . drupal_get_path('module', 'bueditor') . '/bueditor.inc';
    $loaded = TRUE;
  }
}