<?php
/**
 * @file
 * Drupal needs this blank file.
 */

include_once 'diy_structure.features.inc';

/**
 * Implementation of hook_init().
 */
function diy_structure_init() {
  if(!path_is_admin(current_path())) {
    //Javascript um einen Text im Eingabefeld vorzuschlagen
    //drupal_add_js('function inputChange(el, text) { if(el.value == \'\') el.value = text; else el.value = \'\';}');
    drupal_add_js(drupal_get_path('module', 'diy_structure') . '/js/structure.js');
  }

  // Async pinterest load
  drupal_add_js("(function(d){
          var f = d.getElementsByTagName('SCRIPT')[0], p = d.createElement('SCRIPT');
          p.type = 'text/javascript';
          p.async = true;
          p.src = '//assets.pinterest.com/js/pinit.js';
          f.parentNode.insertBefore(p, f);
        }(document));",
    array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
  );

  // Setup rich snippets for google
  diy_structure_rich_snippet_setup();
}

/**
 * Setup rich snippets for google
 */
function diy_structure_rich_snippet_setup() {

  // set rating tags
  if($node = menu_get_object()) {

    // setup informations for structured data
    $config = array(
      'article'     => array(
        'type' => 'Article',
        'images' => array(
          'field_article_teaser_upload',
          'field_header_image',
          'field_image'
        ),
        'rate' => 'field_rate_article'
      ),
      'material'    => array(
        'type' => 'Article',
        'images' => array(
          'field_tools_teaser_upload'
        ),
        'rate' => 'field_rate_article'
      ),
      'ct_werkzeug' => array(
        'type' => 'Article',
        'images' => array(
          'field_tools_teaser_upload'
        ),
        'rate' => 'field_rate_article'
      ),
      'news' => array(
        'type' => 'NewsArticle',
        'images' => array(
          'field_header_image'
        )
      )
    );

    if(in_array($node->type, array_keys($config))) {
      $current_config = $config[$node->type];

      // we need at one image (required for google)
      if($field_teaser = field_get_items('node', $node, $current_config['images'][0])) {

        $title = check_plain($node->title);
        $created = date_iso8601($node->created);
        $updated = date_iso8601($node->changed);

        $images = array(image_style_url('richsnippet', $field_teaser[0]['uri']));

        if(count($current_config['images']) > 1) {
          $image_fields = $current_config['images'];
          array_shift($image_fields);

          foreach($image_fields as $image_field) {
            if($field_image = field_get_items('node', $node, $image_field)) {
              $images[] = image_style_url('richsnippet', $field_image[0]['uri']);
            }
          }
        }

        $structured_data = array(
          "@context" => "http://schema.org/",
          "@type" => $current_config['type'],
          "headline" => $title,
          "datePublished" => $created,
          "dateModified" => $updated,
          "image" => $images,
          "author" => array(
            "@type" => 'Person',
            "name" => $node->name
          ),
          "publisher" => array(
            "@type" => 'Organization',
            "name" => variable_get('site_name', ''),
            "logo" => array(
              "@type" => 'ImageObject',
              "url" => file_create_url(drupal_get_path('theme', 'diy') . '/images/logo_structured_data.jpg')
            )
          )
        );

        diy_structure_rich_snippet_rating($structured_data, $current_config, $node);

        $element = array(
          '#type' => 'markup',
          '#markup' => '<script type="application/ld+json">' . str_replace('\\/', '/', json_encode($structured_data))  . '</script>',
        );
        drupal_add_html_head($element, 'google-structured-data-markup');


      }
    }
  }
}

/**
 * Implements HOOK_html_head_alter().
 */
function diy_structure_html_head_alter(&$head_elements) {
  // the amp modules adds metadata but does not offer the option to disable that
  // since we add metadata ourself, lets remove the amp-data
  if(isset($head_elements['amp_metadata'])) {
    unset($head_elements['amp_metadata']);
  }
}

/**
 * Add data for rating informations
 *
 * @param $structured_data
 * @param $config
 */
function diy_structure_rich_snippet_rating(&$structured_data, $config, $node) {
  // only try to add rating informations, when field is defined in config
  if(!isset($config['rate'])) {
    return;
  }

  $field_name = $config['rate'];
  $field_info = field_info_field($field_name);
  $field_info_instance = field_info_instance('node', $field_name, $node->type);

  $tag = $field_info['settings']['axis'];
  $stars = $field_info_instance['settings']['stars'];

  $votes = fivestar_get_votes('node', $node->nid, $tag, FALSE);

  if(isset($votes['average']['value']) && isset($votes['count']['value'])) {
    $rating = round(($votes['average']['value']/100) * $stars, 1);
    $count = $votes['count']['value'];

    $structured_data["aggregateRating"] = array(
      "@type" => "AggregateRating",
      "ratingValue" => $rating,
      "bestRating" => $stars,
      "worstRating" => "1",
      "ratingCount" => $count
    );
  }
}

/**
 * Provides path prefix
 */
function diy_structure_get_path_prefix($node_type, $language) {
  $prefix = array(
    'article' => array(
      'de' => 'wissen',
      'en' => 'knowledge',
      'und' => 'knowledge'
    ),
    'material' => array(
      'de' => 'wissen',
      'en' => 'knowledge',
      'und' => 'knowledge'
    ),
    'ct_werkzeug' => array(
      'de' => 'wissen',
      'en' => 'knowledge',
      'und' => 'knowledge'
    )
  );

  if(isset($prefix[$node_type][$language])) {
    return $prefix[$node_type][$language];
  }

  return $node_type;
}


function diy_structure_get_tags_field($node_type) {
  $tags = array(
    'article' => 'field_business',
    'material' => 'field_tools_category',
    'ct_werkzeug' => 'field_tools_category'
  );

  return $tags[$node_type];
}

function diy_structure_get_tags_field_cannonical($node_type) {
  $tags = array(
    'article' => 'field_business_canonical',
    'material' => 'field_tools_canonical_category',
    'ct_werkzeug' => 'field_tools_canonical_category'
  );

  return $tags[$node_type];
}

/**
 * Provides support node types
 */
function diy_structure_check_node_types($type) {
  $supported = array('article', 'material', 'ct_werkzeug');

  if(in_array($type, $supported)) {
    return true;
  }

  return false;
}

/**
 * Creating URL Alias for each Article
 */
function diy_structure_node_presave($node) {
  include_once drupal_get_path('module', 'pathauto') . '/pathauto.inc';

  if(diy_structure_check_node_types($node->type)) {
    // first, delete all existing alias entries

    // path is language sensitive
    $language = !empty($node->language) ? $node->language : LANGUAGE_NONE;

    // TODO make language sensible
    db_delete('url_alias')
      ->condition('source', 'node/' . $node->nid)
      ->condition('language', $language)
      ->execute();

    // provide vocab name hardcoded
    //$translated_vocabulary_name = diy_structure_get_path_prefix($node->type, $language);

    // Prepare all other aliases
    // Do not create the same as in cannoncial_business
    /*$terms = field_get_items('node', $node, diy_structure_get_tags_field($node->type), $language);

    // If there are any terms selected
    if(is_array($terms)) {
      foreach($terms as $term) {
        $tid = $term['tid'];

        // Load current term
        $term = taxonomy_term_load($tid);
        $term_name = $term->name;

        // Load parent because we should be on level 1
        // level 0 -> maler
        // level 1 -> verputzen
        $parent = taxonomy_get_parents($tid);

        // if no parent -> something is wrong -> no alias
        if($parent) {
          $parent = reset($parent);

          $vocab = taxonomy_vocabulary_load($parent->vid);

          $parent_url = url('taxonomy/term/' . $parent->tid);
          $parent_url = ltrim($parent_url, '/');
          $parent_url_parsed =language_url_split_prefix($parent_url, language_list());
          $parent_url = $parent_url_parsed[1];

          // otherweise, create alias, yeah!
          $new_alias = $parent_url .'/'. pathauto_cleanstring($term_name) .'/'. pathauto_cleanstring($node->title);

          $path = array(
            'source' => 'node/' . $node->nid,
            'alias' => $new_alias,
          );

          $path['language'] = $language;

          path_save($path);
        }
      }
    }*/

    // create cannonical alias
    $cannonical_term = field_get_items('node', $node, diy_structure_get_tags_field_cannonical($node->type), $language);
    if($cannonical_term) {
      $cannonical_term = reset($cannonical_term);
      $ctid = $cannonical_term['tid'];

      // eg Verputzen
      $cterm = taxonomy_term_load($ctid);
      $cterm_name = $cterm->name;

      // eg Maler
      $cparent = taxonomy_get_parents($ctid);

      if($cparent) {
        $cparent = reset($cparent);

        $vocab = taxonomy_vocabulary_load($cparent->vid);

        $cparent_url = drupal_get_path_alias('taxonomy/term/' . $cparent->tid);
        $cparent_url = ltrim($cparent_url, '/');
        $cparent_url_parsed =language_url_split_prefix($cparent_url, language_list());
        $cparent_url = $cparent_url_parsed[1];

        // eg wissen/maler/verputzen/kantenschutz...
        $new_alias = $cparent_url .'/'. pathauto_cleanstring($cterm_name) .'/'. pathauto_cleanstring($node->title);

        // first, check if alias exists
        // e.g. cannonical business
        $existing_alias = drupal_lookup_path('source', $new_alias, $language);

        // cannonical alias was is other list too - delete this item
        if($existing_alias) {
          db_delete('url_alias')
            ->condition('alias', $new_alias)
            ->execute();
        }

        $path = array(
          'source' => 'node/' . $node->nid,
          'alias' => $new_alias,
        );

        $path['language'] = $language;

        path_save($path);
      }
    }
  }
}

/**
 * Function for retrieving custom url alias
 *
 * $node nodeobject to be printed
 * $term termobject from url
 *
 * @return path alias
 */
function diy_structure_get_url($node, $term) {
  include_once drupal_get_path('module', 'pathauto') . '/pathauto.inc';

  $term_url = url('taxonomy/term/' . $term->tid);
  $term_url = ltrim($term_url, '/');
  $term_url_parsed =language_url_split_prefix($term_url, language_list());
  $term_url = $term_url_parsed[1];


  $language = !empty($node->language) ? $node->language : LANGUAGE_NONE;
  //$translated_vocabulary_name = diy_structure_get_path_prefix($node->type, $language);

  // first, construct correct alias

  // get parent of our term eg Maler
  $parent = taxonomy_get_parents($term->tid);

  // if there is a parent, we are lucky
  // current channel page is eg maler/verputzen
  // if there is no parent, we are at maler, so we have to chooce one term down the tree
  if($parent) {
    $parent = reset($parent);

    $parent_url = url('taxonomy/term/' . $parent->tid);
    $parent_url = ltrim($parent_url, '/');
    $parent_url_parsed =language_url_split_prefix($parent_url, language_list());
    $parent_url = $parent_url_parsed[1];

    $vocab = taxonomy_vocabulary_load($parent->vid);

    $alias = $parent_url .'/'. pathauto_cleanstring($term->name) .'/'. pathauto_cleanstring($node->title);

  } else {

    // retrieve all child of current term
    $tree = taxonomy_get_tree(5, $term->tid);
    $vocab = taxonomy_vocabulary_load(5);

    // look if one is suiteable
    // return asap
    foreach($tree as $t) {
      // candidate alias
      $alias =  $term_url .'/'. pathauto_cleanstring($t->name) .'/'. pathauto_cleanstring($node->title);

      $node_alias = drupal_lookup_path('source', $alias, $language);

      if($node_alias == 'node/' . $node->nid) break;
    }
  }

  // second, check if it exists and return value
  if(isset($alias)) {
    $node_alias = drupal_lookup_path('source', $alias, $language);
    if($node_alias == 'node/' . $node->nid) return url($alias);
  }

  // if not we have to return internal representation
  return url('node/'. $node->nid);
}

/**
 * Implementation of HOOK_form_alter().
 */
function diy_structure_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_login') {
    // set new page title
    drupal_set_title(t('Log In'));

    // unset not needed stuff
    unset($form['name']['#description']);
    unset($form['pass']['#description']);

    // add link to register
    $form['register_link'] = array(
      '#type'   => 'item',
      '#weight' => -21,
      '#title'  => t('Register'),
      '#markup' => t('No account yet?')  . ' ' . l(t('Signup!'), 'user/register')
    );

    // Add password request link
    $form['submit']['#prefix'] = l(t('Forgot your password?'), 'user/password', array('attributes' => array('class' => 'password-link')));
  }
}

/**
 * Implementation of HOOK_form_FORM_alter().
 */
function diy_structure_form_comment_form_alter(&$form, &$form_state) {

  // overwrite title only on comment replay page
  // not on save comment at article
  if(isset($form['#action']) && arg(0) == 'comment' && arg(1) == 'reply') {
    drupal_set_title(t('Answer to comment'));
  }
};

/**
 * Generates title for comment reply page
 */
function diy_structure_get_comment_reply_title($nid, $cid) {
  $node = node_load($nid);

  $node_title = $node->title;

  $parent_comment = comment_load($cid);
  $comment_title = $parent_comment->name;

  $title = t('!comment_title answer | !node_title on !node_date | Comment @', array('!comment_title' => $comment_title, '!node_title' => $node_title, '!node_date' => format_date($node->created, 'custom', 'd.m.Y')));

  return $title;
}

/**
 * Implementation of HOOK_menu_alter().
 */
function diy_structure_menu_alter(&$items) {
  // Hide unwanted tabs
  $items['user']['type'] = MENU_CALLBACK;
  $items['user/register']['type'] = MENU_CALLBACK;
  $items['user/password']['type'] = MENU_CALLBACK;

}

/**
 * Implementation of HOOK_preprocess_views_view_fields().
 */
function diy_structure_preprocess_views_view_fields(&$variables) {
  // add video to title display

  if($variables['view']->name == 'sidebar_videos' || $variables['view']->name == 'similar_videos') {
    if(isset($variables['fields']['title'])) {
      $old_output = $variables['fields']['title']->content;

      $node = node_load($variables['row']->nid);
      $video = field_get_items('node', $node, 'field_video_youtube');

      if(isset($video[0]['video_id'])) {
        $video_id = $video[0]['video_id'];

        if($variables['view']->row_index == 0) {
          // generate video output
          $options = array(
            'video_id' => $video_id,
            'image_style' => 'youtube_sidebar'
          );

          $youtube_image = theme('youtube_thumbnail', $options);
          $youtube_link = l($youtube_image, 'node/'. $node->nid, array('html' => TRUE));

          $old_output = $youtube_link;

          $variables['fields']['title']->content = $youtube_link;
        } else {
          // generate video output
          $options = array(
            'video_id' => $video_id,
            'image_style' => 'youtube_sidebar_thumb'
          );

          $youtube_image = theme('youtube_thumbnail', $options);
          $youtube_link = l($youtube_image, 'node/'. $node->nid, array('html' => TRUE));

          $variables['fields']['title']->content = $youtube_link . $old_output;
        }
      }
    }
  }
}

/**
 * Implementation of HOOK_node_view().
 */
function diy_structure_node_view($node, $view_mode = 'full') {

  if (($view_mode == 'full' || $view_mode == 'amp') && !drupal_is_front_page()) {

    $_cannonical_helper = array(
      'article' => 'field_business_canonical',
      'material' => 'field_tools_canonical_category',
      'ct_werkzeug' => 'field_tools_canonical_category'
    );

    if(in_array($node->type, array('article', 'material', 'ct_werkzeug', 'video', 'page'))) {
      $breadcrumb = array();

      // add front page
      $breadcrumb[] = l(t('Home'), NULL);

      if(isset($_cannonical_helper[$node->type])) {
        $cannonical = field_get_items('node', $node, $_cannonical_helper[$node->type]);
        if(isset($cannonical[0]['tid'])) {
          if($term = taxonomy_term_load($cannonical[0]['tid'])) {

            $parent = taxonomy_get_parents($term->tid);
            if($parent) {
              $parent = reset($parent);
              $breadcrumb[] = l($parent->name, 'taxonomy/term/' . $parent->tid);
            }

            $breadcrumb[] = l($term->name, 'taxonomy/term/' . $term->tid);
          }
        }
      }

      // add node title and do not link
      $breadcrumb[] = check_plain($node->title);

      drupal_set_breadcrumb($breadcrumb);
    }
  }
}

/**
 * Implementation of HOOK_views_pre_view().
 */
function diy_structure_views_pre_view(&$view, &$items) {

  // Set breadcrumb on channels
  if($view->name == 'taxonomy_search' && $view->current_display == 'page') {

    // should be a term
    if(isset($view->args[0]) && is_numeric($view->args[0])) {
      if($term = taxonomy_term_load($view->args[0])) {
        $breadcrumb = array();
        $breadcrumb[] = l(t('Home'), NULL);

        // Home / Maler / Verputzen
        $parent = taxonomy_get_parents($term->tid);
        if($parent) {
          $parent = reset($parent);
          $breadcrumb[] = l($parent->name, 'taxonomy/term/' . $parent->tid);
        }

        $breadcrumb[] = $term->name;
        drupal_set_breadcrumb($breadcrumb);
      }
    }
  }
}

/**
 * Implementation of hook_preprocess_node().
 */
function diy_structure_preprocess_node(&$variables) {
  $node = $variables['node'];

  if($variables['type'] == 'how_to') {

    if($field_title_prefix = field_get_items('node', $node, 'field_how_to_title_prefix')) {
      $variables['custom_title_prefix'] = $field_title_prefix[0]['value'];
    }

    if($field_collapsible = field_get_items('node', $node, 'field_how_to_collapsible')) {
      if($field_collapsible[0]['value'] == 1) {
        drupal_add_library('system', 'ui.accordion');
        $variables['is_accordion'] = true;
      }
    }

    if($field_center_blocks = field_get_items('node', $node, 'field_how_to_center_text_blocks')) {
      if($field_center_blocks[0]['value'] == 1) {
        $variables['classes_array'][] = 'center-text-blocks';
      }
    }
  }

  if($variables['type'] == 'navigator_block') {
    if($field_display = field_get_items('node', $node, 'field_navigator_block_display')) {
      $value = $field_display[0]['value'];

      // Box [Box [Box [Box]]]
      if($value == 2) {
        $variables['theme_hook_suggestions'][] = 'node__navigator_block_boxes';

        if($field_sections = field_get_items('node', $node, 'field_navigator_block_sections')) {
          $sections = min(count($field_sections), 4);
          $variables['grid_width'] = 12 / $sections;
        }
      }

      if($value == 3) {
        $variables['theme_hook_suggestions'][] = 'node__navigator_block_slider';
      }
    }
  }

  if($variables['type'] == 'header') {

    if(drupal_is_front_page()) {
      $variables['dropdown_menu'] = drupal_get_form('diy_startpage_navigator_knowledge_form');
    }

    if($node = menu_get_object('node')) {
      if(in_array($node->type, array('video', 'article', 'material', 'ct_werkzeug'))) {
        if(isset($variables['content']['field_header_link'])) {
          unset($variables['content']['field_header_link']);
        }
        if(isset($variables['content']['field_header_body'])) {
          unset($variables['content']['field_header_body']);
        }

        $variables['small'] = true;
      }
    }
  }
}

/**
 * Doing stuff for field_collections
 */
function diy_structure_preprocess_entity(&$variables) {
  global $language;

  if($variables['entity_type'] == 'field_collection_item' && $variables['field_collection_item']->field_name == 'field_how_to_section') {
    $title = field_get_items('field_collection_item', $variables['field_collection_item'], 'field_how_to_title');
    $variables['new_title'] = $title[0]['value'];

    $host = $variables['field_collection_item']->hostEntity();

    if($host && $host_field = field_get_items('node', $host, 'field_how_to_section')) {
      foreach($host_field as $key => $data) {
        if($data['value'] == $variables['field_collection_item']->item_id) {
          $variables['new_title'] = '<span class="main-color">' . str_pad(($key + 1), 2, '0', STR_PAD_LEFT) . '_</span>' . $variables['new_title'];
          break;
        }
      }
    }

    if($host && $field_collapsible = field_get_items('node', $host, 'field_how_to_collapsible')) {
      if($field_collapsible[0]['value'] == 1) {
        $variables['is_accordion'] = true;
      }
    }

    if($field_display = field_get_items('field_collection_item', $variables['field_collection_item'], 'field_how_to_display')) {
      if($field_display[0]['value'] != 0) {
        $variables['classes_array'][] = 'display-mode-' . $field_display[0]['value'];
      }
    }

    if(field_get_items('field_collection_item', $variables['field_collection_item'], 'field_how_to_image')) {
      $variables['classes_array'][] = 'display-mode-image';
    }
  }


  if($variables['entity_type'] == 'field_collection_item' && $variables['field_collection_item']->field_name == 'field_navigator_block_sections') {
    if($field_link = field_get_items('field_collection_item', $variables['field_collection_item'], 'field_navigator_block_s_link')) {

      // returns eg. node/451
      // TODO
      $current_page = drupal_get_normal_path(current_path());
      $link_path = parse_url($field_link[0]['url'], PHP_URL_PATH);
      if(strpos($link_path, '/' . $language->language) === 0) {
        $link_path = substr($link_path, 4);
      }

      if($current_page == drupal_get_normal_path($link_path)) {
        $variables['is_active'] = TRUE;
      }

      $variables['full_link'] = $field_link[0]['url'];

      if(($field_link[0]['title'] == $field_link[0]['url']) || strpos($field_link[0]['title'], '...')) {
        unset($variables['content']['field_navigator_block_s_link']);
      }
    }
  }
}

/**
 * Implements HOOK_proprocess_field().
 */
function diy_structure_preprocess_field(&$variables, $hook) {
  if($variables['element']['#field_name'] == 'field_header_line_2') {
    $domain = domain_get_domain();

    if(isset($variables['items'][0]['#markup'])) {
      $variables['items'][0]['#markup'] = strtr($variables['items'][0]['#markup'], array('[custom-current-domain]' => $domain['subdomain']));
    }
  }
}

/**
 * Implementation of HOOK_preprocess_page().
 */
function diy_structure_preprocess_page(&$vars) {
  // hide title on how_to pages
  if(isset($vars['node'])) {
    if($vars['node']->type == 'how_to') {
      $vars['title'] = '';
      $vars['breadcrumb'] = '';
    }
  }

  // add Organization structured data
  global $base_url;

  $structured_data = array(
    "@context" => "http://schema.org/",
    "@type" => "Organization",
    "name" => variable_get('site_name', ''),
    "url" => $base_url,
    "logo" => file_create_url(drupal_get_path('theme', 'diy') . '/images/logo_structured_data.jpg'),
  );

  $element = array(
    '#type' => 'markup',
    '#markup' => '<script type="application/ld+json">' . str_replace('\\/', '/', json_encode($structured_data))  . '</script>',
  );

  drupal_add_html_head($element, 'google-structured-data-markup-organization');

  // add breadcrumbs
  if($breadcrumbs = drupal_get_breadcrumb()) {
    $structured_data = array(
      "@context" => "http://schema.org/",
      "@type" => "BreadcrumbList",
      "itemListElement" => array()
    );

    $counter = 1;
    foreach($breadcrumbs as $breadcrumb) {
      $current_data = array(
        "@type" => "ListItem",
        "position" => $counter,
        "item" => array(
          "name" => strip_tags($breadcrumb)
        )
      );

      // only try to parse breadcrumb if its a link
      if(strpos($breadcrumb, '<a') === 0) {
        if ($link_element = new SimpleXMLElement($breadcrumb)) {
          if (isset($link_element['href']) && !empty($link_element['href'])) {
            $current_data["item"]["@id"] = (string)$link_element['href'];
          }
        }
      }

      $structured_data["itemListElement"][] = $current_data;

      $counter++;
    }

    $element = array(
      '#type' => 'markup',
      '#markup' => '<script type="application/ld+json">' . str_replace('\\/', '/', json_encode($structured_data))  . '</script>',
    );

    drupal_add_html_head($element, 'google-structured-data-markup-breadcrumbs');
  }

}

/**
 * Helper for loading article for video
 */
function diy_structure_video_get_article($nid) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'article')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_article_video', 'nid', $nid, '=')
    ->range(0, 1)
    ->addMetaData('account', user_load(1)); // Run the query as user 1.
  $result = $query->execute();
  if (isset($result['node'])) {
    $nids = array_keys($result['node']);
    return node_load(reset($nids));
  }

  return false;
}

/**
 * Implements HOOK_page_alter().
 */
function diy_structure_page_alter(&$page) {

  // special header for article and news
  if($node = menu_get_object('node')) {
    if(in_array($node->type, array('article', 'news'))) {
      if(isset($page['preface_first'])) {
        unset($page['preface_first']);
      }

      $block = block_load('diy_structure', 'diy_structure_header_backblock');
      $page['preface_first'][] = _block_get_renderable_array( _block_render_blocks(array($block)));
    }

    if(in_array($node->type, array('product'))) {
      $block = block_load('diy_structure', 'diy_structure_header_backblock');
      $page['postheader'][] = _block_get_renderable_array( _block_render_blocks(array($block)));

    }
  }

  if(!isset($page['preface_first'])) {
    $header_set = false;
    $cannonical_term_tid = false;

    if($headers = drupal_get_http_header()) {
      if(isset($headers['status']) && (strpos($headers['status'], '404') !== FALSE || strpos($headers['status'], '403') !== FALSE)) {
        if($error_header = variable_get('diy_defaults_default_header_error', '')) {
          if($block = nodeblock_block_view($error_header)) {
            $page['preface_first'][] = $block['content'];
            $header_set = true;
          }
        }
      }
    }

    if($node = menu_get_object('node')) {
      global $language;

      $canonical_node = false;

      // we need a related article
      if($node->type == 'video') {
        if($article = diy_structure_video_get_article($node->nid)) {
          $canonical_node = $article;
        }
      }

      if(in_array($node->type, array('material', 'ct_werkzeug'))) {
        $canonical_node = $node;
      }

      if($canonical_node) {
        $cannonical_term = field_get_items('node', $canonical_node, diy_structure_get_tags_field_cannonical($canonical_node->type), $language);

        $cannonical_term = reset($cannonical_term);
        $cannonical_term_tid = $cannonical_term['tid'];
      }
    }

    if(arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
      $cannonical_term_tid = arg(2);
    }

    if($cannonical_term_tid) {
      if($nodes = taxonomy_select_nodes($cannonical_term_tid, FALSE, FALSE, array('t.created' => 'DESC'))) {

        $query = new EntityFieldQuery();
        $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'header')
          ->propertyCondition('status', 1)
          ->propertyCondition('nid', $nodes, 'IN')
          ->range(0, 1);

        $result = $query->execute();
        if (isset($result['node'])) {
          $header_nids = array_keys($result['node']);

          $block = nodeblock_block_view(reset($header_nids));
          $page['preface_first'][] = $block['content'];
          $header_set = true;
        }
      }
    }

    // show default header
    if(!$header_set) {
      if($header = variable_get('diy_defaults_default_header', '')) {
        if($block = nodeblock_block_view($header)) {
          $page['preface_first'][] = $block['content'];
        }
      }
    }
  }
}

/**
 * Implements HOOK_block_info().
 */
function diy_structure_block_info() {

  $blocks['diy_structure_channel_top'] = array(
    'info' => t('DIY Structure knowledge channel top text block'),
  );

  $blocks['diy_structure_channel_bottom'] = array(
    'info' => t('DIY Structure knowledge channel bottom text block'),
  );

  $blocks['diy_structure_channel_navigation'] = array(
    'info' => t('DIY Structure channel navigation'),
  );

  $blocks['diy_structure_amazon_placement'] = array(
    'info' => t('DIY Structure amazon placement block'),
  );

  $blocks['diy_structure_header_backblock'] = array(
    'info' => t('DIY Structure header back block'),
  );

  $blocks['diy_structure_header_channel'] = array(
    'info' => t('DIY Structure header channel back block'),
  );

  $blocks['diy_structure_header_icon_detail'] = array(
    'info' => t('DIY Structure header icon detail block'),
  );

  $blocks['diy_structure_pinterest_block'] = array(
    'info' => t('DIY Structure pinterest block'),
  );

  return $blocks;
}

/**
 * Implements HOOK_block_view().
 */
function diy_structure_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'diy_structure_channel_top':
      $block['content'] = diy_structure_channel_text_block_content('field_channel_header', 'field_channel_header_title');
      break;
    case 'diy_structure_channel_bottom':
      $block['content'] = diy_structure_channel_text_block_content('field_channel_footer', 'field_channel_footer_title');
      break;
    case 'diy_structure_channel_navigation':
      $block['subject'] = t('Choose your topic');
      $block['content'] = diy_structure_channel_navigation();
      break;
    case 'diy_structure_amazon_placement':
      $block['content'] = diy_structure_amazon_placement_block_content();
      break;
    case 'diy_structure_header_backblock':
      $block['content'] = diy_structure_header_back_block_content();
      break;
    case 'diy_structure_header_channel':
      $block['content'] = diy_structure_header_channel_back_block_content();
      break;
    case 'diy_structure_header_icon_detail':
      $block['content'] = diy_structure_header_icon_block_content();
      break;
    case 'diy_structure_pinterest_block':
      $block['content'] = diy_structure_pinterest_block_content();
      break;
  }

  return $block;
}

function diy_structure_pinterest_block_content() {
  return '<a data-pin-do="embedUser" href="http://www.pinterest.com/diybook2pin/" data-pin-scale-width="90" data-pin-scale-height="300" data-pin-board-width="300"></a>';
}

function diy_structure_channel_navigation() {
  if(arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    if($term = taxonomy_term_load(arg(2))) {
      if($term->vid == 5) {

        $terms = taxonomy_get_tree($term->vid, $term->tid, 1, TRUE);
        if(!$terms) {
          if($parents = taxonomy_get_parents($term->tid)) {
            $parent = reset($parents);
            $terms = taxonomy_get_tree($term->vid, $parent->tid, 1, TRUE);
          } else {
            return;
          }
        }

        $links = array();
        foreach($terms as $term) {
          if($field_promote = field_get_items('taxonomy_term', $term, 'field_promote')) {
            if($field_promote[0]['value']) {
              $links[] = l($term->name, 'taxonomy/term/' . $term->tid);
            }
          }
        }

        return theme('item_list', array(
          'items' => $links,
          'title' => NULL,
          'type' => 'ul',
          'attributes' => array()
        ));

      }
    }
  }

  return;
}

function diy_structure_header_back_block_content() {
  if($node = menu_get_object('node')) {
    if($node->type == 'article') {
      if($field_business_canonical = field_get_items('node', $node, 'field_business_canonical')) {
        return l(t('back to overview'), 'taxonomy/term/' . $field_business_canonical[0]['tid'], array('attributes' => array('title' => t('back to overview'))));
      }

    }
    if($node->type == 'news') {
      return l(t('back to overview'), 'news', array('attributes' => array('title' => t('back to overview'))));
    }

    if($node->type == 'product') {
      if($field_tool_material = field_get_items('node', $node, 'field_tool_material')) {
        return l(t('back to overview'), 'node/' . $field_tool_material[0]['nid'], array('attributes' => array('title' => t('back to overview'))));
      }
      return l(t('back to overview'), 'prod', array('attributes' => array('title' => t('back to overview'))));
    }
  }

  return l(t('back to overview'), 'javascript:history.back();', array('attributes' => array('title' => t('back to overview')), 'external' => true));
}

function diy_structure_header_icon_block_content() {
  $output = '';

  if($node = menu_get_object('node')) {

    if($field_guidebook_taxonomy = field_get_items('node', $node, 'field_guidebook_taxonomy')) {
      $term = taxonomy_term_load($field_guidebook_taxonomy[0]['tid']);

      $icon_markup = '';
      if($field_icon = field_get_items('taxonomy_term', $term, 'field_icon')) {
        $icon_markup = theme_image_style(array(
          'style_name' => 'navigator_small_icon',
          'path' => $field_icon[0]['uri'],
          'width' => NULL,
          'height' => NULL
        ));
      }
      $output .= '<div class="channel-block-title">' . $icon_markup . '<h2>' . $term->name . '</h2>' . '</div>';

      if($node->type == 'topic') {
        return $output . l(t('back to overview'), 'guidebook/' . $term->tid, array('attributes' => array('title' => t('back to overview'))));
      }
    }
  }
}

function diy_structure_header_channel_back_block_content() {
  // TODO move to template file
  $output = '';
  $back_url = 'taxonomy/term/71';

  if(arg(0) == 'taxonomy' && arg(1) == 'term') {
    if($term = taxonomy_term_load(intval(arg(2)))) {

      $show_term = $term;
      if($parents = taxonomy_get_parents($term->tid)) {
        $show_term = reset($parents);
        $back_url = 'taxonomy/term/' . $show_term->tid;
      }

      $icon_markup = '';
      if($field_icon = field_get_items('taxonomy_term', $show_term, 'field_icon')) {
        $icon_markup = theme_image_style(array(
          'style_name' => 'navigator_small_icon',
          'path' => $field_icon[0]['uri'],
          'width' => NULL,
          'height' => NULL
        ));
      }

      $name = $show_term->name;
      $output .= '<div class="channel-block-title">' . $icon_markup . '<h2>' . $name . '</h2>' . '</div>';
    }
  }


  return $output . l(t('back to overview'), $back_url, array('attributes' => array('title' => t('back to overview'))));
}

/**
 * Block callback for amazon placement block
 */
function diy_structure_amazon_placement_block_content() {
  $node = menu_get_object();
  if(isset($node->type) && in_array($node->type, array('ct_werkzeug', 'material'))) {
    $phrase = $node->title;

    if($field_amazon_phrase = field_get_items('node', $node, 'field_amazon_phrase')) {
      $phrase = $field_amazon_phrase[0]['value'];
    }

    return theme('diy_structure_amazon_placement_content', array('phrase' => drupal_encode_path($phrase)));
  }
}

/**
 * Block callback for channel top text
 */
function diy_structure_channel_text_block_content($text_field, $title_field) {
  if($node = menu_get_object()) {
    if($node->type == 'topic') {
      $config = array();

      if($text_field == 'field_channel_header') {
        $text_field = 'field_teaser';
      }

      // add text before view
      $field_header = field_get_items('node', $node, $text_field);
      if(isset($field_header[0]['value'])) {
        $config += array('text' => $field_header[0]['value']);
      }

      $field_header_title = field_get_items('node', $node, $title_field);
      if(isset($field_header_title[0]['value'])) {
        $config += array('title' => $field_header_title[0]['value']);
      }

      if($config) {
        return theme('diy_structure_channel_block_content', $config);
      }
    }
  }


  $tid_pos = 2;

  if(arg(0) == 'newsfeed' || arg(0) == 'guidebook') {
    $tid_pos = 1;
  }


  if(((arg(0) == 'taxonomy' && arg(1) == 'term') ||
      (arg(0) == 'newsfeed') ||
      (arg(0) == 'guidebook')) && is_numeric(arg($tid_pos))) {

    $tid = intval(arg($tid_pos));

    $term = taxonomy_term_load($tid);

    $config = array();

    // add text before view
    $field_header = field_get_items('taxonomy_term', $term, $text_field);
    if(isset($field_header[0]['value'])) {
      $config += array('text' => token_replace($field_header[0]['value'], array('term' => $term)));
    }

    $field_header_title = field_get_items('taxonomy_term', $term, $title_field);
    if(isset($field_header_title[0]['value'])) {
      $config += array('title' => $field_header_title[0]['value']);
    }

    if($config) {
      return theme('diy_structure_channel_block_content', $config);
    }
  }
}

/**
 * Implements HOOK_theme().
 */
function diy_structure_theme($existing, $type, $theme, $path) {
  return array(
    'diy_structure_channel_block_content' => array(
      'template' => 'text-block',
      'path' => drupal_get_path('module', 'diy_structure') . '/templates',
      'variables' => array(
        'title' => NULL,
        'text' => NULL
      )
    ),
    'diy_structure_amazon_placement_content' => array(
      'template' => 'amazon-block',
      'path' => drupal_get_path('module', 'diy_structure') . '/templates',
      'variables' => array(
        'phrase' => NULL
      )
    )
  );
}
