
	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 ()
	{
		let ss = sessionStorage.getItem ( 'StatisticPageInitialized' );
		
		if ( ss == 'true' )
			return;
		
		sessionStorage.setItem ( 'StatisticPageInitialized', true );

		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.CallbackFct = ExamsListDetailDepartmentsChanged;
			InitStudiesCBList ( IdcStatStudyStudiesCBMenu );

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


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

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

			IdcStatStudyAgeCBMenu = new C_CheckboxMenu ( "IdcStatStudyAgeContainer", "IdcStatStudyAgeCBMenu0", Translate("Click here to select ages") );
			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 ()
	{
			console.log ( "StatPreviewCSV..." );

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

			if ( $('#IdcStatPreviewSerieDTContainer').is (":visible") == true )
			{
					console.log ( "Refresh serie!!!" );
					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 ()
	{
			console.log ( "StatStudyDisplayCSV..." );

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

						console.log ( " Visible ["+i+"] : " + col.Label + " / " + col.Data + " / " + col.Visible + " / " + col.Position + " /  " + col.Index );
						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 ();
				
				console.log ( "data.status : " + data.status );
				console.log ( "data.file : " + data.file );
				/*
				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 ()
	{
			console.log ( "StatSerieDisplayCSV..." );

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

						console.log ( " Visible ["+i+"] : " + col.Label + " / " + col.Data + " / " + col.Visible + " / " + col.Position + " /  " + col.Index );
						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 ();
				
				console.log ( "data.status : " + data.status );
				console.log ( "data.file : " + data.file );
				/*
				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 ()
	{	
		console.log ('VVVVVVVVVVVVVVVVV'); $('#IdcDlgStatStudyModelExport').modal('hide');
	}


	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 ) 
    {
    	console.log ( "prepare_and_download..." );
    	console.log ( " url : " + url );
    	console.log ( " downloadurl : " + 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 )
	{
			console.log ( "StatStudyPreviewDTGetData..." );

			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 ());
			console.log ( "d.mstuid : " + d.mstuid );

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

	function  StatStudyPreviewDTDrawCallback ( dtIdent )
	{
			WaitingStop ();

			CSVExportStudyListUpdateCheckbox ();
	}

	function StatSeriePreviewDTGetData ( d )
	{
			console.log ( "StatSeriePreviewDTGetData..." );

			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 ());
			console.log ( "d.mstuid : " + d.mstuid );
			console.log ( "d.mserid : " + d.mserid );
			console.log ( "d.modid : " + d.modid );

			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 )
	{
			console.log ( "OnExportCSVStudyExportCBClicked..." );

			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 )
					{
							console.log ( "e.checked : " + e.checked );
							GCSVStudyExportListCB [i].ToExport = e.checked;
							break;
					}
			}
	}

	function OnExportCSVSerieExportCBClicked ( e )
	{
			console.log ( "OnExportCSVSerieExportCBClicked..." );

			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 )
					{
							console.log ( "e.checked : " + e.checked );
							GCSVSerieExportListCB [i].ToExport = e.checked;
							break;
					}
			}
	}




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

function ExportCSVStudyListLoad ()
{
		console.log ( "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 ()
{
		console.log ( "CSVExportStudyListUpdateCheckbox..." );

		let rowsData 	= $('#IdcStatStudyPreviewDT').DataTable().rows().data ();
		console.log ( "rowsData.length : " + rowsData.length );
		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 ()
{
		console.log ( "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 ()
{
		console.log ( "CSVExportSerieListUpdateCheckbox..." );

		let rowsData 	= $('#IdcStatSeriePreviewDT').DataTable().rows().data ();
		console.log ( "rowsData.length : " + rowsData.length );
		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 ()
{
	console.log ( 'StatStudyTabShown...' );
	$('#IdcStatSerieDiv').hide ();
	$('#IdcStatPreviewSerieDTContainer').hide ();
	$('#IdcStatPreviewStudyDTContainer').show ();
}

function StatSerieTabShown ()
{
	console.log ( 'StatSerieTabShown...' );

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

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



function StatJasperRender()
{
    console.log("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');
    console.log ( " inputs1.length : " + inputs1.length );
    inputs1.forEach ( input1 => {
    	console.log ( "input1 : " + input1.dataset.name + " / " + input1.dataset.ident2 );

    	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 (',');
    }

    console.log ( " checkbox : " , checkbox );

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

    console.log ( "parameters not checkbox ...");
    for ( const [key, value] of Object.entries(parameters) ) 
    {
    	console.log ( " key : " + key + " / " + value );
        bodyParams.append(key, value);
    }

    console.log ( "checkbox ...");
    for ( const [key, value] of Object.entries(checkbox) ) 
    {
    	console.log ( " key : " + key + " / " + value );
        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";
			console.log ( "iframe.src : " + iframe.src );
    		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 ) 
	{
		console.log ( "javaType : " + 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") );
						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'
	);
}