<?php

/**
 * Implements hook_form_formID_alter().
 */
function imce_mkdir_form_imce_profile_form_alter(&$form, &$form_state) {
  include_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'imce_mkdir') . '/imce_mkdir.inc';
  return _imce_mkdir_form_imce_profile_form_alter($form, $form_state);
}

/**
 * Custom profile process. Redefines mkdir permission based on some other parameters.
 */
function imce_mkdir_process_profile(&$imce) {
  if (!$imce['error']) {
    $imce['mkdirnum'] = (int) $imce['mkdirnum'];
    $imce['perm']['mkdir'] = $imce['perm']['mkdir'] && (!$imce['mkdirnum'] || ($imce['direct'] && $imce['mkdirnum'] > count($imce['subdirectories'])));
    $imce['perm']['rmdir'] = $imce['perm']['rmdir'] && (!$imce['mkdirnum'] || $imce['direct']);
  }
}

/**
 * Custom content. Returns directory creation form
 */
function imce_mkdir_content(&$imce) {
  if (!$imce['error'] && (imce_perm_exists($imce, 'mkdir') || imce_perm_exists($imce, 'rmdir'))) {
    $path = drupal_get_path('module', 'imce_mkdir');
    drupal_add_js($path . '/imce_mkdir.js');
    drupal_add_css($path . '/imce_mkdir.css');
    $form = drupal_get_form('imce_mkdir_form', array('imce' => &$imce));
    return drupal_render($form);
  }
}

/**
 * Mkdir form.
 */
function imce_mkdir_form($form, &$form_state, $ref) {
  $imce =& $ref['imce'];
  include_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'imce_mkdir') . '/imce_mkdir.inc';
  return _imce_mkdir_form($form, $form_state, $imce);
}

/**
 * Ajax operation: mkdir
 */
function imce_js_mkdir(&$imce) {
  if ($imce['perm']['mkdir']) {
    $_POST['op'] = t('Add');
    drupal_get_form('imce_mkdir_form', array('imce' => &$imce));
    return array('diradded' => array_map('rawurlencode', $imce['diradded']));
  }
}

/**
 * Ajax operation: rmdir
 */
function imce_js_rmdir(&$imce) {
  if ($imce['perm']['rmdir']) {
    $_POST['op'] = t('Remove');
    drupal_get_form('imce_mkdir_form', array('imce' => &$imce));
    return array('dirremoved' => array_map('rawurlencode', $imce['dirremoved']));
  }
}