<%@page import="com.capgemini.framework.common.SettingsHelper"%>
<%@page import="com.capgemini.framework.common.StringHelper" %>
<%@page import="com.capgemini.reports.database.javabean.enumeration.ReportCriteriaEnum"%>
<%@page import="com.capgemini.reports.database.manager.MngSchedulingCriteriaVal"%>
<%@page import="java.util.Map"%>
<%
    /*
     * Available request parameters:
     *  "isUpdateReport"       (boolean)             Is this a submission of a NEW report or an UPDATE?
     *  "idReport"             (long)    <Optional>  Report Id in case of an UPDATE request
     */
    boolean isDevMode            = SettingsHelper.isDevMode();
    boolean isUpdate = Boolean.valueOf(request.getParameter("isUpdateReport"));
    Long    reportID             = isUpdate ? Long.valueOf(request.getParameter("idReport")) : new Long(-1);
	
	/* Default values for development environment only */
	String theDefaultProductBefore = "";
	String theDefaultProductAfter = "";
	String theDefaultUnitAfter="";
	String theDefaultUnitBefore="";
	String theDefaultMatricule="";
	String theDefaultLMR="-";
	String theDefaultClasse ="";
	String theDefaultMajorMinor="";
	String theDefaultUniqueConjoint ="";
		
    if (isDevMode){ // Devmode default values
	    theDefaultProductAfter = "97R0";
		theDefaultUnitAfter    = "550";
		theDefaultUnitBefore   = "520";
		theDefaultMatricule    = "GE90 M10 MOTEUR ASSEMBLE";
		theDefaultLMR          = "-";
	}
	
    if( isUpdate){ // Existing values to reload from DB
        Map<ReportCriteriaEnum, String> theFunctionalCriteriaValues = new MngSchedulingCriteriaVal().getFunctionalMap(reportID);
	
        // Product
	    theDefaultProductBefore  = StringHelper.replaceNullByEmpty( theFunctionalCriteriaValues.get(ReportCriteriaEnum.PRODUCT_BEFORE));
	    theDefaultProductAfter   = StringHelper.replaceNullByEmpty( theFunctionalCriteriaValues.get(ReportCriteriaEnum.PRODUCT_AFTER));
        theDefaultMatricule      = StringHelper.replaceNullByEmpty( theFunctionalCriteriaValues.get(ReportCriteriaEnum.MATRICULE));
	    //Unit
		theDefaultUnitAfter      = StringHelper.replaceNullByEmpty( theFunctionalCriteriaValues.get(ReportCriteriaEnum.UNIT_AFTER));
		theDefaultUnitBefore     = StringHelper.replaceNullByEmpty( theFunctionalCriteriaValues.get(ReportCriteriaEnum.UNIT_BEFORE));  
	    // Overall
		theDefaultClasse         = StringHelper.replaceNullByEmpty( theFunctionalCriteriaValues.get(ReportCriteriaEnum.CLASSE));
		theDefaultMajorMinor     = StringHelper.replaceNullByEmpty( theFunctionalCriteriaValues.get(ReportCriteriaEnum.MAJOR_MINOR));
		theDefaultUniqueConjoint = StringHelper.replaceNullByEmpty( theFunctionalCriteriaValues.get(ReportCriteriaEnum.CONJOINT_UNIQUE));
	    // LMR
		theDefaultLMR            = StringHelper.replaceNullByEmpty( theFunctionalCriteriaValues.get(ReportCriteriaEnum.LMR));	
	}
%>

<!-- Build input radio classe 1 / classe 2, major / minor, conjoint / unique, build LMR-->
<%! private String getSelectedClasse(final String theClasse){
        String selectedClasseOne = "";
        String selectedClasseTwo = "";
        StringBuilder buildSelect = new StringBuilder();
        if("1".equals(theClasse)){
            selectedClasseOne ="selected=\"selected\"";
        }else{
            selectedClasseTwo ="selected=\"selected\"";
        }
        buildSelect.append("<option ").append(selectedClasseOne).append(" value=\"1\">1</option>");
        buildSelect.append("<option ").append(selectedClasseTwo).append(" value=\"2\">2</option>");    
        
        return buildSelect.toString();
    }
    
    private String getSelectedMajorMinor(final String theMajorMinor){
        String selectedMajor = "";
        String selectedMinor = "";
        StringBuilder buildSelect = new StringBuilder();
        if("Majeur".equals(theMajorMinor)){
            selectedMajor ="selected=\"selected\"";
        }else{
            selectedMinor ="selected=\"selected\"";
        }
        buildSelect.append("<option ").append(selectedMajor).append(" value=\"Majeur\">Majeur</option>");
        buildSelect.append("<option ").append(selectedMinor).append(" value=\"Mineur\">Mineur</option>");    
        
        return buildSelect.toString();    
    }
    
    private String getSelectedUniqueConjoint(final String theUniqueConjoint){
        String selectedUnique = "";
        String selectedConjoint = "";
        StringBuilder buildSelect = new StringBuilder();
        if("Conjoint".equals(theUniqueConjoint)){
            selectedConjoint = "selected=\"selected\"";
        }else{
            selectedUnique   = "selected=\"selected\"";
        }
        buildSelect.append("<option ").append(selectedConjoint).append(" value=\"Conjoint\">Conjoint</option>");
        buildSelect.append("<option ").append(selectedUnique  ).append(" value=\"Unique\"  >Unique</option>");    
        
        return buildSelect.toString();    
    }

    /* generate js Array*/
    private String generateArrayLMRs(final String theLMRsList){
        String[] lmrList = StringHelper.splitWithoutDelim(";", theLMRsList);
        StringBuilder theTableCode = new StringBuilder("var LMRsArray = new Array();\n");
        int i = 0;
        for(String curLMR : lmrList ){
            theTableCode.append("LMRsArray[").append(i).append("]='").append(curLMR).append("';");
            i++;
        }
        return theTableCode.toString();
    }
%>



<% if( isUpdate && !theDefaultLMR.contains("-")){ %>
    <script>	
    	<%=generateArrayLMRs(theDefaultLMR)%>
    	
    	function fillFieldsLMR(){
    		//LMRsArray
    		for (var i=0;i<LMRsArray.length;i++){
    			addLMRLine(LMRsArray[i]);
    		}
    	}
    
    	function addLMRLine(lmrValue){
    		var emptyLine = createline(lmrValue);
    		var totalLinesDiv=document.getElementById("total_lines");
    		totalLinesDiv.appendChild(emptyLine);
    	}
    	
    	function createline(lmrValue){
    		var emptyLine = document.createElement("div");
    		emptyLine.id = 'line';
    		emptyLine.name='line';
    		emptyLine.align = 'left';
    		emptyLine.style.borderBottom = '1px solid #CCC7D1';
    
    		var childinputText = document.createElement("input");
    		childinputText.type = "text";
    		childinputText.id = 'LMR';
    		childinputText.name='LMR';
    		childinputText.value=lmrValue;
    		childinputText.style.width = '240px';
    		childinputText.style.height = '22px';
    		childinputText.style.border= 'none';
    		childinputText.style.backgroundImage = 'none';
    		emptyLine.appendChild(childinputText);
    
    		var childImage = document.createElement("img");
    		childImage.src = "../ihm/icone-moins.png";		
    		childImage.style.width = '20px';
    		childImage.style.height = '20px';
    		childImage.setAttribute('onclick','delLine(this);');
    		emptyLine.appendChild(childImage);
    		return emptyLine;
    	}
	</script>	
<% } %> 	

<!-- HTML, will probably be imported right inside a form -->
<table cellspacing="0" cellpadding="3" border="0">
	<tr>
		<td class="tdFieldTitle delimitedPart" colspan="2">Informations de la configuration &quot;Apr&egrave;s&quot; :</td>
		<td class="tdFieldTitle delimitedPart" colspan="2">Informations de la configuration &quot;Avant&quot; :</td>
	</tr>
    <!-- useful?
	<tr>
        <td>
        </td>
    </tr> -->
	<tr>
		<td class="tdFieldTitle required" valign="top">Produit* :</td>
        <td>
        	<input type="text" id="product_id" name="product_id" value="<%= theDefaultProductBefore %>" onchange="adaptProducts()"/>
        </td>
		<td class="tdFieldTitle" valign="top">Produit (non modifiable) :</td>
        <td>
            <input type="text" id="product_id_bis" name="product_id_bis" value="<%= theDefaultProductAfter %>" disabled/>
        </td>
	</tr>
	<tr>
		<td class="tdFieldTitle required" valign="top">Unit* :</td>
        <td>
            <input type="text" id="unit_after" name="unit_after" value="<%= theDefaultUnitAfter %>" />
        </td>
		<td class="tdFieldTitle required" valign="top">Unit de r&eacute;f&eacute;rence* :</td>
        <td>
            <input type="text" id="unit_before" name="unit_before" value="<%= theDefaultUnitBefore %>"/>
        </td>
	</tr>
	<tr>
        <td>
            <br/>
            <br/>
        </td>
    </tr> 
	<tr>
        <td class="tdFieldTitle delimitedPart" colspan="2">Informations suppl&eacute;mentaires :</td>
    </tr>
	<tr>
        <td>
        </td>
    </tr>
	<tr>
        <td class="tdFieldTitle">Matricule :</td>
        <td>
            <input type="text" id="matricule" name="matricule" value="<%= theDefaultMatricule %>" maxlength="50"/>
        </td>
    </tr>
	<tr>
		<td class="tdFieldTitle required">Classe* :</td>
		<td>
            <select type="text" id="classe" name="classe">
			    <% if( isUpdate ) { %>
					<%= getSelectedClasse(theDefaultClasse) %> 
			    <% } else { %> 
				    <option selected="selected" value="1">1</option>
                    <option value="2">2</option>				
			    <% } %>					
			</select>
		</td>
    </tr>
	<tr>
        <td class="tdFieldTitle required">Majeur ou Mineur* :</td>
		<td>
            <select type="text" id="major_minor" name="major_minor">
			    <% if( isUpdate ){ %>
					<%= getSelectedMajorMinor(theDefaultMajorMinor) %> 
			    <% }else{  %> 
				    <option selected="selected" value="Majeur">Majeur</option>
				    <option value="Mineur">Mineur</option>		
			    <% } %>
			</select>
		</td>
    </tr>
	<tr>
        <td class="tdFieldTitle required">Unique ou Conjoint* :</td>
		<td>
            <select type="text" id="conjoint_unique" name="conjoint_unique">
			    <% if( isUpdate ){ %>
				    <%= getSelectedUniqueConjoint(theDefaultUniqueConjoint) %> 
			    <% } else { %> 
			        <option selected="selected" value="Conjoint">Conjoint</option>
			        <option value="Unique">Unique</option>	
			    <% } %>					
			</select>
		</td>
    </tr>
	<tr>
        <td class="tdFieldTitle">Modifications Retir&eacute;es :</td>
		<td align="right" style="text-decoration:none;width:300px; ">
			<div id="total_lines" name="total_lines" style="overflow-y:scroll;height:100px;width:313px;border:1px solid #CCC7D1; border-radius:2px;">
			</div>					
	        <% if( isUpdate && !theDefaultLMR.contains("-") ){ %>
			<script>
				fillFieldsLMR();
			</script>
	        <% }else{ %> 
			<div>
                <img src="/kurt-web/ihm/icone-plus.png" width="30" height="30" onclick="addLine()" align="right">
            </div> 
	        <% } %>
		</td>
	</tr>
	<tr>
        <td class="tdFieldTitle" colspan="4" style="text-align:center;">
        <br/>
        	<div id="loading" style="display:none;">
        		<i>Traitement en cours...</i>
                <br/>
                <img src="/kurt-web/ihm/progress.gif" vspace="6" width="129" height="20">
        	</div>
        </td>
    </tr>
</table>

<!-- Internal functional Javascript methods (checks etc.) -->
<script>
	/* Automatic checks before sending the form */
	function checkForm()
	{
		var isCheckOk = false;

		if (isMandatoryFieldEmpty("product_id")){
			parent.Dialog("Erreur", "Veuillez saisir le champ obligatoire : Produit &quot;Apr&egrave;s&quot;.");
		}else if (isMandatoryFieldEmpty("unit_after")){
			parent.Dialog("Erreur", "Veuillez saisir le champ obligatoire : Unit &quot;Apr&egrave;s&quot;.");
		}else if (isMandatoryFieldEmpty("unit_before")){
			parent.Dialog("Erreur", "Veuillez saisir le champ obligatoire : Unit &quot;Avant&quot;.");
		}else if (!isNumber("unit_after")){
			document.getElementById("unit_after").focus();
			parent.Dialog("Erreur", "Vous devez saisir un entier dans le champ Unit &quot;Apr&egrave;s&quot;.");
		}else if (!isNumber("unit_before")){
			document.getElementById("unit_before").focus();
			parent.Dialog("Erreur", "Vous devez saisir un entier dans le champ Unit &quot;Avant&quot;.");
		}else if (parseInt(document.getElementById("unit_after").value) <= parseInt(document.getElementById("unit_before").value)){
			document.getElementById("unit_before").focus();
			parent.Dialog("Erreur", "Les Units &quot;Avant&quot; et &quot;Apr&egrave;s&quot; doivent &ecirc;tre diff&eacute;rents, le Unit &quot;Avant&quot; &eacute;tant inf&eacute;rieur au Unit &quot;Apr&egrave;s&quot;.");
		}else {
			isCheckOk = true;
		}
		return isCheckOk;
	}

	function checkIsLMR(){
		var currentLMRs = document.getElementById("LMR");
		if(currentLMRs.length<=9){
			alert(lmrArray);
			return true;			
		}else{
			lmrArray=currentLMRs.split("\\s*\\;\\s*");
			alert(lmrArray);
			if(lmrArray.length=1){
				/* No use of ";" for the LMR's separation */
				return false;
			}
		}	
	}

	function adaptProducts(){
		document.getElementById("product_id_bis").value=document.getElementById("product_id").value;	
	}
	
	function createEmptyline(){
		var emptyLine = document.createElement("div");
		emptyLine.id = 'line';
		emptyLine.name='line';
		emptyLine.align = 'left';
		emptyLine.style.borderBottom = '1px solid #CCC7D1';

		var childinputText = document.createElement("input");
		childinputText.type = "text";
		childinputText.id = 'LMR';
		childinputText.name='LMR';
		childinputText.value="";
		childinputText.style.width = '240px';
		childinputText.style.height = '12px';
		childinputText.style.border= 'none';
		childinputText.style.backgroundImage = 'none';
		emptyLine.appendChild(childinputText);

		var childImage = document.createElement("img");
		childImage.src = "../ihm/icone-moins.png";		
		childImage.style.width = '20px';
		childImage.style.height = '20px';
		childImage.setAttribute('onclick','delLine(this);');
		emptyLine.appendChild(childImage);
		return emptyLine;
	}

	function addLine(){
		var emptyLine = createEmptyline();
		var totalLinesDiv=document.getElementById("total_lines");
		totalLinesDiv.appendChild(emptyLine);
	}

	function delLine(link){
		var lineDiv = link.parentNode;
		var totalLinesDiv = lineDiv.parentNode;
		if(totalLinesDiv.childNodes.length>1){
			totalLinesDiv.removeChild(lineDiv);
		}	
	}

</script>

<% if( !isUpdate ){ %>	
	<script>
        // Add 4 empty lines for the user
		for (var i=0;i<4;i++){
            addLine();
		}
	</script>
<% } %> 		