<?php
require_once '../autoload.php';
?>

<!DOCTYPE html>
<html lang="en" style="height: 100%; font-size: 12px;">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>eoQUAL - Audit</title>

    <?php
			$libmanager = new eoLibrariesManagerQual ();
			$libmanager->init_page();
			$libmanager->render_library ();
		?>

		
		<style type="text/css">

			.rotate180 {
    		-webkit-transform: rotate(180deg);
    		-moz-transform: rotate(180deg);
    		-o-transform: rotate(180deg);
    		-ms-transform: rotate(180deg);
    		transform: rotate(180deg);
			}

			.clickablepoint{
				cursor:pointer;
			}

			.clickablepoint:hover{
				font-weight:bold;
				text-decoration:underline;
			}

			.missingdoc{
				cursor:pointer;
				text-decoration:underline;
				color:red;
				<?php /*font-size: 12px;*/ ?>
			}

			.pdflink{
				cursor:pointer;
				text-decoration:underline;
				color:blue;
				font-size: 14px;
			}
		
			.doc_text {
    		background: #ddd;
    		color: black;
    		padding: .2em ,.5em;
    		border: solid .1em ;
    		border-radius: 1em;
    		margin-top: 1.2em;
			}

			.doc_text :last-child {margin-bottom: 0}
			.doc_text :first-child {margin-top: 0; padding: 2em;}

			.pointValidated{
				background-color: rgb(163,209,173);
				cursor: pointer;
			}

			.pointOK{
				background-color: rgb(163,209,173);
				cursor: pointer;
			}

			.pointKO{
				background-color: rgb(248,215,218);
				cursor: pointer;
			}

			.pointKOK{
				background-color: rgb(255,243,205);
				cursor: pointer;
			}

		</style>

  </head>
  


  <script type="text/javascript">
  		
  		G_USE_ID = localStorage.getItem("UseID");

  		sessionStorage.setItem ( 'ProcedurePageInitialized', 							false );
  		sessionStorage.setItem ( 'StaffPageInitialized', 									false );
  		sessionStorage.setItem ( 'DevicePageInitialized',									false );
  		sessionStorage.setItem ( 'InstitutionalDocumentPageInitialized', 	false );

  		G_ServerAddress = '<?php echo ($config_servernameorip); ?>';
  		G_ServerFolder  = '<?php echo ($GLOBALS["EOQUAL_ROOT"]); ?>';

  		
  		class CPoint{
				constructor( id, chapterTitle,pointID,pointTitle ){
					this.ChapterTitle = chapterTitle;
					this.ID= id;
					this.pointID=pointID;
					this.pointTitle=pointTitle;
					this.previousID=-1;
					this.nextID=-1;
				}
			};

			class subrecord{
				constructor(){
					this.audit_id=-1;
					this.scope_id=-1;
					this.scope2_id=-1;
					this.point_id=-1;
					this.tag_id=-1;
					/*this.force_doctext="";
					this.force_docid=-1;*/
					this.remark="";		
					this.forcedstatus=false;
					this.doc_id=-1;
				}
			};

			var first_point 	= -1;
  		var point_list 		= new Array();
			var current_point = -1;
			var audit_id			= -1;
			var audit_title		= "";
	
			<?php 
					if ( isset ( $_REQUEST['audit_id'] ) ) 
					{
						$audit_id = $_REQUEST['audit_id'];
						echo "audit_id=".$_REQUEST['audit_id'].";";
							
						$conn = get_dbconnection();
				
						$sql = "select title from audit where id=".$audit_id;
			
						$query = pg_query($conn,$sql);
						if( $query )
						{
								if( $row = pg_fetch_row($query) )
								{
										$audit_title = $row[0];

										echo "audit_title = '" . addslashes($audit_title) . "';\n";
								}
						}
					}
			?>
			

			function OnGeneratePDF ()
			{
					$('#IdcAuditDlg').modal('show');
			}

			function generatePDF ()
			{
					// $('#IdcAuditDlg').modal('hide');

					console.log ( " Device : " + $('#IdcAppendiceDevice').is (':checked') );

					WaitingStart ( Translate("PDF creation in progress...") );
					$.post (
							"./generate_audit_pdf.php",
							{
									audit_id: 									audit_id,
									annex_procedure: 						$('#IdcAppendiceProcedure').is (':checked'),
									annex_staff: 								$('#IdcAppendiceStaff').is (':checked'),
									annex_device: 							$('#IdcAppendiceDevice').is (':checked'),
									annex_legaldocument: 				$('#IdcAppendiceLegalDocument').is (':checked'),
									annex_institutiondocument: 	$('#IdcAppendiceInstitutionDocument').is (':checked')
							},
							function (data)
							{		
									WaitingStop ();
											
									if ( data.status == "OK" )
									{
											let url = G_ServerAddress + G_ServerFolder + "/PDFViewer/eoQUALPDFViewer.php?filename=" + data.filename;
											DocumentViewerShow ( audit_title, null, url );
									}
									else
											MsgWarning ( "Erreur durant la création du document !!!" );
							}
					);
			}

			function savePage ()
			{
				if( audit_id!=-1 )
				{
					var modifarray=[];
					var remarks= document.getElementsByClassName( "remark" );
			
					for(var i=0; i<remarks.length;i++)
					{
						var value= remarks[i].value.trim();
						if(value.length==0) continue;
						var idrem= remarks[i].id;
						let obj = new subrecord();
						obj.audit_id=audit_id;
						var id_s = idrem.split('_');
						obj.remark=value;
						for(var j=0;j<id_s.length;j++)
						{
							switch(j)
							{
								case 1: obj.point_id=id_s[j];break;
								case 2: obj.tag_id=id_s[j];break
								case 3: obj.scope_id=id_s[j];break;
								case 4: obj.doc_id=id_s[j];break;
								case 5: obj.scope2_id=id_s[j];break;
								//case 6: obj.force_docid=id_s[j];break;
								//case 7: obj.force_doctext=id_s[j];break;
								default: break;
							}
						}
						modifarray.push(obj);
					}
					var procremarks =document.getElementsByClassName("procremark");
					for(var i=0;i< procremarks.length;i++)
					{
						var value=procremarks[i].value.trim();
						// if(value.length==0) continue;
						var idrem= procremarks[i].id;
						let obj = new subrecord();
						obj.audit_id=audit_id;
						var id_s = idrem.split('_');
						obj.point_id=id_s[1];
						obj.scope_id=-1;
						obj.doc_id=-1;
						obj.scope2_id=-1;
						obj.remark=value;
						modifarray.push(obj);
					}
			
			
					var remarkmiss=document.getElementsByClassName("remarkred");
					for(var i=0;i<remarkmiss.length;i++)
					{
						var value = remarkmiss[i].value.trim();
						if(value.length==0) 
							continue;
						var idrem=remarkmiss[i].id;
						let obj = new subrecord();
						obj.audit_id=audit_id;
						var id_s= idrem.split('_');
						obj.remark=value;
						var cbox_id ="forceOK";
						for(var j=0;j<id_s.length;j++)
						{
							if(j>0)
								cbox_id+="_"+id_s[j];
							switch(j)
							{
								case 1: obj.point_id=id_s[j];break;
								case 2: obj.tag_id=id_s[j];break;
								case 3: obj.scope_id=id_s[j];break;
								case 4: obj.scope2_id=id_s[j];break;
								default: break;
							}
						}
						var cbs=document.getElementById(cbox_id);
						var force=false;
						if(cbs)
							force=cbs.checked;
						obj.forcedstatus=force;
						modifarray.push(obj);
					}
			
					var cbs= document.getElementsByClassName("force_statuscb");
					for(var j=0; j< cbs.length;j++)
					{
						var value=cbs[j].value;
						var idcv=cbs[j].id;
					}
			
					var xhra= getxhr();
					var param_c="audit_id="+audit_id+"&point_id="+current_point;
					xhra.onreadystatechange = function f()
					{
						if(xhra.readyState == 4 && xhra.status == 200) 
						{
							var  response = xhra.responseText;
							reponse = clean(xhra.responseXML.documentElement);
						}
					};
					xhra.open("POST","../database/bquaadril/cleanpoint.php",true);
					xhra.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
					xhra.send(param_c);
				
					for(var i=0; i< modifarray.length;i++)
					{
						var obj=modifarray[i];
						var param = "audit_id="+obj.audit_id+"&point_id="+obj.point_id+"&tag_id="+obj.tag_id+"&scope_id="+obj.scope_id+"&scope2_id="+obj.scope2_id+"&remark="+encodeURIComponent(obj.remark)+"&forcestatus="+obj.forcedstatus+"&doc_id="+obj.doc_id;
				
						var xhr= getxhr();
						xhr.onreadystatechange = function f()
						{
							if(xhr.readyState == 4 && xhr.status == 200) 
							{
								var  response = xhr.responseText;
								reponse = clean(xhr.responseXML.documentElement);
							}
						};
			
						xhr.open("POST","../database/bquaadril/pointsaver.php",false);
						xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
						xhr.send(param);
					}
			
					getSummaryStatus();
					selectpoint( current_point );
				}
			}

			function selectpoint( idpoint)
			{
					if ( idpoint==-1 ) return;
					if ( current_point != -1)
					{	
							var tr_sumelement = document.getElementById("summary_"+current_point);					
							tr_sumelement.style.fontWeight = "normal";		
					}
		
					current_point=idpoint;		
		
					if ( current_point != -1 )
					{	
						var tr_sumelement = document.getElementById("summary_"+current_point);					
						tr_sumelement.style.fontWeight = "bold";		
					}
		
					document.getElementById('summary_'+current_point).scrollIntoView();
					var param="id="+idpoint;
					var xhr= getxhr();
					xhr.onreadystatechange = function f()
					{
							if(xhr.readyState == 4 && xhr.status == 200) 
							{
								var  response = xhr.responseText;
								reponse = clean(xhr.responseXML.documentElement);
								var description=reponse.getElementsByTagName('description').item(0).firstChild.nodeValue;
								var num=reponse.getElementsByTagName('num').item(0).firstChild.nodeValue;
								var maindiv=document.getElementById('main_div');
								var xhr2=getxhr();
				
								var tmp = "";
								
								tmp += "<div class=\"row flex-grow-1 m-0 p-0\" style=\"min-height: 0px;\">";

								tmp += "<div class=\"mh-100\" style=\"flex: 1; background-color: white; width: 100%; overflow-y:auto;\">";
				
								tmp += 		"<table id=\"IdcElementsTable\" style=\"background-color: white; width: 100%;\">";
								tmp += 			"<tr style=\"background-color: white;\">";
								tmp += 				"<td><br></td>";
								tmp += 				"<td colspan=\"2\" style=\"background-color: white; padding-top: 20px; padding-bottom: 8px; border-bottom: solid thin gray; color: #646464;\">";
								tmp += 					"<b>Associated procedures</b>";
								tmp +=				"</td>";
								tmp += 			"</tr>";
								tmp += 			"<tr style=\"color:default\">";
								tmp += 				"<td><br></td>";
								tmp += 				"<td style=\"height: 106px;\" colspan=\"2\" ><span><br></span>";
								tmp +=						"<div id=\"IdcDocTable\" style=\"display: table; width: 100%;\" border=\"0\">";				// Table
								tmp +=							"<div style=\"display: table-row-group;\">";											// Table body
				
								var color;
								xhr2.onreadystatechange= function f()
								{
										if(xhr2.readyState == 4 && xhr2.status == 200) 
										{
											var  response2 = xhr2.responseText;
											reponse2= clean(xhr2.responseXML.documentElement);
											var _check= reponse2.getElementsByTagName('check').item(0);
											var _c_id= _check.getAttribute("id");
											var _c_val= _check.getAttribute("value");
											var _c_validated= _check.getAttribute("validated");

											color = "point"+_c_val;
											if(_c_validated=="true")	
												color="pointValidated";
					
											var procedures = reponse2.getElementsByTagName('procedure');
											var procname="";
											var nbrdocs=0;
											var expecteds = reponse2.getElementsByTagName('expected');
											var tag_id=-1;
											if ( expecteds.length>0 )
											{
													procname = expecteds.item(0).getAttribute("procedure");
													nbrdocs = expecteds.item(0).getAttribute("nbrdocs");
													tag_id = expecteds.item(0).getAttribute("tag_id");
											}
						
											var entities = reponse2.getElementsByTagName('entity');
					
											if( procedures.length > 0 )
											{
													var realfilename= procedures.item(0).getAttribute('fname');
													var remark= procedures.item(0).getAttribute("remark");
													var label= procedures.item(0).getAttribute("label");
													let name = procedures.item(0).getAttribute("name");
													if( label.length == 0 ) 
														{
																// label = realfilename;
															label = name;
														}
							
													tmp +=					"<div style=\"display: table-row;\">";	// Table row
													tmp +=						"<div style=\"display: table-cell; vertical-align: middle;  width: 20%; font-size: 12px;\">Procedure <span style=\"font-size: 12px;\" class=\"pdflink\" onclick=\"displayPDFViewer('"+realfilename+"',"+procedures.item(0).getAttribute("docid")+");\">"+label+"</span></div>";	// Table cell
													tmp +=						"<div style=\"display: table-cell;\"><textarea class=\"procremark\" contenteditable=\"true\" style = \"width:99%; border: solid 1px lightgray; height:60px;\" id=\"procremark_"+_c_id+"\">"+remark+"</textarea></div>";	// Table cell
													tmp +=					"</div>";	// Table row
													tmp +=				"</div>";		// Table body
													tmp +=			"</div>";		// Table
													tmp +=		"</td>";
													tmp +=	"</tr>";
							
											}
											else 
											{
													if(procname!="")
													{
															tmp +=			"<div style=\"display: table-cell; width: 20%; vertical-align: top;\">";	// First column
								
															tmp +=				"<div style=\"display: table; width: 100%; height: 100%;\">";
															tmp +=					"<div style=\"display: table-row;\">";
															tmp +=						"<div style=\"display: table-cell;\"><span class=\"missingdoc\" onclick=\"displayModalWindow("+tag_id+",'VIEW_PROCEDURE',-1,'procedure');\">Missing procedure</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i> "+procname+"</i></div>";
															tmp +=					"</div>";
															tmp +=				"</div>";
															tmp +=			"</div>";
													}
											}
											console.log ( "entities.length : " + entities.length );
											if( entities.length > 0 )
											{
													tmp += "<tr style=\"background-color: white\">";
													tmp += 		"<td><br></td>";
													tmp += 		"<td colspan=\"2\" style=\"background-color: white; border-bottom: solid thin gray; padding-top: 20px; padding-bottom: 8px; color: #646464;\">";
													tmp += 			"<b>Records</b>";
													tmp +=		"</td>";
													tmp += "</tr>";
											}
						
											for(var j = 0; j<entities.length && entities.length;j++)
											{
													var ent_name = entities.item(j).getAttribute("name");
													var ent_type = entities.item(j).getAttribute("type");
													var ent_tag = entities.item(j).getAttribute("tagid");
													var ent_id = entities.item(j).getAttribute("ent_id");
													var ent_docs=entities.item(j).getElementsByTagName("document");
													var ent_view= entities.item(j).getAttribute("type_view");
													var tmp_nbrdoc="";
													var statuscolor="green";
													var ent_tagname = entities.item(j).getAttribute("tagname");

													console.log ( " ent_name : " + ent_name );
							
													if( ent_docs.length < nbrdocs )
													{
															var ent_misdocs=entities.item(j).getElementsByTagName("documentmis");
															var __remval="";
															var __forcestatus="";
															statuscolor="red";
															if(ent_misdocs.length>0)
															{
																	__remval=ent_misdocs.item(0).getAttribute("remark");
																	if(ent_misdocs.item(0).getAttribute("forcestatus")=="t") __forcestatus="checked";
																	if(__forcestatus=="checked")
																			statuscolor="green";
															}
								
															tmp_nbrdoc =	"<div style=\"display: table; width: 100%;\">";
															tmp_nbrdoc +=						"<div style='display: table-row;'><i><h5>"+ent_tagname+"</h5></i></div>";
															tmp_nbrdoc +=		"<div style=\"display: table-row;\">";
								
															tmp_nbrdoc +=			"<div style=\"display: table-cell; width: 20%; vertical-align: top;\">";	// First column
															tmp_nbrdoc +=				"<div style=\"display: table; width: 100%; height: 100%;\">";
															tmp_nbrdoc +=					"<div style=\"display: table-row;\">";
															tmp_nbrdoc +=						"<div style=\"display: table-cell;\"><span class=\"missingdoc\" onclick=\"displayModalWindow("+ent_tag+",'"+ent_view+"',"+ent_id+",'"+ent_type+"');\">"+(nbrdocs-ent_docs.length)+" document(s) missing</span></div>";
															tmp_nbrdoc +=					"</div>";
															tmp_nbrdoc +=					"<div style=\"display: table-row;\">";
															tmp_nbrdoc +=						"<div style=\"display: table-cel;\" colspan=\"3\">&nbsp;&nbsp;&nbsp;<input class=\"force_statuscb\" type=\"checkbox\" "+__forcestatus+" id=\"forceOK_"+_c_id+"_"+ent_tag+"_"+ent_id+"\"><span style=\"font-size:12px;\" >Forcer le status &agrave; OK</span></input></div>";
															tmp_nbrdoc +=					"</div>";
															tmp_nbrdoc +=				"</div>";
								
															tmp_nbrdoc +=			"</div>";
								
															tmp_nbrdoc +=			"<div style=\"display: table-cell;\">";										// Second column
															tmp_nbrdoc +=				"<br><textarea contenteditable=\"true\" class=\"remarkred\" style = \"width: 98%; border: solid 1px lightgray; min-height: 80px;\" id=\"remark_"+_c_id+"_"+ent_tag+"_"+ent_id+"\">"+__remval+"</textarea>";
															tmp_nbrdoc +=			"</div>";
								
															tmp_nbrdoc +=		"</div>";
								
															tmp_nbrdoc +=	"</div>";
													}

													var cplttxt="";
								
													for( var dd =0 ; dd< ent_docs.length; dd++ )
													{
															var ent_doc_ = ent_docs.item(dd);
															var add_div="";
									
															if( ent_doc_.firstChild )
															{
																	add_div = ent_doc_.firstChild.nodeValue;
															}
									
															if(ent_doc_.getAttribute("force_result")=="KO") 
																	statuscolor="red";
									
															var cpltid="";
										
															if(ent_doc_.parentNode.nodeName=="subentity")
															{
																	cpltid="_"+ent_doc_.parentNode.getAttribute("subent_id");
																	if( statuscolor == "red" ) 
																			cplttxt="<tr><td colspan=\"3\">&nbsp;&nbsp;&nbsp;<input style=\"font-size: 12px;\" class=\"force_statuscb\" type=\"checkbox\" id=\"forceOK_"+_c_id+"_"+ent_tag+"_"+ent_id+"\">Forcer le status &agrave; OK</input></td></tr>";
									 						}
									
															var label = ent_doc_.getAttribute("label");
															if( label.length == 0 ) label = ent_doc_.getAttribute("realfname");
									
															tmp_nbrdoc += "<div style=\"display: table; width: 100%;\">";
															tmp_nbrdoc += 	"<div style=\"display: table-row; \">";
															tmp_nbrdoc += 		"<div style=\"display: table-cell; width: 20%; vertical-align: top;\">";
									 					 	tmp_nbrdoc +=			"<span class=\"pdflink\" onclick=\"displayPDFViewer('"+ent_doc_.getAttribute("realfname")+"',"+ent_doc_.getAttribute("docid")+");\">"+label+"</span>";
															tmp_nbrdoc += 		"</div>";
															if( add_div.length > 0 )
															{
																	tmp_nbrdoc += 		"<div style=\"display: table-cell; vertical-align: middle; align-items: center; padding: 2px;\">";

																	tmp_nbrdoc += 			"<div style=\"background-color: lightgray; font-size: 12px; border: solid 1px; border-radius: 5px; min-height: 60px; padding: 10px;\" >";
																	tmp_nbrdoc +=				add_div;
																	tmp_nbrdoc += 			"</div>";
										
																	tmp_nbrdoc += 		"</div>";
										
																	tmp_nbrdoc += 		"<div style=\"display: table-cell; min-width: 10px;\">";		// Separator
																	tmp_nbrdoc += 		"</div>";
															}
															tmp_nbrdoc += 		"<div style=\"display: table-cell; padding: 10px;\">";
															tmp_nbrdoc +=			"<div>";
															tmp_nbrdoc +=			"<textarea contenteditable=\"true\" style = \"width: 98%; border: solid 1px lightgray; height: 100%; min-height: 60px;\" class=\"remark\" tag_id=\""+ent_tag+"\" id=\"remark_"+_c_id+"_"+ent_tag+"_"+ent_id+"_"+ent_doc_.getAttribute("docid")+cpltid +"\">"+ent_doc_.getAttribute("remark")+"</textarea>";
															tmp_nbrdoc +=			"</div>";
															tmp_nbrdoc += 		"</div>";
															tmp_nbrdoc += 	"</div>";
															tmp_nbrdoc += "</div>";
														}	
								
														tmp_nbrdoc += cplttxt;
							
														if( ent_type != "institution" ) 
														{
																tmp += "<tr>";
																tmp +=		"<td></td>";
																tmp +=		"<td colspan=\"2\">";
								
																tmp +=			"<div style=\"display: table; width: 100%;\">";
																if( j > 0 )
																{
																		tmp +=				"<div style=\"display: table-row;\">";						// First row
																		tmp +=					"<div style=\"display: table-cell;\"><hr></div>";		// Separator
																		tmp +=				"</div>";
																}
								
																tmp +=				"<div style=\"display: table-row;\">";						// Second row
																tmp +=					"<div style=\"display: table-cell;\">";
																tmp +=						"<div style=\"display: table; width: 100%;\">";
																tmp +=							"<div style=\"display: table-row;\">";
																tmp +=								"<div style=\"display: table-cell; background-color:"+statuscolor+";width:10px; \" id=\"col_"+_c_id+"_"+ent_tag+"_"+ent_id+"\">&nbsp;&nbsp;</div>";
																tmp +=								"<div style=\"display: table-cell; width: 10px;\"></div>";
																tmp +=								"<div style=\"display: table-cell; color: #484848; font-size: 14px;\"><b>"+ent_name+"</b></div>";
																tmp +=							"</div>";
																tmp +=						"</div>";
																tmp +=					"</div>";		
																tmp +=				"</div>";
								
																tmp +=				"<div style=\"display: table-row;\">";						// Third row
																tmp +=					"<div style=\"display: table-cell;\">";
								
																tmp +=						"<div style=\"display: table; width: 100%;\">";
																tmp +=							"<div style=\"display: table-row;\">";						
																tmp +=								"<div style=\"display: table-cell;\">";						
																tmp += 									tmp_nbrdoc;
																tmp +=								"</div>";
																tmp +=							"</div>";
																tmp +=						"</div>";
								
																tmp +=					"</div>";
																tmp +=				"</div>";

																tmp +=			"</div>";
								
																tmp +=		"</td>";
																tmp +=	"</tr>";
														}
														else
														{
																tmp += "<tr>";
																tmp +=		"<td></td>";
																tmp +=		"<td colspan=\"2\">";
								
																tmp +=			"<div style=\"display: table; width: 100%;\">";
																if( j > 0 )
																{
																		tmp +=				"<div style=\"display: table-row;\">";						// First row
																		tmp +=					"<div style=\"display: table-cell;\"><hr></div>";		// Separator
																		tmp +=				"</div>";
																}
								
																tmp +=				"<div style=\"display: table-row;\">";						// Third row
																tmp +=					"<div style=\"display: table-cell;\">";
								
																tmp +=						"<div style=\"display: table; width: 100%;\">";
																tmp +=							"<div style=\"display: table-row;\">";						
																tmp +=								"<div style=\"display: table-cell;\">";						
																tmp += 									tmp_nbrdoc;
																tmp +=								"</div>";
																tmp +=							"</div>";
																tmp +=						"</div>";
								
																tmp +=					"</div>";
																tmp +=				"</div>";

																tmp +=			"</div>";
								
																tmp +=		"</td>";
																tmp +=	"</tr>";
														}
												}
						
												var documents = reponse2.getElementsByTagName('document');
												var actual_nbrdocs= documents.length;
												if(documents.length>0)
												{
							
												}
										}
								};
								xhr2.open("POST","../database/bquaadril/checkrules.php",false);
								xhr2.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
								if(audit_id!=-1)
									param+="&audit_id="+audit_id;
								xhr2.send(encodeURI(param));

								tmp += "</table>";				
				
								tmp += "</div>";

								tmp += "</div>";
				
								tmp1 = "<div class=\"row m-0 p-0\">";
								tmp1 += "<table id=\"IdcChapterTable\" style=\"width: 100%;\" cellspacing=\"0\" cellpadding=\"5\" border=\"0\">";
								tmp1 += 	"<tbody>";
								tmp1 +=			"<tr style=\"background-color: #000000; color: #ffffff;\" class=\""+color+"\" id=\"status_header\">";
								tmp1 +=				"<td colspan=\"3\">"+point_list[current_point].ChapterTitle+"</td>";
								tmp1 +=			"</tr>";
								tmp1 +=			"<tr>";
								tmp1 += 			"<td id=\"version_td\" style=\"background-color: #ffcc99;\"><b>"+num+"</b><br></td>";
								tmp1 += 			"<td class=\""+color+"\" id=\"description_td\" colspan=\"2\" style=\"color: #000000; padding-top: 15px; padding-bottom: 10px;\">"+description+"</td>";
								tmp1 += 		"</tr>";
								tmp1 +=		"</tbody>";
								tmp1 += "</table>";

								tmp1 += "</div>";

								tmp1 += tmp;
				
								maindiv.innerHTML = tmp1;
				
								let bgc = $("#summary_"+idpoint).css("background-color");
								$("#nav_pointtitle").css ("background-color", bgc);
								nav_pointtitle.innerHTML = "<b>"+point_list[current_point].pointID+"&nbsp;&nbsp;&nbsp;"+point_list[current_point].pointTitle+"</b>";
				
								if(document.getElementById("summary_"+idpoint).classList.contains("pointValidated"))
								{
									
										but_validate.style.display="none";
										but_save.style.display="none";
										but_devalidate.style.display="inline-block";
								}	
								else
								{
										but_validate.style.display="inline-block";
                    but_save.style.display="inline-block";
                    but_devalidate.style.display="none";
								}
						}
				};
				xhr.open("POST","../database/bquaadril/getquaadpoint.php",true);
				xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
				xhr.send(encodeURI(param));
			}

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

				var param="";
				if(audit_id!=-1) param="audit_id="+audit_id;
				var xhr=getxhr();
				xhr.onreadystatechange = function f()
				{
					if(xhr.readyState == 4 && xhr.status == 200) 
					{
						var  response = xhr.responseText;
				
						reponse = clean(xhr.responseXML.documentElement);
						var checks=reponse.getElementsByTagName('check');
						console.log ( " checks.length : " + checks.length );
						for(var i=0; i<checks.length;i++)
						{
							var check= checks.item(i);
							var c_id= check.getAttribute("id");
							var c_val= check.getAttribute("value");
							var tr_sumelement = document.getElementById("summary_"+c_id);
							var bmpCheck = document.getElementById("bmpcheck_"+c_id);
							var valid = check.getAttribute("validated");

							console.log ( " c_id : " + c_id );
							console.log ( " c_val : " + c_val );
					
							tr_sumelement.className="";
							if( valid == "true" )
							{
								bmpCheck.style.display = "inline";
								tr_sumelement.classList.add("pointValidated");
								continue;
							}
							else
							{
								bmpCheck.style.display = "none";
							}		
							if(c_val=="KOK")
					 			tr_sumelement.classList.add("pointKOK");
							if(c_val=="OK")
								tr_sumelement.classList.add("pointOK");
							if(c_val=="KO")
								tr_sumelement.classList.add("pointKO");
						}
					}
				};
		
				xhr.open("POST","../database/bquaadril/checkrules.php",false);
				xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
				xhr.send(param);
			}

			function displayPDFViewer(title,docid)
			{
					let caption = title;
					/*
					DocumentViewerShow ( caption );
		
					let url = G_ServerAddress + G_ServerFolder + "/PDFViewer/eoQUALPDFViewer.php?docid="+docid;
		
					document.getElementById ( 'IdcDocumentViewerFrame' ).src = url;
					*/
					let url = G_ServerAddress + G_ServerFolder + "/PDFViewer/eoQUALPDFViewer.php?docid="+docid;
					DocumentViewerShow ( caption, null, url );
			}



			function displayModalWindow ( tagid,view,view_id,scope )
			{
 					let url = "./index.php?selected_tag_id="+tagid+"&pageid="+view+"&selected_id="+view_id+"&scope="+scope;

					$('#IdcTest03').hide ();
					$('#IdcTest02').hide ();
					$('#IdcTest01').show ();


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

					$('#IdcAutoAuditPanLeftMask').height ( $('#IdcAutoAuditPanLeft').prop('scrollHeight') );
					
					switch ( view )
					{
							case 'VIEW_PROCEDURE':
									$('#IdcDivProcedure').show ();
									InitProcedurePage ();
									break;

							case 'VIEW_STAFF':
									$('#IdcDivStaff').show ();
									InitStaffPage ();
									break;

							case 'VIEW_INSTITUTIONDOCUMENT':
									$('#IdcDivInstitutionalDocument').show ();
									InitInstitutionalDocumentPage ();
									break;

							case 'VIEW_DEVICE':
									$('#IdcDivDevice').show ();
									InitDevicePage ();
									break;
					}
					

					// document.getElementById ( "IdcToCorrect" ).innerHTML  = "<b>Blabla</div>";

					return;

					var myWins= new dhtmlXWindows();
					var  win = myWins.createWindow("Add_doc",pan_right.scrollLeft, pan_right.scrollTop, pan_right.offsetWidth-18, pan_right.offsetHeight);
		
		 			myWins.attachViewportTo("pan_right");
					myWins.window("Add_doc").setModal(true);
					myWins.window("Add_doc").attachURL("./index.php?selected_tag_id="+tagid+"&pageid="+view+"&selected_id="+view_id+"&scope="+scope, false);
		
					myWins.attachEvent("onClose", function(win){
							getSummaryStatus();
							selectpoint(current_point);
							return true;
					});
			}

			function devalidateCurrentPoint()
			{
					var param = "audit_id="+audit_id+"&point_id="+current_point;
                var xhr = getxhr();
                xhr.onreadystatechange = function f(){
                        if(xhr.readyState == 4 && xhr.status == 200) {
                        }
                }

                xhr.open("POST","../database/bquaadril/devalidate.php",false);
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
					xhr.send(param);
		 			getSummaryStatus();
          selectpoint( current_point );
			}

			function validateCurrentPoint()
			{
				savePage();
		
				if( document.getElementById("status_header").classList.contains("pointOK") )
				{
					var param = "audit_id="+audit_id+"&point_id="+current_point;
					var xhr = getxhr();
					xhr.onreadystatechange = function f()
					{
						if(xhr.readyState == 4 && xhr.status == 200 ) 
						{
						}
					}
					xhr.open("POST","../database/bquaadril/validate.php",false);
					xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
					xhr.send( param );
		
					getSummaryStatus();
                        
					selectpoint( current_point );
				}
				else 
				{
						/*		console.log( "Bad status: can't validate" );
						alert("Bad status: can't validate");*/
				}
			}

			function AuditBackClicked ()
			{
					getSummaryStatus ();
					selectpoint( current_point );

					$('#IdcTest01').hide ();
					$('#IdcDivProcedure').hide ();
					$('#IdcDivStaff').hide ();
					$('#IdcDivInstitutionalDocument').hide ();
					$('#IdcDivDevice').hide ();
					$('#IdcTest03').show ();
					$('#IdcTest02').show ();

					$('#IdcAutoAuditPanLeftMask').hide ();

					window.location.reload();
					
			}

  </script>
  



  <body style="min-height: 100%; height: 100%;">
  
  		<div class="h-100 w-100 m-0 p-0 bg-light">

  				<div class="h-100 w-100 m-0 p-0">
							
							<div class="d-flex flex-column w-100 h-100 m-0 p-0">
									<div class="row w-100 m-0 p-0 ps-4 pt-2 pb-2 ximeo_bg-dark-1 text-white">
												<div class="col-auto m-0 p-0 ps-1 pt-1 pb-1">
														<img src="../bmp/eoQUAL.png" title="First element" style="width:110px; vertical-align:middle;"/>
												</div>
												<div class="col-auto m-0 p-0 ps-4 pt-1" style="font-size: 1.5em;">Auto-audit</div>
												<div class="col-auto m-0 p-0 ps-2 pe-2 pt-1" style="font-size: 1.5em;">-</div>
												<div class="col-auto m-0 p-0 pt-1" style="font-size: 1.5em;"><?php echo $row[0]; ?></div>
												<div class="col-auto m-0 p-0 ps-2 pe-2 pt-1" style="font-size: 1.5em;">-</div>
												<div class="col-auto m-0 p-0 pt-1" style="font-size: 1.5em;"><?php echo $row[1]; ?></div>

												<div class="col 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-4">
                										<button id="IdcStatApplyButton" class="btn btn-primary text-center pt-0 pb-0 ps-2 pe-2" style="background-color: #2F83B0" onclick="OnGeneratePDF()">
                  											<img src="../bmp/validate_white.png" class="imgclickable float-start me-2" style="width: 20px; vertical-align: middle;">
                  											<span data-langkey="Generate pdf..."></span>
                										</button>
              									</div>
              							</div>
              					</div>
									</div>

									<div class="row flex-grow-1 w-100 m-0 p-0" style="min-height: 0px;">
											<div id="IdcBQSplitter1_2" class="splitter-v w-100 h-100 p-0" data-ratio="0.3" style="background-color: #F0F0F0;">
			
													<div class="pan-left m-0 p-0 ximeo_bg-light" style="overflow: auto; position: relative;">

														<div id="IdcAutoAuditPanLeft"  class="w-100 h-100 m-0 p-0">
															<?php 
															$conn = get_dbconnection();
															$audit_id=$_REQUEST['audit_id'];
															$sql = "select quaad_point.id,istitle,description_summary,level2||coalesce(nullif('.'||level3,'.-1'),'')||coalesce(nullif('.'||level4,'.-1'),'')||coalesce(nullif('-'||inlevelorder,'-0'),''),* from quaad_point, quaad_description where quaad_point.id = quaad_description.id_quaadpoint  and language='FR' and quaadversion=(select type from audit where id={$audit_id}) order by level1,level2,level3,level4,level5,inlevelorder";
															$query = pg_query($conn,$sql);
															if( $query )
															{
																	$wastitle= -1;
																	$chapter_title= "";
																	$previous=-1;
																	while( $row=pg_fetch_row($query) )
																	{
																		if( $row[1] == "t" )
																		{
																			if($wastitle==0)
																			{
																			?>
																				</tbody>
																				</table>
																				</div>
																				</td></tr>
																			<?php 
																			}
											
																			echo "<table style=\"width: 100%;\">";
																			echo 	"<tr>";
																			echo 			"<td>";
																			echo 				"<div id=\"chapter_".$row[0]."\" style=\"font-size:14px; float: left; color:#484848; margin-left:10px; margin-top:10px; margin-bottom:3px;\"><b>".$row[2]."</b></div>";
																			echo 			"</td>";
																			echo 	"</tr>";
											
																			$wastitle=1;
																			$chapter_title = $row[2];
																		}
																		else
																		{
																			if($wastitle == 1)
																			{
																			?>
																				<tr>
																					<td>
																						<div style="font-size:12px; float:left; color:#323232; margin-left: 0px; margin-right: 0px; width: 100%;">
																							<table style="border-spacing: 0px; width: calc(100% - 10px); margin-left: 10px; ">
																								<tbody>
														
																			<?php
																			}

																			echo "<script>point_list[".$row[0]."]= new CPoint(".$row[0].", \"".$chapter_title."\",\"".$row[3]."\",\"".str_replace("\n","<br>",$row[2])."\");point_list[".$row[0]."].previousID=".$previous.";";
																			if($previous !=-1)
																			{
																				echo "point_list[".$previous."].nextID=".$row[0].";";
																			}
																			echo "if (first_point==-1) first_point = ".$row[0].";";
																			echo "</script>";
									
																			echo 	"<tr class=\"clickablepoint\" id=\"summary_".$row[0]."\" onclick=\"selectpoint(".$row[0].");\";>" ;
																			echo 			"<td style=\"border-bottom: 1px solid gray; width:10px; padding-left: 4px; padding-top: 0px;\"><img id=\"bmpcheck_".$row[0]."\" src=\"../bmp/check.png\" title=\"\" style=\"height:20px; width:20px; vertical-align:middle; \"></img></td>" ;
																			echo 			"<td style=\"border-bottom: 1px solid gray; min-width:60px; padding-left: 10px; padding-top: 6px; padding-right: 10px; padding-bottom: 6px;\">".$row[3]."</td>" ;
																			echo 			"<td style=\"border-bottom: 1px solid gray; padding-left: 10px; padding-top: 6px; padding-right: 10px; padding-bottom: 6px;\">".$row[2]."</td>" ;
																			echo 	"</tr>" ;
									
																			$wastitle = 0;
																			$previous = $row[0];
																		}
																	}
									
																	if($wastitle==0)
																	{
																	?>
																		</tbody>
																	</table>
															</div>
													</table>
																<?php
															}
														}
													?>
														</div>

														<div id="IdcAutoAuditPanLeftMask" style="display: none; opacity: 0.3; background-color: #000000; position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 9999;">
														</div>
													</div>	<!-- end pan left -->

													<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">
																<div id="IdcTest01" class="w-100 h-100 m-0 p-0" style="display: none;">
																	<div class="d-flex flex-column w-100 h-100 m-0 p-0">
																			<div class="row flex-grow-1 m-0 p-0 bg-light" style="min-height: 0px;">
																					<div id="IdcToCorrect" class="w-100 h-100 mh-100 m-0 p-0">
																						<?php include ("Procedure.php"); 							?>
																						<?php include ("Staff.php");		 							?>
																						<?php include ("Device.php");		 							?>
																						<?php include ("InstitutionalDocument.php");	?>
																					</div>
																			</div>
																	<div class="row m-0 p-0 pb-2 ximeo_bg-dark-1">
																			<div class="col 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-4">
                														<button class="btn btn-primary text-center pt-0 pb-0 ps-2 pe-2" style="background-color: #2F83B0" onclick="AuditBackClicked()">
                  														<img src="../bmp/back_white_2.png" class="imgclickable float-start me-2" style="width: 20px; vertical-align: middle;">
                  														<span data-langkey="Return"></span>
                														</button>
              														</div>
              													</div>
              											</div>
																	</div>
																</div>

																</div>

																<div id="IdcTest02"class="row flex-grow-1 m-0 p-0" style="min-height: 0px;">
																	<div  class="m-0 p-0 mh-100" >
																		<div id="main_div" class="d-flex flex-column w-100 h-100 m-0 p-0">
																		</div>
																	</div>
																</div>
																
																<div id="IdcTest03" class="row w-100 m-0 p-0 pb-2 pt-1 ximeo_bg-dark-1 text-white">

																		<div class="col-auto m-0 p-0">
																			<img src="../bmp/first.png" title="First element" class="clickablepoint" style="width:32px;vertical-align:middle;" 	onclick="selectpoint(point_list.find(el => el !== undefined).ID)">
																			<img src="../bmp/next1.png" title="Previous element" class="rotate180 clickablepoint" style="width:32px;height:32px;vertical-align:middle;" 	onclick="selectpoint( point_list[current_point].previousID )">
																			<img src="../bmp/next1.png"  title="Next element" style="width:32px; height:32px; vertical-align:middle;" class="clickablepoint" onclick="selectpoint(point_list[current_point].nextID );">
																			<img src="../bmp/first.png" title="Last element" class="rotate180 clickablepoint" style="width:32px;vertical-align:middle;"	onclick="selectpoint( point_list[point_list.length-1].ID )">
																		</div>

																		<div class="col flex-grow-1 m-0 p-0 ps-2 pe-4" style="min-width: 0px;">
																			<div class="d-flex align-items-center m-0 p-0 w-100 h-100">
              														<div id="nav_pointtitle" class="m-0 p-0 ps-2 w-100 text-black" style="text-overflow: ellipsis;overflow: hidden; white-space:nowrap;"></div>
              												</div>
              											</div>

																		<div class="col-auto m-0 p-0">
																			
																			<div class="d-flex flex-row-reverse align-items-center w-100 h-100 m-0 p-0">
                  											<div class="col-md-auto m-0 p-0 pe-4">
                													<button id="but_validate" class="btn btn-secondary text-center pt-0 pb-0 ps-2 pe-2" onclick="validateCurrentPoint();" style="display: none;">
                  													<img src="../bmp/validate_white.png" class="imgclickable float-start me-2" style="width: 20px; vertical-align: middle;">
                  													<span data-langkey="Validate the point"></span>
                													</button>
                													<button id="but_devalidate" class="btn btn-secondary text-center pt-0 pb-0 ps-2 pe-2" onclick="devalidateCurrentPoint();" style="display: none;">
                  													<img src="../bmp/validate_white.png" class="imgclickable float-start me-2" style="width: 20px; vertical-align: middle;">
                  													<span data-langkey="Devalidate the point"></span>
                													</button>
              													</div>

              													<div class="col-md-auto m-0 p-0 pe-4">
                													<button id="but_save" class="btn btn-secondary text-center pt-0 pb-0 ps-2 pe-2" onclick="savePage();" style="display: none;">
                  													<img src="../bmp/save_white.png" class="imgclickable float-start me-2" style="width: 20px; vertical-align: middle;">
                  													<span data-langkey="Save modifications"></span>
                													</button>
              													</div>
              												</div>
             												
              											</div>
																</div>
														</div>
													</div>
					
											</div>
									</div>
							</div>
							
  				</div>

  				<div id="IdcAuditDlg"  class="modal" tabindex="-1" role="dialog" aria-hidden="false">
				
							<div class="modal-dialog modal-sm modal-dialog-centered" role="document">
									<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="Audit report creation"></h5>
													<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" onclick="$('#IdcAuditDlg').modal('hide')"></button>
											</div>
										
											<div class="modal-body">
													<div class="m-0 p-0 pb-2 fw-bold">
														Annexes à intégrer au rapport : 
													</div>
													<form class="m-0 p-0 ps-2">			
															<div class="form-check">
  																<input class="form-check-input" type="checkbox" value="" id="IdcAppendiceProcedure" checked>
  																<label class="form-check-label" for="IdcAppendiceProcedure" data-langkey="Procedures"></label>
															</div>
															<div class="form-check">
  																<input class="form-check-input" type="checkbox" value="" id="IdcAppendiceStaff" checked>
  																<label class="form-check-label" for="IdcAppendiceStaff" data-langkey="Staff documents"></label>
															</div>
															<div class="form-check">
  																<input class="form-check-input" type="checkbox" value="" id="IdcAppendiceDevice" checked>
  																<label class="form-check-label" for="IdcAppendiceDevice" data-langkey="Devices documents"></label>
															</div>

															<div class="form-check">
  																<input class="form-check-input" type="checkbox" value="" id="IdcAppendiceLegalDocument" checked>
  																<label class="form-check-label" for="IdcAppendiceLegalDocument" data-langkey="Legal documents"></label>
															</div>

															<div class="form-check">
  																<input class="form-check-input" type="checkbox" value="" id="IdcAppendiceInstitutionDocument" checked>
  																<label class="form-check-label" for="IdcAppendiceInstitutionDocument" data-langkey="Institutional documents"></label>
															</div>
															

													</form>
											</div>
						
											<div class="modal-footer">
													<button type="button" class="ximeo_button ximeo_bg-dark-2" data-dismiss="modal" data-langkey="Cancel" onclick="$('#IdcAuditDlg').modal('hide')">Cancel</button>
													<button type="button" class="ximeo_button" data-toggle="button" data-langkey="OK" onclick="$('#IdcAuditDlg').modal('hide'); generatePDF ();">OK</button>
											</div>
									</div>
							</div>
					</div>

  				<?php include ("./DocumentViewer.html");			?>		<!-- See DocumentViewer.js 			-->
  				<?php include ("waiting.html");								?>
  				<?php include ("msg_dlg.html"); 							?>

  		</div>

   	
  		<script>
  			IdcAuditSplitter1_2 	= new C_Splitter ( "IdcBQSplitter1_2" );

  			getSummaryStatus ();
  			
  			
  			for ( let i=0; i<point_list.length; i++ )
  			{

  				// console.log ( "point_list [i].ID : " + point_list [i].pointID );
  			}
  			if ( first_point != -1 )
  			{
  				current_point = first_point;
  				selectpoint ( current_point );
  			}

			context.init({preventDoubleContext: false});

			window.addEventListener(`contextmenu`, (e) => {
		 		e.preventDefault();
		 	});

  			switchLanguage ( CurrentLanguage );
  		</script>
  
  </body>
  

</html>
