<?php

/**
* Implements hook_menu().
*/
function ctools_automodal_admin_menu() {
  $items['admin/config/system/ctools_automodal_admin'] = array(
    'title' => t('Ctools Automodal Settings'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ctools_automodal_admin_admin_settings_form'),
    'access arguments' => array('administer modules'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'includes/ctools_automodal_admin.admin.inc'
  );
  return $items;
}

function ctools_automodal_admin_init() {
  ctools_include('modal');
  ctools_modal_add_js();
}

/**
* Implements hook_modal_paths() of ctools_automodal module.
*/
function ctools_automodal_admin_menu_alter(&$items) {
  $paths = array();
  $automodal_paths = variable_get('ctools_automodal_admin_extra_paths', array());
  foreach ($automodal_paths as $item) {
    $items[$item]['modal'] = TRUE;
  }
  $modal_content_types = variable_get('ctools_automodal_admin_modal_content_types', array());
  foreach ($modal_content_types as $item) {
    $items[$item]['modal'] = TRUE;
  }
  return $paths;
}

/**
* Implements hook_form_node_form_alter(&$form, &$form_state, $form_id).
*/
function ctools_automodal_admin_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Check if node form is automodal.
  // If it is, add own submit function.
  $node = $form_state['node'];
  $modal_content_types = variable_get('ctools_automodal_admin_modal_content_types', array());
  if (isset($modal_content_types[$node->type]) && $modal_content_types[$node->type]) {
    // Check if it's ajax request
    if (isset($_POST['js']) || isset($_POST['ajax_html_ids'])) {
      $form['actions']['submit']['#submit'][] = 'ctools_automodal_admin_add_content_submit';
    }
  }
}

function ctools_automodal_admin_add_content_submit($form, &$form_state) {
  // Call the rest of submits, because after this submit script will end.
  $submits = $form['actions']['submit']['#submit'];
  // Find the rest of submits.
  foreach ($submits as $key => $item) {
    unset($submits[$key]);
    if ($item == 'ctools_automodal_admin_add_content_submit') {
      break;
    }
  }
  // Call it.
  foreach ($submits as $function) {
    if (function_exists($function)) {
      $function($form, $form_state);
    }
  }
  // Redirect to destination, if set, or to node path.
  if (isset($_GET['destination'])) {
    $destination = drupal_get_destination();
    ctools_automodal_admin_ajax_redirect($destination['destination']);
  }
  else if (isset($form_state['redirect'])) {
    ctools_automodal_admin_ajax_redirect($form_state['redirect']);
  }
}

function ctools_automodal_admin_ajax_redirect($path) {
  ctools_include('ajax');
  ctools_add_js('ajax-responder');
  $commands[] = ctools_modal_command_dismiss();
  $commands[] = ctools_ajax_command_redirect($path);
  print ajax_render($commands);
  exit();
}