<?php

/**
 * @file
 * Provides Colorbox support to YouTube Field display settings.
 */

/**
 * The machine name for the YouTube Colorbox link type used by display settings.
 */
define('YOUTUBE_COLORBOX_LINK_TYPE', 'colorbox');

/**
 * Implements hook_field_formatter_info_alter().
 */
function youtube_colorbox_field_formatter_info_alter(&$info) {
  $info['youtube_thumbnail']['settings'][YOUTUBE_COLORBOX_LINK_TYPE]['parameters'] = array(
    'width' => 640,
    'height' => 480,
    'autoplay' => '1',
  );
}

/**
 * Implements hook_youtube_thumbnail_link_types_alter().
 */
function youtube_colorbox_youtube_thumbnail_link_types_alter(&$link_types) {
  // Add the "Colorbox" link type to YouTube Field's thumbnail display settings.
  $link_types[YOUTUBE_COLORBOX_LINK_TYPE] = t('Colorbox');
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function youtube_colorbox_form_youtube_settings_form_alter(&$form, &$form_state) {
  // Provide warning about the need to set 'Enable Colorbox load' to TRUE in the
  // Colorbox module settings. Otherwise links provided by YouTube Colorbox will
  // not work as expected. This warning appears in the YouTube module settings.
  if (!variable_get('colorbox_load', FALSE)) {
    $args = array('!colorbox_settings' => l(t('Colorbox module settings'), 'admin/config/media/colorbox'));
    $message = t("Please enable 'Enable Colorbox load' in the !colorbox_settings for thumbnails linked by YouTube Field Colorbox to work as expected.", $args);
    drupal_set_message($message, 'warning');
  }
}

/**
 * Implements hook_youtube_thumbnail_field_formatter_settings_alter().
 */
function youtube_colorbox_youtube_thumbnail_field_formatter_settings_alter(&$element, $instance, $settings, $field_name) {
  $colorbox = $settings[YOUTUBE_COLORBOX_LINK_TYPE];

  // Set the states input name variable. JS states functionality will otherwise
  // break in Panels if the entity type is 'ctools'.
  $input_name = 'fields[' . $field_name . '][settings_edit_form][settings][image_link]';
  $input_name = ($instance['entity_type'] != 'ctools') ? $input_name : 'image_link';

  // Setting elements.
  $element[YOUTUBE_COLORBOX_LINK_TYPE] = array(
    '#type' => 'fieldset',
    '#title' => t('Colorbox Settings'),
    '#states' => array(
      'visible' => array(
        ':input[name="' . $input_name . '"]' => array('value' => YOUTUBE_COLORBOX_LINK_TYPE),
      ),
    ),
    '#tree' => TRUE,
  );
  $element[YOUTUBE_COLORBOX_LINK_TYPE]['parameters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Parameters'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $element[YOUTUBE_COLORBOX_LINK_TYPE]['parameters']['width'] = array(
    '#type' => 'textfield',
    '#title' => t('Width'),
    '#size' => 5,
    '#required' => TRUE,
    '#field_suffix' => 'px',
    '#default_value' => $colorbox['parameters']['width'],
    '#element_validate' => array('youtube_colorbox_element_is_int'),
  );
  $element[YOUTUBE_COLORBOX_LINK_TYPE]['parameters']['height'] = array(
    '#type' => 'textfield',
    '#title' => t('Height'),
    '#size' => 5,
    '#required' => TRUE,
    '#field_suffix' => 'px',
    '#default_value' => $colorbox['parameters']['height'],
    '#element_validate' => array('youtube_colorbox_element_is_int'),
  );
  $element[YOUTUBE_COLORBOX_LINK_TYPE]['parameters']['autoplay'] = array(
    '#type' => 'checkbox',
    '#title' => t('Play video automatically when loaded (autoplay).'),
    '#default_value' => $colorbox['parameters']['autoplay'],
    '#return_value' => 1,
  );
  $element[YOUTUBE_COLORBOX_LINK_TYPE]['parameters']['mute'] = array(
    '#type' => 'checkbox',
    '#title' => t('Mute video by default when loaded (mute).'),
    '#default_value' => $colorbox['parameters']['mute'],
    '#return_value' => 1,
  );
  $element[YOUTUBE_COLORBOX_LINK_TYPE]['parameters']['loop'] = array(
    '#type' => 'checkbox',
    '#title' => t('Loop the playback of the video (loop).'),
    '#default_value' => $colorbox['parameters']['loop'],
    '#return_value' => 1,
  );
  $element[YOUTUBE_COLORBOX_LINK_TYPE]['parameters']['controls'] = array(
    '#type' => 'checkbox',
    '#title' => t('Always hide video controls (controls).'),
    '#default_value' => $colorbox['parameters']['controls'],
    '#return_value' => 1,
  );
  $element[YOUTUBE_COLORBOX_LINK_TYPE]['parameters']['autohide'] = array(
    '#type' => 'checkbox',
    '#title' => t('Hide video controls after play begins (autohide).'),
    '#default_value' => $colorbox['parameters']['autohide'],
    '#return_value' => 1,
  );
  $element[YOUTUBE_COLORBOX_LINK_TYPE]['parameters']['iv_load_policy'] = array(
    '#type' => 'checkbox',
    '#title' => t('Hide video annotations by default (iv_load_policy).'),
    '#default_value' => $colorbox['parameters']['iv_load_policy'],
    '#return_value' => 3,
  );
  $element[YOUTUBE_COLORBOX_LINK_TYPE]['gallery'] = array(
    '#type' => 'checkbox',
    '#title' => t('Group all videos on the page into a gallery'),
    '#default_value' => $colorbox['gallery'],
  );
}

/**
 * An element validation callback to check if the value is a positive integer.
 */
function youtube_colorbox_element_is_int($element, $form_state, $form) {
  if (intval($element['#value']) < 1) {
    $args = array('@element_title' => $element['#title']);
    form_error($element, t('@element_title must be a positive integer value.', $args));
  }
}

/**
 * Implements hook_youtube_thumbnail_link_uri_alter().
 */
function youtube_colorbox_youtube_thumbnail_link_uri_alter(&$uri, &$settings, $item) {
  if ($settings['image_link'] != YOUTUBE_COLORBOX_LINK_TYPE) {
    return;
  }

  // Always open in an iframe for proper origin access.
  $settings[YOUTUBE_COLORBOX_LINK_TYPE]['parameters']['iframe'] = TRUE;

  // Field display settings.
  $parameters = $settings[YOUTUBE_COLORBOX_LINK_TYPE]['parameters'];

  // Invert parameters that should be 0 when their options are selected.
  $invert_parameters = array('controls');
  foreach ($invert_parameters as $parameter) {
    if (isset($parameters[$parameter])) {
      $parameters[$parameter] = $parameters[$parameter] ? 0 : 1;
    }
  }

  // Global YouTube module configuration.
  $domain = variable_get('youtube_privacy', FALSE) ? 'youtube-nocookie.com' : 'youtube.com';
  $player_class = variable_get('youtube_player_class', 'youtube-field-player');
  if (!variable_get('youtube_suggest', TRUE)) {
    $parameters['rel'] = '0';
  }
  if (variable_get('youtube_modestbranding', FALSE)) {
    $parameters['modestbranding'] = '1';
  }
  if (variable_get('youtube_theme', FALSE)) {
    $parameters['theme'] = 'light';
  }
  if (variable_get('youtube_color', FALSE)) {
    $parameters['color'] = 'white';
  }
  if (variable_get('youtube_enablejsapi', FALSE)) {
    global $base_url;
    $parameters['enablejsapi'] = '1';
    $parameters['origin'] = $base_url;
  }
  if (variable_get('youtube_wmode', TRUE)) {
    $parameters['wmode'] = 'opaque';
  }

  $uri = array(
    'path' => 'https://www.' . $domain . '/embed/' . $item['video_id'],
    'options' => array(
      'attributes' => array(
        'class' => array('colorbox-load', $player_class),
        'id' => drupal_html_id($player_class),
      ),
      'html' => TRUE,
      'external' => TRUE,
      'query' => $parameters,
    ),
  );

  if (!empty($settings[YOUTUBE_COLORBOX_LINK_TYPE]['gallery'])) {
    $uri['options']['attributes']['rel'] = 'youtube-gallery';
  }
}
