<?php
/**
 * @file
 */

// Drupal needs this blank file.

include_once('enterprise_base.features.inc');

function enterprise_base_menu() {

  $items['admin/structure/enterprise_base'] = array(
    'title' => 'Enterprise Apps',
    'description' => 'Structure configuration for enterprise apps.',
    'page callback' => 'enterprise_base_apps_structures_list',
    'access arguments' => array('administer widgets sets'),
    'type' => MENU_NORMAL_ITEM,
    'weight' => 0,
    'file' => 'enterprise_base.admin.inc',
  ); 
  $items['admin/structure/enterprise_base/blocks/edit/%enterprise_base_app_structures'] = array(
    'title' => 'Edit app blocks',
    'description' => 'Configure app block settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('enterprise_base_apps_structures_blocks_form', 5),
    'access arguments' => array('administer widgets sets'),
    'type' => MENU_CALLBACK,
    'file' => 'enterprise_base.admin.inc',
  ); 
  
  $items['enterprise_base/util'] = array(
    'title' => 'Enterprise base util',
    'page callback' => 'enterprise_base_util',
    'access callback' => TRUE,
    'access arguments' => FALSE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function enterprise_base_util() {
  return drupal_render(drupal_get_form('block_admin_display_form'));
	return '';
}

/**
 * Implements hook_theme().
 */
function enterprise_base_theme() {
  return array(
    // Theme functions in widget.module.
    // Theme functions in widget.admin.inc.
    'enterprise_base_apps_structures_list' => array(
      'variables' => array('apps_structures' => NULL),
    ),
  );
}

/**
 * Runs various cleanup tasks after a new app has been installed
 */
function enterprise_base_content_apps_install_cleanup() {
	drupal_flush_all_caches();
}

function enterprise_base_attach_field_inline_image($bundle_name, $entity_type = 'node') {
  $profile = variable_get('install_profile', 'standard');
  if ($profile != 'openenterprise') {
    return '';
  }
  $definition = enterprise_inline_field_definition();
  $fields = field_info_fields();

  if (!isset($fields['field_inline_image'])) {
    $field = $definition['field_config'];
    field_create_field($field);
  }
  else {  	
	  $field = $fields['field_inline_image'];
  }
	// check field does not already exist
	if (isset($field['bundles'][$entity_type]) && in_array($bundle_name, $field['bundles'][$entity_type])) {
		return;
	}

  $instance = $definition['field_instance'];
  $instance['bundle'] = $bundle_name;
  $instance['entity_type'] = 'node';  
  field_create_instance($instance);

  return;
}

function enterprise_inline_field_definition() {
  $field = array(
    'field_config' => array(
      'active' => '1',
      'cardinality' => '-1',
      'deleted' => '0',
      'entity_types' => array(),
      'field_name' => 'field_inline_image',
      'foreign keys' => array(
        'fid' => array(
          'columns' => array(
            'fid' => 'fid',
          ),
          'table' => 'file_managed',
        ),
      ),
      'indexes' => array(
        'fid' => array(
          0 => 'fid',
        ),
      ),
      'module' => 'image',
      'settings' => array(
        'default_image' => FALSE,
        'uri_scheme' => 'public',
      ),
      'translatable' => '0',
      'type' => 'image',
    ),
    'field_instance' => array(
      'bundle' => 'page',
      'deleted' => '0',
      'description' => 'Upload an image to insert in this node. After selecting the image, press "Insert" to add to the page.',
      'display' => array(
        'default' => array(
          'label' => 'hidden',
          'settings' => array(),
          'type' => 'hidden',
          'weight' => -1,
        ),
        'teaser' => array(
          'label' => 'hidden',
          'settings' => array(),
          'type' => 'hidden',
          'weight' => -1,
        ),
      ),
      'entity_type' => 'node',
      'field_name' => 'field_inline_image',
      'label' => 'Image',
      'required' => FALSE,
      'settings' => array(
        'alt_field' => TRUE,
        'file_directory' => 'inline-images',
        'file_extensions' => 'png gif jpg jpeg',
        'max_filesize' => '',
        'max_resolution' => '',
        'min_resolution' => '',
        'title_field' => TRUE,
        'user_register_form' => FALSE,
      ),
      'widget' => array(
        'module' => 'image',
        'settings' => array(
          'caption_from_title' => 1,
          'filefield_sources' => array(
            'filefield_sources' => array(
              'attach' => 0,
              'imce' => 'imce',
              'reference' => 'reference',
              'remote' => 'remote',
            ),
            'source_attach' => array(
              'absolute' => 0,
              'attach_mode' => 'copy',
              'path' => 'file_attach',
            ),
            'source_reference' => array(
              'autocomplete' => 0,
            ),
          ),
          'insert' => 1,
          'insert_class' => 'inline',
          'insert_default' => 'image',
          'insert_styles' => array(
            'auto' => 0,
            'image' => 'image',
            'image_large' => 'image_large',
            'image_medium' => 'image_medium',
            'image_thumbnail' => 'image_thumbnail',
            'link' => 0,
          ),
          'insert_width' => '',
          'preview_image_style' => 'thumbnail',
          'progress_indicator' => 'bar',
        ),
        'type' => 'image_image',
        'weight' => 40,
      ),
    ),
  );	
  return $field;
}

/**
 * Implements hook_menu_local_tasks_alter().
 */
function enterprise_base_menu_local_tasks_alter(&$data, $router_item, $root_path) {
//dsm($data);
//dsm($router_item);
//dsm($root_path);
  global $user;

  // assign active_type if view has a content type filter
  $active_type = FALSE;
  if((arg(0) != 'admin') && isset($router_item['page_callback']) &&  ($router_item['page_callback'] == 'views_page')) {
    //$view = views_page($router_item['page_arguments'][0], $router_item['page_arguments'][0]);
    $view = views_get_view($router_item['page_arguments'][0]);
    $tfilter = FALSE; 
//dsm($view);
    if (isset($view->display['default']->display_options['filters']['type'])) {
      $tfilter = $view->display['default']->display_options['filters']['type'];
    }
    $display = $router_item['page_arguments'][1];
    if (is_array($display)) {
      $display = array_shift($display);
    }
    if (isset($view->display[$display]->display_options['filters']['type'])) {
      $tfilter = $view->display[$display]->display_options['filters']['type'];
    }
    if ($tfilter) {
      if (($tfilter['table'] == 'node')) {
        if (!isset($tfilter['operator']) || ($tfilter['operator'] == 'in')) {
          $active_type = array_shift($tfilter['value']);
        }
      }
    }
  }
  
  // set active_type if enterprise_base view
  if (($root_path == 'nodes' || $root_path == 'node')) {
    $active_type = arg(1);
  }
  // set active_type if enterprise_base view
  if (($user->uid > 0) && ($root_path == 'node/%')) {
  	$node = node_load(arg(1));
    $active_type = $node->type;
  }

  
  if ($active_type) {
    $type = node_type_load($active_type);
    if (!isset($type->name)) {
      return;
    }
    $content_name = strtolower($type->name);
    $item = menu_get_item('node/add/' . str_replace('_', '-', $active_type));

    if ($item['access']) {
      $item['title'] = t('Add @type_name', array('@type_name' => strtolower($content_name)));
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $item,
      );
    }
    $href = 'admin/content/node/' . $active_type;
    $item = menu_get_item($href);
//dsm($item);
    if ($item['access']) {
      $item['href'] = $href;
      $item['title'] = t('Administer @type_name', array('@type_name' => $content_name));
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $item,
      );
    }
  }

  
  
  if ($root_path == 'admin/content' || (strpos($root_path, 'admin/content/node') === 0)) {
  	drupal_add_css(drupal_get_path('module', 'enterprise_base') . '/enterprise_base.content_admin.css');
  	$custom_view = ($root_path != 'admin/content') ? TRUE : FALSE;
    $active_type = arg(3);
    // if active type, clear + add content action
    if (isset($active_type)) {
    	unset($data['actions']['output'][0]);
    }
    $types = node_type_get_names();
    // add contextual add content type link
    if (isset($active_type) && $active_type) {
      $type_name = strtolower($types[$active_type]);
      $item = menu_get_item('node/add/' . str_replace('_', '-', $active_type));
      $item['title'] = t('Add @type_name', array('@type_name' => $type_name));
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $item,
      );
    }
    // add all sub-tab if on content to trigger display of subtabs on some themes (e.g. Rubik)
    $href = 'admin/content/node';
    $item = menu_get_item($href);    
    if ($item['access']) {
      $item['href'] = $href;
      $item['title'] = ' ' . t('All');
      $output = array(
        '#theme' => 'menu_local_task',
        '#link' => $item,
      );
      if (!isset($active_type)) {
        $output['#active'] = TRUE;
      }
      $data['tabs'][1]['output'][] = $output; 
    }  
    // add sub-tabs for content types
    $count = count($types) + 1;
    $data['tabs'][1]['count'] = $count;
    $i = 0;
    foreach ($types AS $type => $name) {
      $href = 'admin/content/node/' . $type;
      $item = menu_get_item($href);
      // if custom admin view exists for content type, skip adding sub-tab
      if ($item['path'] != 'admin/content/node') {
        continue;
      }
  //dsm($item);
      if ($item['access']) {
        $item['href'] = $href;
        $item['title'] = $name;
        $output = array(
            '#theme' => 'menu_local_task',
            '#link' => $item,
        );
        if ($type == $active_type) {
          $output['#active'] = TRUE;
        }
        $data['tabs'][1]['output'][] = $output;
      }
      $i++;
    } 
    usort($data['tabs'][1]['output'], '_enterprise_base_content_sort_tabs'); 
  } 
//dsm($data);
}

function _enterprise_base_content_sort_tabs($a, $b) {
  return strnatcmp($a['#link']['title'], $b['#link']['title']);
}

/**
 * Implement hook_form_alter
 * @param unknown_type $form
 * @param unknown_type $form_state
 * @param unknown_type $form_id
 */
function enterprise_base_form_alter(&$form, &$form_state, $form_id) {

	//dsm(LANGUAGE_NONE);
	if ($form_id == 'field_ui_field_edit_form') {
	  $options = array(
	    '' => t('Standard'),
	    'sidebar' => t('Sidebar'),
	    //'verticaltabs' => t('Vertical tabs'),
	  );
	  $field_name = $form['#field']['field_name'];
//dsm($form_state);
	  $default = '';
	  if (isset($form_state['build_info']['args'][0]['enterprise_edit_form_display'])) {
	  	$default = $form_state['build_info']['args'][0]['enterprise_edit_form_display'];
	  }
	  //if (isset($form_state['field'][$field_name][LANGUAGE_NONE]['instance']['enterprise_edit_form_display'])) {
    //  $default = $form_state['field'][$field_name][LANGUAGE_NONE]['instance']['enterprise_edit_form_display'];
    //}
	  $form['instance']['enterprise_edit_form_display'] = array(
	    '#type' => 'radios',
	    '#title' => t('Edit form display location'),
	    '#description' => t('Select where you want this field to display on the edit form. Sidebar is recommended for meta data.'),
	    '#default_value' => $default,
	    '#options' => $options,
	  );
	  //$form['#submit'][] = 'enterprise_base_form_field_ui_field_edit_form_submit';		
	}
	// use JavaScript to move 
	elseif (isset($form['#node_edit_form'])) {
    // if admin theme is Rubik, enhance node admin
		$theme = variable_get('admin_theme', 'bartik');
		$node_admin = variable_get('node_admin_theme', 'bartik');
		if (($theme != 'rubik') || (!$node_admin)) {
			return;
		}
		drupal_add_js(drupal_get_path('module', 'enterprise_base') . '/js/enterprise_base.edit_form.js');
		drupal_add_css(drupal_get_path('module', 'enterprise_base') . '/css/enterprise_base.edit_form.css');
		if (isset($form_state['field']) && is_array($form_state['field'])) {
		  foreach ($form_state['field'] AS $name => $field) {
		    if (!isset($field[LANGUAGE_NONE]['instance'])) {
		      continue;
		    }
		  	$field[LANGUAGE_NONE]['instance'] += array(
		  	  'enterprise_edit_form_display' => '',
		  	);
		  	$display = $field[LANGUAGE_NONE]['instance']['enterprise_edit_form_display'];
		  	if ($display == 'sidebar') {
          $form[$name]['#attributes']['class'][] = 'display_sidebar';
          // set field to scrollable if checkboxes or radios
          if (isset($form[$name][LANGUAGE_NONE]['#type']) && in_array($form[$name][LANGUAGE_NONE]['#type'], array('checkboxes', 'radios'))) {
          	$form[$name][LANGUAGE_NONE]['#attributes']['class'][] = 'scrollable';
          }
		  	}
		  	// if closed vocabular, add + add term link to field
		  	$fdata = $form_state['field'][$name][LANGUAGE_NONE];
		  	if (($fdata['field']['type'] == 'taxonomy_term_reference')  && ($fdata['instance']['widget']['type'] == 'options_buttons')) {
		  		$vocab_name = $fdata['field']['settings']['allowed_values'][0]['vocabulary'];

		  	  $item = menu_get_item("admin/structure/taxonomy/$vocab_name/add");
			    if ($item['access']) {
			    	$form[$name][LANGUAGE_NONE]['#attributes']['class'][] = 'with-action-links';
			    	// TODO work out styling
			      $form[$name][LANGUAGE_NONE]['#field_suffix'] = '<ul class="action-linksx"><li>' . l('+ ' . t('Add @name term', array('@name' => $vocab_name)), "admin/structure/taxonomy/$vocab_name/add", array('html' => TRUE, 'attributes' => array('target' => "_blank", 'class' => array('add-term-link')))) . '</li></ul>';
			      
			    }
		  	}
		  }
		}
		// move schedual
		if (isset($form['scheduler_settings'])) {
			unset($form['scheduler_settings']['#group']);
			unset($form['scheduler_settings']['#attached']);
			$form['scheduler_settings']['#title'] = $form['scheduler_settings']['publish_on']['#title'];
			unset($form['scheduler_settings']['publish_on']['#title']);
			$form['scheduler_settings']['#attributes']['class'][] = 'display_sidebar';	
			$form['scheduler_settings']['#weight'] = -10;
		}
		if (isset($form['metatags'])) {
			$form['metatags']['#weight'] = -20;
			
		}
	}
  //dsm($form_id);
  //dsm($form);
  //dsm($form_state); 	
}

function enterprise_base_app_structures_load($app) {
  $apps_structures = enterprise_base_apps_structures();
  return $apps_structures[$app];
}

function enterprise_base_apps_structures() {
  $apps_structures = &drupal_static(__FUNCTION__);

  // Grab from cache or build the array.
  if (!isset($sets)) {
    if (FALSE && $cache = cache_get('enterprise_base_apps_structures', 'cache')) {
      $apps_structures = $cache->data;
    }
    else {
      $apps_structures = array();

      // Select the module-defined sets.
      foreach (module_implements('enterprise_base_apps_structures') as $module) {
        $app_structures = module_invoke($module, 'enterprise_base_apps_structures');
        foreach ($app_structures as $app_name => $app_structure) {
          $app_structure['name'] = $app_name;
          $app_structure['module'] = $module;
          $apps_structures[$app_name] = $app_structure;
        }
      }
      drupal_alter('enterprise_base_apps_structures', $apps_structures);
      cache_set('enterprise_base_apps_structures', $apps_structures);
    }
  }

  return $apps_structures;
}

function enterprise_base_enterprise_base_apps_structures() {
  $structures = array();
  $structures['base'] = array(
    'title' => t('Base'),
  );
  $visibility = array(
    'all' => array(
      'title' => t('Show on all pages in the site'),
      'path' => array(
        'visibility' => 0,
        'pages' => '',
      ),
    ),
    'view' => array(
      'title' => t('Show only on the content list pages'),
      'path' => array(
        'visibility' => 1,
        'pages' => 'nodes*',
      ),
    ),
  );
  $structures['base']['blocks'] = array(
    'views:enterprise_content-block' => array(
      'defaults' => array(
        'regions' => array('sidebar_first'),
        'visibility' => 'view',
      ),
      'visibility' => $visibility,
    ),

  );
  return $structures;   
}

