<?php


require_once 'SubFW/autoload.php';
	
?>
<!DOCTYPE html>
 <html lang="en">

 <head>

   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
   <meta name="description" content="">
   <meta name="author" content="">
   <!--<link rel="shortcut icon" type="image/x-icon" href="<?php echo $GLOBALS['approot']?>/eoDACSCommon/pics/eodacs.png" />-->
   <?php   	
	$libmanager= new eoLibrariesManagerDACS();
	$libmanager->init_page();
	$libmanager->render_library();
	
?>
   <script>
   window.eoDACS= window.eoDACS || {};

		eoDACS.Country					= '<?php echo($config_eodacs_country); ?>';
		eoDACS.ServerAddress 			= '<?php echo($config_servernameorip); ?>';
		eoDACS.ServerFolder  			= '<?php echo($GLOBALS["EODACS_ROOT"]); ?>';
		eoDACS.JasperTemplatesFolder 	= '<?php echo($GLOBALS["JASPER_TEMPLATES_FOLDER"]); ?>';
		eoDACS.CurrentLanguage 			= '<?=$_SESSION["lang"]?>';
	</script>

<!---- STATISTIC 1  --->
	<style>

			.cinvertimg{
  			filter: invert(100%);
			}

			.weekDays-selector input {
  			display: none!important;
			}

			.weekDays-selector input[type=checkbox] + label {
  			display: inline-block;
  			border-radius: 6px;
  			background: #dddddd;
  			height: 40px;
  			width: 30px;
  			margin-right: 3px;
  			line-height: 40px;
  			text-align: center;
  			cursor: pointer;
  			moz-user-select: none;
   			-khtml-user-select: none;
   			-webkit-user-select: none;

   			/*
     			Introduced in Internet Explorer 10.
     			See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
   			*/
   			-ms-user-select: none;
   			user-select: none;
			}	

			.weekDays-selector input[type=checkbox]:checked + label {
  			background: #d4aa00;
  			color: #ffffff;
			}

			labeldate{
  			display: inline-block;
  			width: 50px;
			}


			.mycontainer{
  			/*  background-color:#2E4272;*/
    			display:flex;
    			height:100%;
			}
			.myfixed{
    			/*  background-color:#4F628E;*/
    			width: 290px;
			}

			.myflex-item{
  			/*    background-color:#7887AB;*/
    			flex-grow: 1;
			}

			.row .no-float {
      			display: table-cell;
      			float: none;
  			}

		</style>


		<script>

			function init_layout ()
			{
         

  				$(function() 
  				{
    			__solmodality = $('#modality').searchableOptionList({
      			texts: {
        			selectNone: 'Select all'
      			},
      			events: {
      			},

      			maxHeight: '300px',
      			showSelectNoneOnly: true,
      			showSelectionBelowList: true,
            data: '<?php echo $GLOBALS["EODACS_ROOT"];?>/SubFW/database/common/get_modality.php?modality=*'
    			});
  				});

  				$(function() 
  				{
    			__solmasterstudy = $('#masterstudy').searchableOptionList({
      			texts: {
        			selectNone: 'Select all'
      			},
      			events: {

      				},

      			maxHeight: '300px',
      			showSelectNoneOnly: true,
      			showSelectionBelowList: true,
      			data: '<?php echo $GLOBALS["EODACS_ROOT"];?>/SubFW/database/stats/get_studymaster.php'
    			});
  				});
  				

  				window.changeChartStyle = changeChartStyle;
  				window.setLayout = setLayout;
  				window.setActiveChart = setActiveChart;
  				window.selectActiveStyle = selectActiveStyle;
  				window.refreshData = refreshData;
  
  				initChartConfig ();

  				var checkExist = setInterval(function() {
    				if(typeof __solmodality !== "undefined" && typeof __solmasterstudy !== "undefined"){
      				//variable exists, do what you want
      				defaultLayout();
      				clearInterval(checkExist);
    				}
				}, 150);

  				document.getElementById("IdcStatApplyButton").addEventListener("click", function(event) {
					
					
    				event.preventDefault();
					
    				llayout2refresh.forEach(lid => {
      					var layoutselected = chartSelectedByLayout[lid];
      					if(layoutselected !== undefined && (layoutselected.chartobj != null || layoutselected.default !== undefined))
        				refreshData(lid);
      					}
    				);
  				});

  				if(typeof resizeLayout === 'function')
      				resizeLayout();
			}


<?php
  //for variable $chartlist
  require_once '../Config/statistic/chartconfig.php';
?>

function defaultLayout()
{
    <?php get_default_graphics(); ?>

    setLayout('l2x2');
}


var chartConfigByID = Array();
var chartSelectedByLayout = Array();
var llayout2refresh = Array();

function initChartConfig ()
{
  	<?php
  	$idx = 0;
    foreach ( $chartlist as $chart )
    { 
    	   $idx++;
    	   ?>

     	  var objconf = Array();

      	objconf.label = '<?php echo $chart->label; ?>';
      	objconf.idtype = '<?php echo $chart->id;?>';
      	objconf.url = '<?php echo $chart->url;?>';

        

      	objconf.style = Array();
      	objconf.style["bar"] = 0;
      	objconf.style["barstacked"] = 0;
      	objconf.style["pie"] = 0;
     	objconf.style["line"] = 0;
      	objconf.style["linestacked"] = 0;

      	<?php
        	if($chart->stylebar){ ?>
          		objconf.style["bar"] = 1;
      	<?php } ?>

      <?php
        if($chart->stylebarstacked){ ?>
          objconf.style["barstacked"] = 1;
      <?php } ?>

      <?php
        if($chart->stylepie){ ?>
          objconf.style["pie"] = 1;
      <?php } ?>

      <?php
        if($chart->styleline){ ?>
          objconf.style["line"] = 1;
      <?php } ?>

      <?php
        if($chart->stylelinestacked){ ?>
          objconf.style["linestacked"] = 1;
      <?php } ?>
        chartConfigByID['<?php echo $chart->id;?>'] = objconf;

  <?php
    }
  ?>
}


function GetChartConfigByID ( idtype )
{
	for  ( let i=0; i<chartConfigByID.length; i++ )
	{
		let id = chartConfigByID [i].idtype;
	}
}

function selectActiveStyle(id,idstyle)
{
    //chart type must be selected in order to select a style
    if ( chartSelectedByLayout[id] === undefined )
    {
      
      return;
    }


    var idtype = chartSelectedByLayout[id].idtype;
    var chartConfig = chartConfigByID[idtype];
    // var chartConfig = GetChartConfigByID (idtype);
    if(idstyle == null || idstyle=='' || chartConfig.style[idstyle] == 0)
    {
      idstyle = '';
      if(idstyle == '' && chartConfig.style.bar)
      {
        idstyle = 'bar';
      }
      if(idstyle == '' && chartConfig.style.barstacked)
      {
        idstyle = 'barstacked';
      }
      if(idstyle == '' && chartConfig.style.pie)
      {
        idstyle = 'pie';
      }
      if(idstyle == '' && chartConfig.style.line)
      {
        idstyle = 'line';
      }
      if(idstyle == '' && chartConfig.style.linestacked)
      {
        idstyle = 'linestacked';
      }
    }


    var tagactivechart = document.getElementById('selectedstyleid'+id);
    tagactivechart.setAttribute ( 'class',		getIconChartStyle(idstyle) );
    chartSelectedByLayout[id].style = idstyle;
}

function setActiveChart(id,idtype)
{
  var oldstyle = null;
  var oldchartobj = null;
  if(chartSelectedByLayout[id] !== undefined)
  {
    oldstyle = chartSelectedByLayout[id].style;
    oldchartobj = chartSelectedByLayout[id].chartobj;
  }

  var newchart = {idtype:idtype,style: oldstyle,chartobj:oldchartobj};
  chartSelectedByLayout[id] = newchart;


  var chartConfig = chartConfigByID[idtype];
  // var chartConfig = GetChartConfigByID(idtype);

  var tagcharttype = document.getElementById('selectedchartypeid'+id);
  tagcharttype.innerHTML = chartConfig.label;

  var divstylelistid = document.getElementById('styleid'+id);
  divstylelistid.innerHTML = getChartStyleList(id,idtype);

  selectActiveStyle(id,oldstyle);

}


function getChartTypeList(id)
{
  var chartlist='';
  <?php
    foreach($chartlist as $chart){
        ?> chartlist+=  '<a class="dropdown-item" onclick="window.setActiveChart(\''+id+'\',\'<?php echo $chart->id;?>\');window.refreshData(\''+id+'\');"><?php echo $chart->label;?></a>';
  <?php
    }
  ?>

  return chartlist;

}

function get_chartoption(selectedstyle)
{
  var sx = false;
  var sy = false;
  var dx = true;
  var dy = true;
  var chartjsstyle = 'bar';
  switch(selectedstyle)
  {
    case 'barstacked':
      chartjsstyle = 'bar';
      sx = true;
      sy = true;
    break;
    case 'pie':
      chartjsstyle = 'pie';
      dx = false;
      dy = false;
    break;
    case 'linestacked':
      chartjsstyle = 'line';
      sy = true;
    break;
    default: chartjsstyle = selectedstyle;
  }

  return {style: chartjsstyle, stackedx: sx, stackedy:sy,displayx:dx,displayy:dy};

}

function changeChartStyle(id)
{
	alert("changechartstyle");
  var ret = get_chartoption(chartSelectedByLayout[id].style);

  if(chartSelectedByLayout[id].chartobj)
  {
    //make a copy of config because chartjs modifies the config object;--
    chartSelectedByLayout[id].config.type = ret.style;
    chartSelectedByLayout[id].config.options.scales.xAxes[0].stacked = ret.stackedx;
    chartSelectedByLayout[id].config.options.scales.xAxes[0].gridLines.display = ret.displayx;

    chartSelectedByLayout[id].config.options.scales.yAxes[0].stacked = ret.stackedy;
    chartSelectedByLayout[id].config.options.scales.yAxes[0].gridLines.display = ret.displayy;

    var newconfig = {};
    Object.assign(newconfig,chartSelectedByLayout[id].config)
    drawChart(id,newconfig);

  }
}

function getChartStyleList(id, idtype)
{
  	if(idtype == null && chartSelectedByLayout[id] === undefined)
  	{
    	if(chartSelectedByLayout[id] === undefined)
    	{
     	 	return '';
    	}	

    	idtype = chartSelectedByLayout[id].idtype;
  	}

  	chartConfig = chartConfigByID[idtype];
  	// chartConfig = GetChartConfigByID(idtype);
  	var chartypelist = '';

  	if(chartConfig.style.bar)
  	{
   		chartypelist += '<a class="dropdown-item" name="bar" onclick="event.stopPropagation();window.selectActiveStyle(\''+id+'\',this.name);window.changeChartStyle(\''+id+'\');">Bar</a>';
  	}

  	if(chartConfig.style.barstacked)
  	{
    	chartypelist += '<a class="dropdown-item" name="barstacked" onclick="event.stopPropagation();window.selectActiveStyle(\''+id+'\',this.name);window.changeChartStyle(\''+id+'\');">Bar stacked</a>';
  	}

  	if(chartConfig.style.pie)
  	{
    	chartypelist += '<a class="dropdown-item" name="pie" onclick="event.stopPropagation();window.selectActiveStyle(\''+id+'\',this.name);window.changeChartStyle(\''+id+'\');">Pie</a>';
  	}

  	if(chartConfig.style.line)
  	{
    	chartypelist += '<a class="dropdown-item" name="line" onclick="event.stopPropagation();window.selectActiveStyle(\''+id+'\',this.name);window.changeChartStyle(\''+id+'\');">Line</a>';
  	}

  	if(chartConfig.style.linestacked)
  	{
    	chartypelist += '<a class="dropdown-item" name="linestacked" onclick="event.stopPropagation();window.selectActiveStyle(\''+id+'\',this.name);window.changeChartStyle(\''+id+'\');">Line stacked</a>';
  	}
  	
  	if(chartypelist == '')
    	chartypelist = '<a class="dropdown-item" name="none" onclick="event.stopPropagation();window.selectActiveStyle(\''+id+'\',this.name)>No style defined</a>';

  	return chartypelist;
}


function getIconChartStyle(id)
{
  var icon = '';
  switch(id)
  {
    case 'bar': icon = 'fas fa-chart-bar'; break;
    case 'barstacked': icon = 'fas fa-chart-bar'; break;
    case 'pie': icon = 'fas fa-chart-pie';break;
    case 'line': icon = 'fas fa-chart-line';break;
    case 'linestacked': icon = 'fas fa-chart-line';break;
    default: icon = 'fas fa-chart-bar';
  }

  return icon;
}

/*
function GetCurrentDate()
{
	dte = new Date();

	currentDate = dte.getFullYear() + "-" +(dte.getMonth() + 1) + "-" + dte.getDate();

	return currentDate;
}
*/
/*
function GetCurrentTime()
{
	dte = new Date();

	currentTime = dte.getHours() + ":" + dte.getMinutes() + ":" + dte.getSeconds();

	return currentTime;
}
*/

function GetDayOfWeek()
{
  var dayOfWeek = "";

  for(var i=1; i<8; i++)
  {
    ident = "day" + i;

    if(document.getElementById(ident).checked)
    {
      dayOfWeek += i;
      dayOfWeek += ",";
    }
  }
  if(dayOfWeek.length > 0)
    dayOfWeek = dayOfWeek.substring(0, dayOfWeek.length-1);

  return dayOfWeek;
}


function refreshData(id)
{
	
    get_chart_data_for_layout(id);
}


function formatParams( params ){
  return "?" + Object
        .keys(params)
        .map(function(key){
          return key+"="+encodeURIComponent(params[key])
        })
        .join("&")
}

function get_chart_data_for_layout(id)
{
	
	
    var layoutselected = chartSelectedByLayout[id];
    var chartConfig = chartConfigByID[layoutselected.idtype];

    
    var fromDate  = $('#IdcStatisticFromDate').val ();
    var toDate    = $('#IdcStatisticToDate').val ();
  
    fromDate  = StdDate2DICOMDate ( fromDate );
    toDate    = StdDate2DICOMDate ( toDate );

    var params = {
        type: layoutselected.idtype,
        style: layoutselected.style,
        modid: __solmodality.getSelectionID(),
        mstuid: __solmasterstudy.getSelectionID(),
        from: fromDate,
        to: toDate,
        dow: GetDayOfWeek()
    }

    var request_url = chartConfig.url + formatParams(params);

    $.ajax
  		(
  			{
				type: 'GET',
				url:  request_url,
				dataType: 'json',
				success: function(data)
  				{
            var layoutselected = chartSelectedByLayout[id];
            var chartConfig = chartConfigByID[layoutselected.idtype];
  				  var chartoption = get_chartoption(layoutselected.style);
            var count = 30;
            var minselected='';
            var maxselected='';
            

            //make a copy of config because chartjs modifies the config object;--
            var layoutselected = chartSelectedByLayout[id];
            layoutselected.config = {};
            layoutselected.config = {
              type: chartoption.style,
              options: {
                responsive: true,
                maintainAspectRatio: false,

                elements: {
                  rectangle: {
                    borderSkipped: 'bottom'
                  }
                },
                responsive: true,
                legend: {
                  position: 'top',
                },
                title: {
                  display: false,
                  text: chartConfig.label
                },


                scales: {
                  xAxes:
                  [
                    {
                      ticks:
                      {
                        min: minselected,
                        max: maxselected
                      },
                      stacked: chartoption.stackedx,
                      gridLines: 	{	display: chartoption.displayx		},
                    }
                  ],
                  yAxes:
                  [
                    {
                      ticks:
                      {
                        suggestedMin: 0
                      },
                      stacked:	chartoption.stackedy,
                      gridLines: 	{	display: chartoption.displayy		}
                    }
                  ],

                },
                plugins: {
                  zoom: {
                    interaction: ['scroll', 'drag'],

                    pan: {
                      enabled: true,
                      mode: 'x',
                //      speed: 10,
                //      threshold: 5
                    },
                    zoom: {
                      enabled: true,


                      mode: 'x',
                      // Speed of zoom via mouse wheel
                      // (percentage of zoom on a wheel event)
                      speed: 0.1,

                      // Minimal zoom distance required before actually applying zoom
                      threshold: 2,

                      // On category scale, minimal zoom level before actually applying zoom
                      sensitivity: 1,

                    }
                  }
                }
              }
            };

            layoutselected.config.originaldata = data;
            var newconfig = {}
            Object.assign(newconfig,layoutselected.config);
            drawChart(id,newconfig);
          }
        }
      );
}

function drawChart(id,config)
{
  var newData =
  {
    labels: [],
    datasets:  []
  };
  var data = config.originaldata;

  var subdatasetlabel = [];

  if(data != null)
  {
    for(var key in data)
    {
      var x_data = data[key];
      newData.labels.push(key);
      for(var key2 in x_data)
      {
        // var datainfo;
        // datainfo.label = x_data[key2].label;
        // datainfo.data = [];
        subdatasetlabel.push(x_data[key2].label);
      }
    }

    subdatasetlabel = subdatasetlabel.filter((v, i, a) => a.indexOf(v) === i);

    var multidataset = false;

    var colorHash = new ColorHash();
    var colorsimpledataset = [];
    if(config.type != "pie" && subdatasetlabel.length > 1)
    {
      multidataset = true;
    }
    else
    {
      for(var i = 0; i < newData.labels.length;i++)
      {
        colorsimpledataset.push(colorHash.hex(newData.labels[i]));
      }
    }


    //init datasets
    for(var i = 0; i < newData.labels.length;i++)
    {
      var x_data = data[newData.labels[i]];

      var idx = 0;
      for(var j = 0; j < subdatasetlabel.length;j++)
      {
        if(i == 0)
        {
          if(multidataset == true)
          {

          //  newData.datasets[idx] = graphDatasetProperties;

            newData.datasets[idx] = { label:subdatasetlabel[j], backgroundColor:colorHash.hex(subdatasetlabel[j]), data:new Array(newData.length) };

            idx++;

          }
          else
          {

            newData.datasets[idx] = { };

            newData.datasets[idx].label				= subdatasetlabel[j];
            newData.datasets[idx].backgroundColor	= colorsimpledataset;
            newData.datasets[idx].data				= new Array(newData.length);

          }
        }
      }

      for(var key2 in x_data)
      {
        for(var j=0; j<newData.datasets.length; j++)
        {

          if(x_data[key2].label == newData.datasets[j].label)
            newData.datasets[j].data[i] = x_data[key2].value;
        }

      }
    }


    config.data = newData;


    createChart(id,config);

  }
}

function createChart(id,config)
{
  var ctx = document.getElementById('canvasid'+id).getContext('2d');
  var canvasdiv = document.querySelector('#canvasid'+id);

  if(chartSelectedByLayout[id].chartobj != null)
    chartSelectedByLayout[id].chartobj.destroy();
  chartSelectedByLayout[id].chartobj = new window.Chart(ctx, config);

}



function setLayout ( lidselected )
{
	 	var lidlist = ['l1x1','l2x1','l1_1x2','l1x2','l2x2'];

  	lidlist.forEach(element => document.getElementById(element).style.backgroundColor="");
  	document.getElementById(lidselected).style.backgroundColor="#d758ba";
  	llayout2refresh = [];
  	var node = document.getElementById('layoutcontainer');
  	node.innerHTML = '';
  	var cols = 2;
  	var rows = 2;
  	var col_to_change = 0;
  	switch ( lidselected )
  	{
    	case 'l1x1': cols = 1; rows = 1;break;
    	case 'l2x1': cols = 1; rows = 2;break;
    	case 'l1_1x2': cols = 1; rows = 2;col_to_change = 1;break;
    	case 'l1x2': cols = 2; rows = 1;break;
    	case 'l2x2': cols = 2; rows = 2;break;
  	}

  	var rowheight = 100/rows;
  	var rowstringtotal= '';
  	for ( var y = 0; y < rows; y++ )
  	{
        let pt= ( y==1 )? 'pt-2' : 'pt-0';

    	 let rowstring = '<div class="row row-cols-'+cols+' '+pt+'" style="min-height:'+rowheight+'%; max-height:'+rowheight+'%; height:'+rowheight+'%">';
    	 for ( let x = 0; x < cols; x++ )
    	 {
      		  let id = x+'_'+y;

            llayout2refresh.push(id);

            var lid = 'layoutid'+id;
            var selectedstyleid = 'selectedstyleid'+id;
            var selectedcharttypeid = 'selectedchartypeid'+id;
            var styleid = 'styleid'+id;
            var chartid = 'chartid'+id;
            var canvasid = 'canvasid'+id;
            var activechartidtype = null;
            var activechartstyle = null;

            if(chartSelectedByLayout[id] !== undefined)
            {
                activechartidtype = chartSelectedByLayout[id].idtype;
                activechartstyle = chartSelectedByLayout[id].style;
            }
            
            let ps = ( x==1 )? 'ps-2' : 'ps-0';

            rowstring += '<div id="'+lid+'" class="col h-100 m-0 p-0 '+ps+'">';
            rowstring += 	 '<div class="card mb-3 h-100">';
            rowstring += 		  '<div class="card-header">';
            rowstring += 			   '<div class="row">';
            rowstring += 				     '<div class="dropdown" style="display:inline-block;">';
            rowstring += 					      '<button class="btn btn-secondary btn-sm dropdown-toggle" type="button" id="IdcStyleMenuButton0" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="color: #000000; background-color: #f7f7f7; border-color: #f7f7f7;">';
            rowstring += 					          '<i id="'+selectedstyleid+'" class="'+getIconChartStyle(activechartstyle)+'"></i>';
            rowstring +=                '</button>';
            rowstring +=                '<div class="dropdown-menu" id="'+styleid+'" aria-labelledby="IdcStyleMenuButton0" x-placement="bottom-start" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(0px, 31px, 0px);">';
          	rowstring +=                   getChartStyleList(id,activechartidtype);
            rowstring +=                '</div>';
            rowstring +=             '<div class="dropdown" style="display:inline-block;">';
            rowstring +=                 '<button id="'+selectedcharttypeid+'" class="btn btn-secondary btn-sm dropdown-toggle" type="button"  data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="color: #000000; background-color: #f7f7f7; border-color: #f7f7f7;">';
            rowstring += (activechartidtype == null)? 'Chart type' : chartConfigByID[activechartidtype].label;
            rowstring +=                 '</button>';
            rowstring +=                 '<div class="dropdown-menu" aria-labelledby="IdcMenuButton3" id="IdcDivMenuArea3">';
            rowstring +=                     getChartTypeList(id);
            rowstring +=                 '</div>';
            rowstring += '             </div>';
            rowstring += '          </div>';
            rowstring += '      </div>';
            rowstring += '    </div>';
            rowstring += '    <div id="chart-container" style="width: 100%;max-height: 100% !important; height: 100%;">';
            rowstring += '      <canvas id="'+canvasid+'"></canvas>';
            rowstring += '    </div>';
            rowstring += '  </div>';
            //end of col;
            rowstring +='</div>';
       }
        
       rowstring += '</div>';

       cols += col_to_change;
       col_to_change = 0;
       rowstringtotal += rowstring;
    }
    node.innerHTML = rowstringtotal;
    llayout2refresh.forEach(lid => {
       var layoutselected = chartSelectedByLayout[lid];
       if ( layoutselected !== undefined && (layoutselected.chartobj != null || layoutselected.default !== undefined) )
    		  refreshData(lid);
       }
  	  );
}


</script>
<!-- END STATISTIC 1 -->

<script>

	StatStudyPreviewDTListMenu= [
		{
			header: ''
		},
		{
			img: 'SubFW/bmp/setup_1_blue.png',
			text: 'Grid properties...',
			action: function(e,selector) { IdcStatStudyPreviewDT.Properties(); }
		}		
	];

	StatSeriePreviewDTListMenu= [
		{
			header: ''
		},
		{
			img: 'SubFW/bmp/setup_1_blue.png',
			text: 'Grid properties...',
			action: function(e,selector) { IdcStatSeriePreviewDT.Properties(); }
		}		
	];
	
	var GCSVStudyExportListCB				= new Array();

	function InitStatisticPage()
	{
	
		IdcStatStudyPreviewDT= new C_DataTable();
		IdcStatStudyPreviewDT.DataSrcType= 0;
		IdcStatStudyPreviewDT.Ident= 'IdcStatStudyPreviewDT';
		IdcStatStudyPreviewDT.Container	= 'IdcStatPreviewStudyDTContainer';
		IdcStatStudyPreviewDT.CfgParameterName 	= 'StatDTStudyPreviewProperties';
		IdcStatStudyPreviewDT.DataSrc= 'SubFW/database/stats/GetDTStatStudyPreview.php';
		IdcStatStudyPreviewDT.DataFct= StatStudyPreviewDTGetData;
		IdcStatStudyPreviewDT.DrawCallbackFct= StatStudyPreviewDTDrawCallback;
		IdcStatStudyPreviewDT.DeferLoading= 0;
		IdcStatStudyPreviewDT.SetColReorder(true);

		IdcStatStudyPreviewDT.AddColumn('','',				0,true,0,40,false,'','',ExportCSVStudySendCBRenderer 	);			
		IdcStatStudyPreviewDT.AddColumn('ID','stu_id',0,false,1,40,false,'','');		
		IdcStatStudyPreviewDT.AddColumn('Etude','study',1,true,2,140,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('Patient','patientname',1,true,3,140,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('Nbre phase','nbphase',1,true,4,40,true,'text-end','');		
		IdcStatStudyPreviewDT.AddColumn('Classification','classification',1,true,5,80,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('Age','age',1,true,6,50,true,'text-end','');		
		IdcStatStudyPreviewDT.AddColumn('IMC','imc',1,true,7,50,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('Taille','height',1,true,8,50,true,'text-end','');		
		IdcStatStudyPreviewDT.AddColumn('Poids','pat_weight',1,true,9,50,true,'text-end','');		
		IdcStatStudyPreviewDT.AddColumn('Modality','modality',1,true,10,60,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('Radiologist','radiologist',1,true,11,90,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('Technologist','technologist',1,true,12,90,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('DLP','dlp',1,true,13,50,true,'text-end','');		
		IdcStatStudyPreviewDT.AddColumn('Description','study_description',1,true,14,100,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('PDS(mGy.cm²)','pds',1,true,15,100,true,'text-end','');		
		IdcStatStudyPreviewDT.AddColumn('PDS 3D(mGy.cm²)','pds_3d',1,true,16,50,true,'text-end','');		
		IdcStatStudyPreviewDT.AddColumn('DGM(mGy)','dgm',1,true,17,40,true,'text-end','');		
		IdcStatStudyPreviewDT.AddColumn('CCAM','ccam',1,true,18,50,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('Patient ID','patient_id',1,true,19,60,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('A.N.','accessionnumber',1,true,20,40,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('Durée de scopie(s)','fluoro_time',1,true,21,40,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('PDS de scopie(mGy.cm²)','fluoro_dap',1,true,22,40,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('Commentaire 1','comment_1',1,true,23,40,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('Commentaire 2','comment_2',1,true,24,40,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('Commentaire 3','comment_3',1,true,25,40,true,'','');		
		IdcStatStudyPreviewDT.AddColumn('RP dose totale(mGy)','dose_rp_total',1,true,26,50,true,'text-end','');		
		IdcStatStudyPreviewDT.AddColumn('RP dose totale(mGy)','dose_rp_total',1,true,27,50,true,'text-end','');		
		IdcStatStudyPreviewDT.AddColumn('Fluoro dose(RP) totale(mGy)','fluoro_dose_rp_total',1,true,28,50,true,'text-end','');		
		IdcStatStudyPreviewDT.AddColumn(Translate('Birthdate'),'birthdate',1,true,29,100,true,'','');		

		IdcStatStudyPreviewDT.SetColReorder(true);

		//IdcStatStudyPreviewDT.LoadUserCfg(G_USE_ID);





		IdcStatSeriePreviewDT= new C_DataTable();
		IdcStatSeriePreviewDT.DataSrcType = 0;
		IdcStatSeriePreviewDT.Ident	= 'IdcStatSeriePreviewDT';
		IdcStatSeriePreviewDT.Container	= 'IdcStatPreviewSerieDTContainer';
		IdcStatSeriePreviewDT.CfgParameterName= 'StatDTSeriePreviewProperties';
		IdcStatSeriePreviewDT.DataSrc = 'SubFW/database/stats/GetDTStatSeriePreview.php';
		IdcStatSeriePreviewDT.DataFct = StatSeriePreviewDTGetData;
		IdcStatSeriePreviewDT.DrawCallbackFct = StatSeriePreviewDTDrawCallback;
		IdcStatSeriePreviewDT.DeferLoading= 0;
		IdcStatSeriePreviewDT.SetColReorder(true);

		IdcStatSeriePreviewDT.AddColumn('','',0,true,0,40,false,'','',ExportCSVSerieSendCBRenderer 	);			
		IdcStatSeriePreviewDT.AddColumn('ID','stu_id',0,false,1,40,false,'','');		
		IdcStatSeriePreviewDT.AddColumn(Translate('Study'),'studydescription',1,true,2,140,true,'','');		
		IdcStatSeriePreviewDT.AddColumn(Translate('Serie'),'seriedescription',1,true,3,140,true,'','');		
		IdcStatSeriePreviewDT.AddColumn('Classification','classification',1,true,4,120,true,'','');		
		IdcStatSeriePreviewDT.AddColumn('Patient','patientname',1,true,5,140,true,'','');		
		IdcStatSeriePreviewDT.AddColumn('Age','age',1,true,6,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn(Translate('Sex'),'sex',1,true,7,80,true,'text-center','');		
		IdcStatSeriePreviewDT.AddColumn('Acquisition','acquisition_type',1,true,8,140,true,'','');		
		IdcStatSeriePreviewDT.AddColumn('Protocol','protocol_name',1,true,9,100,true,'','');		
		IdcStatSeriePreviewDT.AddColumn('Date','studydate_fmt',1,true,10,140,true,'','');		
		IdcStatSeriePreviewDT.AddColumn('mAs','mas',1,true,11,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('kV','kv',1,true,12,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('CTDiVol','ctdivol',1,true,13,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('spirale_length','spirale_length',1,true,14,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('pdl','pdl',1,true,15,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('pds','pds',1,true,16,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('dgm','dgm',1,true,17,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('compression','compression_force',1,true,18,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('breast_thickness','breast_thickness',1,true,19,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('incidence','incidence',1,true,20,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('anode_filter','anode_filter',1,true,21,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('air_kerma','air_kerma',1,true,22,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('dose_rp','dose_rp',1,true,23,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('scopie duration','scopie_duration',1,true,24,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('pitch','pitch',1,true,25,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('mA','ma',1,true,26,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('Opening','opening',1,true,27,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn(Translate('Comment'),'study_comment',1,true,28,140,true,'','');		
		IdcStatSeriePreviewDT.AddColumn('Acqui. plane','acquisition_plane',1,true,29,120,true,'','');		
		IdcStatSeriePreviewDT.AddColumn(Translate('Modality'),'modality',1,true,30,100,true,'text-center','');		
		IdcStatSeriePreviewDT.AddColumn('Expo. time','exposure_time',1,true,31,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('primary_angle','primary_angle',1,true,32,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('primary_angle_end','primary_angle_end',1,true,33,80,true,'text-end','');		
		// IdcStatSeriePreviewDT.AddColumn('secondary_angle','secondary_angle',1,true,34,80,true,'text-end','');		
		// IdcStatSeriePreviewDT.AddColumn('secondary_angle_end','secondary_angle_end',1,true,35,80,true,'text-end','');		
		IdcStatSeriePreviewDT.AddColumn('distance_focus_detector','distance_focus_detector',1,true,34,80,true,'text-end','');		
		// IdcStatSeriePreviewDT.AddColumn('field_length','field_length',1,true,35,80,true,'text-end','');		
		// IdcStatSeriePreviewDT.AddColumn('field_width','field_width',1,true,38,80,true,'text-end','');		
		// IdcStatSeriePreviewDT.AddColumn('field_area','field_area',1,true,39,80,true,'text-end','');		

		//IdcStatSeriePreviewDT.LoadUserCfg(G_USE_ID);
		
		
			
		$(document).ready(function() 
		{
			let currentDate= GetCurrentDate();

			IdcStatStudyPreviewDT.Create();
			context.attach('#IdcStatStudyPreviewDT',StatStudyPreviewDTListMenu);

			IdcStatSeriePreviewDT.Create();
			context.attach('#IdcStatSeriePreviewDT',StatSeriePreviewDTListMenu);

			IdcStatisticStudySplitter1_2 	= new C_Splitter("IdcStatisticStudySplitter1_2");
			IdcStatisticSerieSplitter1_2 	= new C_Splitter("IdcStatisticSerieSplitter1_2");
			IdcStatisticJasperSplitter1_2 	= new C_Splitter("IdcStatisticJasperSplitter1_2");

			$("#IdcStatStudyFrom").val(currentDate);
			$("#IdcStatStudyTo").val(currentDate);

			IdcStatStudyStudiesCBMenu= new C_CheckboxMenu("IdcStatStudyStudiesContainer","IdcStatStudyStudiesCBMenu0",Translate("Click here to select studies"));
			IdcStatStudyStudiesCBMenu.UnselectAll();
			IdcStatStudyStudiesCBMenu.ClearAll();
			// IdcStatStudyStudiesCBMenu.CallbackFct= ExamsListDetailDepartmentsChanged;
			InitStudiesCBList(IdcStatStudyStudiesCBMenu);

			IdcStatStudySeriesCBMenu= new C_CheckboxMenu("IdcStatStudySeriesContainer","IdcStatStudySeriesCBMenu0",Translate("Click here to select series"));
			IdcStatStudySeriesCBMenu.UnselectAll();
			IdcStatStudySeriesCBMenu.ClearAll();
			InitSeriesCBList(IdcStatStudySeriesCBMenu);


			IdcStatStudyModalitiesCBMenu= new C_CheckboxMenu("IdcStatStudyModalitiesContainer","IdcStatStudyModalitiesCBMenu0",Translate("Click here to select modalities"));
			IdcStatStudyModalitiesCBMenu.UnselectAll();
			IdcStatStudyModalitiesCBMenu.ClearAll();
			// IdcStatStudyModalitiesCBMenu.CallbackFct= ExamsListDetailDepartmentsChanged;
			InitModalitiesCBList(IdcStatStudyModalitiesCBMenu);

			IdcStatStudyIMCCBMenu= new C_CheckboxMenu("IdcStatStudyIMCContainer","IdcStatStudyIMCCBMenu0",Translate("Click here to select IMC"));
			IdcStatStudyIMCCBMenu.UnselectAll();
			IdcStatStudyIMCCBMenu.ClearAll();
			InitIMCCBList(IdcStatStudyIMCCBMenu);

			IdcStatStudyAgeCBMenu= new C_CheckboxMenu("IdcStatStudyAgeContainer","IdcStatStudyAgeCBMenu0",Translate("Click here to select ages"));
			IdcStatStudyAgeCBMenu.UnselectAll();
			IdcStatStudyAgeCBMenu.ClearAll();
			InitAgeCBList(IdcStatStudyAgeCBMenu);

//			IdcStatStudyPreviewDT.Refresh();

			StatJasperRefreshReportsList();

			$('#IdcStatJasperSelect').on('change',StatJasperReportChanged);

			window.addEventListener("message",function(event) {
    			if(event.data.action=== "CloseOOEditor") 
    			{
      				const iframeEditor= document.getElementById("IdcStatisticEditorFrame");
      				if(iframeEditor) 
      				{
        				iframeEditor.style.display= "none"; // ou iframe.remove();
        				$("#IdcStatisticMainFrame").show();
      				}
    			}
  			});

			document.getElementById('IdcStatisticStudyTab').addEventListener('shown.bs.tab',()=> { StatStudyTabShown(); });
			document.getElementById('IdcStatisticSerieTab').addEventListener('shown.bs.tab',()=> { StatSerieTabShown(); });

			switchLanguage(eoDACS.CurrentLanguage);
		});
	}

	function StatPreviewCSV()
	{
			

			if($('#IdcStatPreviewStudyDTContainer').is(":visible")== true)
			{
					IdcStatStudyPreviewDT.RealRefresh();
					ExportCSVStudyListLoad();
			}

			if($('#IdcStatPreviewSerieDTContainer').is(":visible")== true)
			{
					IdcStatSeriePreviewDT.RealRefresh();
					ExportCSVSerieListLoad();
			}

			
	}

	/*
	function StatShowEditor()
	{
			StatStudyExportCSV();

			$("#IdcStatisticMainFrame").hide();
			$("#IdcStatisticEditorFrame").show();

			// $('#IdcStatisticEditorFrame').attr('src','SubFW/html/OnlyOfficeEditor.php?doc_id='+doc_id);
			$('#IdcStatisticEditorFrame').attr('src','SubFW/html/OnlyOfficeEditor.php');
	}
	*/

	function StatDisplayCSV()
	{
			if($('#IdcStatPreviewStudyDTContainer').is(":visible")== true)
					StatStudyDisplayCSV();

			if($('#IdcStatPreviewSerieDTContainer').is(":visible")== true)
					StatSerieDisplayCSV();
	}

	function StatStudyDisplayCSV()
	{
			

			let fields= "";
			for(let i=0; i<IdcStatStudyPreviewDT.ColumnsList.GetNbColumns(); i++)
			{
						let col= IdcStatStudyPreviewDT.ColumnsList.GetColumnFromIdx(i);

						
						if(col.Visible== true && col.Type== 1)
								fields += col.Data + ' as "' + col.Label + '",';
			}

			fields= fields.slice(0,-1);

			let excluded= "";

			for(let i=0; i<GCSVStudyExportListCB.length; i++)
			{
					if(GCSVStudyExportListCB [i].ToExport== false)
						excluded += GCSVStudyExportListCB [i].stu_id + ",";
			}
			excluded= excluded.slice(0,-1);


			let orderCol= $('#IdcStatStudyPreviewDT').DataTable().order();
			let order= IdcStatStudyPreviewDT.ColumnsList.GetColumnFromIdx(orderCol [0][0]).Data + " " + orderCol [0][1];


			WaitingStart(Translate('Please wait while the file is generated'));


			$.post(
			"./SubFW/database/stats/export_study_csv.php",
			{
				fields: 	fields,
				excluded: excluded,
				order: 		order,
				from: 		$('#IdcStatStudyFrom').val(),
				to: 			$('#IdcStatStudyTo').val(),
				imc: 			encodeURIComponent(IdcStatStudyIMCCBMenu.GetSelection2String()),
				age: 			encodeURIComponent(IdcStatStudyAgeCBMenu.GetSelection2String()),
				modid: 		encodeURIComponent(IdcStatStudyModalitiesCBMenu.GetSelection2String()),
				mstuid: 	encodeURIComponent(IdcStatStudyStudiesCBMenu.GetSelection2String())
			},
			function(data) 
			{
				WaitingStop();
				
				
				
				/*
				var a= document.createElement("a");
 				document.body.appendChild(a);
 				a.href= 'tmp/'+data.file;
 				a.click();
 				document.body.removeChild(a);
 				*/

 				$("#IdcStatisticMainFrame").hide();
				$("#IdcStatisticEditorFrame").show();

				// $('#IdcStatisticEditorFrame').attr('src','SubFW/html/OnlyOfficeEditor.php?doc_id='+doc_id);
				$('#IdcStatisticEditorFrame').attr('src','SubFW/html/OnlyOfficeEditor.php?filename='+data.file);
			}
		);
	}




	function StatSerieDisplayCSV()
	{
			

			let fields= "";
			for(let i=0; i<IdcStatSeriePreviewDT.ColumnsList.GetNbColumns(); i++)
			{
						let col= IdcStatSeriePreviewDT.ColumnsList.GetColumnFromIdx(i);

						
						if(col.Visible== true && col.Type== 1)
								fields += col.Data + ' as "' + col.Label + '",';
			}

			fields= fields.slice(0,-1);

			let excluded= "";

			for(let i=0; i<GCSVSerieExportListCB.length; i++)
			{
					if(GCSVSerieExportListCB [i].ToExport== false)
						excluded += GCSVSerieExportListCB [i].stu_id + ",";
			}
			excluded= excluded.slice(0,-1);


			let orderCol= $('#IdcStatSeriePreviewDT').DataTable().order();
			let order= IdcStatSeriePreviewDT.ColumnsList.GetColumnFromIdx(orderCol [0][0]).Data + " " + orderCol [0][1];


			WaitingStart(Translate('Please wait while the file is generated'));


			$.post(
			"./SubFW/database/stats/export_serie_csv.php",
			{
				fields: 	fields,
				excluded: excluded,
				order: 		order,
				from: 		$('#IdcStatStudyFrom').val(),
				to: 			$('#IdcStatStudyTo').val(),
				imc: 			encodeURIComponent(IdcStatStudyIMCCBMenu.GetSelection2String()),
				age: 			encodeURIComponent(IdcStatStudyAgeCBMenu.GetSelection2String()),
				modid: 		encodeURIComponent(IdcStatStudyModalitiesCBMenu.GetSelection2String()),
				mstuid: 	encodeURIComponent(IdcStatStudyStudiesCBMenu.GetSelection2String())
			},
			function(data) 
			{
				WaitingStop();
				
				
				
				/*
				var a= document.createElement("a");
 				document.body.appendChild(a);
 				a.href= 'tmp/'+data.file;
 				a.click();
 				document.body.removeChild(a);
 				*/

 				$("#IdcStatisticMainFrame").hide();
				$("#IdcStatisticEditorFrame").show();

				// $('#IdcStatisticEditorFrame').attr('src','SubFW/html/OnlyOfficeEditor.php?doc_id='+doc_id);
				$('#IdcStatisticEditorFrame').attr('src','SubFW/html/OnlyOfficeEditor.php?filename='+data.file);
			}
		);
	}


	function StatStudyExportModel()
	{
		$('#IdcDlgStatStudyModelExport').modal('show');
	}
		
	function StatStudyExportModelValidate()
	{	
		
	}


	function downloadWithTemplate(id)
	{
    	download(id);

    	$('#IdcDlgStatStudyModelExport').modal('hide');
	}

	function download(selected_template_id)
  {
      let fromdate= $('#IdcStatStudyFrom').val();
      let todate= $('#IdcStatStudyUntil').val();

      let mstuid= IdcStatStudyStudiesCBMenu.GetSelection2String();
      let age= IdcStatStudyAgeCBMenu.GetSelection2String();
      let modality= IdcStatStudyModalitiesCBMenu.GetSelection2String();
      let imc= IdcStatStudyIMCCBMenu.GetSelection2String();

      var endpoint= eoDACS.ServerFolder + '/SubFW/database/stats/prepare_exportstat.php';

      var params= {
        type: "exportstudy",
        mstuid:   mstuid,
        modid:    modality,
        age:    age,
        imc:    imc,
        from:     fromdate,
        to:     todate,
        statid : selected_template_id
      }

      var url= endpoint + formatParams(params);
      var downloadurl= eoDACS.ServerFolder + '/Common/download_file.php';

      WaitingStart(Translate('Please wait while the file is generated'));

      /*
      var progressmsg= document.getElementById('progressbarmsg');
      progressmsg.innerHTML= "<?php echo $_WaitGenerateDownload;?>";
      var progressbar= document.getElementById('progressbar');
      progressbar.style.display= 'block';
      var progressbarbar= document.getElementById('progressbarbar');
      progressbarbar.style.display= 'block';
      */

      prepare_and_download(url,downloadurl);
  }

  function prepare_and_download(url,downloadurl) 
    {
    	
    	
    	

  		var xhr= new XMLHttpRequest();
  		xhr.open("GET",url,true);
  		xhr.onload= function(e) {
    		if(xhr.readyState=== 4) 
    		{
      			if(xhr.status=== 200) 
      			{
      				WaitingStop();

        			var xmlDoc=xhr.responseXML;

        			if(get_nodevalue(xmlDoc,"status")=='0')
        			{
          				var id= get_nodevalue(xmlDoc,"id");
          				var a= document.createElement("a");
          				document.body.appendChild(a);
          				a.id=id;
          				a.href=downloadurl+'?id='+id;
          				a.click();
          				document.body.removeChild(a);
          				// var progressbar= document.getElementById('progressbar');
          				// if(progressbar !== null)
            			//		progressbar.style.display= 'none';
            			
        			}
        			else
        			{
          				// var progressbarbar= document.getElementById('progressbarbar');
          				// if(progressbarbar !== null)
            			// 	progressbarbar.style.display= 'none';

          				// var progressbarmsg= document.getElementById('progressbarmsg');
          				// progressbarmsg.innerHTML=  get_nodevalue(xmlDoc,"errormessage");


          				MsgWarning(get_nodevalue(xmlDoc,"errormessage"));

        			}
      			} 
      			else 
      			{
        			console.error(xhr.responseXML);
      			}
    		}
  		};
  		xhr.onerror= function(e) {
    		console.error(xhr.responseXML);
  		};
  		xhr.send(null);
	}




	function StatStudyPreviewDTGetData(d)
	{
			

			WaitingStart(Translate('Request in progress. Please wait.'));

			d.from   	= $('#IdcStatStudyFrom').val();
			d.to   		= $('#IdcStatStudyTo').val();
			d.imc 		= encodeURIComponent(IdcStatStudyIMCCBMenu.GetSelection2String());
			d.age 		= encodeURIComponent(IdcStatStudyAgeCBMenu.GetSelection2String());
			d.modid 	= encodeURIComponent(IdcStatStudyModalitiesCBMenu.GetSelection2String());
			d.mstuid 	= encodeURIComponent(IdcStatStudyStudiesCBMenu.GetSelection2String());
			

			return $.extend({},d);
	}
	

	function  StatStudyPreviewDTDrawCallback(dtIdent)
	{
			WaitingStop();

			CSVExportStudyListUpdateCheckbox();
	}

	function StatSeriePreviewDTGetData(d)
	{
			

			WaitingStart(Translate('Request in progress. Please wait.'));

			d.from   	= $('#IdcStatStudyFrom').val();
			d.to   		= $('#IdcStatStudyTo').val();
			d.imc 		= encodeURIComponent(IdcStatStudyIMCCBMenu.GetSelection2String());
			d.age 		= encodeURIComponent(IdcStatStudyAgeCBMenu.GetSelection2String());
			d.modid 	= encodeURIComponent(IdcStatStudyModalitiesCBMenu.GetSelection2String());
			d.mstuid 	= encodeURIComponent(IdcStatStudyStudiesCBMenu.GetSelection2String());
			d.mserid 	= encodeURIComponent(IdcStatStudySeriesCBMenu.GetSelection2String());
			

			return $.extend({},d);
	}
	

	function  StatSeriePreviewDTDrawCallback(dtIdent)
	{
			WaitingStop();

			CSVExportSerieListUpdateCheckbox();
	}
		

	function ExportCSVStudySendCBRenderer(data,ident,rowIdx,colIdx)
	{
		let id= "IdcCSVExportStudyListSendCB_" + rowIdx;
		return '<div class="w-100 m-0 p-0 text-center"><input id='+id+' class="XIMEO_DT-Checkbox" type="checkbox" data-row_idx='+rowIdx+' data-col_idx='+colIdx+' onclick="OnExportCSVStudyExportCBClicked(this)"/></div>';
	}

	function ExportCSVSerieSendCBRenderer(data,ident,rowIdx,colIdx)
	{
		let id= "IdcCSVExportSerieListSendCB_" + rowIdx;
		return '<div class="w-100 m-0 p-0 text-center"><input id='+id+' class="XIMEO_DT-Checkbox" type="checkbox" data-row_idx='+rowIdx+' data-col_idx='+colIdx+' onclick="OnExportCSVSerieExportCBClicked(this)"/></div>';
	}

	function OnExportCSVStudyExportCBClicked(e)
	{
			

			let rowIdx= $(e).data('row_idx');

			let stu_id= IdcStatStudyPreviewDT.GetRowData(rowIdx).stu_id;

			for(let i=0; i<GCSVStudyExportListCB.length; i++)
			{
					if(GCSVStudyExportListCB [i].stu_id== stu_id)
					{
							
							GCSVStudyExportListCB [i].ToExport= e.checked;
							break;
					}
			}
	}

	function OnExportCSVSerieExportCBClicked(e)
	{
			

			let rowIdx= $(e).data('row_idx');

			let stu_id= IdcStatSeriePreviewDT.GetRowData(rowIdx).stu_id;

			for(let i=0; i<GCSVSerieExportListCB.length; i++)
			{
					if(GCSVSerieExportListCB [i].stu_id== stu_id)
					{
							
							GCSVSerieExportListCB [i].ToExport= e.checked;
							break;
					}
			}
	}




function CSVExportStudyListRow(stu_id,toexport)
{
	this.stu_id 		= stu_id;
	this.ToExport 	= toexport;
}

function ExportCSVStudyListLoad()
{
		

		GCSVStudyExportListCB= new Array();

		var xhra= getxhr();
			
		xhra.onloadend= function f()
		{
			if(xhra.readyState== 4 && xhra.status== 200)  
			{
				let responseText= xhra.responseText;

				let jsonOK= true;
				let jsonData= "";
				try { jsonData= JSON.parse(responseText)
				} catch(e) { jsonOK= false; console.log(e); }

				if(jsonOK)
				{
					for(let i=0; i<jsonData.data.length; i++)
					{
						let stu_id 		= jsonData.data [i].stu_id;

						GCSVStudyExportListCB.push(new CSVExportStudyListRow(stu_id,true));
					}
				}
				else
					console.log("Bad JSON !!! ");
			}
		};

		let fromDate 	= $('#IdcStatStudyFrom').val();
		let toDate 		= $('#IdcStatStudyTo').val();
		let modid 	= encodeURIComponent(IdcStatStudyModalitiesCBMenu.GetSelection2String());
				
		let url= "SubFW/database/stats/GetDTStatStudyPreview.php?from="+fromDate+"&to="+toDate+"&modid="+modid;
			
		xhra.open('GET',url,true);
		xhra.send();
}

function CSVExportStudyListUpdateCheckbox()
{
		

		let rowsData 	= $('#IdcStatStudyPreviewDT').DataTable().rows().data();
		
		for(let j=0; j<rowsData.length; j++)
		{
				let stu_id= rowsData [j].stu_id;

				let toExport= false;
				if(GCSVStudyExportListCB.length== 0)
				{
						toExport= true;
				}
				else
				{
						let data= CSVExportStudyListGetData(stu_id);
						if(data != null)
								toExport= data.ToExport;
						else
								console.log(" data is null !!!");
				}

				if(toExport== true) document.getElementById("IdcCSVExportStudyListSendCB_" + j).checked= true; else document.getElementById("IdcCSVExportStudyListSendCB_" + j).checked= false;
		}
}

function CSVExportStudyListGetData(stu_id)
{
	for(let i=0; i<GCSVStudyExportListCB.length; i++)
	{
		if(GCSVStudyExportListCB [i].stu_id== stu_id)
		{
			return GCSVStudyExportListCB [i];
		}
	}

	return null;
}

















function CSVExportSerieListRow(ser_id,toexport)
{
	this.ser_id 		= ser_id;
	this.ToExport 	= toexport;
}

function ExportCSVSerieListLoad()
{
		

		GCSVSerieExportListCB= new Array();

		var xhra= getxhr();
			
		xhra.onloadend= function f()
		{
			if(xhra.readyState== 4 && xhra.status== 200)  
			{
				let responseText= xhra.responseText;

				let jsonOK= true;
				let jsonData= "";
				try { jsonData= JSON.parse(responseText)
				} catch(e) { jsonOK= false; console.log(e); }

				if(jsonOK)
				{
					for(let i=0; i<jsonData.data.length; i++)
					{
						let ser_id 		= jsonData.data [i].ser_id;

						GCSVSerieExportListCB.push(new CSVExportSerieListRow(ser_id,true));
					}
				}
				else
					console.log("Bad JSON !!! ");
			}
		};

		let fromDate 	= $('#IdcStatStudyFrom').val();
		let toDate 		= $('#IdcStatStudyTo').val();

		let modid 	= encodeURIComponent(IdcStatStudyModalitiesCBMenu.GetSelection2String());
				
		let url= "SubFW/database/stats/GetDTStatSeriePreview.php?from="+fromDate+"&to="+toDate+"&modid="+modid;
		
			
		xhra.open('GET',url,true);
		xhra.send();
}

function CSVExportSerieListUpdateCheckbox()
{
		

		let rowsData 	= $('#IdcStatSeriePreviewDT').DataTable().rows().data();
		
		for(let j=0; j<rowsData.length; j++)
		{
				let ser_id= rowsData [j].ser_id;

				let toExport= false;
				if(GCSVSerieExportListCB.length== 0)
				{
						toExport= true;
				}
				else
				{
						let data= CSVExportSerieListGetData(ser_id);
						if(data != null)
								toExport= data.ToExport;
						else
								console.log(" data is null !!!");
				}

				if(toExport== true) document.getElementById("IdcCSVExportSerieListSendCB_" + j).checked= true; else document.getElementById("IdcCSVExportSerieListSendCB_" + j).checked= false;
		}
}

function CSVExportSerieListGetData(stu_id)
{
	for(let i=0; i<GCSVSerieExportListCB.length; i++)
	{
		if(GCSVSerieExportListCB [i].stu_id== stu_id)
		{
			return GCSVSerieExportListCB [i];
		}
	}

	return null;
}







function StatStudyTabShown()
{
	
	$('#IdcStatSerieDiv').hide();
	$('#IdcStatPreviewSerieDTContainer').hide();
	$('#IdcStatPreviewStudyDTContainer').show();
}

function StatSerieTabShown()
{
	

	$('#IdcStatSerieDiv').show();

	$('#IdcStatPreviewStudyDTContainer').hide();
	$('#IdcStatPreviewSerieDTContainer').show();
}



function StatJasperRender()
{
    

    WaitingStart();

    const jrxmlFile 			= $('#IdcStatJasperSelect').find(':selected').val();
    const pdfMode 				= $('#IdcStatJasperPDFCheck').is(':checked');

    const paramsDiv 	= document.getElementById('IdcStatJasperParameters');
    const inputs 		= paramsDiv.querySelectorAll('input,select,textarea');

    const parameters= {};
    inputs.forEach(input=> 
    {
        const name= input.name || input.id;
        const value= input.value;
        if(name) 
        	parameters[name]= value;
    });


    const checkbox= {};
    const inputs1 		= paramsDiv.querySelectorAll('.ximeo_sol-selected-display-item');
    
    inputs1.forEach(input1=> {
    	

    	let name 	= input1.dataset.name;
    	let value 	= input1.dataset.ident2;

    	if(!checkbox [name])
    		checkbox [name]= [];
    	checkbox[name].push(value);
    });

    for(const name in checkbox)
    {
    	checkbox [name]= checkbox [name].join(',');
    }

    

    const bodyParams= new URLSearchParams();
    bodyParams.append('jrxml',"Statistic/" + jrxmlFile);
    bodyParams.append('output','stdout');
    bodyParams.append('format',pdfMode ? 'pdf' : 'html');

    
    for(const [key,value] of Object.entries(parameters)) 
    {
    	
        bodyParams.append(key,value);
    }

    
    for(const [key,value] of Object.entries(checkbox)) 
    {
    	
        bodyParams.append(key,value);
    }

    fetch('./SubFW/html/JasperConverter.php',{
        method: 'POST',
        body: bodyParams
    })
    .then(response=> {
        if(!response.ok) throw new Error("Erreur HTTP");
        return pdfMode ? response.blob() : response.text();
    })
    .then(data=> {
        WaitingStop();

        if(pdfMode) 
        {
    		const pdfUrl= URL.createObjectURL(data);

    		const iframe= document.createElement('iframe');

    		iframe.src 			= eoDACS.ServerAddress + eoDACS.ServerFolder + "/Common/PDFViewer.php";
			
    		iframe.className 	= 'w-100 h-100';
    		iframe.style.flex 	= '1';
    		iframe.style.border= 'none';

    		const container= document.getElementById('IdcStatJasperRender');
    		container.innerHTML= ''; 
    		container.appendChild(iframe);

    		iframe.onload=()=> {
        		iframe.contentWindow.postMessage({
            		type: 'load-pdf-blob',
            		blobUrl: pdfUrl
        		},'*');
    		};
		}
        else 
        {
            $('#IdcStatJasperRender').html(data);
        }
    })
    .catch(error=> {
        WaitingStop();
        console.error("Erreur lors de la récupération :",error);
    });
}


function StatJasperReportChanged() 
{
	function getInputType(javaType) 
	{
		
        switch(javaType.toLowerCase()) 
        {
        	case 'java.sql.date':
        		return 'date';
        	case 'java.lang.long':
        		return 'number';
            case 'int':
            case 'integer':
            case 'long':
                return 'number';
            case 'date':
                return 'date';
            case 'boolean':
                return 'checkbox';
            default:
                return 'text';
        }
    }

    
    const selectedOption= $('#IdcStatJasperSelect').find('option:selected');
    const params= selectedOption.data('params') || [];
    const idcParamsDiv= $('#IdcStatJasperParameters');

    idcParamsDiv.empty();

    if(params.length > 0) 
    {
    	params.forEach(param=> 
    		{
 				const inputType= getInputType(param.type);
                
    			if(param.name.toLowerCase().includes('list'))
    			{
        			if(param.name.toLowerCase().includes('modality'))
            		{
           				let tmp= 	'<div class="mb-3 w-100">';
           				tmp += 			'<label for="param_'+param.name+'" class="form-label fw-bold">'+Translate(param.name)+'</label>';
           				tmp += 			'<div id="IdcParamList_'+param.name+'" class="w-100">';
           				tmp += 			'</div>';
           				tmp += 		'</div>';

           				idcParamsDiv.append(tmp);

           				let idcELModalityFilter= new C_CheckboxMenu("IdcParamList_" + param.name,param.name,Translate("Select"));
						idcELModalityFilter.UnselectAll();
						idcELModalityFilter.ClearAll();
						InitModalitiesCBList(idcELModalityFilter);
           			}
        		}
                else
                {
                	
                	let tmp= 	'<div class="mb-3">';

                	tmp += 			'<label for="param_'+param.name+'" class="form-label fw-bold">'+Translate(param.name)+'</label>';

                	let val= '';
                	if(inputType== 'date')
                		val= new Date().toISOString().split('T')[0];

               		tmp +=			'<input type="'+inputType+'" class="form-control form-control-sm w-auto" name="'+param.name+'" id="param_'+param.name+'" value="'+val+'">';


                	tmp += 		'</div>';

                	idcParamsDiv.append(tmp);
                }
            });
	} 
    else 
    {
    	idcParamsDiv.append('<p class="text-muted"><em>Aucun paramètre requis pour ce rapport.</em></p>');
   	}

    switchLanguage(eoDACS.CurrentLanguage);
}


function StatJasperRefreshReportsList()
{
	$('#IdcStatJasperSelect').empty();

	$.post(
			"./SubFW/html/JasperParser.php",
			{

				folder: 		"Statistic"
			},
			function(data) 
			{
				const reports= data.reports || [];

				reports.forEach(report=> { 
					let fileNameWithoutExt= report.file.replace(/\.jrxml$/i,'');

					if(fileNameWithoutExt.toLowerCase().includes('sub')== false)
					{
						$('#IdcStatJasperSelect').append(
							$('<option>',{ 
								value: report.file,
								text: fileNameWithoutExt
							}).data('params',report.parameters)
						)
					};
				})

				StatJasperReportChanged();
			},
			'json'
	);
}
</script>


   <title>eoDACS</title>
	

  <style>
  </style>
  </head>
  <body class="vh-100">
  <div class="container-fluid max-vh-100 h-100  p-0 bg-warning overflow-hidden">
  <div id="IdcUserContentDiv_" class="h-100 w-100 p-0 m-0" >
	<div id="IdcDivStatistic"  class="w-100 h-100 p-2 m-0 ximeo_bg-light" style="display: block !important">

		<iframe id="IdcStatisticEditorFrame" class="w-100 h-100" style="display: none;"></iframe>

		<div id="IdcStatisticMainFrame" class="d-flex flex-column w-100 h-100 m-0 p-0 rounded-top bg-white">
											
			<div class="row w-100 m-0 ps-0 pe-0 pt-0 pb-0 rounded-top">
		
				<ul class="nav nav-tabs rounded-top" id="myTab" role="tablist">
					<li class="nav-item" role="presentation">
						<button class="nav-link active" id="IdcStatisticGraphicTab" data-langkey="Graphics" data-bs-toggle="tab" data-bs-target="#IdcStatisticGraphicPanel" type="button" role="tab">
						</button>
					</li>
					<li class="nav-item" role="presentation">
						<button class="nav-link" id="IdcStatisticStudyTab" data-langkey="Study" data-bs-toggle="tab" data-bs-target="#IdcStatisticStudyPanel" type="button" role="tab">
						</button>
					</li>
					<li class="nav-item" role="presentation">
						<button class="nav-link" id="IdcStatisticSerieTab" data-langkey="Serie" data-bs-toggle="tab" data-bs-target="#IdcStatisticStudyPanel" type="button" role="tab">
						</button>
					</li>
					<li class="nav-item" role="presentation">
						<button class="nav-link" id="IdcStatisticJasperTab" data-langkey="Jasper reports" data-bs-toggle="tab" data-bs-target="#IdcStatisticJasperPanel" type="button" role="tab">
						</button>
					</li>
				</ul>
		
			</div>


			<div class="row flex-grow-1 m-0 ps-0 pe-0 pt-0 pb-0" style="min-height: 0px;">

				<div class="tab-content m-0 p-0 pt-2 bg-light" style="max-height: 100% !important;">
							
					<div class="tab-pane show active fade h-100 w-100 m-0 p-0" id="IdcStatisticGraphicPanel" role="tabpanel" aria-labelledby="IdcStatisticGraphicTab">		
					<!--- STATISTIC 1 -->
					 <div id="layout1" class="w-100 h-100 m-0 p-0" >
  			
		  <!-- <div class="row h-100 w-100 m-0 p-0"> -->

          <div class="h-100 d-flex flex-row m-0 p-0 h-100 w-100 ">

      		<div class="col-3 bg-white m-0 p-0" >
              <div class="row  m-0 p-0 pb-3">
                  <div class="col m-0 p-0 w-100">
                        <div class="row m-0 p-2 pb-3 w-100 ">
                          <div class="m-0 p-0 border-bottom fw-bold" data-langkey="Layout :"></div>
                        </div>
                        <div class="row w-100 m-0 p-0 ps-1">
                          <div class="col"><img id="l1x1" class="img-radio imgclickable ximeo_bmp" onclick="window.setLayout(this.id);" title="Layout 1x1" src="../eoDACS/SubFW/bmp/SerieLayout1X1.png"></div>
                          <div class="col"><img id="l2x1" class="img-radio imgclickable ximeo_bmp" onclick="window.setLayout(this.id);" title="Layout 2x1" src="../eoDACS/SubFW/bmp/SerieLayout2X1.png"></div>
                          <div class="col"><img id="l1_1x2" class="img-radio imgclickable ximeo_bmp" onclick="window.setLayout(this.id);" title="Layout 2x1" src="../eoDACS/SubFW/bmp/SerieLayout1_1X2.png"></div>
                          <div class="col"><img id="l1x2" class="img-radio imgclickable ximeo_bmp" onclick="window.setLayout(this.id);" title="Layout 1x2" src="../eoDACS/SubFW/bmp/SerieLayout1X2.png"></div>
                          <div class="col"><img id="l2x2" class="img-radio imgclickable ximeo_bmp" onclick="window.setLayout(this.id);" title="Layout 2x2" src="../eoDACS/SubFW/bmp/SerieLayout2X2.png"></div>
                        </div>
              		</div>
              </div>	


              <div class="row m-0 p-2 pb-3 w-100">
                  <div class="m-0 p-0 border-bottom fw-bold" data-langkey="Period :"></div>
              </div>

              <div class="row m-0 p-0 ps-1 pb-2 w-100">
                  <div class="col-4 m-0 p-0 ps-2">
                      <label for="IdcStatisticFromDate" class="col-form-label m-0 p-0 pt-1" data-langkey="From :"></label>
                  </div>
                  <div class="col-auto m-0 p-0">
                      <input type="date" class="form-control form-control-sm m-0 p-0 ps-2 fs-6" id ="IdcStatisticFromDate" autocomplete="off" size="8" placeholder="jj/mm/aaaa" >
                  </div>
              </div>
              
              <div class="row m-0 p-0 ps-1 pb-2 w-100">
                  <div class="col-4 m-0 p-0 ps-2">
                      <label for="IdcStatisticToDate" class="col-form-label m-0 p-0 pt-1" data-langkey="To :"></label>
                  </div>
                  <div class="col-auto m-0 p-0">
                      <input type="date" class="form-control form-control-sm m-0 p-0 ps-2 fs-6" id ="IdcStatisticToDate" autocomplete="off" size="8" placeholder="jj/mm/aaaa">
                  </div>
              </div>
                  				
              <div class="row w-100 m-0 p-0 pb-3 mb-2">
                  <div class="col"><label class="ximeo_checkbox_1"><input id="day1" type="checkbox" checked><div class="div-checked" data-langkey="Mo."></div></label></div>
                  <div class="col"><label class="ximeo_checkbox_1"><input id="day2" type="checkbox" checked><div class="div-checked" data-langkey="Tu."></div></label></div>
                  <div class="col"><label class="ximeo_checkbox_1"><input id="day3" type="checkbox" checked><div class="div-checked" data-langkey="We."></div></label></div>
                  <div class="col"><label class="ximeo_checkbox_1"><input id="day4" type="checkbox" checked><div class="div-checked" data-langkey="Th."></div></label></div>
                  <div class="col"><label class="ximeo_checkbox_1"><input id="day5" type="checkbox" checked><div class="div-checked" data-langkey="Fr."></div></label></div>
                  <div class="col"><label class="ximeo_checkbox_1"><input id="day6" type="checkbox" checked><div class="div-checked" data-langkey="Sa."></div></label></div>
                  <div class="col"><label class="ximeo_checkbox_1"><input id="day7" type="checkbox" checked><div class="div-checked" data-langkey="Su."></div></label></div>
              </div>

              <div class="row m-0 p-2 pb-3 w-100">
                  <label class="m-0 p-0 fw-bold pb-2" for="masterstudy" data-langkey="Studies :"></label>
                  <div class="m-0 p-0 ps-1" id='masterstudy' data-sol-name='character' multiple='multiple'></div>
              </div>

              <div class="row m-0 p-2 pb-3 w-100">
              		<label class="m-0 p-0 fw-bold pb-2" for="inputModality" data-langkey="Modalities :"></label>
              		<div class="m-0 p-0 ps-1" id='modality' data-sol-name='character' multiple='multiple'></div>
              </div>
              
            <div class="row w-100 m-0 mt-4 p-0 pb-3 ps-2 pe-2">
              <div class="col w-100 m-0 p-0 pt-2 border-top">
                <div class="d-flex flex-row-reverse w-100 h-100 m-0 p-0">
                  <div class="col-md-auto h-100 m-0 p-0 pt-2 pe-2">
                <button id="IdcStatApplyButton" class="ximeo_button">
                  <img src="./SubFW/bmp/validate_white.png" class="ximeo_img_button">
                  <span data-langkey="Apply"></span>
                </button>
              </div>
              </div>
              </div>
            </div>

      		</div>
            			
          <div class="col flex-grow-1 m-0 p-0 ps-2" style="min-width: 0px;">
            <div class="container-fluid" id="layoutcontainer" style="min-height:100%;height:100%">
            </div>
          </div>

        </div>

  		 <!-- </div> -->
		
    </div>
	<!-- END STATISTIC 1 -->
					</div>

					<div class="tab-pane fade h-100 w-100 m-0 p-0" id="IdcStatisticStudyPanel" role="tabpanel" aria-labelledby="IdcStatisticStudyTab">		
						<div id="IdcStatisticStudySplitter1_2" class="splitter-v w-100 h-100 p-0 m-0" data-ratio="0.25">
			
							<div class="pan-left m-0 p-0 ps-3 pe-3 pb-2">

								<div class="row w-100 m-0 p-0">
									<label class="form-label fw-bold m-0 p-0 pb-1" data-langkey="Studies :"></label>
									<div id="IdcStatStudyStudiesContainer" class="m-0 p-0 mb-1"></div>
								</div>

								<div id="IdcStatSerieDiv" class="row w-100 m-0 p-0" style="display:none;">
									<label class="form-label fw-bold m-0 p-0 pb-1" data-langkey="Series :"></label>
									<div id="IdcStatStudySeriesContainer" class="m-0 p-0 mb-1"></div>
								</div>

								<div class="row w-100 m-0 p-0 pt-3">
									<div class="col-md-auto m-0 p-0 pe-3">
										<label class="form-label fw-bold m-0 p-0 pb-2" for="IdcStatStudyFrom" data-langkey="From :"></label>
										<input type="date" id="IdcStatStudyFrom" class="form-control form-control-sm m-0 p-0 ps-2 fs-6" autocomplete="off" size="8" placeholder="jj/mm/aaaa" />
									</div>
									<div class="col-md-auto m-0 p-0">
										<label class="form-label fw-bold m-0 p-0 pb-2" for="IdcStatStudyTo" data-langkey="Until :"></label>
										<input type="date" id="IdcStatStudyTo" class="form-control form-control-sm m-0 p-0 ps-2 fs-6" autocomplete="off" size="8" placeholder="jj/mm/aaaa">
									</div>
								</div>

								<div class="row w-100 m-0 p-0 pt-3">
									<label class="form-label fw-bold m-0 p-0 pb-1" data-langkey="Modalities :"></label>
									<div id="IdcStatStudyModalitiesContainer" class="m-0 p-0 mb-1"></div>
								</div>

								<div class="row w-100 m-0 p-0 pt-3 pb-4 border-bottom">
									<div class="col-md-auto m-0 p-0 pe-4">
										<label class="form-label fw-bold m-0 p-0 pb-1" data-langkey="I.M.C. :"></label>
										<div id="IdcStatStudyIMCContainer" class="m-0 p-0 mb-1"></div>
									</div>
								</div>

								<div class="row w-100 m-0 p-0 pt-3 pb-4 border-bottom">
									<div class="col-md-auto m-0 p-0">
										<label class="form-label fw-bold m-0 p-0 pb-1" data-langkey="Ages :"></label>
										<div id="IdcStatStudyAgeContainer" class="m-0 p-0 mb-1"></div>
									</div>
								</div>

								<div class="row w-100 m-0 p-0 pt-2">
  									<div class="d-flex flex-row-reverse flex-wrap w-100 m-0 p-0">
    
    									<div class="h-100 m-0 p-0 pt-2 pe-2">
      										<button class="ximeo_button ximeo_app-color" onclick="StatStudyExportModel();">
        										<img src="./SubFW/bmp/export_model-1.png" class="ximeo_img_button">
        										<span data-langkey="Export from a model..."></span>
      										</button>
    									</div>

    									<div class="h-100 m-0 p-0 pt-2 pe-2">
      										<button class="ximeo_button ximeo_app-color" onclick="StatPreviewCSV();">
        										<img src="./SubFW/bmp/export_csv-1.png" class="me-2" style="width: 22px; vertical-align: middle;">
        										<span data-langkey="Preview CSV"></span>
      										</button>
    									</div>

  									</div>
								</div>


							</div>

							<div class="separator_v">
							</div>

							<div class="pan-right m-0 p-0">
								<div class="d-flex flex-column w-100 h-100 m-0 p-0 ps-2 pe-2 pb-2">
									<div class="row w-100 m-0 p-0 pt-2 pb-2 ximeo_app-color text-white fw-bold rounded-top">
										<span data-langkey="Preview" data-id="-1"></span>
									</div>
									<div class="row flex-grow-1 m-0 p-0 border" style="min-height:0px;">
										<div id="IdcStatPreviewStudyDTContainer" class="w-100 h-100 m-0 p-0" style="min-height:0px; display: none;">
										</div>
										<div id="IdcStatPreviewSerieDTContainer" class="w-100 h-100 m-0 p-0" style="min-height:0px; display: none;">
										</div>
									</div>

									<div class="row w-100 m-0 p-0">
										<div class="d-flex flex-column w-100 h-100 m-0 p-0">
											<div class="d-flex flex-row-reverse w-100 h-100 m-0 p-0">
                  						
                  								<div class="col-md-auto h-100 m-0 p-0 pt-2 pe-2">
                									<button class="ximeo_button ximeo_app-color" onclick="StatDisplayCSV();">
                									<!-- <button class="ximeo_button" onclick="StatShowEditor();"> -->
                  										<img src="./SubFW/bmp/export_model-1.png" class="ximeo_img_button ximeo_app-color" >
                  										<span data-langkey="Export to CSV"></span>
                									</button>
              									</div>
              								</div>
										</div>
									</div>
								</div>
							</div>
						
						</div>
					</div>

					<div class="tab-pane fade h-100 w-100 m-0 p-0" id="IdcStatisticSeriePanel" role="tabpanel" aria-labelledby="IdcStatisticSerieTab">		
						<div id="IdcStatisticSerieSplitter1_2" class="splitter-v w-100 h-100 p-0" data-ratio="0.5" style="background-color: #F0F0F0;">
			
							<div class="pan-left ximeo_bg-light m-0 p-0">
								
							</div>

							<div class="separator_v">
							</div>

							<div class="pan-right ximeo_bg-light m-0 p-0">
							</div>
						
						</div>
					</div>



					<div class="tab-pane show active fade h-100 w-100 m-0 p-0" id="IdcStatisticJasperPanel" role="tabpanel" aria-labelledby="IdcStatisticJasperTab">	
						<div id="IdcStatisticJasperSplitter1_2" class="splitter-v w-100 h-100 p-0" data-ratio="0.25" style="background-color: #F0F0F0;">
			
							<div class="pan-left ximeo_bg-light m-0 p-0 bg-light">


								<div class="d-flex flex-column w-100 h-100 m-0 p-0 ps-2 pe-2 bg-light">

									<div class="row w-100 m-0 p-0">
										<div class="w-100 m-0 p-0 ps-1 pe-1 pt-2 d-flex align-items-end">
  											<div class="d-flex flex-column w-100 me-2">
    											<label class="form-label fw-bold" for="IdcStatJasperSelect">Rapport :</label>
    											<select id="IdcStatJasperSelect" class="form-select form-select-sm"></select>
  											</div>

  											<button id="refreshBtn" class="btn btn-sm ximeo_app-color" type="button">
    											<img src="SubFW/bmp/refresh.png" data-langkey_title="Refresh" class="imgclickable ximeo_bmp"
      														onclick="StatJasperRefreshReportsList()" />
  											</button>
										</div>
									</div>

									<div class="row flex-grow-1 m-0 p-0 pt-3 overflow-auto" style="min-height:0px;">
										<div id="IdcStatJasperParameters" class="m-0 p-0 pt-2 pb-2 ps-2 pe-2">
										</div>
									</div>

									<div class="row m-0 p-0 ps-2 pt-2 pb-2 pe-2 border-top">
										<div class="h-100 m-0 p-0 d-flex justify-content-end">
											<div class="form-check">
      											<input class="form-check-input" type="checkbox" value="" id="IdcStatJasperPDFCheck">
      											<label class="form-check-label" for="IdcStatJasperPDFCheck">
        											Affichage PDF
      											</label>
    										</div>
										</div>
									</div>

									<div class="row m-0 p-0 ps-2 pt-2 pb-2 pe-2 border-top">
										<div class="h-100 m-0 p-0 d-flex justify-content-end">
      										<button class="ximeo_button ximeo_app-color" onclick="StatJasperRender();">
        										<img src="./SubFW/bmp/export_model-1.png" class="ximeo_img_button">
        										<span data-langkey="Show report">Render</span>
      										</button>
    									</div>
    								</div>

    							</div>

							</div>

							<div class="separator_v">
							</div>

							<div class="pan-right ximeo_bg-light m-0 p-0">
								<div id="IdcStatJasperRender" class="w-100 h-100 m-0 p-0 ps-2 pe-2 pb-2 bg-light d-flex overflow-auto">
								</div>
							</div>
						
						</div>	
					</div>






				</div>

			</div>


		</div>
		
	</div>






	<div id="IdcDlgStatStudyModelExport"  class="modal" tabindex="-1" style="z-index: 1080 !important;" data-ident="" data-onsavefunction="" data-bs-backdrop="static" role="dialog" aria-hidden="true">
		<div class="modal-dialog modal-dialog-centered modal-sm" role="document" style="resize: true;">
			<div class="modal-content">
										
				<div class="modal-header p-3 pb-3 pt-3 border-bottom bg-light">
					<h5 class="fw-bold mb-0" data-langkey="Export template available"></h5>
					<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
				</div>
										
				<div class="modal-body w-100 p-1">
					<ol class="list-group">
         				<?php
         					$conn= get_dbconnection();
       						if($conn)
       						{
       		  					$sql= "select stat_id,label from stats_template where removed= false and type= 'STUDY';";

       		  					if($query=pg_query($conn,$sql))
       		  					{
       		    					while($row= pg_fetch_row($query))
       		    					{ ?>
       									<li class="stattemplate" id="<?=$row[0]?>" onclick="downloadWithTemplate(this.id)"><?=htmlspecialchars($row[1])?></li>
       								<?php }
       							}
       						} ?>
      				</ol>
				</div>
						
				<div class="modal-footer">
						
					<div class="col-md-auto">
						<button class="ximeo_button" onclick="StatStudyExportModelValidate();">
							<img src="./SubFW/bmp/validate_white.png" class="ximeo_img_button">
							<span >Validate</span>
						</button>
						<button class="ximeo_button ximeo_bg-dark-2" onclick="$('#IdcDlgStatStudyModelExport').modal('hide');">
							<img src="./SubFW/bmp/close_white.png" class="ximeo_img_button">
							<span data-langkey="Cancel">Cancel</span>
						</button>
					</div>
				</div>
			</div>
		</div>
	</div>
	</div>
	</div>
</body>
	
	<script>
	init_layout();

    $("#IdcStatisticFromDate").val(GetCurrentDate());
    $("#IdcStatisticToDate" ).val(GetCurrentDate());
    
    switchLanguage(eoDACS.CurrentLanguage);
	</script>
	
	<script>
	
		InitStatisticPage(); 
		
	
/*
	window.addEventListener('message',function(event){
		if(event.data.type=== 'savealertmsg') {
			IdcExamListDT.SetRowToSelect('stu_id',event.data.payload.stuid);
			IdcExamListDT.Refresh();
		}
	});*/
	
//});
	</script>
</html>