<?php

/**
 * Implementation of HOOK_menu_alter().
 */
function diy_menu_alter(&$items) {
  // disable default node overview page
  unset($items['node']);
}

/**
 * Implementation of hook_theme()
 */
function diy_theme($existing, $type, $theme, $path) {
  return array(
    'diy_social_link' => array(
      'variables' => array('imagepath' => NULL, 'path' => NULL),
    ),
    'diy_image_container' => array(
      'variables' => array('image' => NULL, 'description' => NULL, 'desc_trim' => NULL),
    ),
    'user_profile_form' => array(
      'arguments' => array('form' => NULL),
      'render element' => 'form',
    ),
  );
}

/**
 * Implementation of hook_block_info().
 */
function diy_block_info() {
  $blocks['diy_footer_social_links'] = array(
    'info' => t('DIY - social links footer'),
  );
  $blocks['diy_footer_links'] = array(
    'info' => t('DIY - links footer'),
  );
  $blocks['diy_write_article'] = array(
    'info' => t('DIY - write article'),
  );  
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function diy_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'diy_footer_social_links':
      $block['subject'] = t('DIY - social links footer');
      $block['content'] = diy_social_links_footer();
      break;
    case 'diy_footer_links':
      $block['subject'] = t('DIY - links footer');
      $block['content'] = diy_links_footer();
      break;
     case 'diy_write_article':
      $block['subject'] = t('Write Article');
      $block['content'] = diy_write_article();
      break; 
      
  }
  return $block;
}

function diy_write_article() {
  $ouput = '';
  
  $ouput .= t('Use the chance to win 200 EUR and document your last project!');

  $ouput .= l('Jetzt mitmachen', 'mitmachen-gewinnen', array('attributes' => array('class' => 'button')));
  
  return $ouput;
}

function diy_links_footer() {
  // TODO
  $output = '';
  
  
  $output .= '<em>Wissen</em>';
  
  $output .= '<ul class="menu">';
  $output .= '<li class="leaf first">' . '<a href="#">Maler</a>' . '</li>';
  $output .= '<li class="leaf">' . '<a href="#">Tischler</a>' . '</li>';
  $output .= '<li class="leaf">' . '<a href="#">Maurer</a>' . '</li>';
  $output .= '<li class="leaf">' . '<a href="#">Installateur</a>' . '</li>';
  $output .= '<li class="leaf">' . '<a href="#">Elektriker</a>' . '</li>';
  $output .= '<li class="leaf">' . '<a href="#">Bodenleger / Fließenleger</a>' . '</li>';
  $output .= '<li class="leaf">' . '<a href="#">Umzug und Transport</a>' . '</li>';
  $output .= '<li class="leaf last">' . '<a href="#">Gärtner</a>' . '</li>';
  
  $output .= '</ul>';
  
  return $output;
}

function diy_social_links_footer() {
  $output = '';
  
  $output .= '<em>' . t('Follow us') . '</em>';
  
  $output .= theme('diy_social_link', array('imagepath' => drupal_get_path('module', 'diy') . '/images/icons/facebook.png', 'path' => 'http://www.facebook.com/diybook'));
  /*$output .= theme('diy_social_link', array('imagepath' => drupal_get_path('module', 'diy') . '/images/icons/twitter.png', 'path' => '#'));*/
  $output .= theme('diy_social_link', array('imagepath' => drupal_get_path('module', 'diy') . '/images/icons/googleplus.png', 'path' => 'https://plus.google.com/110847696921622096107'));
  $output .= theme('diy_social_link', array('imagepath' => drupal_get_path('module', 'diy') . '/images/icons/youtube.png', 'path' => 'http://www.youtube.com/diybook'));
  
  return $output;
}

function diy_diy_social_link($variables) {
  return l(theme_image(array('path' => $variables['imagepath'], 'attributes' => array())), $variables['path'], array('html' => true));
}

function diy_diy_image_container($variables) {
  $output = '';
  $output .= $variables['image'];
  
  if(!empty($variables['description'])) {
    $description = $variables['description'];
    
    if(!empty($variables['desc_trim'])) {
      $description = views_trim_text(array('max_length' => $variables['desc_trim'], 'ellipsis' => TRUE, 'word_boundary' => TRUE, 'html' => TRUE), $description);
    }
    
    $output .= '<div class="description">';
    $output .= $description;
    $output .= '</div>';
  }
  
  return $output;
}


function diy_facet_items_alter(&$build, &$settings) {
  if ($settings->facet == "field_ingesamt") {
    foreach($build as $key => $item) {
      $build[$key]["#markup"] = t($item["#markup"]);
    }
  }

  if ($settings->facet == "field_ingesamt:average_rating") {

    foreach($build as $key => $item) {
      if(is_numeric($item["#markup"])) {
        $build[$key]["#html"] = TRUE;
        $path = drupal_get_path('module', 'fivestar');
        drupal_add_css($path . '/css/fivestar.css');
        
        //  t('Stars: !count', array('!count' => round(($item["#markup"]/100) * 5, 1))) .
        $build[$key]["#markup"] = theme('fivestar_static', array(
          'stars' => 5,
          'rating' => $item["#markup"],
          'widget' => array(
              'name' => 'basic',
              'css' => $path . '/widgets/basic/basic.css',
            ),
          'tag' => '')
        );
      
      }
    }
  }

  if ($settings->facet == "field_article_difficulty") {
    foreach($build as $key => $item) {
      $build[$key]["#markup"] = t($item["#markup"]);
    }
  }

  if ($settings->facet == "field_rate_article:average_rating") {

    foreach($build as $key => $item) {
      if(is_numeric($item["#markup"])) {
        $build[$key]["#html"] = TRUE;
        $path = drupal_get_path('module', 'fivestar');
        drupal_add_css($path . '/css/fivestar.css');

        //  t('Stars: !count', array('!count' => round(($item["#markup"]/100) * 5, 1))) .
        $build[$key]["#markup"] = theme('fivestar_static', array(
            'stars' => 5,
            'rating' => $item["#markup"],
            'widget' => array(
              'name' => 'basic',
              'css' => $path . '/widgets/basic/basic.css',
            ),
            'tag' => '')
        );

      }
    }
  }

  if($settings->facet == 'field_article_classification') {
    foreach($build as $key => &$item) {
      if(isset($item['#indexed_value']) && strpos($item['#markup'], 'classification-') === false) {
        $item['#markup'] = '<i class="classification-'. $item['#indexed_value']  .'"></i>' . $item['#markup'];
        $item['#html'] = true;
      }
    }
  }

}



/**
 * Implementation of hook_form_alter().
 */
function diy_form_alter(&$form, &$form_state, $form_id) {
  global $language;
  
  if($form_id == 'article_node_form' && isset($form['field_business_canonical'])) {
    foreach($form['field_business_canonical']['und']['#options'] as $key => $label) {
      if(substr($label, 0, 1) != '-') { 
        unset($form['field_business_canonical']['und']['#options'][$key]);
      }    
    }
  }
  /*
   * Altering Register form
   */
  if($form_id == 'user_register_form') {
    drupal_set_title(t('User - Register'));
    
    $form['account']['mail']['#title'] = t('E-Mail Address');
    unset($form['account']['mail']['#description']);
    
    unset($form['legal']['#title']);
    $link_legal = url('legal', array('language' => $language, 'base_url' => base_path()));
    $form['legal']['legal_accept']['#title'] = t('I confirm that i have read and understood <a href="@link" target="_blank">the terms & conditions</a>', array('@link' => $link_legal));

    $form['actions']['submit']['#value'] = t('Register');
  }

  /*
   * Altering Login form
   */
   if($form_id == 'user_login') {
    drupal_set_title(t('User - Login'));

    unset($form['name']['#description']);
    $form['name']['#title'] = t('E-Mail Address');
    unset($form['pass']['#description']);
  }
  
  /*
   * Altering Password reset form ("Forgot password" page)
   */
  if($form_id == 'user_pass') {
    $form['markup'] = array(
      '#type' => 'markup',
      '#markup' => t('Enter your e-mail address and reset instructions will be sent to it.'),
      '#weight' => -50,
    );
    unset($form['name']['#description']);
    $form['name']['#title'] = t('E-Mail Address');
    $form['actions']['submit']['#value'] = t('Request');
  }

  if($form_id == 'user_pass_reset') {
    drupal_set_title(t('User - One Time Login'));
  }  

  /*
   * Altering User profile form (user/%/edit page)
   */  
  if($form_id == 'user_profile_form') {
    drupal_set_title(t('My Account - General Data'));
    
    drupal_add_js(base_path() . 'sites/all/libraries/jquery.bxslider/jquery.bxslider.js');
    drupal_add_css(base_path() . 'sites/all/libraries/jquery.bxslider/jquery.bxslider.css');
    
    #drupal_add_js(base_path() . 'sites/all/libraries/jquery_fileinput/jQuery.fileinput.js');
    
    hide($form['timezone']);
    hide($form['metatags']);
    hide($form['locale']);
    hide($form['contact']);
    unset($form['legal']['#title']);  
    unset($form['picture']['#title']);  

    if(isset($form['account'])) {
      $form['account']['mail']['#weight'] = $form['account']['name']['#weight'] - 1;
    }
    
    $form['picture']['markup_label'] = array(
      '#type' => 'markup',
      '#markup' => '<div class="form-item form-type-textfield avatar-label"><label>' . t('Avatar') . '</label></div>',
      '#weight' => -50,
    );
    
    $form['actions']['submit']['#value'] = t('Update');

    if (isset($_GET['pass-reset-token'])) {
      // Redirect only from user_pass_reset, e.g. user changing password by link from his email letter.
      global $user;
      drupal_goto('user/' . $user->uid . '/change_password', array('query'=>array('pass-reset-token' => $_GET['pass-reset-token'])));
    }
  }
}

/*
 * Theming output of User profile form.
 * It's a pity the module diy.module and theme "diy" has the same name, so there is strange approach - theming in the module's file.
 */
function diy_user_profile_form($vars) {
  $out = '';
  $out .= '<div class="fieldgroup">' 
  . render($vars['form']['field_alias_name']) 
  . render($vars['form']['account'])
  . render($vars['form']['picture']['markup_label']) 
  . '<div class="avatar_field">' . render($vars['form']['picture']) . '</div>'      
  . render($vars['form']['legal']) 
  . '</div>';
  $out .= drupal_render_children($vars['form']);

  drupal_add_js(drupal_get_path('theme', 'diy') . '/js/theme_field_upload.js');
  drupal_add_js(drupal_get_path('theme', 'diy') . '/js/theme_avatar_selection.js');
  
  return $out;
}

/**
 * Implements hook_user_login().
 */
function diy_user_login(&$edit, $account) {  
  //I use here LANGUAGE_NONE because field_alias_name shouldn't be translatible.
  if (empty($account->field_alias_name) || $account->field_alias_name[LANGUAGE_NONE][0]['value']=='') {
    drupal_set_message(t('You should choose an Alias name for your account'));
    drupal_goto('user/' . $account->uid . '/edit');
  }
}
