<?php
/**
 * @file
 * The primary PHP file for the Solstice Bootstrap base theme.
 */

/**
 * Include common functions used through out theme.
 */
include_once dirname(__FILE__) . '/includes/common.inc';

include_once dirname(__FILE__) . '/includes/deprecated.inc';

include_once dirname(__FILE__) . '/includes/preprocess.inc';

include_once dirname(__FILE__) . '/includes/preprocess-node.inc';

include_once dirname(__FILE__) . '/includes/alter.inc';

/**
 * Overrides theme_breadcrumb().
 *
 * @param array $variables
 *        Template variables.
 *
 * @return string.
 */
function solstice_breadcrumb($variables) {
  $output = '';
  $breadcrumb = $variables['breadcrumb'];
  _solstice_remove_breadcrumb_link($breadcrumb);

  if (!empty($breadcrumb)) {
    if (isset($breadcrumb[2]) && $breadcrumb[2] == l('blog/0', t("'s blog"))) {
      // remove "user's blog"
      unset($breadcrumb[2]);
    }
  }

  // Determine if we are to display the breadcrumb.
  $bootstrap_breadcrumb = theme_get_setting('bootstrap_breadcrumb');
  if (($bootstrap_breadcrumb == 1 || ($bootstrap_breadcrumb == 2 && arg(0) == 'admin')) && !empty($breadcrumb)) {
    $output = theme('item_list', array(
      'attributes' => array(
        'class' => array(
          'breadcrumb'
        )
      ),
      'items' => $breadcrumb,
      'type' => 'ol'
    ));
  }

  if (empty($breadcrumb)) {
    $breadcrumb[] = l(t('Home'), '');
    $output = theme('item_list', array(
      'attributes' => array(
        'class' => array(
          'breadcrumb'
        )
      ),
      'items' => $breadcrumb,
      'type' => 'ol'
    ));
  }

  return $output;
}

/**
 * Implements hook_entity_info_alter().
 */
function solstice_entity_info_alter(&$entity_info) {
  $entity_info['user']['view modes']['teaser'] = array(
    'label' => t('Teaser'),
    'custom settings' => FALSE,
  );
}

/**
 * Overrides theme_feed_icon().
 *
 * @param array $variables
 *        Template variables.
 *
 * @return string.
 */
function solstice_feed_icon($variables) {
  $text = t('Subscribe to !feed-title', array(
    '!feed-title' => $variables['title']
  ));
  $classes[] = 'feed-icon';
  if (drupal_is_front_page() || current_path() === "papyrus-ic") {
    $classes[] = 'padding-right-15';
  }
  $image = '<i class="fa fa-rss-square fa-2x"></i>';
  return l($image, $variables['url'], array(
    'html' => TRUE,
    'attributes' => array(
      'class' => $classes,
      'title' => $text
    )
  ));
}

/**
 * Overrides theme_field__field_profile_taxonomy_interests().
 *
 * @param array $variables
 *        Template variables.
 *
 * @return string.
 */
function solstice_field__field_profile_taxonomy_interests($variables) {
  $values = array(
    '#theme' => 'item_list',
    '#items' => array(),
    '#title' => 'Interests',
    '#type' => 'ul',
    '#attributes' => array(
      'class' => 'list-inline'
    )
  );

  $children = element_children($variables['items']);
  foreach ($children as $key) {
    $path = 'interests/' . strtolower($variables['items'][$key]['#options']['entity']->tid);
    if (!drupal_valid_path($path)) {
      $path = $variables['items'][$key]['#href'];
    }

    $variables['items'][$key]['#href'] = $path;
    $variables['items'][$key]['#options']['attributes']['class'][] = 'small';
    $values['#items'][] = render($variables['items'][$key]);
  }

  return render($values);
}


/**
 * Overrides theme_field__field_profile_twitter_handle().
 *
 * @param array $variables
 *        Template variables.
 *
 * @return string Twitter widget link.
 */
function solstice_field__field_profile_twitter_handle($variables) {
  if (!empty($variables['element'][0]['#markup'])) {
    $handle = $variables['element'][0]['#markup'];
    if (!preg_match('/^[A-Za-z0-9_]{1,15}$/', $handle)) {
      // Invalid handle.
      return ' ';
    }
  }
  else {
    return ' ';
  }

  $url = 'https://twitter.com/' . $handle;
  $options = array(
    'attributes' => array(
      'class' => 'twitter-follow-button'
    )
  );
  return l(t('Follow @') . $handle, $url, $options);
}

/**
 * Implements theme_field_multiple_value_form().
 */
function solstice_field_multiple_value_form($variables) {
  $element = $variables['element'];

  $output = array();

  if (!empty($element[0]['#base_type']) && $element[0]['#base_type'] === 'textarea') {
    $element = $element[0];

    $required = !empty($element['#required']) ? theme('form_required_marker', $variables) : '';

    $output['content'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array('form-item'),
      ),
      'content' => array(),
    );

    if (!empty($element['#title'])) {
      if (!empty($element['value']['#title'])) {
        $element['value']['#title'] = "";
      }
      $output['content']['label'] = array(
        'value' => array(
          '#theme' => "html_tag",
          '#tag' => 'label',
          '#value' => t('!title !required', array(
            '!title' => $element['#title'],
            '!required' => $required,
          )),
          '#attributes' => array(
            'class' => array('control-label')
          )
        ),
        '#weight' => 0,
      );
    }

    if (empty($element['value']['#format'])) {
      $element['value']['#format'] = $element['#format'];
    }

    if (!empty($element['summary'])) {
      $output['content']['summary'] = array(
        'value' => $element['summary'],
        '#weight' => 1,
      );
    }

    if (!empty($element['value'])) {
      $output['content']['element'] = array(
        'value' => $element['value'],
        '#weight' => 3,
      );
    }

    if (!empty($element['format'])) {
      $output['content']['format'] = array(
        'value' => $element['format'],
        '#weight' => 4,
      );
    }

    if (!empty($element['#description'])) {
      $output['content']['description'] = array(
        '#type' => 'container',
        '#attributes' => array(
          'class' => array('help-block'),
        ),
        '#weight' => isset($element['#description_display']) && $element['#description_display'] === 'before' ? 2 : 20,
        0 => array('#markup' => filter_xss_admin($element['#description'])),
      );
    }
  }
  elseif (($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED)) {
    $table_id = drupal_html_id($element['#field_name'] . '_values');
    $order_class = $element['#field_name'] . '-delta-order';
    $required = !empty($element['#required']) ? theme('form_required_marker', $variables) : '';

    // Sort items according to '_weight' (needed when the form comes back after
    // preview or failed validation)
    $items = array();
    foreach (element_children($element) as $key) {
      if ($key === 'add_more') {
        $add_more_button =& $element[$key];
      }
      else {
        $items[] =& $element[$key];
      }
    }
    usort($items, '_field_sort_items_value_helper');

    $rows = array();
    // Add the items as table rows.
    foreach ($items as $key => $item) {
      $item['_weight']['#attributes']['class'] = array(
        $order_class,
      );
      $delta_element = drupal_render($item['_weight']);
      $cells = array(
        array(
          'data' => '',
          'class' => array(
            'field-multiple-drag',
          ),
        ),
        drupal_render($item),
        array(
          'data' => $delta_element,
          'class' => array(
            'delta-order',
          ),
        ),
      );
      $rows[] = array(
        'data' => $cells,
        'class' => array(
          'draggable',
        ),
      );
    }

    $output['content'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array('form-item'),
      ),
      'content' => array(),
    );

    $output['content']['label'] = array(
      'value' => array(
        '#theme' => "html_tag",
        '#tag' => 'label',
        '#value' => t('!title !required', array(
          '!title' => $element['#title'],
          '!required' => $required,
        )),
        '#attributes' => array(
          'class' => array('control-label')
        )
      ),
      '#weight' => 0,
    );
    $output['content']['element'] = array(
      '#markup' => theme('table', array(
        //'header' => $header,
        'rows' => $rows,
        'attributes' => array(
          'id' => $table_id,
          'class' => array(
            'field-multiple-table',
          ),
        ),
      )),
      '#weight' => 1,
    );
    $output['content']['add_more'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array('clearfix'),
      ),
      'value' => $add_more_button,
      '#weight' => 2,
    );
    $output['content']['description'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array('help-block'),
      ),
      '#weight' => isset($element['#description_display']) && $element['#description_display'] === 'before' ? 0 : 20,
      0 => array('#markup' => filter_xss_admin($element['#description'])),
    );

    drupal_add_tabledrag($table_id, 'order', 'sibling', $order_class);
  }
  else {
    foreach (element_children($element) as $key) {
      $output[] = $element[$key];
    }
  }
  return drupal_render($output);;
}

/**
 * Overrides theme_menu_local_tasks().
 *
 * @param array $variables
 *        Template variables.
 *
 * @return string.
 */
function solstice_menu_local_tasks(&$variables) {
  $output = '';
  if (!empty($variables['primary'])) {
    $variables['primary']['#prefix'] = '<h2 class="element-invisible">' . t('Primary tabs') . '</h2>';
    $variables['primary']['#prefix'] .= '<ul class="tabs--primary nav nav-tabs solstice-tabs">';
    $variables['primary']['#suffix'] = '</ul>';
    $output .= drupal_render($variables['primary']);
  }
  if (!empty($variables['secondary'])) {
    $variables['secondary']['#prefix'] = '<h2 class="element-invisible">' . t('Secondary tabs') . '</h2>';
    $variables['secondary']['#prefix'] .= '<ul class="tabs--secondary nav nav-tabs solstice-tabs">';
    $variables['secondary']['#suffix'] = '</ul>';
    $output .= drupal_render($variables['secondary']);
  }
  return $output;
}

/**
 * Overrides theme_flickr_photo().
 *
 * @param array $variables
 *        Template variables.
 *
 * @return string.
 */
function solstice_flickr_photo($variables) {
  $photo = $variables['photo'];
  $size = $variables['size'];
  $format = $variables['format'];
  $attribs = $variables['attribs'];
  $attribs['class'] = 'img-thumbnail';
  $img = flickr_img($photo, $size, $attribs);
  $photo_url = flickr_photo_page_url($photo['owner'], $photo['id']);
  $title = is_array($photo['title']) ? $photo['title']['_content'] : $photo['title'];
  return l($img, $photo_url, array(
    'attributes' => array(
      'title' => $title,
      'class' => array(
        'th'
      )
    ),
    'absolute' => TRUE,
    'html' => TRUE
  ));
}

/**
 * Implements hook_library().
 */
function solstice_library() {
  $options = array('scope' => 'footer', 'weight' => 99, 'group' => JS_THEME);
  $items['solstice_twitterwidget'] = array(
    'title' => t('Twitter widgets (JavaScript)'),
    'version' => '1.0',
    'js' => array(
      drupal_get_path('theme', 'solstice') . '/public/js/solstice_twitterwidget.js' => $options
    )
  );
  return $items;
}

/**
 * Overrides theme_menu_tree__main_menu().
 *
 * @param array $variables
 *        Template variables.
 *
 * @return string.
 */
function solstice_menu_tree__main_menu(&$variables) {
  return '<ul class="menu nav navbar-nav">' . $variables['tree'] . '</ul>';
}


/**
 * Implements theme_process_views_view_unformatted().
 */
function solstice_process_views_view_unformatted(&$variables, $hook) {

  $attributes = array();
  foreach ($variables['classes_array'] as $row_key => $classes) {
    $attributes[$row_key]['class'] = $classes;
  }

  foreach ($variables['attributes_array'] as $row_key => $attribute_array) {
    foreach ($attribute_array as $attribute_key => $attribute_value) {
      $attributes[$row_key][$attribute_key] = $attribute_value;
    }
  }

  $variables['solstice_attributes'] = array();
  foreach ($attributes as $row_key => $attribute) {
    $variables['solstice_attributes'][$row_key] = drupal_attributes($attribute);
  }
}

/**
 * Returns HTML for status and/or error messages, grouped by type.
 *
 * An invisible heading identifies the messages for assistive technology.
 * Sighted users see a colored box. See http://www.w3.org/TR/WCAG-TECHS/H69.html
 * for info.
 *
 * @param array $variables
 *        An associative array containing:
 *        - display: (optional) Set to 'status' or 'error' to display only
 *        messages
 *        of that type.
 *
 * @return string The constructed HTML.
 *
 * @see theme_status_messages() @ingroup theme_functions
 */
function solstice_status_messages($variables) {
  // Retrieve messages.
  $message_list = drupal_get_messages($variables['display']);
  return _solstice_static_messages($message_list);
}

/**
 * Generate an array for rendering the given person.
 *
 * @param $person
 *   A user object.
 * @param $view_mode
 *   View mode, e.g. 'full'.
 * @param $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
 *
 * @return
 *   An array as expected by drupal_render().
 */
function person_view($person, $view_mode = 'full', $langcode = NULL) {
  if (!isset($langcode)) {
    $langcode = $GLOBALS['language_content']->language;
  }

  $person->content = array();

  foreach ($person as $key => $value) {
    $person->content[$key] = $value;
  }

  global $base_url;

  if (!empty($person->content['full_name'])) {
    $person->content['full_name'] = array(
      '#theme' => "html_tag",
      '#tag' => 'span',
      '#value' => l($person->content['full_name'], 'https://accounts.eclipse.org/users/' . $person->name),
      '#attributes' => array(
        'class' => array('margin-right-5'),
      )
    );
  }

  if (!empty($person->content['display_badge_eca'])) {
    $person->content['badge_eca'] = array(
      '#markup' => '<img src="https://accounts.eclipse.org/user/eca/badge?mail=' . $person->email . '">'
    );
  }

  if (!empty($person->content['display_badge_committer'])) {
    $person->content['badge_committer'] = array(
      '#theme' => "html_tag",
      '#tag' => 'span',
      '#value' => "Committer",
      '#attributes' => array(
        'class' => array('badge', 'badge-blue'),
      )
    );
  }

  if (!empty($person->content['display_badge_project_lead'])) {
    $person->content['badge_project_lead'] = array(
      '#theme' => "html_tag",
      '#tag' => 'span',
      '#value' => "Project Lead",
      '#attributes' => array(
        'class' => array('badge', 'badge-blue'),
      )
    );
  }

  if (!empty($person->content['display_badge_pmc'])) {
    $person->content['badge_pmc'] = array(
      '#theme' => "html_tag",
      '#tag' => 'span',
      '#value' => "PMC",
      '#attributes' => array(
        'class' => array('badge', 'badge-blue'),
      )
    );
  }

  if (!empty($person->content['badge_extra'])) {
    foreach ($person->content['badge_extra'] as $badge_extra) {
      $person->content['badge_extra'] = array(
        '#theme' => "html_tag",
        '#tag' => 'span',
        '#value' => $badge_extra['title'],
      );
      if (empty($badge_extra['no-class'])) {
        $person->content['badge_extra']['#attributes']['class'] = array('badge', (!empty($badge_extra['class']) ? $badge_extra['class'] : ""));
      }
    }
  }

  if (empty($person->content['picture'])) {
    $loaded_user = user_load_by_name($person->name);
    if (empty($loaded_user)) {
      $loaded_user = drupal_anonymous_user();
    }
    $person->content['picture'] = theme('user_picture', array('account' => $loaded_user));
  }
  else {
    $image = array(
      'path' => $person->picture,
      'alt' => !empty($person->full_name) ? $person->full_name : "Profile picture",
      'attributes' => array(
        'class' => array(
          'img-responsive'
        )
      )
    );
    $person->content['picture'] = theme('image', $image);
  }

  $ef_icon = theme('image', array(
    'path' => $base_url . '/' . drupal_get_path('theme', 'solstice') .'/public/images/logo/eclipse-foundation-icon-black.svg',
    'width' => '16',
    'attributes' => array(
      'style' => 'margin-top:-4px;display:inherit;'
    ),
  ));

  $person->content['ef_username'] = array(
    '#theme' => "html_tag",
    '#tag' => 'span',
    '#value' => $ef_icon . ' ' . $person->name,
    '#attributes' => array(
      'class' => array('margin-right-15'),
    )
  );

  if (!empty($person->github_id)) {
    $person->content['github_id'] = array(
      '#theme' => "html_tag",
      '#tag' => 'span',
      '#value' => '<i class="fa fa-github"></i> ' . $person->github_id,
      '#attributes' => array(
        'class' => array('margin-right-15'),
      )
    );
  }

  $person->content['email'] = array(
    '#theme' => "html_tag",
    '#tag' => 'span',
    '#value' => '<i class="fa fa-envelope"></i> ' . $person->email,
    '#attributes' => array(
      'class' => array('margin-right-15'),
    )
  );

  $build = $person->content;

  unset($person->content);
  $build += array(
    '#theme' => 'solstice_person_profile',
    '#person' => $person,
    '#view_mode' => $view_mode,
    '#language' => $langcode,
  );

  return $build;
}

/**
 * Implements hook_theme().
 */
function solstice_theme($existing, $type, $theme, $path) {
  return array(
    'solstice_person_profile' => array(
      'render element' => 'elements',
      'template' => 'person-profile',
      'path' =>  drupal_get_path('theme', 'solstice') . '/templates/solstice'
    ),
    'site_login_contact_submission_node_form' => array(
      'render element' => 'form',
      'template' => 'site-login-contact-submission',
      'path' => drupal_get_path('theme', 'solstice') . '/templates/forms',
    ),
  );

}

/**
 * Implements hook_process_HOOK().
 */
function solstice_process_solstice_person_profile(&$variables) {
  $variables['container']['classes'] = implode(' ', $variables['container']['classes_array']);
}

/**
 * Implements hook_preprocess_HOOK().
 */
function solstice_preprocess_solstice_person_profile(&$variables) {

  // Helpful $user_profile variable for templates.
  foreach (element_children($variables['elements']) as $key) {
    $variables['person_profile'][$key] = $variables['elements'][$key];
  }

  if ($variables['elements']['#view_mode'] === "teaser") {
    $variables['container']['classes_array'][] = "solstice-block-white-bg";
    $variables['container']['classes_array'][] = "person-profile-teaser";
  }
}

/**
 * Theming function for messages.
 */
function solstice_modr8_message($variables) {
  $teaser = $variables['0'];
  $nodetype = $variables['1'];
  $op = $variables['2'];
  static $already_messaged = FALSE;
  // Don't add the message more than once per page load.
  if ($already_messaged) {
    return;
  }
  if ($teaser) {
    return ' <div class="margin-top-10 margin-bottom-10"><span class="label label-danger">' . t('Pending moderation') . '</span></div>';
  }
  else {
    switch ($op) {
      case 'view':
        drupal_set_message(t("The post has been submitted for moderation and won't be listed publicly until it has been approved."), 'warning');
        break;
      case 'node_form':
        if (!user_access('bypass moderation queue')) {
          drupal_set_message(t('This %type will be submitted for moderation and will not be accessible to other users until it has been approved.', array('%type' => node_type_get_name($nodetype))));
        }
        break;
    }
  }
  $already_messaged = TRUE;
}

/**
* Implements hook_html_head_alter().
*/
function solstice_html_head_alter(&$head_elements) {
  unset($head_elements['system_meta_generator']);
  unset($head_elements['metatag_generator_0']);
}