<?php
/**
 * Dashboard module
 * 
 * Display dashboard in back-office
 * 
 * @package linea21\modules\dashboard
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

//////////// Check Inclusion de pages ////////////
if (!class_exists('auth')){
	include_once("../lib/lib_common.php");
	ReloadIndex('admin');
}
////////////

//////////// Check Droits utilisateur ////////////
if (!$l21auth->hasRight('dashboard')) ReloadIndex('admin');
////////////

include_once("../lib/input_helpers.php");
include_once("../dashboard/common.php");
include_once(override('../level/display.php', THEME_ADMIN_PATH));

$firstlevels = $sql_object->DBSelect(SQL_getLevelsList(true));

$sdi = $sql_object -> DBSelect(SQL_getListSdi("R", 0));
$sdi = add_root_level($sdi, 'sdii_level', 'level_root'); // we add extra field with level root

$link_list_scale=$rub_link."&amp;todo=list&amp;scale_id=";

if (!isset($_GET['scale_id']) && !isset($_POST['scale_id'])) {
	$scale_id = 1;
} else {
	if (isset($_POST['scale_id'])) $scale_id = $_POST['scale_id'];
	if (isset($_GET['scale_id'])) $scale_id = $_GET['scale_id'];
}

$resultscale2 = $sql_object -> DBSelect(SQL_getonescale($scale_id));


function getIndicators($levels, $indicators, $scale_id, $status, $sql_object) {

	global $rub_link;

	$sdi_object= new sdi;

	if($status=='all') $test = true;
	if($status=='attached') $test='Y';
	if($status=='not-attached') $test='N';
	$listing="";

	$link_add=$rub_link."&amp;todo=add&amp;id=";
	$link_det=$rub_link."&amp;todo=det&amp;id=";

	$current_level='';

	$a = array(); // to not display twice an indicator

	// levels loop
	for ($i=0;$i<count($levels);$i++){

		
		if ($levels[$i]['level_name'] != $current_level && $current_level <> '') {
			$listing.="</ul>\n</div>\n";
		}
		if ($levels[$i]['level_id'] != $current_level) {
			$current_level = $levels[$i]['level_id'];
			$listing.="<h3><a href=\"\">".formatText($levels[$i]['level_name'], '2HTML')."</a></h3>";
			$listing.="<div class=\"contboxgray\">\n";
			$listing.="<ul>\n";
		}

		// indicators loop
		for ($j=0;$j<count($indicators);$j++) {
			
			if ($levels[$i]['level_id'] == $indicators[$j]['level_root']) {
				// setting $threshold_value
				// By default initial value
				$threshold_value = $indicators[$j]['sdii_threshold_value'];
				// if set, we get the latest for the given scale
				$r = $sql_object -> DBSelect(SQL_getlastInsertByPublicationDate($indicators[$j]['sdii_id'], $scale_id));
				if(isset($r[0]['sdiv_value']) && !is_null($r[0]['sdiv_threshold'])) {
					$threshold_value = $r[0]['sdiv_threshold'];
				}

				if ($status == 'all' && $indicators[$j]['sdii_to_dashboard']=='N') {
					$cssclass=' not-attached';
				} else {
					$cssclass='';
				}
 				if ($indicators[$j]['sdii_to_dashboard'] == $test  && !in_array($indicators[$j]['sdii_id'], $a)) {
					$listing.="\t<li class=\"li2".$cssclass." indicator-".$indicators[$j]['sdii_type']."\">\n";

					$listing.= getViz($sql_object, $scale_id, $indicators[$j], $threshold_value);

 					$listing.="\t<div class=\"dashboard-indicator-label\">\n";
					$listing.="\t\t<a href=\"".$link_det.$indicators[$j]['sdii_id']."&amp;scale_id=".$scale_id."\" title=\"".formatText($indicators[$j]['sdii_name'], '2ATT')."\" class=\"indic-name\">".formatTextli($indicators[$j]['sdii_name'])."</a>\n";
					if ($indicators[$j]['sdii_statut']=='D') $listing.="<span class=\"state\">"._t('statut','draft')."</span>\n";
					$listing.="\t</div>\n";
					$listing.="\t\t<a href=\"".$link_add.$indicators[$j]['sdii_id']."&amp;scale_id=".$scale_id."\" class=\"ico_add\" title=\""._t('dashboard','add')."\"><i class=\"icon-plus-circled\"></i><span>".  _t('dashboard','add')."</span></a>\n";
					
					$listing.="\t</li>\n";

					array_push($a, $indicators[$j]['sdii_id']); // we add the id into array for not displaying it twice
					
				}
			}
		}
		
	}

	$listing.="</ul>\n</div>\n";

	return $listing;

}

//affichage selectbox échelle
$resultscale = $sql_object -> DBSelect($req_list_scale);
$scale_selectbox="<h2>".formatText($resultscale2[0]['scale_denomination'], '2HTML')."</h2>";
$scale_selectbox.="<div class=\"filterselect\">";
$scale_selectbox.=ScaleSelectBox($resultscale, "scale", $scale_id, $link_list_scale);
$scale_selectbox.="</div>\n";

?>
<div id="chemin">
	<ul>
		<li><a href="index.php" class="chemin_home"><?php echo _t('way','home'); ?></a></li>
		<li><a href="<?php echo $rub_link; ?>" id="chemin_<?php echo $rub; ?>" class="chemin_rub"><?php echo _t('menu','dashboard');?> </a></li>
		<li><span><?php echo _t('dashboard','list'); ?> </span></li>
	</ul>
</div>
<!--end barre haute -->
<?php
// including sparkline code
footerAddJS('../lib/js/jquery.sparkline.min.js');
footerAddInlineJS("$('.inlinebar').sparkline('html', {type: 'bar', barColor: '#8DA8CB'} );");

// including easyTabs
footerAddJS('../lib/js/jQuery-EasyTabs/vendor/jquery.hashchange.min.js');
footerAddJS('../lib/js/jQuery-EasyTabs/lib/jquery.easytabs.min.js');
footerAddInlineJS("$('#tabs-container').easytabs({animate:false});");
?>
<script type="text/javascript">
$(document).ready(function() {

	$("#content ul").each(
			  function() {
			    var elem = $(this);
			    if (elem.children().length == 0) {
			      elem.append("<?php echo _t('divers', 'nodata'); ?>");
			    }
			  }
			);
	
	jQuery('ul.tabs li').click(function(){
		$.sparkline_display_visible();
	});
	
	$(".dashboard-indicator-gauge .cursor").removeAttr("title");
	$(".infobox").hover(
		function() {
			$(this).next().fadeIn('fast');
		},
		function() {
			$(this).next().hide();
		});
});
</script>

<?php
if(defined('ANIMATE_PROGRESS') && ANIMATE_PROGRESS == 1) {
footerAddJS('../lib/js/waypoints/lib/jquery.waypoints.min.js');
?>
		<script type="text/javascript">
		$(document).ready(function() {

			
			function animate_gauge(obj) {
				var tmp = $(obj).css('left'); // get position
				$(obj).css('left', -110); // set to min
		 		$( obj ).animate({left : tmp}, getRandomInt(2000, 4000)); // animate
			};

			function animate_raw(obj) {
				var $this = obj;
				var endval = $this.attr('data-value');
				// console.log('data-value : ' + $this.attr('data-value'));
				  $({ Counter: 0 }).animate({ Counter: endval }, {
						duration: getRandomInt(2000, 4000),
						easing: 'swing',
						step: function () {
						   $this.text(Math.ceil(this.Counter) > endval ? number_f(endval) : number_f(Math.ceil(this.Counter)));
						},
						done: function() {
							// console.log("end value : " + endval);
							$this.text(number_f(endval));
						}
						
				  });
			};

			/**
			* Waypoints animation - Method A
			* animate when scrolled to object position
			*/
			var waypoints_gauge = $('.dashboard-indicator-gauge > img.cursor').waypoint({
				  handler: function(direction) {
				    animate_gauge($(this.element));
				    this.destroy();
				  }, 
		      offset: 'bottom-in-view'     
			});
			var waypoints_raw = $('.dashboard-indicator-raw > span.infobox.value:not(".boolean-mask")').waypoint({
				  handler: function(direction) {
				    animate_raw($(this.element));
				    this.destroy();
				  }, 
		      offset: 'bottom-in-view'     
			});

			
			/**
			* Animate anyway - Method B
			*/
			// animate the gauges representation
// 			$('.dashboard-indicator-gauge > img.cursor').each(function(index) {
// 				animate_gauge($(this));
// 			});
// 			// animate raw representation
// 			$('.dashboard-indicator-raw > span.infobox.value:not(".boolean-mask")').each(function(index) {
// 				console.log($(this));
// 			 animate_raw($(this));
// 			});
		});
		</script>
<?php } ?>
<?php 
//print_r($sdi); 
?>
<div class="contentcontainer">
	<?php	include_once(override($dir.'/menurub.php', THEME_ADMIN_PATH));	?>
	<div id="content">
		<?php echo $scale_selectbox;	?>
		<br style="clear: both;margin-bottom:3em" />
		<div id="tabs-container">
			<ul class="tabs">
				<li class="tab"><a href="#tab1"><?php echo _t('dashboard', 'tab-attached'); ?></a></li>
				<li class="tab"><a href="#tab2"><?php echo _t('dashboard', 'tab-not-attached'); ?></a></li>
				<li class="tab"><a href="#tab3"><?php echo _t('dashboard', 'tab-all'); ?></a></li>
			</ul>
			<div id="tab1" class="tab-content">
				<?php echo getIndicators($firstlevels, $sdi, $scale_id, 'attached', $sql_object); ?>
			</div>
			<div id="tab2" class="tab-content">
				<?php echo getIndicators($firstlevels, $sdi, $scale_id, 'not-attached', $sql_object); ?>
			</div>
			<div id="tab3" class="tab-content">
				<?php echo getIndicators($firstlevels, $sdi, $scale_id, 'all', $sql_object); ?>
			</div>
		</div>
	</div> <!-- closing #content -->
</div> <!-- closing .contentcontainer -->