<?php
/**
 * Conditional logic and data processing.
 *
 * Can be used to hold preprocessors [1] for generating variables before
 * they are merged with the markup inside .tpl.php files.
 *
 * Custom functions, overriding theme functions [2], or any other customization
 * of the raw output should be done here.
 *
 * NB: omit the php closing tag.
 *
 * [1] @see https://drupal.org/node/223430
 * [2] @see https://drupal.org/node/173880#function-override
 *
 * @package Valencia
 * @since 1.0.0
 */

/**
 * Add external scripts and styles.
 *
 * External stylesheets and scripts cannot be inserted in the theme's
 * .info file. You must use this function instead.
 *
 * @since 1.0.0
 *
 * @uses drupal_add_css()
 */
function valencia_preprocess_html( &$variables ) {
	/**
	 * Add a cascading stylesheet to the stylesheet queue.
	 *
	 * Calling drupal_static_reset('drupal_add_css') will clear all cascading stylesheets added so far.
	 *
	 * If CSS aggregation/compression is enabled, all cascading stylesheets added with $options['preprocess']
	 * set to TRUE will be merged into one aggregate file and compressed. Preprocessed inline stylesheets
	 * will not be aggregated into this single file; instead, they are just compressed upon output on the page.
	 * Externally hosted stylesheets are never aggregated or compressed.
	 *
	 * @see drupal_get_css()
	 * @since 1.0.0
	 *
	 * @param string $data Optional. Stylesheet data to be added, depending on what is passed through the
	 *								 $options['type'] parameter.
	 * @param string|array $options {
	 * 		String defining the 'type' of CSS that is being added in the $data parameter or an array which can
	 * 		have any or all the following keys. Optional.
	 *
	 *		@type string $type The type of stylesheet being added. Default <file>. Accepts <file>, <inline>, <external>.
	 * 		@type string $basename Force a basename for the file being added.
	 * 		@type integer $group Number identifying the group in which to add the stylesheet. CSS within higher
	 *							 number group take precedence over CSS within lower number groups.
	 *							 Accepts <CSS_SYSTEM>, <CSS_DEFAULT>, <CSS_THEME>.
	 *		@type bool $every_page Should be set to TRUE if the stylesheet is present on every page of the website.
	 *							   Default <FALSE>.
	 *		@type integer $weight CSS order relative to the same group and $every_page.
	 *		@type string $media Media type for the stylesheet. Default <all>.
	 *		@type bool $preprocess If TRUE and CSS aggregation/compression is enabled, the styles
	 *							   will be aggregated and compressed. Default <TRUE>.
	 *		@type array $browsers Info specifying which browsers should load the CSS item.
	 *							  @link https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_pre_render_conditional_comments/7
	 * }
	 * @return array Queued cascading stylesheets.
	 */
	//drupal_add_css('http://assets.ubuntu.com/sites/guidelines/css/responsive/latest/ubuntu-styles.css', array(
	//    'type'	    => 'external',
	//    'group'	    => CSS_DEFAULT,
	//    'every_page'    => true
	//));

	//drupal_add_css('http://assets.ubuntu.com/sites/ubuntu/1160/u/css/styles.css', array(
	//    'type'	    => 'external',
	//    'group'	    => CSS_DEFAULT,
	//    'every_page'    => true
	//));
   
	drupal_add_css( drupal_get_path( 'theme', 'valencia' ) . '/css/style.css', array(
		'type'			=> 'file',
		'group'			=> CSS_THEME,
		'every_page'	=> true
	));

	/**
	 * Add JavaScript file, setting, or inline code to the page.
	 *
	 * The behaviour of this function depends on the parameters it is called with.
	 * Generally, it handles the addition of JavaScript to the page, either as reference
	 * to an existing file or as inline code. You can:
	 * - Add a file ('file')
	 * - Add inline JavaScript code ('inline'). Make sure to wrap code in `(function($){})(jQuery);`
	 * - Add external JavaScript ('external')
	 * - Add settings ('setting'). Will be accessible at Drupal.settings
	 *
	 * If JavaScript aggregation is enabled, all JavaScript files added with $options['preprocess']
	 * set to TRUE will be merged into one aggregate file. Preprocessed inline JavaScript will not be
	 * aggregated into this single file. Externally hosted JavaScripts are never aggregated.
	 *
	 * @see drupal_get_js()
	 * @since 1.0.0
	 *
	 * @param string $data Optional. If given, the value depends on the $options or $options['type'] parameter.
	 * @param string|array $options {
	 *		String defining the type of JavaScript that is being added in the $data parameter (<file>,
	 *		<setting>, <inline>, <external>), or an associative array. JavaScript settings should always
	 *		pass the string 'setting' only. Other types can have the following elements in the array. Optional.
	 *
	 *		@type string $type Type of JavaScript. Default <file>. Accepts <file>, <inline>, <external>, <setting>.
	 *		@type string $scope Location of the script. Can use custom regions. Default <header>. Accepts <header>, <footer>.
	 *		@type integer $group Number of the JS group. Defines priority (higher first). Accepts <JS_LIBRARY>, <JS_DEFAULT>,
	 *							 <JS_THEME>.
	 *		@type bool $every_page If present in every page of the website. Default <FALSE>.
	 *		@type integer $weight Priority relative to the scope, group, and every_page. Higher first.
	 *		@type bool $defer If TRUE, defer attribute is set on the script tag. Default <FALSE>.
	 *		@type bool $cache Cache JS file. Used only when $type references a JS file. Default <TRUE>.
	 *		@type bool $preprocess If TRUE and aggregation is enabled, script file will be aggregated. Default <TRUE>.
	 * }
	 * @return array JavaScript file, settings, and inline code, including Drupal defaults.
	 */
		drupal_add_js('http://assets.ubuntu.com/sites/ubuntu/1160/u/js/plugins/modernizr.2.7.1.js', array(
			'type'          => 'external',
			'group'         => JS_LIBRARY,
			'every_page'    => 'TRUE'
		));

		drupal_add_js('http://assets.ubuntu.com/sites/ubuntu/1160/u/js/plugins/yui-combined.min.js', array(
			'type'          => 'external',
			'group'         => JS_DEFAULT,
			'every_page'    => 'TRUE',
			'scope'         => 'footer'
		));

		drupal_add_js("if(!core){ var core = {}; } core.globalPrepend = 'body';", array(
			'type'          => 'inline',
			'group'         => JS_DEFAULT,
			'every_page'    => 'TRUE',
			'scope'         => 'footer'
		));

		drupal_add_js('http://assets.ubuntu.com/sites/guidelines/js/responsive/core.js', array(
			'type'          => 'external',
			'group'         => JS_THEME,
			'every_page'    => 'TRUE',
			'scope'         => 'footer'
		));

		drupal_add_js('http://assets.ubuntu.com/sites/ubuntu/1160/u/js/plugins/respond.min.js', array(
			'type'          => 'external',
			'group'         => JS_THEME,
			'every_page'    => 'TRUE',
			'scope'         => 'footer'
		));
}

/**
 * Add our hooks to the page
 *
 */
function valencia_preprocess_page( &$vars ) {
    // Remove the title from all pages but news
    if (isset($vars['node'])) {
        if ($vars['node']->type !== 'blog') {
            $vars['title'] = '';
        }
    }

    // Get the entire main menu tree
    $main_menu_tree = menu_tree_page_data('main-menu');
    // and add the active trail
    menu_tree_add_active_path($main_menu_tree);

    // Add the rendered output to menu
    $vars['valencia_menu'] = menu_tree_output($main_menu_tree);
}

/**
 * Add the active trail indicators into the tree.
 *
 * The data returned by menu_tree_page_data() has link['in_active_trail'] set 
 * to TRUE for each menu item in the active trail. The data returned from 
 * menu_tree_all_data() does not contain the active trail indicators. This is a 
 * helper function that adds it back in.
 *
 * Source: 
 * http://drupalcontrib.org/api/drupal/contributions!menu_block!menu_block.module/function/menu_tree_add_active_path/7
 */
function menu_tree_add_active_path(&$tree) {
	// Grab any menu item to find the menu_name for this tree.
	$menu_item = current($tree);
	$tree_with_trail = menu_tree_page_data($menu_item['link']['menu_name']);

	// To traverse the original tree down the active trail, we use a pointer.
	$subtree_pointer = &$tree;

	// Find each key in the active trail.
	while ($tree_with_trail) {
		foreach ($tree_with_trail as $key => &$value) {
			if ($tree_with_trail[$key]['link']['in_active_trail']) {
				// Set the active trail info in the original tree.
				$subtree_pointer[$key]['link']['in_active_trail'] = TRUE;
				// Continue in the subtree, if it exists.
				$tree_with_trail = &$tree_with_trail[$key]['below'];
				$subtree_pointer = &$subtree_pointer[$key]['below'];
				break;
			}
			else {
				unset($tree_with_trail[$key]);
			}
		}
	}
}

/**
 * Choose which menu create basing on the id
 */
function valencia_links__system_main_menu($vars) {
	switch ($vars['id']) {
		case 'header':
			return valencia_header_menu($vars);
		case 'subheader':
			return valencia_subheader_menu($vars);
		case 'breadcrumb':
			return valencia_breadcrumb_menu($vars);
		case 'footer':
			return valencia_footer_menu($vars);
	}
}

/** 
 * Custom links for header menu
 * Follows http://design.ubuntu.com/web-style-guide/scaffolding#navigation
 */
function valencia_header_menu($vars) {
    // Var with all HTML of the menu
    $html = '<ul>';

    foreach ($vars['links'] as $key => $link) {
        // To print every menu voice only one, see Drupal API
        if (is_numeric($key)) {
            $link_title = $link['#title'];
            $link_href = $link['#href'];

            if ($link['#original_link']['in_active_trail']) {
                $html .= '<li>' . l($link_title, $link_href, array(
                    'html' => 'true',
                    'attributes' => array(
                        'class' => array(
                            'active'
                    )))) . '</li>';
            }
            else {
                $html .= '<li>' . l($link_title, $link_href, array('html' => 'true')) . '</li>';
            }
        }
    }

    $html .= '</ul>';
    return $html;
}

/** 
 * Custom links for subheader menu
 * Follows a custom design
 *
 * We need to print only the submenu of active menu
 */
function valencia_subheader_menu($vars) {
	// Var with all HTML of the menu
	$html = '';

	foreach ($vars['links'] as $key => $link) {
		// To print every menu voice only one, see Drupal API
		if (is_numeric($key)) {
			// Check for submenu, but only if they are of first level and this 
			// is the active link
			if (!empty($link['#below']) && $link['#original_link']['depth'] === '1' && $link['#original_link']['in_active_trail']) {
				// If there is a submenu create it using the header function, 
				// because they have the same struct
				$sub_menu = theme('links__system_main_menu', array(
					'links' => $link['#below'],
					'id'    => 'header'
				));
				$html .= $sub_menu;
			}
		}
	}

	return $html;
}

/**
 * Custom breadcrumb and third level menu
 * Follows partially http://design.ubuntu.com/web-style-guide/scaffolding#navigation
 *
 * Breadcrumb is printed only on page with deep level > 1
 * Also, if there is, we print third level menu
 */
function valencia_breadcrumb_menu($vars) {
    // Var with all HTML
    $html = '';

    foreach ($vars['links'] as $key => $link) {
        // See Drupal API, is to print every menu voice only one
        if (is_numeric($key)) {
            // We need only active links, with children and we
            // don't want the news page
            if ($link['#original_link']['in_active_trail'] &&
                !empty($link['#below']) &&
                $link['#title'] !== 'News') {
                // If is the first level link and it has children,
                // we start to create the breadcrumb
                if(!empty($link['#below']) && $link['#original_link']['depth'] === '1') {
                    $html .= '<ul class="breadcrumb">';
                    // Now we need to attach second level menu
                    $sub_menu = theme('links__system_main_menu', array(
                        'links' => $link['#below'],
                        'id'    => 'breadcrumb'
                    ));
                    $html .= $sub_menu;
                }
                // Second level link: could be the active one, or only a
                // breadcrumb for third level (or both)
                else if ($link['#original_link']['depth'] === '2') {
                    // If it hasn't child, is the active link
                    if (empty($link['#below'])) {
                        $link_title = $link['#title'];
                        $link_href = $link['#href'];
                        $html .= '<li class="active">' . l($link_title, $link_href, array('html' => 'true')) . '</li>';
                        // We close the ul with class breadcrumb, as per design
                        $html .= '</ul>';
                    }
                    else {
                        // If it has children could be active or not. 
                        // To check we need to create first the third level 
                        // menu, and check if any of the third level menu links 
                        // is active
                        list ($has_child_active_link, $third_level_menu) = valencia_third_level_menu($link['#below']);

                        $link_title = $link['#title'];
                        $link_href = $link['#href'];

                        // If a child is active, this one isn't active
                        if ($has_child_active_link) {
                            $html .= '<li>' . l($link_title, $link_href, array('html' => 'true')) . '&nbsp;&rsaquo;</li>';
                        }
                        else {
                            $html .= '<li class="active">' . l($link_title, $link_href, array('html' => 'true')) . '</li>';
                        }

                        // We close the ul with class breadcrumb, as per design
                        $html .= '</ul>';

                        // Then, third level menu 
                        $html .= $third_level_menu;  
                    }
                }    
            }
        }
    }

    return $html;
}

/**
 * Create third level menu html
 * Follows http://design.ubuntu.com/web-style-guide/scaffolding#navigation
 *
 * Don't call this function directly, is only for valencia_breadcrumb_menu()
 *
 * Return an array: the first element is a bool that indicate if there is an 
 * active link, the second element is the html of third level menu
 */
function valencia_third_level_menu($vars) {
	// Var with all HTML
	$html = '<ul class="third-level">';
	// This becomes TRUE if there is an active link
	$has_active_link = FALSE;

	foreach ($vars as $key => $link) {
		// See Drupal API, is to print every menu voice only one
		if (is_numeric($key)) {
			if ($link['#original_link']['in_active_trail']) {
				$has_active_link = TRUE;
				$link_title = $link['#title'];
				$link_href = $link['#href'];
				$html .= '<li class="active">' . l($link_title, $link_href, array('html' => 'true')) . '</li>';
			}
			else {
				$link_title = $link['#title'];
				$link_href = $link['#href'];
				$html .= '<li>' . l($link_title, $link_href, array('html' => 'true')) . '</li>';
			}
		}
	}

	$html .= '</ul>';

	return array($has_active_link, $html);
}

/**
 * Custom links for footer menu
 * Follows http://design.ubuntu.com/web-style-guide/scaffolding#footer
 *
 * TODO: Remove active class from the link of open page
 * This doesn't hurt the layout at the moment, but doesn't follow the 
 * indications, so can be a problem in the future.
 * https://gitlab.com/ubuntu-it-web/valencia/issues/5
 *
 * TODO: Check if there are > 7 categories, and add footer of type B for 
 * categories after the 7th
 * https://gitlab.com/ubuntu-it-web/valencia/issues/6
 */
function valencia_footer_menu($vars) {
    // Var with all HTML of the menu
    $html = '<ul>';
    // Counter to select first element of every submenu to add class .first
    $voice_number = 0;

    foreach ($vars['links'] as $key => $link) {
        // To print every menu voice only one, see Drupal API
        if (is_numeric($key)) {
            // Store the submenu links
            $sub_menu = '';
            $link_title = $link['#title'];
            // Check for submenu, but only if they are of first level!
            if (!empty($link['#below']) && $link['#original_link']['depth'] === '1') {
                // If there is a submenu create it using the same function
                $sub_menu = theme('links__system_main_menu', array(
                    'links' => $link['#below'],
                    'id'    => 'footer'
                ));
            }

            /**
             * We have 3 types of link:
             * - First level link, they are h2 title, and will be identify for
             *   by their depth of 1
             * - First link of second level menus, they have class .first,
             *   identified by $voice_number
             * - Others links of second level menus
             */
            if ($link['#original_link']['depth'] === '1') {
                // First level menu is h2
                $html .= '<li><h2>' . l($link_title, $link['#href'], array('html' => 'true')) . '</h2>' . $sub_menu . '</li>';
            }
            else if ($voice_number === 0) {
                // The first submenu of every menu has class first
                $html .= '<li class="first">' . l($link_title, $link['#href'], array('html' => 'true')) . $sub_menu . '</li>';
            }
            else {
                // Submenu voice
                $html .= '<li>' . l($link_title, $link['#href'], array('html' => 'true')) . $sub_menu . '</li>';
            }
            $voice_number++;
        }
    }

    $html .= '</ul>';
    return $html;
}

if ( !function_exists( 'region_empty' ) ) :
/**
 * Check if region is empty.
 *
 * Examines the block visibility setting for the current path to work out
 * if the region is occupied.
 *
 * @param string $region Region name.
 * @return bool. True if empty, false otherwise.
 */
function region_empty( $region ) {
	$empty = 1;
	$result = db_query_range( 'SELECT n.pages, n.visibility FROM {blocks} n WHERE n.region="%s" AND n.theme="%s"', $region, $GLOBALS['theme'], 0, 10 );

	if ( count($result) > 0 ) {
		while ( $node = db_fetch_object($result) ) {
			if ( $node->visibility < 2 ) {
				$path = drupal_get_path_alias($_GET['q']);
				// Compare with the internal and path alias (if any)
				$page_match = drupal_match_path($path, $node->pages);

				if ( $path != $_GET['q'] )
					$page_match = $page_match || drupal_match_path( $_GET['q'], $node->pages );

				/**
				 * When $block->visibility has a value of 0, the block is displayed on
				 * all pages except those listed in $block->pages. When set to 1, it
				 * is displayed only on those pages listed in $block->pages.
				 */
				$page_match = !( $node->visibility xor $page_match );
			} else {
				$page_match = drupal_eval( $block->pages );
			}

			if ( $page_match )
				$empty = 0;
		}
	}

	return $empty;
}
endif;
