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

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

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

	let IdcSurveyConclusionEditor = null;
	

	function InitSurveyPage ()
	{
		// return;
		
		let ss = sessionStorage.getItem ( 'SurveyPageInitialized' );

		if ( ss == 'true' )
			return;
		
		sessionStorage.setItem ( 'SurveyPageInitialized', true );

		IdcSurveyDT = new C_DataTable ();
		IdcSurveyDT.DataSrcType		= 0;
		IdcSurveyDT.Ident 			= 'IdcSurveyDT';
		IdcSurveyDT.Container 		= 'IdcSurveyDTContainer';
		IdcSurveyDT.DataSrc 		= 'SubFW/database/survey/GetDTSurveys.php';
		IdcSurveyDT.DataFct			= SurveyDTGetData;
		IdcSurveyDT.SetColReorder 	( false );
		IdcSurveyDT.OnSelectChanged	( SurveyDTSelectChanged 	);
		IdcSurveyDT.AddColumn ( Translate('id'),			'id',			 			0, false,  0,    50, false, '', 				'' );
		IdcSurveyDT.AddColumn ( Translate('Type'),			'type',						1, false,  1, 	 50, false,  '', 				'' );
		IdcSurveyDT.AddColumn ( Translate('Status'),		'status',	 				1, false,  2, 	 50, false,  '', 				'' );
		IdcSurveyDT.AddColumn ( Translate('Status'),		'status_name', 				1, true,   3, '10%', true,  '', 				'', function (data) {return Translate(data);} );
		IdcSurveyDT.AddColumn ( Translate('Type'),			'survey_type', 				1, true,   4, '10%', true,  '', 				'', function (data) {return Translate(data);}  );
		IdcSurveyDT.AddColumn ( Translate('Begin date'),	'begindate',	 			1, true,   5, '10%', true,  'text-center',		'', DICOMDate2StdDateFR );
		IdcSurveyDT.AddColumn ( Translate('End date'),		'enddate',		 			1, true,   6, '10%', true,  'text-center',		'', DICOMDate2StdDateFR );
		IdcSurveyDT.AddColumn ( Translate('Title'),			'title',		 			1, true,   7, '20%', true,  '', 				'' );
		IdcSurveyDT.AddColumn ( Translate('Description'),	'description',	 			1, true,   8, '40%', true,  '', 				'' );
		IdcSurveyDT.AddColumn ( Translate('Comment'),		'comment',		 			1, false,  9, '40%', false,  '', 				'' );
		IdcSurveyDT.AddColumn ( Translate('Conclusion'),	'conclusion',	 			1, true,  10, '40%', false,  '', 				'' );
		IdcSurveyDT.AddColumn ( Translate('Actions'),		'listofactiondescription',	1, false, 11,    50, false,  '', 				'' );
		IdcSurveyDT.SetColumnFilter ( 3, '<div class="m-0 p-0 ps-2 pe-2"><select class="form-select m-0 p-0 ps-2" id="IdcSurveyStatusFilter" aria-label="Default select example" onchange="IdcSurveyDT.Refresh();"><option value="-1">*</option></select></div>' );
		IdcSurveyDT.SetColumnFilter ( 7, '<div class="m-0 p-0 ps-0 pe-1 pb-2"><input id="IdcSurveyTitleFilter" class="form-control pt-0 pb-0" oninput="IdcSurveyDT.Refresh()" type="text" placeholder="'+Translate("Title")+'"></div>' );
		IdcSurveyDT.LoadUserCfg ( G_USE_ID );


		IdcSurveyFieldDT = new C_DataTable ();
		IdcSurveyFieldDT.DataSrcType		= 0;
		IdcSurveyFieldDT.Ident 			= 'IdcSurveyFieldDT';
		IdcSurveyFieldDT.Container 		= 'IdcSurveyFieldDTContainer';
		IdcSurveyFieldDT.DataSrc 		= 'SubFW/database/survey/GetDTSurveyFields.php';
		IdcSurveyFieldDT.DataFct		= SurveyFieldDTGetData;
		IdcSurveyFieldDT.SetColReorder 	( false );
		IdcSurveyFieldDT.OnSelectChanged	( SurveyFieldDTSelectChanged 	);
		IdcSurveyFieldDT.AddColumn ( '',					'shortcut',		 			0, true,   0,   110, false, '', 				'<img class=\"SurveyField_Edit imgclickable  ps-2 pe-2\" title=\"'+Translate ( 'Edit' )+'\" src=\"'+G_ServerFolder+'/eoQUAL/SubFW/bmp/edit_blue.png\" style=\"height: 18px; width: auto;\"></img><img class=\"SurveyField_Delete imgclickable pe-2\" title=\"'+Translate ( 'Delete' )+'\" src=\"'+G_ServerFolder+'/eoQUAL/SubFW/bmp/trash.png\" style=\"height: 18px; width: auto;\"></img><img class=\"SurveyField_Down imgclickable pe-2\" title=\"'+Translate ( 'Down' )+'\" src=\"'+G_ServerFolder+'/eoQUAL/SubFW/bmp/arrow_down.png\" style=\"height: 18px; width: auto;\"></img><img class=\"SurveyField_Up imgclickable pe-2\" title=\"'+Translate ( 'Up' )+'\" src=\"'+G_ServerFolder+'/eoQUAL/SubFW/bmp/arrow_up.png\" style=\"height: 18px; width: auto;\"></img>' );
		IdcSurveyFieldDT.AddColumn ( Translate('id'),		'id',			 			0, false,  1,    50, false, '', 				'' );
		IdcSurveyFieldDT.AddColumn ( Translate('Type'),		'type',						0, false,  2,  	 50, false,  '', 				'' );
		IdcSurveyFieldDT.AddColumn ( Translate('Position'),	'position',					0, false,  3,  	 50, true,  '', 				'' );
		IdcSurveyFieldDT.AddColumn ( Translate('Type'),		'type_name',				1, true,   4, '20%', false,  '', 				'', Translate );
		IdcSurveyFieldDT.AddColumn ( Translate('Text'),		'content',	 				1, true,   5, '80%', false,  '', 				'' );
		IdcSurveyFieldDT.AddColumn ( 'ai_analysis',			'ai_analysis', 				0, false,  6,    50, false,  '', 				'' );
		IdcSurveyFieldDT.LoadUserCfg ( G_USE_ID );

		IdcSurveyResponseDT = new C_DataTable ();
		IdcSurveyResponseDT.DataSrcType		= 0;
		IdcSurveyResponseDT.Ident 			= 'IdcSurveyResponseDT';
		IdcSurveyResponseDT.Container 		= 'IdcSurveyResponseDTContainer';
		IdcSurveyResponseDT.DataSrc 		= 'SubFW/database/survey/GetDTSurveyResponses.php';
		IdcSurveyResponseDT.DataFct			= SurveyResponseDTGetData;
		IdcSurveyResponseDT.SetColReorder 	( false );
		IdcSurveyResponseDT.OnSelectChanged	( SurveyResponseDTSelectChanged 	);
		IdcSurveyResponseDT.AddColumn ( Translate('ID'),			'id',			 		0, true,   0, '10%', true,  '', 				'' );
		IdcSurveyResponseDT.AddColumn ( Translate('Date'),			'rdate',	 			1, true,   1, '90%', true,  '', 				'' );
		IdcSurveyResponseDT.LoadUserCfg ( G_USE_ID );

		IdcSurveyConclusionDocumentsDT				= new C_DocumentDT ( "IdcSurveyConclusionDocumentsDT" );
		IdcSurveyConclusionDocumentsDT.Caption  	= 'Documents';
		IdcSurveyConclusionDocumentsDT.DocType		= "survey";
		IdcSurveyConclusionDocumentsDT.ExtType		= "survey";
		IdcSurveyConclusionDocumentsDT.Container	= 'IdcSurveyConclusionDocumentsDTContainer';
		IdcSurveyConclusionDocumentsDT.Editor		= SurveyEdition;
		IdcSurveyConclusionDocumentsDT.LoadUserCfg ( G_USE_ID );

		
		$(document).ready(function () 
		{
			new ResizeObserver ( function (ev) { QUILLEditorResize ('IdcSurveyDescriptionTextEditor'); } ).observe ( document.getElementById ('IdcSurveyDescriptionEditorContainer' ) );
			new ResizeObserver ( function (ev) { QUILLEditorResize ('IdcSurveyConclusionTextEditor'); } ).observe ( document.getElementById ('IdcSurveyConclusionEditorContainer' ) );

			document.getElementById ('IdcSurveyDesignTab' ).addEventListener ( 'shown.bs.tab', () => { SurveyDesignTabShown (); } );
			document.getElementById ('IdcSurveyPreviewTab').addEventListener ( 'shown.bs.tab', () => { SurveyPreviewTabShown (); } );
			document.getElementById ('IdcSurveyResultTab' ).addEventListener ( 'shown.bs.tab', () => { SurveyResultTabShown (); } );

			IdcSurveySplitter1_2 	= new C_Splitter ( "IdcSurveySplitter1_2" );
			IdcSurveySplitter3_4 	= new C_Splitter ( "IdcSurveySplitter3_4" );
			IdcSurveySplitter5_6 	= new C_Splitter ( "IdcSurveySplitter5_6" );
			IdcSurveySplitter7_8 	= new C_Splitter ( "IdcSurveySplitter7_8" );

			IdcSurveySplitter1_2.LoadUserCfg		( G_USE_ID );
			IdcSurveySplitter3_4.LoadUserCfg		( G_USE_ID );
			IdcSurveySplitter5_6.LoadUserCfg		( G_USE_ID );
			IdcSurveySplitter7_8.LoadUserCfg		( G_USE_ID );

			IdcSurveyDT.Create ();
			context.attach ( '#IdcSurveyDT', SurveyDTListMenu );
			IdcSurveyDT.SetRowToSelect('first_row');


			IdcSurveyFieldDT.Create ();
			context.attach ( '#IdcSurveyFieldDT', SurveyFieldDTListMenu );
			IdcSurveyFieldDT.SetRowToSelect('first_row');


			IdcSurveyResponseDT.Create ();
			context.attach ( '#IdcSurveyResponseDT', SurveyResponseDTListMenu );
			IdcSurveyResponseDT.SetRowToSelect('first_row');

			
			FillStatusList				( 'IdcSurveyStatusFilter', 	'survey' );
			FillStatusList 				( 'IdcSurveyStatus', 	 	'survey' );
			FillSurveyTypesList			( 'IdcSurveyType')
			FillSurveyFieldTypesList	( 'IdcSurveyFieldType')

			$('#IdcSurveyFieldDT tbody').on('click', '.SurveyField_Edit', function () 
			{
				let row = $(this).closest('tr');
				// let id = $('#IdcSurveyFieldDT').DataTable().row( row ).data().id;
					
				SurveyEditField ( row );
			} );	

			$('#IdcSurveyFieldDT tbody').on('click', '.SurveyField_Delete', function () 
			{
				let row = $(this).closest('tr');
					
				SurveyDeleteField ( row );
			} );

			$('#IdcSurveyFieldDT tbody').on('click', '.SurveyField_Down', function () 
			{
				let row = $(this).closest('tr');
					
				SurveyFieldPosition ( row, 'down' );
			} );	

			$('#IdcSurveyFieldDT tbody').on('click', '.SurveyField_Up', function () 
			{
				let row = $(this).closest('tr');
					
				SurveyFieldPosition ( row, 'up' );
			} );	


			IdcSurveyConclusionDocumentsDT.Create (2);
			
  			IdcSurveyConclusionEditor = new Quill('#IdcSurveyConclusionTextEditor', {
  					modules: {
    					toolbar: [
      						[{'font': []}],
      						[{ 'size': ['small', false, 'large', 'huge'] }],
      						[{ header: [1, 2, 3, false] }],
      						[{'align' : []}],
      						['bold', 'italic', 'underline'],
      						[{'list': 'ordered'}, {'list': 'bullet'}, {'list': 'check'}],
      						// ['image', 'video', 'code-block', 'link'],
      						['image'],
      						[{'color': []}, {'background' : []}],

    					],
  					},
  					placeholder: Translate('Conclusion of the investigation...'),
  					theme: 'snow', // or 'bubble'
				});

  			IdcSurveyDescriptionEditor = new Quill('#IdcSurveyDescriptionTextEditor', {
  					modules: {
    					toolbar: [
      						[{'font': []}],
      						[{ 'size': ['small', false, 'large', 'huge'] }],
      						[{ header: [1, 2, 3, false] }],
      						[{'align' : []}],
      						['bold', 'italic', 'underline'],
      						[{'list': 'ordered'}, {'list': 'bullet'}, {'list': 'check'}],
      						// ['image', 'video', 'code-block', 'link'],
      						['image'],
      						[{'color': []}, {'background' : []}],

    					],
  					},
  					placeholder: Translate('Conclusion of the investigation...'),
  					theme: 'snow', // or 'bubble'
				});

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

			switchLanguage ( CurrentLanguage );

			// CDTUpdateColumns ('IdcSurveyDT');
		});
	}

	function SurveyEdition ( doc_id )
	{
		$("#IdcSurveySplitter1_2").hide ();
		$("#IdcSurveyEditorFrame").show ();

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

	function SurveyDTGetData ( d )
	{
		d.begindate  	= '01/01/1999';
		d.enddate 		= '31/12/2025';
		d.title 		= $('#IdcSurveyTitleFilter').val ();
		d.status_id 	= $('#IdcSurveyStatusFilter :selected').val ();
		
		return $.extend( {}, d );
	}
	
	function SurveyDTSelectChanged ( rowsIdx )
	{
		let id 				= -1;
		let title			= '';
		let type			= -1;
		let status			= -1;
		let begindate		= '';
		let enddate			= '';
		let description		= '';
		let conclusion		= '';
		let listofaction 	= '';
		

		if ( rowsIdx.length == 1 )		// Only one row selected
		{
			let rowIdx = rowsIdx [0];

			id				= $('#IdcSurveyDT').DataTable().row( rowIdx ).data().id;
			title 			= $('#IdcSurveyDT').DataTable().row( rowIdx ).data().title;
			begindate		= $('#IdcSurveyDT').DataTable().row( rowIdx ).data().begindate;
			enddate			= $('#IdcSurveyDT').DataTable().row( rowIdx ).data().enddate;
			type			= $('#IdcSurveyDT').DataTable().row( rowIdx ).data().type;
			status			= $('#IdcSurveyDT').DataTable().row( rowIdx ).data().status;
			description		= $('#IdcSurveyDT').DataTable().row( rowIdx ).data().description;
			conclusion		= $('#IdcSurveyDT').DataTable().row( rowIdx ).data().conclusion;
			listofaction	= $('#IdcSurveyDT').DataTable().row( rowIdx ).data().listofactiondescription;
			
		}



		$('#IdcDivSurvey' ).data ('sur_id', id );
			
		$('#IdcSurveyType' ).val 		( type ).change();
		$('#IdcSurveyTitle' ).val 		( title );
		IdcSurveyDescriptionEditor.setContents ( IdcSurveyDescriptionEditor.clipboard.convert({
  			html: description
		}));
		$('#IdcSurveyStatus' ).val 		( status ).change();
		$('#IdcSurveyBeginDate' ).val 	( DICOMDate2StdDate(begindate) );
		$('#IdcSurveyEndDate' ).val 	( DICOMDate2StdDate(enddate) );
		$('#IdcSurveyConclusionTasks').html ( listofaction );

		IdcSurveyConclusionEditor.setContents ( IdcSurveyConclusionEditor.clipboard.convert({
  			html: conclusion
		}));



		IdcSurveyFieldDT.Refresh ();

		

		IdcSurveyResponseDT.Refresh ();



		SurveyUpdatePreview ();



		SurevyUpdateResult ();




		IdcSurveyConclusionDocumentsDT.ExtID = id;	
		IdcSurveyConclusionDocumentsDT.Refresh ();
		
	}

	function OnSurveyAddOK ( response )
	{
		if ( response != '-1')
		{
			IdcSurveyDT.SetRowToSelect ( 'id', response );

			IdcSurveyDT.Refresh ();
		}
		else
			OnSurevyAddError ();
	}

	function OnSurveyAddError ()
	{
		MsgWarning ( Translate("Unable to add survey !!!") );
	}

	function SurveyAdd ()
	{
		let id 	= -1;

		let params = "id=" + id;
		PostASyncData ( "SubFW/database/survey/SaveSurvey.php", params, 'application/x-www-form-urlencoded', OnSurveyAddOK, OnSurveyAddError );
	}

	function SurveySave ()
	{
		let id 	= $('#IdcDivSurvey' ).data ('sur_id');

		let title			= $('#IdcSurveyTitle' ).val ();
		let begindate 		= $('#IdcSurveyBeginDate' ).val ();
		let enddate 		= $('#IdcSurveyEndDate' ).val ();
		let type 			= $('#IdcSurveyType' ).val ();
		let status 			= $('#IdcSurveyStatus' ).val ();
		let description		= IdcSurveyDescriptionEditor.getSemanticHTML ();
		let comment			= $('#IdcSurveyComment' ).val ();
		let conclusion 		= IdcSurveyConclusionEditor.getSemanticHTML ();

		let params = "id=" + id;
		params += "&title=" + title;
		params += "&begindate=" + begindate;
		params += "&enddate=" + enddate;
		params += "&type=" + type;
		params += "&status=" + status;
		params += "&description=" + encodeURIComponent(description);
		params += "&comment=" + comment;
		params += "&conclusion=" + encodeURIComponent(conclusion);
		
		
		PostASyncData ( "SubFW/database/survey/SaveSurvey.php", params, 'application/x-www-form-urlencoded', OnSurveyAddOK, OnSurveyAddError );
	}

	function OnDeleteSurveyOK ( response )
	{
		if ( response != '-1')
			IdcSurveyDT.Refresh ();
		else
			OnDeleteSurveyError ();
	}

	function OnDeleteSurveyError ()
	{
		MsgWarning ( Translate("Unable to delete survey !!!") );
	}

	function DeleteSurvey ()
	{
		let selRows = IdcSurveyDT.GetSelectedRows ();
		if ( selRows.length == 1 )
		{
			let id = IdcSurveyDT.GetRowData ( selRows [0] ).id;

			PostASyncData ( "SubFW/database/survey/delete_survey.php", "id="+id, 'application/x-www-form-urlencoded', OnDeleteSurveyOK, OnDeleteSurveyError );
		}
	}

	function SurveyDelete ()
	{
		let selRows = IdcSurveyDT.GetSelectedRows ();
		if ( selRows.length == 1 )
		{
			MsgYesNo ( Translate("Delete selected survey ?"), DeleteSurvey );
		}
		else
		{
			MsgWarning ( Translate("No survey selected !!!") );
		}
	}

	function FillSurveyTypesList ( idSelect )
	{
		var xhra= getxhr();
			
		xhra.onloadend = function f()
		{
			if ( xhra.readyState == 4 && xhra.status == 200 )  
			{
				let idcSelect 		= document.getElementById ( idSelect );
				let reponse			= clean(xhra.responseXML.documentElement);
				let status		 	= reponse.getElementsByTagName ( 'survey_type' );
				
				for ( let i=0; i<status.length; i++ )
				{
					let id			= status.item (i).getAttribute ( "id" 	);
					let name		= status.item (i).getAttribute ( "name" );

					if ( id != -1 )
					{
						let option_elem = document.createElement('option');
  
						option_elem.value 		= id;
						option_elem.textContent = name;
  
						idcSelect.appendChild ( option_elem );				
					}
				}
			}
		};

		let url = "SubFW/database/survey/get_survey_types.php";
		xhra.open ('GET', url, false );
		xhra.send ();
	}



	// #################################################################################################""
	// ### Survey fields

	function SurveyFieldDTGetData ( d )
	{
		d.survey_id = $('#IdcDivSurvey' ).data ('sur_id');

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

	function SurveyFieldDTSelectChanged ( rowsIdx )
	{
		console.log ( "SurveyFieldDTSelectChanged..." );
	}

	function SurveyAddField ()
	{
		$('#IdcSurveyFieldEdit').modal ( 'show' );
		$('#IdcSurveyFieldEdit').data ( "id", -1);
	}

	function SurveyEditField ( rowIdx )
	{
		let id 			= $('#IdcSurveyFieldDT').DataTable().row( rowIdx ).data().id;
		let type 		= $('#IdcSurveyFieldDT').DataTable().row( rowIdx ).data().type;
		let content 	= $('#IdcSurveyFieldDT').DataTable().row( rowIdx ).data().content;
		let ai_analysis	= $('#IdcSurveyFieldDT').DataTable().row( rowIdx ).data().ai_analysis;

		console.log ( "ai_analysis : " + ai_analysis );

		$('#IdcSurveyFieldEdit' ).data ('id', id);
		$('#IdcSurveyFieldType').val ( type ).change ();
		$('#IdcSurveyFieldContent').val ( content );

		$('#IdcSurveyFieldIA').prop ('checked', (ai_analysis=='t')? true : false  );

		$('#IdcSurveyFieldEdit').modal ( 'show' );
	}


	function OnSurveyFieldSaveOK ( response )
	{
		if ( response != '-1')
		{
			IdcSurveyFieldDT.SetRowToSelect ( 'id', response );

			IdcSurveyFieldDT.Refresh ();
		}
		else
			OnSurveyFieldSaveError ();
	}

	function OnSurveyFieldSaveError ()
	{
		MsgWarning ( Translate("Unable to save survey field !!!") );
	}

	function SurveyFieldEditValidate ()
	{
		let survey_id 	= $('#IdcDivSurvey' ).data ('sur_id');
		let id 			= $('#IdcSurveyFieldEdit' ).data ('id');
		let type 		= $('#IdcSurveyFieldType').val ();
		let content 	= $('#IdcSurveyFieldContent').val ();
		let ai_analysis	= ($('#IdcSurveyFieldIA').prop ('checked') == true)? true : false;
		let position 	= -1;

		if ( id == -1 )
		{
			let nbRow = IdcSurveyFieldDT.GetRowNumber ();

			if ( nbRow > 0 )
				position = parseInt(IdcSurveyFieldDT.GetRowData ( nbRow-1 ).position) + 1;
			else
				position = 0;
		}

		let params = "survey_id=" + survey_id;
		params += "&id=" + id;
		params += "&type=" + type;
		params += "&content=" + content;
		params += "&position=" + position;
		params += "&ai_analysis=" + ai_analysis;
		console.log ( "params : " + params );
		
		PostASyncData ( "SubFW/database/survey/SaveSurveyField.php", params, 'application/x-www-form-urlencoded', OnSurveyFieldSaveOK, OnSurveyFieldSaveError );


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

	function SurveyFieldEditCancel ()
	{
		$('#IdcSurveyFieldEdit').modal ( 'hide' );
	}

	function SurveyFieldDelete ( id )
	{
		console.log ( "SurveyFieldDelete..." );

		// let selRows = IdcSurveyFieldDT.GetSelectedRows ();
		// if ( selRows.length == 1 )
		{
			// let id = IdcSurveyFieldDT.GetRowData ( selRows [0] ).id;

			console.log ( " id : " + id );

			PostASyncData ( "SubFW/database/survey/delete_survey_field.php", "id="+id, 'application/x-www-form-urlencoded', function (){IdcSurveyFieldDT.Refresh ();}, function () {MsgWarning (Translate("Unable to delete field !!!"));} );
		}
	}

	function SurveyDeleteField ( rowIdx )
	{
		let id 			= $('#IdcSurveyFieldDT').DataTable().row( rowIdx ).data().id;

		MsgYesNo ( Translate("Delete selected field ?"), function () { SurveyFieldDelete(id); } );
	}

	function FillSurveyFieldTypesList ( idSelect )
	{
		var xhra= getxhr();
			
		xhra.onloadend = function f()
		{
			if ( xhra.readyState == 4 && xhra.status == 200 )  
			{
				let idcSelect 		= document.getElementById ( idSelect );
				let reponse			= clean(xhra.responseXML.documentElement);
				let status		 	= reponse.getElementsByTagName ( 'survey_field_type' );
				
				for ( let i=0; i<status.length; i++ )
				{
					let id			= status.item (i).getAttribute ( "id" 	);
					let name		= status.item (i).getAttribute ( "name" );

					if ( id != -1 )
					{
						let option_elem = document.createElement('option');
  
						option_elem.value 		= id;
						option_elem.textContent = Translate (name);
  
						idcSelect.appendChild ( option_elem );				
					}
				}
			}
		};

		let url = "SubFW/database/survey/get_survey_field_types.php";
		xhra.open ('GET', url, false );
		xhra.send ();
	}



	function SurveyDesignTabShown ()
	{
		console.log ( "SurveyDesignTabShown..." );
	}

	function SurveyPreviewTabShown ()
	{
		console.log ( "SurveyPreviewTabShown..." );

		SurveyUpdatePreview ();
	}

	

	/*
	function SurveyResultTabShown ()
	{
		console.log ( "SurveyResultTabShown..." );

		$.post (
			"./SubFW/database/survey/draw_result.php",
			{
				survey_id: $('#IdcDivSurvey' ).data ('sur_id')
			},
			function (data, status)
			{
				SurveyDrawResult (data,status);
			}
		);
	}
	*/

	function SurveyResultTabShown ()
	{
		SurevyUpdateResult ();
	}

	function SurevyUpdateResult ()
	{
		$.post (
			"./SubFW/database/survey/draw_result.php",
			{
				survey_id: $('#IdcDivSurvey' ).data ('sur_id')
			},
			function (data, status)
			{
				SurveyDrawResult (data,status);
			}
		);
	}

	
	function SurveyUpdatePreview ()
	{
		console.log ( "SurveyUpdatePreview..." );

		let survey_id = $('#IdcDivSurvey' ).data ('sur_id');

		RenderPage ( "SubFW/html/SurveyCompleting.php?survey_id="+survey_id+"&preview=1", "IdcSurveyPreviewDiv" );
	}

	function SurveyFieldPosition ( row, direction )
	{
		console.log ( "direction : " + direction );

		let nbRow = IdcSurveyFieldDT.GetRowNumber ();
		let rowIdx	= $('#IdcSurveyFieldDT').DataTable().row( row ).index();

		// let id 			= $('#IdcSurveyFieldDT').DataTable().row( row ).data().id;
		// let position	= $('#IdcSurveyFieldDT').DataTable().row( row ).data().position;

		if ( direction == 'up' && rowIdx == 0 )
		{
			console.log ( "Up not possible !!!" );
			return;
		}
		if ( direction == 'down' && (rowIdx >= (nbRow-1)) )
		{
			console.log ( "Down not possible !!!" );
			return;
		}

		let id1;
		let position1;
		let id2;
		let position2;

		if ( direction == 'down' )
		{
			id1 = IdcSurveyFieldDT.GetRowData ( rowIdx ).id;
			id2 = IdcSurveyFieldDT.GetRowData ( rowIdx+1 ).id;
			position1 = IdcSurveyFieldDT.GetRowData ( rowIdx+1 ).position;
			position2 = IdcSurveyFieldDT.GetRowData ( rowIdx ).position;
		}
		else
		{
			if ( direction == 'up' )
			{
				id1 = IdcSurveyFieldDT.GetRowData ( rowIdx ).id;
				id2 = IdcSurveyFieldDT.GetRowData ( rowIdx-1 ).id;
				position1 = IdcSurveyFieldDT.GetRowData ( rowIdx-1 ).position;
				position2 = IdcSurveyFieldDT.GetRowData ( rowIdx ).position;
			}
		}

		let params = "id1=" + id1;
		params += "&id2=" + id2;
		params += "&position1=" + position1;
		params += "&position2=" + position2;
		
		PostASyncData ( "SubFW/database/survey/SetSurveyFieldPosition.php", params, 'application/x-www-form-urlencoded', OnSetSurveyFieldPositionOK, OnSurveyFieldSaveError );
	}

	function OnSetSurveyFieldPositionOK ( response )
	{
		if ( response != '-1')
		{
			IdcSurveyFieldDT.SetRowToSelect ( 'id', response );

			IdcSurveyFieldDT.Refresh ();
		}
		else
			OnSurevyFieldAddError ();
	}




	function SurveyProcessResult ()
	{
		$.post (
			"./SubFW/database/survey/get_survey_result.php",
			{
				survey_id: $('#IdcDivSurvey' ).data ('sur_id')
			},
			function (data, status)
			{
				let nbResult 	= data.NbResult;
				console.log ( " nbResult : " + nbResult );

				let results 	= data.Results;
				console.log ( " results : " + results );
				console.log ( " results.length : " + results.length );
				

				for ( let i=0; i<results.length; i++ )
				{
					console.log ( "results [i] : " + results[i].field_id + " / type :" + results[i].type + " / " + results [i].min + " / " + results[i].max );
				}

				SurveyDrawResultData ( data );
			}
		);
	}


	function SurveyDrawResult ( data, result )
	{
		console.log ( "SurveyDrawResult..." );



				
		// let survey_id 	= $('#IdcDivSurvey' ).data ('sur_id');
		let survey_id 			= data.id;
		let title		= data.title;
		let description  = data.description;

		console.log ( "Survey : " + survey_id + " / " + title + " / " + description );

		let nbFields = data.fields.length;
		console.log ( " nbFields : " + nbFields );

		let idcPreviewDiv = document.getElementById ( 'IdcSurveyResultDetail' );

		let tmp ='';

		for ( let i=0; i<data.fields.length; i++ )
		{
			console.log ( " fields ["+i+"] : " + data.fields[i].id + " / " + data.fields[i].type + " / " + data.fields[i].content );

			let id  	= data.fields[i].id;
			let type 	= data.fields[i].type;
			let content = data.fields[i].content;

			tmp += '<div class="row m-0 p-0 ps-3 pe-3">';
			switch ( parseInt(type) )
			{
				case 1: 	// Main header
					tmp += '<div class="d-flex flex-column p-2">';
					tmp += 		'<div class="row bg-light w-100 m-0 p-0 ps-3 pt-2 pb-2 border rounded-top">';
					tmp += 			'<div class="col ">'+content+'</div>';
					tmp += 			'<div class="col-auto fw-bold"><div id="IdcSurveyResult_'+id+'"></div></div>';
					tmp += 		'</div>';
					tmp += "</div>";
					break;

				case 2: 	// Yes-No
					{
						let name = 'radio_' + survey_id + '_' + id;
						tmp += '<div class="d-flex flex-column p-2">';
						tmp += 		'<div class="row w-100">';
						tmp += 			'<div class="col flex-grow-1">'+content+'</div>';
						tmp += 			'<div class="col-auto"><div id="IdcSurveyResult_'+id+'"></div></div>';
						tmp += 		'</div>';
						tmp += '</div>';
					}
					break;

				case 3: 	// 5 smileys
					let name = 'radio_' + survey_id + '_' + id;
					tmp += '<div class="d-flex flex-column p-2">';
					tmp += 		'<div class="row w-100">';
					tmp += 			'<div class="col flex-grow-1">'+content+'</div>';
					tmp += 			'<div class="col-auto"><div id="IdcSurveyResult_'+id+'"></div></div>';
					tmp += 		'</div>';
					tmp += '</div>';
					break;
				
				case 4: 	// Header Yes-No
					{
						let name = 'radio_' + survey_id + '_' + id;
						tmp += '<div class="d-flex flex-column p-2">';
						tmp += 		'<div class="row w-100">';
						tmp += 			'<div class="col flex-grow-1 fw-bold">'+content+'</div>';
						tmp += 			'<div class="col-auto fw-bold"><div id="IdcSurveyResult_'+id+'"></div></div>';
						tmp += 		'</div>';
						tmp += '</div>';
					}
					break;

				case 5: 	// Header 5 smileys
					tmp += '<div class="d-flex flex-column p-2">';
					tmp += 		'<div class="row w-100">';
					tmp += 			'<div class="col flex-grow-1 fw-bold">'+content+'</div>';
					tmp += 			'<div class="col-auto fw-bold"><div id="IdcSurveyResult_'+id+'"></div></div>';
					tmp += 		'</div>';
					tmp += '</div>';
					break;

				case 6: 	// Header
					tmp += '<div class="d-flex flex-column p-2">';
					tmp += 		'<div class="row w-100">';
					tmp += 			'<div class="col flex-grow-1 fw-bold">'+content+'</div>';
					tmp += 		'</div>';
					tmp += '</div>';

					break;
			}

			tmp += '</div>';
		}



		idcPreviewDiv.innerHTML = tmp;

		// switchLanguage ( CurrentLanguage );


		SurveyProcessResult ();
	}

	function SurveyDrawResultData ( data )
	{
		console.log ( "### SurveyDrawResultData..." );

		let idcResume = document.getElementById ( 'IdcSurveyResultResume' );
		idcResume.innerHTML = '<div class="row m-0 h5 p-0 ps-3 pe-3 pt-3 pb-2 border-bottom fw-bold">Résumé : </div>';
		idcResume.innerHTML += '<div class="row m-0 p-0 ps-3 pe-3 fw-bold">Enquête meneé du '+data.BeginDate+' au '+data.EndDate+'.</div>';
		idcResume.innerHTML += '<div class="row m-0 p-0 ps-3 pe-3 fw-bold">Nombre de réponses : '+data.NbResult+'</div>';
		idcResume.innerHTML += '<div class="row m-0 p-0 ps-3 pe-3 pb-3 border-bottom fw-bold"><span class="m-0 p-0" id="IdcSurveyResultAverage"></span></div>';
		idcResume.innerHTML += '<div class="row m-0 h5 p-0 ps-3 pe-3 pt-3 pb-2 border-bottom fw-bold">Détail de réponses : </div>';

		let results 	= data.Results;
		console.log ( " results.length : " + results.length );
		
		let sum_total = 0.0;
		let cnt_total = 0;

		let lastTitle1 	= -1;
		let s1 			= 0.0;
		let cnt1 		= 0;

		let lastTitle5 	= -1;
		let s5 			= 0.0;
		let cnt5 		= 0;

		let lastTitle6 	= -1;
		let s6 			= 0.0;
		let cnt6 		= 0;

		
		for ( let i=0; i<results.length; i++ )
		{
			let type 	= results [i].type;
			let idc 	= 'IdcSurveyResult_'+results[i].field_id;

			console.log ( "=== Type ["+i+"] : " + type );
			console.log ( "  lastTitle1 : " + lastTitle1 );

			if ( type == 1 )	// Main title
			{
				if ( lastTitle1 != - 1 )
				{
					let idc = 'IdcSurveyResult_'+lastTitle1;

					let avg = s1 / cnt1;

					console.log ( "  avg : " + avg );

					if ( document.getElementById ( idc ) != undefined )
					{
						let val = (100.0*parseFloat(avg)).toFixed ( 1 );
						let tmp = 	'<div class="progress" style="min-width: 140px;">';
  						tmp += 			'<div class="progress-bar" role="progressbar" style="width: '+val+'%" aria-valuenow="'+val+'" aria-valuemin="0" aria-valuemax="100">'+val+' %</div>';
						tmp +=		'</div>';

						document.getElementById ( idc ).innerHTML = tmp;
					}
				}

				lastTitle1 = results[i].field_id;
				s1 		= 0.0;
				cnt1 	= 0;
			}
			else
			{
				if ( type != 3 )
				{
					if ( lastTitle5 != -1 )
					{
						let idc = 'IdcSurveyResult_'+lastTitle5;

						let avg = s5 / cnt5;

						if ( document.getElementById ( idc ) != undefined )
						{
							let val = (100.0*parseFloat(avg)).toFixed ( 1 );
							let tmp = 	'<div class="progress" style="min-width: 140px;">';
  							tmp += 			'<div class="progress-bar" role="progressbar" style="width: '+val+'%" aria-valuenow="'+val+'" aria-valuemin="0" aria-valuemax="100">'+val+' %</div>';
							tmp +=		'</div>';

							document.getElementById ( idc ).innerHTML = tmp;
						}

						lastTitle5 = -1;
					}
				}

				if ( type == 1 || type == 3 || type == 5 )
				{
					if ( lastTitle6 != -1 )
					{
						let idc = 'IdcSurveyResult_'+lastTitle6;

						let avg = s6 / cnt6;

						if ( document.getElementById ( idc ) != undefined )
						{
							let val = (100.0*parseFloat(avg)).toFixed ( 1 );
							let tmp = 	'<div class="progress" style="min-width: 140px;">';
  							tmp += 			'<div class="progress-bar" role="progressbar" style="width: '+val+'%" aria-valuenow="'+val+'" aria-valuemin="0" aria-valuemax="100">'+val+' %</div>';
							tmp +=		'</div>';

							document.getElementById ( idc ).innerHTML = tmp;
						}

						lastTitle6 = -1;
					}
				}

				if ( type == 5 )	// Header 5 smileys
				{
					lastTitle5 = results[i].field_id;
					s5 		= 0.0;
					cnt5 	= 0;
				}

				if ( type == 6 )	// Header
				{
					lastTitle6 = results[i].field_id;
					s6 		= 0.0;
					cnt6 	= 0;
				}

				if ( type == 2 || type == 4 )	// Yes-no
				{
					if ( document.getElementById ( idc ) != undefined )
					{
						let val = (100.0*parseFloat(results [i].avg)/5).toFixed ( 1 );
						let tmp = 	'<div class="progress ms-1" style="min-width: 140px;">';
  						tmp += 			'<div class="progress-bar" role="progressbar" style="width: '+val+'%" aria-valuenow="'+val+'" aria-valuemin="0" aria-valuemax="100">'+val+' %</div>';
						tmp +=		'</div>';

						document.getElementById ( idc ).innerHTML = tmp;
					}

					s1 += parseFloat(results [i].avg);
					cnt1++;

					s6 += parseFloat(results [i].avg);
					cnt6++;

					sum_total += parseFloat(results [i].avg);
					cnt_total++;
				}

				if ( type == 3 ) // 5 smileys
				{
					if ( document.getElementById ( idc ) != undefined )
					{
						let val = (100.0*parseFloat(results [i].avg)/5).toFixed ( 1 );
						let tmp = 	'<div class="progress" style="min-width: 140px;">';
  						tmp += 			'<div class="progress-bar" role="progressbar" style="width: '+val+'%" aria-valuenow="'+val+'" aria-valuemin="0" aria-valuemax="100">'+val+' %</div>';
						tmp +=		'</div>';

						document.getElementById ( idc ).innerHTML = tmp;
					}

					s1 += (parseFloat(results [i].avg)/5);
					cnt1++;

					s5 += (parseFloat(results [i].avg)/5);
					cnt5++;

					sum_total += (parseFloat(results [i].avg)/5);
					cnt_total++;
				}
			}

			if ( i == results.length-1 )
			{
				if ( lastTitle1 != - 1 )
				{
					let idc = 'IdcSurveyResult_'+lastTitle1;

					let avg = s1 / cnt1;

					// if ( document.getElementById ( idc ) != undefined )
					// 	document.getElementById ( idc ).innerHTML = (10.0*parseFloat(avg)).toFixed ( 2 ) + " / 10";
					if ( document.getElementById ( idc ) != undefined )
					{
						let val = (100.0*parseFloat(avg)).toFixed ( 1 );
						let tmp = 	'<div class="progress" style="min-width: 140px;">';
  						tmp += 			'<div class="progress-bar" role="progressbar" style="width: '+val+'%" aria-valuenow="'+val+'" aria-valuemin="0" aria-valuemax="100">'+val+' %</div>';
						tmp +=		'</div>';

						document.getElementById ( idc ).innerHTML = tmp;
					}
				}

				if ( lastTitle5 != -1 )
				{
					let idc = 'IdcSurveyResult_'+lastTitle5;

					let avg = s5 / cnt5;

					// if ( document.getElementById ( idc ) != undefined )
					// 	document.getElementById ( idc ).innerHTML = (10.0*parseFloat(avg)).toFixed ( 2 ) + " / 10";
					if ( document.getElementById ( idc ) != undefined )
					{
						let val = (100.0*parseFloat(avg)).toFixed ( 1 );
						let tmp = 	'<div class="progress" style="min-width: 140px;">';
  						tmp += 			'<div class="progress-bar" role="progressbar" style="width: '+val+'%" aria-valuenow="'+val+'" aria-valuemin="0" aria-valuemax="100">'+val+' %</div>';
						tmp +=		'</div>';

						document.getElementById ( idc ).innerHTML = tmp;
					}

					lastTitle5 = -1;
				}

				if ( lastTitle6 != -1 )
				{
					let idc = 'IdcSurveyResult_'+lastTitle6;

					let avg = s6 / cnt6;

					if ( document.getElementById ( idc ) != undefined )
					{
						let val = (100.0*parseFloat(results [i].avg)/5).toFixed ( 1 );
						let tmp = 	'<div class="progress" style="min-width: 140px;">';
  						tmp += 			'<div class="progress-bar" role="progressbar" style="width: '+val+'%" aria-valuenow="'+val+'" aria-valuemin="0" aria-valuemax="100">'+val+' %</div>';
						tmp +=		'</div>';

						document.getElementById ( idc ).innerHTML = tmp;
					}

					lastTitle6 = -1;
				}
			}
		}
		
		let average = (10.0*parseFloat(sum_total)/cnt_total).toFixed (2);
		document.getElementById ('IdcSurveyResultAverage').innerHTML = "Moyenne : " + average + " / 10";

	}



	function SurveyConclusionTaskSelect ()
	{
		let survey_id = $('#IdcDivSurvey' ).data ('sur_id' );

		SetTaskInfo ( 1, 'survey', survey_id );
		
		var element = $('#IdcDivTask').detach();

		DocumentViewerShow ( Translate ("Tasks"), element, null, OnSurveyConclusionCloseModalTask );
		IdcTaskDT.Refresh ();

		$('#IdcDivTask').show ();
	}

	function OnSurveyConclusionCloseModalTask ()
	{
		SetTaskInfo ( 0, '' );

		var element = $('#IdcDivTask').detach();
		$('#IdcMainContainer').append(element);

		let survey_id = $('#IdcDivSurvey' ).data ('sur_id' );
		IdcSurveyDT.SetRowToSelect ( 'id', survey_id );
		IdcSurveyDT.Refresh ();
	}



	function SCEditorContainerChanged ()
	{
			console.log ("SCEditorContainerChanged...");
	}



	function QUILLEditorResize ( ident )
	{
		let container = document.getElementById ( ident ).parentElement;

		let tb = container.querySelector ('.ql-toolbar');

		if ( tb != undefined )
		{
			let newHeight = parseInt(container.clientHeight) - parseInt ( tb.offsetHeight );

			$('#' + ident ).attr ( "style", "height: "+newHeight+"px !important;" );
		}
	}
	

	function SurveyConclusionSave ()
	{
		let id 	= $('#IdcDivSurvey' ).data ('sur_id');

		let title			= $('#IdcSurveyTitle' ).val ();
		let begindate 		= $('#IdcSurveyBeginDate' ).val ();
		let enddate 		= $('#IdcSurveyEndDate' ).val ();
		let type 			= $('#IdcSurveyType' ).val ();
		let status 			= $('#IdcSurveyStatus' ).val ();
		let description		= IdcSurveyDescriptionEditor.getSemanticHTML ();
		let comment			= $('#IdcSurveyComment' ).val ();
		let conclusion 		= IdcSurveyConclusionEditor.getSemanticHTML ();

		let params = "id=" + id;
		params += "&title=" + title;
		params += "&begindate=" + begindate;
		params += "&enddate=" + enddate;
		params += "&type=" + type;
		params += "&status=" + status;
		params += "&description=" + encodeURIComponent(description);
		params += "&comment=" + comment;
		params += "&conclusion=" + encodeURIComponent(conclusion);
			
		PostASyncData ( "SubFW/database/survey/SaveSurvey.php", params, 'application/x-www-form-urlencoded', OnSurveyAddOK, OnSurveyAddError );
	}



	//#########################################################################################################################
	//### SurveyResponses

	function SurveyResponseDTGetData ( d )
	{
		d.survey_id = $('#IdcDivSurvey' ).data ('sur_id');
		
		return $.extend( {}, d );
	}
	
	function SurveyResponseDTSelectChanged ( rowsIdx )
	{
		let id 			= -1;
		let rdate		= '';

		if ( rowsIdx.length == 1 )		// Only one row selected
		{
			let rowIdx = rowsIdx [0];

			id		= $('#IdcSurveyResponseDT').DataTable().row( rowIdx ).data().id;
			rdate	= $('#IdcSurveyResponseDT').DataTable().row( rowIdx ).data().rdate;
		}

		SurveyUpdatePreviewResponse ( id );
	}

	function SurveyUpdatePreviewResponse ( id )
	{
		console.log ( "SurveyUpdatePreview..." );

		let survey_id = $('#IdcDivSurvey' ).data ('sur_id');

		RenderPage ( "SubFW/html/SurveyCompleting.php?survey_id="+survey_id+"&preview=1"+"&resp_id="+id, "IdcSurveyPreviewResponseDiv" );
	}
