<?php
/**
 * @file
 * Module file for diy_startpage.
 */


/**
 * adds needed js-files
 */
function diy_startpage_preprocess_page(&$vars) {
  #drupal_add_js(drupal_get_path('module', 'diy_startpage') . '/js/jquery.maphilight.min.js');
  if(drupal_is_front_page()) {
    drupal_add_js(drupal_get_path('module', 'diy_startpage') . '/js/startpage.js');
    $vars['scripts'] = drupal_get_js(); // necessary in D7?
  }
}

/**
 * Implements HOOK_block_info().
 */
function diy_startpage_block_info() {
  
  $blocks['diy_startpage_business'] = array(
    'info' => t('Sidebar block for area terms'),
  );

  $blocks['diy_startpage_social'] = array(
    'info' => t('Frontpage block social links'),
  );

  $blocks['diy_startpage_search_tabs'] = array(
    'info' => t('Frontpage block navigator tabs'),
  );

  $blocks['diy_startpage_section_social'] = array(
    'info' => t('Frontpage block section social'),
  );

  $blocks['diy_startpage_section_why'] = array(
    'info' => t('Frontpage block section why'),
  );

  $blocks['diy_startpage_text_block_1'] = array(
    'info' => t('Frontpage block text 1'),
  );


  return $blocks;
}


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

  switch ($delta) {
    case 'diy_startpage_business':
      $block['subject'] = t('topic selection');
      $block['content'] = diy_startpage_business_content();
      break;
    case 'diy_startpage_social':
      $block['content'] = diy_startpage_social_links();
      break;
    case 'diy_startpage_search_tabs':
      $block['content'] = diy_startpage_navigator_block_tabs();
      break;
    case 'diy_startpage_text_block_1':
      $block['content'] = diy_startpage_text_block();
      break;
    case 'diy_startpage_section_social':
      $block['content'] = diy_startpage_section_social();
      break;
    case 'diy_startpage_section_why':
      $block['content'] = diy_startpage_section_why();
      break;
  }
  return $block;
}

function diy_startpage_section_social() {
  if($google = variable_get('diy_defaults_pfrontpage_social_plus', '')) {
    $google = l(theme_image(array('path' => drupal_get_path('theme', 'diy') . '/images/social_google_gray.png', 'attributes' => array())), $google, array('html' => true, 'attributes' => array('target' => '_blank', 'class' => 'social-icon google', 'rel' => 'nofollow')));
  }
  if($facebook = variable_get('diy_defaults_pfrontpage_social_facebook', '')) {
    $facebook = l(theme_image(array('path' => drupal_get_path('theme', 'diy') . '/images/social_facebook_gray.png', 'attributes' => array())), $facebook, array('html' => true, 'attributes' => array('target' => '_blank', 'class' => 'social-icon facebook', 'rel' => 'nofollow')));
  }
  if($youtube = variable_get('diy_defaults_pfrontpage_social_youtube', '')) {
    $youtube = l(theme_image(array('path' => drupal_get_path('theme', 'diy') . '/images/social_youtube_gray.png', 'attributes' => array())), $youtube, array('html' => true, 'attributes' => array('target' => '_blank', 'class' => 'social-icon youtube', 'rel' => 'nofollow')));
  }
  $rss = l(theme_image(array('path' => drupal_get_path('theme', 'diy') . '/images/social_rss_gray.png', 'attributes' => array())), 'rss', array('html' => true, 'attributes' => array('class' => 'social-icon rss')));
  $pinterest = l(theme_image(array('path' => drupal_get_path('theme', 'diy') . '/images/social_pinterest_gray.png', 'attributes' => array())), 'https://www.pinterest.com/diybook2pin', array('html' => true, 'attributes' => array('target' => '_blank', 'class' => 'social-icon pinterest', 'rel' => 'nofollow')));

  return theme('diy_startpage_section_social', array(
    'heading' => t('Get connected'),
    'heading1' => t('ongoing updates'),
    'text' => t('Follow and share experience'),
    'google' => $google,
    'facebook' => $facebook,
    'youtube' => $youtube,
    'rss' => $rss,
    'pinterest' => $pinterest
  ));
}
function diy_startpage_section_why() {
  $accordeon = array();
  foreach(array(1,2,3) as $number) {
    $heading = variable_get('diy_defaults_pfrontpage_why_heading' . $number, '');
    $content = variable_get('diy_defaults_pfrontpage_why_content' . $number, '');

    if($heading && $content) {
      $accordeon[] = array(
        'heading' => $heading,
        'content' => $content,
        'icon_class' => 'acc_icon_' . $number
      );
    }
  }

  drupal_add_css('system', 'ui.accordion');

  $image = theme_image(array('path' => drupal_get_path('theme', 'diy') . '/images/diy_logo_white.png', 'attributes' => array()));

  return theme('diy_startpage_section_why', array(
    'heading' => variable_get('diy_defaults_pfrontpage_why_headline', ''),
    'sections' => $accordeon,
    'image' => $image
  ));
}


/*
 * Block callback
 */
function diy_startpage_social_links() {
  $heading = variable_get('diy_defaults_pfrontpage_social_heading', '');
  $google = variable_get('diy_defaults_pfrontpage_social_plus', '');
  $facebook = variable_get('diy_defaults_pfrontpage_social_facebook', '');
  $youtube = variable_get('diy_defaults_pfrontpage_social_youtube', '');

  $logo = theme_image(array('path' => drupal_get_path('theme', 'diy') . '/images/prefooter_text_logo_small.png', 'alt' => t('DIY Logo'), 'attributes' => array('class' => 'logo')));

  if($google) {
    $google = l(theme_image(array('path' => drupal_get_path('theme', 'diy') . '/images/social_google.png', 'attributes' => array())), $google, array('html' => true, 'attributes' => array('target' => '_blank', 'class' => 'social-icon google')));
  }
  if($facebook) {
    $facebook = l(theme_image(array('path' => drupal_get_path('theme', 'diy') . '/images/social_facebook.png', 'attributes' => array())), $facebook, array('html' => true, 'attributes' => array('target' => '_blank', 'class' => 'social-icon facebook')));
  }
  if($youtube) {
    $youtube = l(theme_image(array('path' => drupal_get_path('theme', 'diy') . '/images/social_youtube.png', 'attributes' => array())), $youtube, array('html' => true, 'attributes' => array('target' => '_blank', 'class' => 'social-icon youtube')));
  }

  $rss = l(theme_image(array('path' => drupal_get_path('theme', 'diy') . '/images/social_rss.png', 'attributes' => array())), 'rss', array('html' => true, 'attributes' => array('class' => 'social-icon rss')));

  return theme('diy_startpage_social', array(
    'logo' => $logo,
    'heading' => $heading,
    'google' => $google,
    'facebook' => $facebook,
    'youtube' => $youtube,
    'rss' => $rss
  ));
}

/*
 * Block callback for frontpage text block
 */
function diy_startpage_text_block() {
  $title = variable_get('diy_defaults_pfrontpage_text_heading1', '');
  $content = variable_get('diy_defaults_pfrontpage_text_content1', '');

  $settings = array(
    'title' => $title,
    'content' => $content
  );

  if($quote = variable_get('diy_defaults_pfrontpage_quote', '')) {
    $settings += array('quote' => $quote);
  }

  if($portrait = variable_get('diy_defaults_pfrontpage_portrait', '')) {
    if($portrait_file = file_load($portrait)) {
      $portrait_image = theme_image_style(array(
        'path' => $portrait_file->uri,
        'style_name' => 'large',
        'width' => NULL,
        'height' => NULL
      ));
      $settings += array('portrait' => $portrait_image);
    }
  }

  return theme('diy_startpage_text', $settings);
}

function diy_startpage_navigator_block_tabs() {
  $data = _diy_startpage_get_navigator_data_all();

  $config = array(
    'grid-width' => 12 / count($data)
   );

  return theme('diy_startpage_navigator_tabs', array('sections' => $data, 'config' => $config));
}

function _diy_startpage_get_navigator_data_all() {
  $data = array();

  foreach(array(1,2,3) as $delta) {
    $nav_data = _diy_startpage_get_navigator_data($delta);

    if(isset($nav_data['title']) && !empty($nav_data['title'])) {
      $data[$delta] = $nav_data;
    }
  }

  return $data;
}

function _diy_startpage_get_navigator_data($delta) {
  $data = array();

  $data['title'] = variable_get('diy_defaults_pfrontpage_navigator_tab_header' . $delta, '');
  $data['text'] = variable_get('diy_defaults_pfrontpage_navigator_tab_text' . $delta, '');

  if($image = variable_get('diy_defaults_pfrontpage_navigator_tab_image' . $delta, '')) {
    $file = file_load($image);
    $data['image'] = theme_image(array('path' => $file->uri, 'attributes' => array()));
  }

  $action_link = variable_get('diy_defaults_pfrontpage_navigator_action_link' . $delta, '');
  $action_text = variable_get('diy_defaults_pfrontpage_navigator_action_text' . $delta, '');

  if($action_link && $action_text) {
    $data['link'] = l($action_text, $action_link);
  }

  return $data;
}

/**
 * Form for knowledge frontpage block.
 */
function diy_startpage_navigator_knowledge_form() {
  /*
  $tid = variable_get('diy_defaults_bauen_renovieren_term', '71');

  $output[0] = t('Categoryselect');
  if($term = taxonomy_term_load($tid)) {
    if($term->vid == 7) {

      $businesses = field_get_items('taxonomy_term', $term, 'field_business');

      if(!empty($businesses)) {
        $links = array();

        foreach($businesses as $business) {
          if($business_term = taxonomy_term_load($business['tid'])) {
            $output[$business_term->tid] = $business_term->name;
          }
        }
      }
    }
  }
  */

  $output = array();
  $output[0] = t('Categoryselect');

  if($terms = taxonomy_get_tree(5, 0, 1)) {
    foreach($terms as $term) {
      $output[$term->tid] = $term->name;
    }
  }

  $form['select'] = array (
    '#title' => t('do it yourself'),
    '#title_display' => 'invisible',
    '#type' => 'select',
    '#options' => $output,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search')
  );

  return $form;
}

/**
 * Submit handler for knowledge frontpage block.
 */
function diy_startpage_navigator_knowledge_form_submit($form, &$form_state) {
  if(!empty($form_state['values']['select']) && $form_state['values']['select'] != 0) {
    drupal_goto('taxonomy/term/' . intval($form_state['values']['select']));
  } else {
    drupal_goto('<front>');
  }
}

/**
 * Implements HOOK_views_pre_execute().
 */
function diy_startpage_views_pre_view(&$view) {  
  global $language;
  if($view->name == 'taxonomy_search') {
    if(isset($view->args[0])) {
      if($term = taxonomy_term_load($view->args[0])) {
        
        // meta tags a are complicated here
        // the url parameter contains the term id of area (eg. living room)
        // a view lines down, we are changing the argument handling to the terms
        // used by apache solr. so we have to do metatag stuff by hand.
        metatag_entity_view($term, 'taxonomy_term', 'full', $language->language);
        
        // if term is bereich, change args to linked businesses        
        if($term->vid == 7) {
          
          // set to all
          // if no field_businesses are set, show all
          $view->args[0] = 'all';
            
          #$house = diy_startpage_area_channel();
          
          #$view->attachment_before = $house;
          $field_items = field_get_items('taxonomy_term', $term, 'field_business');
          if(!empty($field_items)) {
            $businesses = array_map(function($item) { return $item['tid']; }, $field_items);
            
            $view->args[0] = implode(',', $businesses);
          } 
        }
      }
    }    
  }
  
  if($view->name == 'startpage') {
    #$house = diy_startpage_area_channel();
    #$view->attachment_before = $house;
  }
}

/**
 * Callback function for business 
 */
function diy_startpage_business_content() {

  if(arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    if($term = taxonomy_term_load(arg(2))) {
      if($term->vid == 7) {
        
        $businesses = field_get_items('taxonomy_term', $term, 'field_business');
        
        if(!empty($businesses)) {
          $links = array();
          
          foreach($businesses as $business) {
            if($business_term = taxonomy_term_load($business['tid'])) {
              $links[] = array(
                'href' => 'taxonomy/term/' . $business_term->tid,
                'title' => $business_term->name,
              ); 
            }
          }
          
          return theme('links', array(
            'links' => $links, 
            'attributes' => array()
          ));
        }
      }
    }
  }
  
  return FALSE;
}

/**
 * Implements HOOK_theme().
 */
function diy_startpage_theme($existing, $type, $theme, $path) {
  return array(
    'diy_startpage_house' => array(
      'template' => 'house',
      'variables' => array(
        'links' => array(),
        'image' => NULL,
      )
    ),
    'diy_startpage_navigator' => array(
      'template' => 'navigator',
      'variables' => array(
        'title' => NULL,
        'content' => NULL,
        'link' => NULL,
        'action_link' => NULL,
        'form' => NULL,
        'quote' => array()
      )
    ),
    'diy_startpage_navigator_tabs' => array(
      'template' => 'navigator_tabs',
      'variables' => array(
        'sections' => array(),
        'config' => array()
      )
    ),
    'diy_startpage_text' => array(
      'template' => 'text',
      'variables' => array(
        'title' => NULL,
        'content' => NULL,
        'image' => NULL
      )
    ),
    'diy_startpage_social' => array(
      'template' => 'social',
      'variables' => array(
        'heading' => NULL,
        'google' => NULL,
        'facebook' => NULL,
        'youtube' => NULL,
        'logo' => NULL,
        'rss' => NULL
      )
    ),
    'diy_startpage_section_social' => array(
      'template' => 'section_social',
      'variables' => array(
        'heading' => NULL,
        'heading1' => NULL,
        'text' => NULL,
        'google' => NULL,
        'facebook' => NULL,
        'youtube' => NULL,
        'rss' => NULL,
        'pinterest' => NULL
      )
    ),
    'diy_startpage_section_why' => array(
      'template' => 'section_why',
      'variables' => array(
        'heading' => NULL,
        'sections' => NULL,
        'image' => NULL
      )
    ),
  );
}

/**
 * Generates house and links
 */
function diy_startpage_area_channel() {
  // check for house - if not set, use detault
  $house = file_create_url(drupal_get_path('module', 'diy_startpage') . '/img/house.png');
  
  foreach(array(1,2,3,4) as $number) {
    if($current_image = variable_get('diy_defaults_frontpage_image' . $number, '')) {
      $start = variable_get('diy_defaults_frontpage_date'. $number .'_start', '');
      $end = variable_get('diy_defaults_frontpage_date'. $number .'_end', '');      
      
      $start_timestamp = mktime(0, 0, 0, $start['month'], $start['day'], $start['year']);
      $end_timestamp = mktime(23, 59, 59, $end['month'], $end['day'], $end['year']);
      
      $now = time();
      if($now > $start_timestamp && $now < $end_timestamp) {     
        if($house = file_create_url(file_load($current_image)->uri)) {
          break; 
        }
      }
    }
  }
  
  $links = array();
  $tree = taxonomy_get_tree(7, 71);
  if($tree) {
    foreach($tree as $term) {
      $links[$term->tid] = array('url' => url('taxonomy/term/' . $term->tid), 'title' => check_plain($term->name));
      
      // mark active term
      if(arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
        if($term_url = taxonomy_term_load(arg(2))) {
          if($term_url->vid == 7 && $term_url->tid == $term->tid) {
            $links[$term->tid] += array('active' => TRUE);
          }
        }
      }
    }
  }
  
  return theme('diy_startpage_house', array('links' => $links, 'image' => $house));
}

/**
 * Implements HOOK_form_alter().
 */
function diy_startpage_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'views_exposed_form' && $form['#id'] == 'views-exposed-form-page-search-page' && drupal_is_front_page()) {

    if(isset($form['search'])) {
      $form['search']['#attributes']['placeholder'] = t('Full text search: your search for your project');
    }

    $form['#prefix'] = '<h3>' . t('Get started with full text search') . '</h3>';

  }

}