<?php


/**
 * Helper function
 */
function diy_code_loader_path() {
  return drupal_get_path('theme', 'diy') . '/images/loader.gif';
}

/**
 * Impelements HOOK_init().
 */
function diy_code_init() {
  if(!path_is_admin(current_path())) {
    drupal_add_js('sites/all/libraries/jcarousel/jquery.jcarousel.min.js');
    drupal_add_js('sites/all/libraries/jcarousel/jquery.touchwipe.min.js');
    drupal_add_js(drupal_get_path('module', 'diy_code') . '/js/carousel.js');

    drupal_add_library('system', 'ui.accordion');
    module_invoke('contextual', 'library');

    drupal_add_css(drupal_get_path('module', 'fivestar') . '/css/fivestar.css');

    if($options = variable_get('diy_defaults_cookie_consent_options', '')) {
      drupal_add_js($options,
        array('type' => 'inline', 'scope' => 'header', 'force header' => TRUE, 'weight' => 999)
      );
      drupal_add_js('//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/1.0.9/cookieconsent.min.js',
        array('type' => 'external', 'scope' => 'header', 'force header' => TRUE, 'weight' => 1000)
      );
    }
  }
}

/**
 * Implementation of hook_theme()
 */
function diy_code_theme() {
  return array(
    'diy_code_carousel_big' => array(
      'variables' => array('images' => NULL, 'pagination' => TRUE),
    ),
    'diy_code_carousel_small' => array(
      'variables' => array(
        'images' => NULL,
        'goto_link' => false
      ),
    ),
    'diy_code_image' => array(
      'variables' => array('image' => NULL)
    )
  );
}

/**
 * Implementation of HOOK_preprocess_html().
 */
function diy_code_preprocess_html(&$vars) {
  $header = false;

  if(isset($vars['page']['header']['preface']['preface_first']) ||
     isset($vars['page']['header']['preface']['preface_second']) ||
     isset($vars['page']['header']['preface']['preface_third'])) {
    $header = true;
  }

  if($header) {
    $vars['classes_array'][] = 'has-featured';
  }

  $vars['classes_array'][] = _diy_code_return_page_section($vars);

  drupal_add_css(drupal_get_path('module', 'diy_code') . '/css/carousel.css');
}

/**
 * Returns current page section
 */
function _diy_code_return_page_section($vars) {

  $class_handwerker = 'section-hw';
  $class_inserat = 'section-ins';
  $class_ratgeber = 'section-rg';
  $class_diy = 'section-diy';

  if(drupal_is_front_page()) {
    return $class_handwerker;
  }

  if(arg(0) == 'node' && is_numeric(arg(1))) {
    $node = node_load(arg(1));

    if(in_array($node->type, array('article', 'video', 'material', 'ct_werkzeug', 'product'))) {
      return $class_diy;
    }

    if(in_array($node->type, array('branche'))) {
      return $class_handwerker;
    }

    if(in_array($node->type, array('inserat', 'application'))) {
      return $class_inserat;
    }

    if(in_array($node->type, array('topic'))) {
      return $class_ratgeber;
    }
  }

  // taxonomy/term - currently channels
  if(arg(0) == 'taxonomy' && arg(1) == 'term') {
    return $class_diy;
  }

  if($view = views_get_page_view()) {
    if(isset($view->name) && $view->name == 'inserate_suche_map') {
      return $class_inserat;
    }

    if(isset($view->name) && $view->name == 'guidebook_channel') {
      return $class_ratgeber;
    }
  }

  // Pfadsystem
  $path_system = array(
    'handwerker' => 'diy_defaults_sections_hw',
    'inserat' => 'diy_defaults_sections_ins',
    'ratgeber' => 'diy_defaults_sections_rg',
    'diy' => 'diy_defaults_sections_diy'
  );

  $current_path = current_path();
  foreach($path_system as $section => $element) {
    if($pathes = variable_get($element)) {
      $pathes = explode("\r\n", $pathes);

      if(is_array($pathes)) {
        foreach($pathes as $path) {

          $internal_path = drupal_lookup_path("source", $path, 'de');

          if($internal_path == $current_path) {
            $var = 'class_' . $section;
            return $$var;
          }
        }
      }
    }
  }

  return $class_handwerker;
}

/**
 * Default theme implementation for normal image
 */
function theme_diy_code_image($variables) {
  $image = $variables['image'];

  if(!isset($image['source']) && !isset($image['path'])) {
    return;
  }

  $my_image = array(
    'style_name' => $image['preset'],
    'path' => $image['path']
  );

  if (isset($image['alt'])) {
    $my_image += array('alt' => $image['alt']);
  }

  return theme('image_style', $my_image);
}

/**
 * Default theme implementation for big carousel
 */
function theme_diy_code_carousel_big($variables) {
  $images = $variables['images'];
  $pagination = $variables['pagination'];

  if (empty($images)) {
    return;
  }

  // process images for item list
  $item_list = array();
  $item_list_thumb = array();
  foreach ($images as $key => $image) {

    // get image style path for that image
    $my_image_path = diy_code_get_full_image_path($image['path']);

    $my_image = array(
      'path' => $my_image_path,
      'title' => $image['title'],
      'attributes' => array()
    );

    if (isset($image['alt'])) {
      $my_image += array('alt' => check_plain($image['alt']));
    }

    $thumb = $my_image;
    $thumb['path'] = $image['path'];
    $thumb['style_name'] = 'article_galleryimage_thumb';

    // main image
    // all but first
    if ($key !== 0) {
      // for internal images we have to process the image style first
      $my_image['attributes'] += array(
        'data-preload' => $my_image_path
      );

      $my_image['path'] = diy_code_loader_path();

      // local image (eg loader.gif can not be processed by image_style, render with theme_image)
      $rendered_upload_image = theme_image($my_image);
    } else {
      $rendered_upload_image = theme_image($my_image);
    }

    // thumb (display 5 images, then switch to loader)
    if ($key > 4) {
      $thumb['attributes'] += array(
        'data-preload' => image_style_url('article_galleryimage_thumb', $image['path'])
      );

      $thumb['path'] = diy_code_loader_path();
      unset($thumb['style_name']);

      $rendered_teaser_image = theme_image($thumb);
    } else {
      $rendered_teaser_image = theme('image_style', $thumb);
    }

    $list_item_content = $rendered_upload_image;
    $list_item_thumb_content = $rendered_teaser_image;


    if (isset($image['description'])) {
      $list_item_content .= '<div class="description">' . $image['description'] . '</div>';
    }

    $item_list[] = $list_item_content;
    $item_list_thumb[] = $list_item_thumb_content;
  }

  $output = '<div class="diyslider-wrapper">';
  $output .= '<div class="diyslider">';

  $output .= '<ul>';
  foreach ($item_list as $item) {
    $output .= '<li>' . $item . '</li>';
  }
  $output .= '</ul>';

  $output .= '</div>';

  $output .= '<a class="diyslider-prev diyslider-button" href="#" rel="nofollow">&lt;</a>';
  $output .= '<a class="diyslider-next diyslider-button" href="#" rel="nofollow">&gt;</a>';

  if ($pagination) {
    $output .= '<div class="diyslider-pagination-wrapper">';
    $output .= '<div class="diyslider-pagination">';

    $output .= '<ul>';
    foreach ($item_list_thumb as $item) {
      $output .= '<li>' . $item . '</li>';
    }
    $output .= '</ul>';

    $output .= '</div>';
    $output .= '<a class="diyslider-pagination-prev diyslider-pagination-button" href="#" rel="nofollow">&lt;</a>';
    $output .= '<a class="diyslider-pagination-next diyslider-pagination-button" href="#" rel="nofollow">&gt;</a>';
    $output .= '</div>';
  }

  $output .= '</div>';

  return $output;
}

/**
 *
 *
 * @param $path
 * @return mixed
 */
function diy_code_get_full_image_path($path) {
  $images = &drupal_static(__FUNCTION__);

  if (!isset($images[$path])) {
    $images[$path] = image_style_url('article_galleryimage', $path);
  }

  return $images[$path];
}

/**
 * Default theme implementation for big carousel
 */
function theme_diy_code_carousel_small($variables) {
  $images = $variables['images'];

  if (empty($images)) {
    return;
  }

  // process images for item list
  $item_list = array();
  foreach ($images as $key => $image) {

    // get image style path for that image
    $my_image_path = diy_code_get_full_image_path($image['path']);

    $my_image = array(
      'path' => $my_image_path,
      'title' => $image['title'],
      'attributes' => array()
    );

    if (isset($image['alt'])) {
      $my_image += array('alt' => check_plain($image['alt']));
    }

    // all but first
    if ($key !== 0) {
      // for internal images we have to process the image style first
      $my_image['attributes'] += array(
        'data-preload' => $my_image_path
      );

      $my_image['path'] = diy_code_loader_path();
      unset($my_image['style_name']);

      // local image (eg loader.gif can not be processed by image_style, render with theme_image)
      $rendered_upload_image = theme_image($my_image);
    } else {
      $rendered_upload_image = theme_image($my_image);

      if (isset($variables['goto_link']) && $variables['goto_link']) {
        $rendered_upload_image .= '<div class="slideshow-switcher">' . t('goto gallery') . '</div>';
      }
    }

    $list_item_content = $rendered_upload_image;


    if (isset($image['description'])) {
      $short = truncate_utf8($image['description'], 140, TRUE, TRUE);

      if ($short == $image['description']) {
        $list_item_content .= '<div class="description">' . check_plain($image['description']) . '</div>';
      } else {
        $list_item_content .= '<div class="description" title="' . check_plain($image['description']) . '">' . check_plain($short) . '</div>';
      }

    }

    $item_list[] = $list_item_content;
  }

  $output = '<div class="diyslider-small-wrapper">';
  $output .= '<div class="diyslider-small">';

  $output .= '<ul>';
  foreach ($item_list as $item) {
    $output .= '<li>' . $item . '</li>';
  }
  $output .= '</ul>';

  $output .= '</div>';

  $output .= '<a class="diyslider-small-prev diyslider-small-button" href="#" rel="nofollow">&lt;</a>';
  $output .= '<a class="diyslider-small-next diyslider-small-button" href="#" rel="nofollow">&gt;</a>';
  $output .= '</div>';


  drupal_add_js(drupal_get_path('module', 'diy_code') . '/js/carousel.js');

  return $output;
}

/**
 * $config
 * [node] - node object
 * [gallery] - gallery field
 * [images] - images from gallery
 * [upload] - field for uploads
 */
function diy_code_get_image($config) {
  $node = $upload = null;
  extract($config);
  $return_image = array();

  // handle upload stuff
  $upload = field_get_items('node', $node, $upload);
  if(isset($upload[0]['uri'])) {
    $return_image['path'] = $upload[0]['uri'];
    $return_image['source'] = 'iternal';
  }

  // Generate ALT Attribute for normal images
  if(!empty($return_image)) {
    $return_image['alt'] = check_plain($node->title);
  }

  return $return_image;
}

/**
 * Custom function to get all image data
 *
 *
 * $config
 * ...
 */
function diy_code_get_images($config) {
  $entity_type = $entity = $upload = $size_preset = null;
  extract($config);
  $return_images = array();


	   

  // handle upload number stuff (uploaded for bildreihe, used for steps)
  if(isset($images_embed)) {
    $images_choosen = field_get_items($entity_type, $entity, $images_embed['field']);
    if(isset($images_choosen['0']['value'])) {
      $images_choosen_value = $images_choosen['0']['value'];



      // contains image numbers like 1,2,3,4...
      $images_choosen_value = explode(',', $images_choosen_value);

      // get parent image upload tool
      $parent = $images_embed['source'];
      $upload_element = field_get_items($parent['entity_type'], $parent['entity'], $parent['field']);

      // iterate through choosen images
      foreach($images_choosen_value as $choosen) {
        if (trim($choosen)) {
          $real_index = trim($choosen) - 1;

          // processing if field collection exists
          if(isset($upload_element[$real_index])) {

            // image handling
            $field_collection = entity_load('field_collection_item', array($upload_element[$real_index]['value']));
            $fci = reset($field_collection);

            $field_gallery_upload = field_get_items('field_collection_item', $fci, 'field_gallery_upload');
            $field_gallery_title = field_get_items('field_collection_item', $fci, 'field_gallery_upload_title');
            $field_gallery_description = field_get_items('field_collection_item', $fci, 'field_gallery_upload_description');

            if(isset($field_gallery_upload[0]['uri'])) {
              $return_images[] = array(
                'path' => $field_gallery_upload[0]['uri'],
                'title' => $field_gallery_title[0]['safe_value'],
                'alt' => $field_gallery_title[0]['safe_value'],
                'description' => $field_gallery_description[0]['safe_value'],
                'source' => 'iternal'
              );
            }
          }
        }
      }
    }
  }

  // handle upload stuff
  $upload = field_get_items($entity_type, $entity, $upload);
  if(is_array($upload) && (count($upload) > 0) && $size_preset) {

    foreach($upload as $fc) {
      $field_collection = entity_load('field_collection_item', array($fc['value']));
      $fci = reset($field_collection);

      $field_gallery_upload = field_get_items('field_collection_item', $fci, 'field_gallery_upload');
      $field_gallery_title = field_get_items('field_collection_item', $fci, 'field_gallery_upload_title');
      $field_gallery_description = field_get_items('field_collection_item', $fci, 'field_gallery_upload_description');

      if(isset($field_gallery_upload[0]['uri'])) {

        $return_images[] = array(
          'path' => $field_gallery_upload[0]['uri'],
          'title' => $field_gallery_title[0]['safe_value'],
          'alt' => $field_gallery_title[0]['safe_value'],
          'description' => $field_gallery_description[0]['safe_value'],
          'source' => 'iternal'
        );
      }
    }
  }

  return $return_images;
}

/**
 * Helper function for apikey per domain

./sites/all/modules/sociallogin/socialloginandsocialshare.admin.inc:  if (!variable_get('socialloginandsocialshare_apikey', FALSE) || !variable_get('socialloginandsocialshare_apisecret', FALSE) ) {
./sites/all/modules/sociallogin/socialloginandsocialshare.admin.inc:  if (!variable_get('socialloginandsocialshare_apikey', FALSE)) {
./sites/all/modules/sociallogin/socialloginandsocialshare.admin.inc:  $form[$group]['socialloginandsocialshare_apikey'] = array(
./sites/all/modules/sociallogin/socialloginandsocialshare.admin.inc:    '#default_value' => variable_get('socialloginandsocialshare_apikey', ''),
./sites/all/modules/sociallogin/socialloginandsocialshare.admin.inc:  $apikey = trim($form_state['values']['socialloginandsocialshare_apikey']);
./sites/all/modules/sociallogin/socialloginandsocialshare.admin.inc:  $apikey = trim($form_state['values']['socialloginandsocialshare_apikey']);
./sites/all/modules/sociallogin/socialloginandsocialshare.install:  variable_del('socialloginandsocialshare_apikey');
./sites/all/modules/sociallogin/socialloginandsocialshare.module:  $api_key = trim(variable_get('socialloginandsocialshare_apikey'));
./sites/all/modules/sociallogin/socialloginandsocialshare.module:  $params['api_key'] = trim(variable_get('socialloginandsocialshare_apikey'));
./sites/all/modules/sociallogin/socialloginandsocialshare_share.module:	  $api_key =trim(variable_get('socialloginandsocialshare_apikey'));
./sites/all/modules/sociallogin/socialloginandsocialshare_share.module:   $api_key = trim(variable_get('socialloginandsocialshare_apikey'));
./sites/all/themes/diy/templates/socialloginandsocialshare-links.tpl.php:$params['api_key'] = trim(variable_get('socialloginandsocialshare_apikey'));

 */
function diy_code_get_loginradius_apikey() {
  // for testing, you can use custom key
  if($overwrite_key = variable_get('diy_defaults_social_login_key', '')) {
    return $overwrite_key;
  }

  $keys = array(
    'diybook_ch' => '65e9a398-d198-4567-8730-3ab91c2125bb',
    'diybook_at' => 'a0b732b0-9b86-403b-aeb3-ad9a158d0720',
    'diybook_de' => 'ac7c626b-8d29-4665-b86a-dd47ad539c77',
    'diybook_eu' => '77b6e4c0-8c01-46f8-8caf-d7c8995ff677'
  );

  $current_domain = domain_get_domain();
  $domain = $current_domain['machine_name'];

  if(isset($keys[$domain])) {
    return $keys[$domain];
  }

  return FALSE;
}

/**
 * Helper function for apisecret per domain

./sites/all/modules/sociallogin/socialloginandsocialshare.admin.inc:  if (!variable_get('socialloginandsocialshare_apikey', FALSE) || !variable_get('socialloginandsocialshare_apisecret', FALSE) ) {
./sites/all/modules/sociallogin/socialloginandsocialshare.admin.inc:  $form[$group]['socialloginandsocialshare_apisecret'] = array(
./sites/all/modules/sociallogin/socialloginandsocialshare.admin.inc:    '#default_value' => variable_get('socialloginandsocialshare_apisecret', ''),
./sites/all/modules/sociallogin/socialloginandsocialshare.admin.inc:  $apisecret = trim($form_state['values']['socialloginandsocialshare_apisecret']);
./sites/all/modules/sociallogin/socialloginandsocialshare.admin.inc:  $apisecret = trim($form_state['values']['socialloginandsocialshare_apisecret']);
./sites/all/modules/sociallogin/socialloginandsocialshare.install:  variable_del('socialloginandsocialshare_apisecret');
./sites/all/modules/sociallogin/socialloginandsocialshare.module:  $secret = trim(variable_get('socialloginandsocialshare_apisecret'));
./sites/all/modules/sociallogin/socialloginandsocialshare.module:  $secret = trim(variable_get('socialloginandsocialshare_apisecret'));
./sites/all/modules/sociallogin/socialloginandsocialshare.pages.inc:    $secret = trim(variable_get('socialloginandsocialshare_apisecret'));
*/
function diy_code_get_loginradius_apisecret() {
  // for testing, you can use custom key
  if($overwrite_secret = variable_get('diy_defaults_social_login_secret', '')) {
    return $overwrite_secret;
  }

  $keys = array(
    'diybook_ch' => '0bdb9ca3-9b85-41c6-b511-3c5af3bd5d32',
    'diybook_at' => '4e9dd292-2983-4547-a6f1-bd2ac95ca08c',
    'diybook_de' => '599ba709-6c09-4034-8a27-736febe86769',
    'diybook_eu' => '091fedee-67db-4d88-8331-dedb94d64ad8'
  );

  $current_domain = domain_get_domain();
  $domain = $current_domain['machine_name'];

  if(isset($keys[$domain])) {
    return $keys[$domain];
  }

  return FALSE;
}

/**
 * Implements HOOK_commerce_paypal_wps_order_form_data().
 */
function diy_code_commerce_paypal_wps_order_form_data_alter(&$data, &$order) {

  $field_commerce_line_items = field_get_items('commerce_order', $order, 'commerce_line_items');
  if(isset($field_commerce_line_items[0]['line_item_id'])) {

    if($first_line_item = commerce_line_item_load($field_commerce_line_items[0]['line_item_id'])) {
      $field_product = field_get_items('commerce_line_item', $first_line_item, 'commerce_product');

      if(isset($field_product[0]['product_id'])) {
        $product_id = $field_product[0]['product_id'];
        if($product = commerce_product_load($product_id)) {

          $title = trim(preg_replace('/\s*\([^)]*\)$/', '', $product->title));
          $data['item_name_1'] = $title;
        }
      }
    }
  }

  // Add description
  $data['on0_1'] = t('DIYBook');

  // Reset count
  $data['os0_1'] = t('contact package');
}

/**
 * Implements hook_entity_info_alter().
 */
function diy_code_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['slider'] = array(
    'label' => t('Slider'),
    'custom settings' => TRUE,
  );
}

/*
function diy_code_flush_caches()
{
    $path = DRUPAL_ROOT . '/aggregated/';
    $js = glob($path.'js/*');
    $css = glob($path.'css/*');
    $time = time();

    foreach ($js as $file) {
        if (is_file($file)) {
            if ($time - filemtime($file) >= 60*60*24*2) { // 2 days
                unlink($file);
            }
        }
    }

    foreach ($css as $file) {
        if (is_file($file)) {
            if ($time - filemtime($file) >= 60*60*24*2) { // 2 days
                unlink($file);
            }
        }
    }
}
*/

function diy_code_metatag_page_cache_cid_parts_alter(&$cid_parts) {
  if(isset($cid_parts['langcode']) && is_object($cid_parts['langcode'])) {
    unset($cid_parts['langcode']);
  }
}

function diy_code_filter_nids_domain($nids) {
  if(empty($nids)) {
    return array();
  }

  $current_domain = domain_get_domain();

  $result = db_query("SELECT DISTINCT(d.nid)
              FROM {domain_access} d
              WHERE ((d.gid = :did AND d.realm='domain_id') OR d.realm = 'domain_site') AND d.nid IN(:nids)", array(':did' => $current_domain['domain_id'], ':nids' => $nids));

  $results = array();
  foreach($result as $record) {
    $results[] = $record->nid;
  }

  return $results;
}

/**
 * Checks if a given comment has a field_email set
 *
 * @param $comment
 * @return bool
 */
function diy_code_check_comment_mail($comment) {
  if($field_email = field_get_items('comment', $comment, 'field_email')) {
    return true;
  }

  return false;
}

/**
 * Checks if a given comment has a parent with a field_email set
 *
 * @param $comment
 * @return bool
 */
function diy_code_check_parent_comment_mail($comment) {
  if(isset($comment->pid) && !empty($comment->pid)) {
    $parent = comment_load($comment->pid);

    if(diy_code_check_comment_mail($parent)) {
      return true;
    }
  }

  return false;
}

/**
 * Implements HOOK_form_alter().
 */
function diy_code_form_alter(&$form, &$form_state, $form_id) {
  // check if we have a mailchimp form
  if(strpos($form_id, 'mailchimp_signup_subscribe_block_') === 0) {

    if(isset($form['mergevars']['EMAIL'])) {
      $form['mergevars']['EMAIL']['#title_display'] = 'invisible';
      $form['mergevars']['EMAIL']['#attributes']['placeholder'] = 'ihre@email.com';
    }

    $form['actions']['#suffix'] = '<div class="signup-text">' . t('Sign up and stay informed') . '</div>';
  }
}