<%
/******************************************************************************
 * Copyright (c) 2000-2005 e-Deal
 *
 * e-Deal S.A.
 * 55 rue Brillat Savarin
 * 75013 Paris
 * France
 *
 * T: +33 (0)1 53 80 80 30
 * F: +33 (0)1 73 01 69 77
 * http://www.e-deal.com
 * 
 * La diffusion de ce code source sous quelque forme que ce soit sans
 * l'autorisation de E-DEAL est interdite.
 *
 * Vous êtes autorisés à modifier ce code source uniquement pour votre usage
 * propre et sous réserve que les mentions de copyright demeurent intactes.
 *
 * Ce code est fourni en l'état. Aucune garantie d'aucune sorte, explicite ou
 * implicite n'est donnée. En aucun cas E-DEAL ne pourra être tenu pour
 * responsable des dommages pouvant résulter de l'utilisation de ce code
 * source.
 ******************************************************************************/
%>
<%@page session="true" contentType="text/html; charset=UTF-8"%>
<%@ page import="com.edeal.frontline.navigation.FlRequest" %>
<%@ page import="com.edeal.frontline.*" %>
<%@ page import="java.util.*" %>
<%@ page import="javax.swing.tree.DefaultMutableTreeNode" %>
<%@taglib uri="http://www.e-deal.com/taglib/fl" prefix="fl" %>
<jsp:useBean class="com.edeal.frontline.SelectionBean" id="Selection" scope="request"/>
<%
final org.apache.commons.logging.Log logger = org.apache.commons.logging.LogFactory.getLog(getClass());
FlRequest flRequest = new FlRequest(request);
FlContext context = flRequest.getContext();
DataDictionary dico = context.getDataDictionary();
String id = null;
try {
	id = Selection.getID();
} catch (FieldNotInitializedException fnie) {
}
String errorID = (String)request.getAttribute("ErrorID");
boolean isCreate = id == null;

String salesModel = context.getContextParameter("SalesModel");

boolean isB2C = "B2C".equalsIgnoreCase(salesModel);

String refPerID = dico.getRefIdByCode("SelMaxTyp", "PER");

String selMaxTypID = null;
try {
	selMaxTypID = Selection.getSelMaxTyp();
} catch (FieldNotInitializedException ex) {
}

Vector criteriaGroups = (Vector)flRequest.getAttribute("criteria_list");
if (criteriaGroups == null) {
	criteriaGroups = new Vector();
}

boolean hasCriteria = false;
for (int i = 0; i < criteriaGroups.size(); i++) {
	Hashtable crit = (Hashtable)criteriaGroups.elementAt(i);
	if (crit.get("criteria_tree") != null) {
		hasCriteria = true;
	}
}
%>
	<link rel="stylesheet" href="<fl:webapp/>/css/smalltabs_css.jsp" type="text/css">
	
	<%
	if(errorID != null) {
		String errorMsg = null;
		if(errorID.equals("NOTBROS")) {
			errorMsg = Utils.getMessage(session, "M3035", "Les critères sélectionnés ne se trouvent pas au même niveau");
		} else if(errorID.equals("ALONE")) {
			errorMsg = Utils.getMessage(session, "M3036", "Veuillez sélectionner plusieurs critères");
		} else if(errorID.equals("ROOTSELECTED")) {
			errorMsg = Utils.getMessage(session, "M3037", "Il n'est pas possible de dégrouper la racine");
		} else if(errorID.equals("TOOMANY")) {
			errorMsg = Utils.getMessage(session, "M3038", "Veuillez ne sélectionner qu'un seul groupe de critères");
		} else if(errorID.equals("LEAFSELECTED")) {
			errorMsg = Utils.getMessage(session, "M3039", "Veuillez sélectionner un groupe de critères");
		} else {
			errorMsg = Utils.getMessage(session, "M303A", "Erreur inconnue") + " (" + errorID + ")";
		}

%>
<script language="javascript">
function doInit() {
	window.alert('<%= Utils.formatToJavascript(errorMsg) %>');
}

</script>
<%
	}
%>
	
	
	<script type="text/javascript" language="javascript">

		
	function doSubmit() {
		var f = document.forms[0];
		return true;
	}
	var maxFreezed = <%= refPerID.equals(selMaxTypID) ? "true" : "false" %>;
	function doCheckMaxFld() {
		var f = document.forms[0];
		var s = f.SelMaxTyp;
		maxFreezed = (s.options[s.selectedIndex].value == '<%= refPerID %>');
		if(maxFreezed || f.SelMax.value == '') {
			f.SelMax.value = 1;
		}
	}
	
	function doAdd(parentID, objID, field) {
		window.open('<fl:link url="/create_criteria.fl?dummy=1" list="true"/>&RootFld=' + field + '&CtrID='+'<%=id%>'+'&CriFobID=' + objID + '&Src=Selection' + (parentID ? '&CriParentID=' + parentID + '&GrpID=' + parentID : ''), 'create_criteria', 'menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes,width=800,height=250');
	}
	
	function doAddEvent(parentID, objID, field) {
		window.open('<fl:link url="/edit_eventcriteria.fl?dummy=1" list="true"/>&RootFld=' + field + '&CtrID=<fl:getProperty name="Selection" property="SelID" alt=""/>&CriFobID=' + objID + (parentID ? '&CriParentID=' + parentID + '&GrpID=' + parentID : ''), 'create_criteria', 'menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes,width=800,height=250');
	}
	
	function doEdit(criteriaID, objID, field) {
		window.open('<fl:link url="/edit_criteria.fl?dummy=1" list="true"/>&RootFld=' + field + '&CriFobID=' + objID + '&id=' + criteriaID + '&CtrID=<%=id%>', 'create_criteria', 'menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes,width=700,height=250');
	}
	
	function doEditEvent(criteriaID, objID, field) {
		window.open('<fl:link url="/edit_eventcriteria.fl?dummy=1" list="true"/>&RootFld=' + field + '&CriFobID=' + objID + '&id=' + criteriaID, 'create_criteria', 'menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes,width=500,height=300');
	}
	
	function hasSelected() {
		var f = document.forms[0];
		if (f.CriID == null) {
			return false;
		}
		var result = false;
		if (f.CriID.length) {
			for (var i = 0; !result && i < f.CriID.length; i++) {
				result = result || f.CriID[i].checked;
			}
		} else {
			result = f.CriID.checked;
		}
		return result;
	}
	function doDeleteCriteria() {
		performOperation('delete');
	}
	function performOperation(operation) {		
		
		if (hasSelected()) {
			var field = criteriaFields.elementAt(CriteriaTabs_selectedSTab);
			var url = '<fl:webapp/>/criteria_operation.fl?op=' + operation + '<%= id != null ? "&CtrID="+ id : "" %>&ErrorID=<%= errorID %>&RootFld=' + field;
			var ids = '';
			var f = document.forms[0];
			if (f.CriID.length) {
				for (var i = 0; i < f.CriID.length; i++) {
					if (f.CriID[i].checked && f.CriID[i].getAttribute('field') == field) {
						ids += '&CriID=' + f.CriID[i].value;
					}
				}
			} else {
				if (f.CriID.checked && f.CriID.getAttribute('field') == field) {
					ids += '&CriID=' + f.CriID.value;
				}
			}
			if (ids != '') {
				url += ids;
				doAjax(url);
			}
		}
	}
	
	function doGroupAnd() {
		performOperation('and');
	}
	
	function doGroupOr() {
		performOperation('or');
	}
	
	function doUngroup() {
		performOperation('ungroup');
	}
	var criteriaFields = new FlVector();
	</script>

<body<% if(errorID != null) { %> onLoad="doInit();"<% } %>>
<fl:form action="/save_selection_edit.fl" bean="Selection">
<% 
if (isB2C) { %>
	<input type="hidden" name="SelMax" value="1">
	<input type="hidden" name="SelMaxTyp" value="<%= refPerID %>">
<% } %>
	<fl:bigTabs objectTitle="<%= Utils.getMessage(session, \"L60F1\", \"Ciblage\") %>" ou="<%= \"/edit_selection.fl\" + (id != null ? \"?id=\" + id : \"\") %>">
		<table class="container" cellpadding="0">
			<tr>
				<td class="titreFiche" colspan="3">
					<table class="fieldline">
						<td class="labelTitreFiche"><fl:label field="SelName" labelClassName="titreFiche"/></td>
						<td class="fieldTitreFiche"><fl:input property="SelName" mandatoryMsgCode="M60A2"/></td>
					</table>
				</td>
			</tr>
			<tr class="ligne_separation"><td colspan="3"></td></tr>
			<tr>
				<td class="column2">
					<table class="container" cellpadding="0">
						<fl:fieldEdit property="SelCode" mandatoryMsgCode="M2001" unicityMsgCode="M60CE" onblur="this.value = checkString(this.value, 'upper')" />
					</table>
				</td>
				<td class="separation"><div class="separation"></div></td>
				<td class="column2">
					<table class="container" cellpadding="0">
						<% if (!isB2C) { %>
						<tr class="fieldline">
							<td class="dataLabel"><fl:label field="SelMax"/></td>
							<td class="dataValue">
								<div class="fieldTable" >
									<table class="fieldTable">
										<tr>
											<td class="bigFieldPart noPaddingLeft"><input type="hidden" name="mandatory" value="SelMax"><input type="hidden" id="mandatory.SelMax" name="mandatory.SelMax" value="Veuillez saisir un nombre maximum d'interlocuteurs."><input id="SelMax" name="SelMax" type="text" value="1" class="input number chpsTextObligatoire" style="text-align: right" onblur="ctrlNumField(this, 'integer', 'Format incorrect. Veuillez corriger'); if (this.value == '') this.value = 1" onfocus="if(maxFreezed) this.blur();"><span id="SelMax_msg" class="mandatory_alert" style="display: none">!</span>
											<%--fl:input property="SelMax" onfocus="if(maxFreezed) this.blur();" onblur="if (this.value == '') this.value = 1" mandatoryMsgCode="M303C" nodiv="true"/--%></td>
											<td class="smallFieldPart" style="padding-left: 10px"><fl:input property="SelMaxTyp" onchange="doCheckMaxFld();" width="auto" nodiv="true"/></td>
										</tr>
									</table>
								</div>
							</td>
						</tr>
						<fl:fieldEdit property="SelDefault"/>
						<% } %>
					</table>
				</td>
			</tr>
		</table>
		<table class="container" cellpadding="0">
			<tr class="ligne_separation"><td></td></tr>
			<tr><td class="titrePartie"><fl:getMessage code="L2007" alt="Description"/></td></tr>
			<tr><td class="dataValue noPaddingLeft"><fl:input property="SelDescription" width="100%" rows="5" nodiv="false"/></td></tr>
			<tr class="ligne_separation"><td></td></tr>
			<tr class="ligne_separation_couleur"><td></td></tr>
			<tr class="ligne_separation"><td></td></tr>
		</table>
<% if (!isCreate) {
%>
		<fl:smallTabs name="CriteriaTabs">
<% 

	for (int i = 0; i < criteriaGroups.size(); i++) { 
		Hashtable group = (Hashtable)criteriaGroups.elementAt(i);
		String title = (String)group.get("title");
		String objSql = (String)group.get("objsql");
		String field = (String)group.get("field");
		String objID = dico.getTable("sql", objSql).getObjID();
		DefaultMutableTreeNode tree = (DefaultMutableTreeNode)group.get("criteria_tree");
							%>
			<fl:sTab id="<%= \"sTab\" + i %>" title="<%= title + (tree != null ? \" (x)\" : \"\") %>">
				<div>
					<script language="javascript" type="text/javascript">criteriaFields.addElement('<%= field %>');</script>
<%
		String criID = "";
		if (tree != null) {
			flRequest.setAttribute("criteria_tree", tree);
			try {
				criID = ((CriteriaBean)tree.getUserObject()).getID();
			} catch (Exception e) {
			}
			String url = "Event".equals(objSql) ? "/marketing/eventcriteria/read.jsp" : "/marketing/criteria/read.jsp";
%>					<jsp:include page="<%= url %>" flush="true" >
						<jsp:param name="Edit" value="1"/>
						<jsp:param name="ObjID" value="<%= objID %>"/>
						<jsp:param name="RootFld" value="<%= field %>"/>
						<jsp:param name="CriID" value="<%= criID %>"/>
					</jsp:include>
<%
			flRequest.removeAttribute("criteria_tree");
		}
%>					<a href="javascript:doAdd<%= "Event".equals(objSql) ? "Event" : "" %>('', '<%= objID %>', '<%= field %>')"><img border="0" src="<fl:webapp/>/icons/ico/save_all_long.gif" width="74px" height="17px"/></a>
				</div>
			</fl:sTab>
<%
	}
%>
		</fl:smallTabs>
<%
}else{%>
<input name="$$returnedHtmlHead" type="hidden" value="...">
<input name="$$returnedHtmlBody" type="hidden" value="...">
<%
}
%>
	</fl:bigTabs>
</fl:form>
</body>
