<?php
/**
 * Project module
*
* Common functions used in back-office to
* displays filter options
*
* @package linea21\modules\project
* @author $Author$ - linea21 <info@linea21.com>
* @version $Id$
* @access public
* @license http://opensource.org/licenses/gpl-3.0.html
*/


/**
 * get_finalities()
 *
 * @param  $id (optionnal) : numeric / false
 * @param  $as_string (optionnal) : true / false
 * @param  $separator (optionnal) : defaulut ','
 * @return array
 */
if(!function_exists('get_finalities')) {

	function get_finalities($id = false, $as_string = true, $separator = ',')
	{
		// we get all values
		$init = $GLOBALS['sql_object']->DBSelect(SQL_getFinalities($id));

		if (! isset ( $init [0] ['finality_id'] )) return false;

		$simple_array = array ();
		$array = array ();

		for($i = 0; $i < count ( $init ); $i ++) {
			$array [$i] ['finality_name'] = $init [$i] ['finality_name'];
			$array [$i] ['finality_id'] = $init [$i] ['finality_id'];
			array_push ( $simple_array, $init [$i] ['finality_name'] );
		}

		if ($as_string) {
			return join ( $separator . ' ', $simple_array );
		} else {
			return $array;
		}

	}
}

function get_sql_status($value) {
	
	$a = array('public' => 'P', 'draft' => 'A', 'archives_p' => 'PA', 'archives_a' => 'AA');

	if(!key_exists($value, $a))  return false;
	else return $a[$value];
}

/**
 * getInternalNav()
 * get internal navigation based on current view
 * @return string
 */
if(!function_exists('getInternalNav')) {
	function getInternalNav() {
	
		$dv_class = $fv_class = $fiv_class = '';
		if(!isset($_REQUEST['view'])) $dv_class = 'active';
		if(isset($_REQUEST['view']) && $_REQUEST['view'] == 'flat') $fv_class = 'active';
		if(isset($_REQUEST['view']) && $_REQUEST['view'] == 'finality') $fiv_class = 'active';
		
		$finality_view = '';
	
		$default_view ='<a href="index.php?rub=project&amp;todo=list" title="'._t('project','level_view').'"  class="'.$dv_class.'">'._t('project','level_view').'</a>';
		$flat_view 	= '<a href="index.php?rub=project&amp;todo=list&amp;view=flat" title="'._t('project','flat_view').'"  class="'.$fv_class.'">'._t('project','flat_view').'</a>';
		if(defined('PROJECT_FINALITIES') && PROJECT_FINALITIES == 1) $finality_view ='<a href="index.php?rub=project&amp;todo=list&amp;view=finality" title="'._t('project','finality_view').'" class="'.$fiv_class.'">'._t('project','finality_view').'</a>';
	
		$navbar = $default_view . $flat_view . $finality_view ;
	
		return sprintf('<div class="mod_link">%s</div><br class="brendstep" />', $navbar);
	
	}
}


if(!function_exists('getMenuFilter')) {

	/**
	 * getMenuFilter()
	 *
	 * @param array $tags
	 * @return string
	 */
	function getMenuFilter ($tags = array(), $finalities = array(), $scales = array(), $priorities = array()) {
	
		footerAddJS('../lib/js/jquery-tag-filtering/jquery.tagfiltering.simo.js');
		addDynamicCSS('../lib/js/jquery-tag-filtering/jquery.tagfiltering.simo.css');
		
		// one call to apply many filters from several lists (ul) with same css class and using distincts data-* attributes
		// to comment if individual filtering are applied
		footerAddInlineJS('$("ul.filter-menu").tagfiltering({target_attr:"data-priorities,data-tags,data-finalities,data-scales", separator:";", callback:compute_values});');
		
		// export Javascript part
		$js =
		'$("#save-export").click( function() {
				var to_export = [];
				var $items = $(".filter-items").children();
		
				// we populate the array to send with ajax
				$items.each(function() {
					if($(this).is(":visible"))  {
						var curval = $(this).attr("data-id");
						// we check if not in array yet - could happen when using "Finality view"
						if($.inArray( curval,to_export) == -1) to_export.push($(this).attr("data-id"));
					}
				});
		
				alertify.success("'. _t('items', 'selected').'".replace("%s", to_export.length));
		
				$.ajax({
					   type: "POST",
					   data: {to_export:to_export},
					   url: "../project/_ajax_save.php?token='.SECRET_KEY.'",
					   success: function(msg){
					   		window.location = "../admin/index.php?rub=project&todo=report";
					   }
					});
			});';
		footerAddInlineJS($js);
		
		$filter_menu  = '<div class="toggle_title"><a id="projects-filter" href="#">'._t('filter', 'content').'</a></div>';
		$filter_menu .= '<div class="contboxwhite" style="display:none">';
		$filter_menu .= getTagsMenuFilter ($tags);
		$filter_menu .= getFinalitiesMenuFilter($finalities);
		$filter_menu .= getScalesMenuFilter($scales);
		$filter_menu .= getPriorityMenuFilter($priorities);
		$filter_menu .= getCompletionMenuFilter();
		$filter_menu .= '<div class="end"><a href="#" id="save-export" class="button regular"><i class="icon-export"></i> '._t('btn', 'save_export').'</a></div><br class="brendstep" />';
		$filter_menu .= '</div>';
		
		return $filter_menu;
	}
}

if(!function_exists('getCompletionMenuFilter')) {

    /**
     * getCompletionMenuFilter()
     *
     * get completion menu filter
     * @param array $tags
     * @return string
     */
    function getCompletionMenuFilter ($steps = PROJECT_STEP, $initialValue = 0) {
        
        // one call to apply many filters from several lists (ul) with same css class and using distincts data-* attributes
        // to comment if individual filtering are applied
        footerAddInlineJS('


            $("#completion-operator").on("change", function() {$( "#completion-filter" ).trigger( "input" );});

            $(document).on("input", "#completion-filter", function() {
                var current = $(this).val();
                var operator = $("#completion-operator").find(":selected").val();
                console.log(current);
                console.log(operator);
                if(operator == "all") {
                    current = 0;
                    operator = ">=";
                    $("#completion-filter").val(current);
                }
                $("#completion-filter-value").text(current + " %").hide().fadeIn();
                $("tbody.filter-items tr").show();
                $("tbody.filter-items tr").filter(function() { 
                    if(operator == ">=") return parseInt($(this).attr("data-completion")) < parseInt(current-1);
                    else if(operator == "<=") return parseInt($(this).attr("data-completion")) > parseInt(current);
                    else return parseInt($(this).attr("data-completion")) != parseInt(current); // operator == "="
                    })
                    .hide(); // !!!! with fadeOut(), compute_values() does not update 
                    compute_values();
        });');
        
        $filter = '';
        $options  = '<select id="completion-operator">
                      <option value="all" checked>'._t('divers', 'select_all').'</option>
                      <option value=">="> >=</option>
                      <option value="<="> <=</option>
                      <option value="="> =</option>
                    </select>';
        $options .= '<input name="completion-filter" id="completion-filter" type="range" min="0" max="100" step="'. $steps . '" value="0" /><span id="completion-filter-value">'.$initialValue.' %</span>';
        
        $filter .= sprintf('<div class="completion-filter"><h3>%s</h3><div class="completion-filter-menu">%s</div></div>', _t('filter', 'by_completion'), $options);
        return $filter;
        
    }
}



if(!function_exists('getPriorityMenuFilter')) {
    
    /**
     * getScalesMenuFilter()
     *
     * get tags menu filter
     * @param array $tags
     * @return string
     */
    function getPriorityMenuFilter ($priorities) {
        
        // to uncomment to apply filter only on scales (without finalities / tags considerations)
        //footerAddInlineJS('$("ul.priorities-filter-menu").tagfiltering({target_attr:"data-priority", exclude_parents:"ul.filter-menu", separator:";", callback:compute_values});');
        
        
        $filter = '';
        
        // we display filter if at least 2 values exists
        if(count($priorities) > 1) {
            $options = '';
            $a = array();
            foreach($priorities as $item) {
                if(!in_array($item['priority_id'], $a)) {
                    $options .= '<li data-tag="'.$item['priority_name'].'" id="priority-'.$item['priority_id'].'"><a class="facet" href="#">'.$item['priority_name'].'</a></li>';
                    array_push($a, $item['priority_id']);
                }
            }
            
            $filter .= sprintf('<div class="priority-filter"><h3>%s</h3><ul class="filter-menu priorities-filter-menu">%s</ul></div>', _t('filter', 'by_priority'), $options);
            
        }
        return $filter;
    }
    
}


if(!function_exists('getScalesMenuFilter')) {

	/**
	 * getScalesMenuFilter()
	 *
	 * get tags menu filter
	 * @param array $tags
	 * @return string
	 */
	function getScalesMenuFilter ($scales) {

		// to uncomment to apply filter only on scales (without finalities / tags considerations)
		//footerAddInlineJS('$("ul.scales-filter-menu").tagfiltering({target_attr:"data-scales", exclude_parents:"ul.filter-menu", separator:";", callback:compute_values});');


		$filter = '';
		
		// we display filter if at least 2 values exists
		if(count($scales) > 1) {
			$options = '';
			$a = array();
			foreach($scales as $item) {
				if(!in_array($item['scale_id'], $a)) {
					$options .= '<li data-tag="'.$item['scale_name'].'" id="scale-'.$item['scale_id'].'"><a class="facet" href="#">'.$item['scale_name'].'</a></li>';
					array_push($a, $item['scale_id']);
				}
			}

			$filter .= sprintf('<div class="scale-filter"><h3>%s</h3><ul class="filter-menu scales-filter-menu">%s</ul></div>', _t('filter', 'by_scale'), $options);

		}
		return $filter;
	}

}


if(!function_exists('getFinalitiesMenuFilter')) {

	/**
	 * getTagsMenuFilter()
	 *
	 * get tags menu filter
	 * @param array $tags
	 * @return string
	 */
	function getFinalitiesMenuFilter ($finalities) {

		// to uncomment to apply filter only on finalities (without scales / tags considerations)
		//footerAddInlineJS('$("ul.finalities-filter-menu").tagfiltering({target_attr:"data-finalities", exclude_parents:"ul.filter-menu", separator:";", callback:compute_values});');


		$filter = '';
		
		// we display filter if at least 2 values exists
		if(count($finalities) > 1) {
			$options = '';
			$a = array();
			foreach($finalities as $item) {
				if(!in_array($item['finality_id'], $a)) {
					$options .= '<li data-tag="'.$item['finality_name'].'" id="finality-'.$item['finality_id'].'"><a class="facet" href="#">'.$item['finality_name'].'</a></li>';
					array_push($a, $item['finality_id']);
				}
			}
				
			$filter .= sprintf('<div class="finality-filter"><h3>%s</h3><ul class="filter-menu finalities-filter-menu">%s</ul></div>', _t('filter', 'by_finality'), $options);
				
		}
		return $filter;
	}

}

if(!function_exists('getTagsMenuFilter')) {

	/**
	 * getTagsMenuFilter()
	 * 
	 * get tags menu filter
	 * @param array $tags
	 * @return string
	 */
	function getTagsMenuFilter ($tags) {
		
		// to uncomment to apply filter only on tags (without scales / finalities considerations)
		//footerAddInlineJS('$("ul.tags-filter-menu").tagfiltering({target_attr:"data-tags", exclude_parents:"ul.filter-menu", separator:";", callback:compute_values});');

		
		$filter = '';
		
		// we display filter if at least 2 values exists
		if(count($tags) > 1) {
			$options = '';
			$a = array();
			foreach($tags as $item) {
				if(!in_array($item['tag_id'], $a)) {
					$options .= '<li data-tag="'.$item['tag_name'].'" id="tag-'.$item['tag_id'].'"><a class="facet" href="#">'.$item['tag_name'].'</a></li>';
					array_push($a, $item['tag_id']);
				}
			}
			
			$filter .= sprintf('<div class="tag-filter"><h3>%s</h3><ul class="filter-menu tags-filter-menu">%s</ul></div>', _t('filter', 'by_tag'), $options);
			
		}
		return $filter;
	}

}