<%
/******************************************************************************
 * 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 contentType="text/html; charset=UTF8" session="true"%>
<%@ page import="com.edeal.frontline.navigation.FlRequest"%>
<%@ page import="com.edeal.frontline.FlContext"%>
<%@ page import="com.edeal.frontline.Utils"%>
<%@ page import="com.edeal.frontline.FieldNotInitializedException"%>
<%@ page import="com.edeal.frontline.FrontlineException"%>
<%@ page import="com.edeal.frontline.FlLocale"%>
<%@ page import="com.edeal.frontline.DataDictionary"%>
<%@ page import="java.util.Vector"%>
<%@ page import="java.util.HashMap"%>
<%@ page import="java.util.Map.Entry"%>
<%@ page import="com.edeal.frontline.navigation.WebUtils"%>
<%@ page import="java.util.*"%>
<%@taglib uri="http://www.e-deal.com/taglib/fl" prefix="fl"%>
<jsp:useBean class="com.edeal.frontline.MassEmailingBean" id="MassEmailing" 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 = MassEmailing.getID();	
	} catch (FieldNotInitializedException fnie) {
	}
	boolean isCreate = id == null;
	
	Integer emlDstType =  null;
	try{
		emlDstType =(Integer)MassEmailing.getProperty("EmlDstType");
	} catch (Exception e) {
	}
	
	String emlTypeDst =  null;
	try{
		emlTypeDst =(String)MassEmailing.getEmlTypeDst();
	} catch (Exception e) {
	}
	
	String emlStatus =  null;
	try{
		emlStatus =(String)MassEmailing.getEmlStatus();
	} catch (Exception e) {
		emlStatus = dico.getRefIdByCode("EmlStatus", "MAKING");
	}
	String emlStatusDisp = (String)dico.getRefDisp(session, "Mes", "Te1", dico.getRefIdByCode("EmlStatus", "MAKING"));
	//récupérer la langue en cours 
	FlLocale locale = FlLocale.getInstance(session);
	String langageID = locale.getLanguageID();
	//si la langue dans fllocal est null alors français pas defaut
	if(langageID == null) {
		try {
			langageID = dico.getRefIdByCode("Lna", "Val", "fr_FR");
		} catch (Exception ex) {
		}
	}
	//code type de message
	String codeMsgModele = dico.getRefIdByCode("tpe", "Te1", "MODELE");
	String codeMsgProduit = dico.getRefIdByCode("tpe", "Te1", "PRODUIT");
	String codeMsgImporte = dico.getRefIdByCode("tpe", "Te1", "IMPORTE");
	
	
	//code type de destination
	String codeDestPer = dico.getRefIdByCode("Mtd", "Te1", "PER");
	String codeDestSil = dico.getRefIdByCode("Mtd", "Te1", "SIL");
	String codeDestPerSil = dico.getRefIdByCode("Mtd", "Te1", "PERSIL");
	
	String emlTypeDstObj = null;
	if (emlTypeDst != null && emlTypeDst.equals(codeDestPer)){
		emlTypeDstObj = dico.getTable("sql", "PERSON").getObjID();
	} else {
		if ((emlTypeDst != null) && ((emlTypeDst.equals(codeDestSil)) || (emlTypeDst.equals(codeDestPerSil)))){
			emlTypeDstObj = dico.getTable("sql", "SILHOUETTE").getObjID();
		}
	}

	
	HashMap<String, String> hmapAllEmailDisplay  = (HashMap<String, String>) flRequest.getAttribute("hmapAllEmailDisplay");
	if (hmapAllEmailDisplay == null) {
		hmapAllEmailDisplay = new HashMap<String, String>();
	}
	HashMap<String, String> hmapEmailDisplay = (HashMap<String, String>) flRequest.getAttribute("hmapEmailDisplay");
	if (hmapEmailDisplay == null) {
		hmapEmailDisplay = new HashMap<String, String>();
	}
	HashMap<String, String> hmapMassEmailingType = (HashMap<String, String>) flRequest.getAttribute("hmapMassEmailingType");
	if (hmapMassEmailingType == null) {
		hmapMassEmailingType = new HashMap<String, String>();
	}
	java.util.Date emlSndDate = (java.util.Date) request.getAttribute("emlSndDate");
	String strDate = "";
	String strTime = "";
	if (emlSndDate != null){
		strDate = Utils.formatToWebDate(session, emlSndDate, true);
		strTime = Utils.formatToWebTime(session, emlSndDate, true).substring(0, 5);
	}

	String strReDate = "";
	String strReTime = "";
	try {
		java.util.Date emlReSndDate = MassEmailing.getEmlReSndDate(); 	
		if (emlReSndDate != null){
			strReDate = Utils.formatToWebDate(session, emlReSndDate, true);
			strReTime = Utils.formatToWebTime(session, emlReSndDate, true).substring(0, 5);
		}
	} catch (FieldNotInitializedException e) {		
	}

	String emlTypeID = null;
	try {
		emlTypeID = (String)dico.getRefIdByCode("EmlType", "CBULKFAX");
	} catch (Exception e) {
	}
	
	%>
<!--[if !IE]><!-->
<style>
.fieldset {
	-moz-border-radius: 8px;
	-webkit-border-radius: 8px;
	border-radius: 8px;
}

</style>
<!--<![endif]-->
<style>
.fieldset {
}

.legend {
	padding: 0.2em 0.5em;
	/*display: block;*/
	font-size: 1em;
	font-weight: bold;
	color: black;
}

.message-editor {
	position: relative;
	left: 0;
	right: 0;
	height: 100%;
	width: 100%;
}


.language_without_message {
	filter: alpha(opacity = 20);
	-moz-opacity: 0.2;
	-khtml-opacity: 0.2;
	opacity: 0.2;
}

.language_current {
	border: 1px solid black;
}

.language_current_without_message {
	border: 1px solid black;
	filter: alpha(opacity = 20);
	-moz-opacity: 0.2;
	-khtml-opacity: 0.2;
	opacity: 0.2;
}
</style>

<script type="text/javascript" language="javascript" src="<fl:webapp/>/js/edeal/libraries/json.org/json2/json2.js"></script>
<script type="text/javascript" language="javascript" src="<fl:webapp/>/netbusiness/emaillink/emaillink.js"></script>
<script type="text/javascript" language="javascript" src="<fl:webapp/>/js/ac/textAC_js.jsp"></script>
<script language="javascript">
	function setMassEmailingID(meID){
		$("input[name='id']").val(meID);
	}	
	 
	function changeLanguage(codeLanguage) {
		var msgAttIDs = $("input[name='MsgAttID']").val()
		if (msgAttIDs != '') {
			saveMessage();
		}	
		loadMessage(codeLanguage);	
		codeLng = codeLanguage;
	}
	function loadMessage(codeLanguage) {
		$.getJSON("<fl:webapp/>/get_message_content.fl?id=" + $("input[name='id']").val() +  "&langageID=" + codeLanguage, function(result) {
			var f = document.forms[0];
			loadAttachments(result.msgID);
			setLangageID(codeLanguage);
			loadLanguage();
			codeLng = codeLanguage;
	    });
	}
	function loadAttachments(msgID) {	
		var ajaxURL = '<fl:webapp/>/get_attachement_div.fl?messageID=' + msgID + '&doc=1';
		doAjax(ajaxURL, attachmentsCallBack);
	}
	function attachmentsCallBack(index) {
		if (eDealXmlhttpArr[index].readyState == 4) {
			$("#div_attachement").html(eDealXmlhttpArr[index].responseText);
		}
		hideWaiting();
	}
	function loadLanguage() {
		var ajaxURL = '<fl:webapp/>/get_language_div.fl?id='+$("input[name='id']").val()+'&languageID='+$("#langageID").val();
		doAjax(ajaxURL, languageCallBack);
	}
	function languageCallBack(index) {
		if (eDealXmlhttpArr[index].readyState == 4) {
			$("#div_language").html(eDealXmlhttpArr[index].responseText);
		}
		hideWaiting();
	}
	
	function setLangageID(lngID) {
		$("#langageID").val(lngID);
	}
	function saveMessage(msgType) {
		var f = document.forms[0];	
	
		var fileName = $("input[name='MsgAttFileName']").val().split('|');
		var file = $("input[name='MsgAttID']").val().split('|');
		
		msgType = (msgType == null)?"<%=codeMsgProduit%>":msgType;
		<% if (emlTypeDstObj == null){%>
			msgObjID = "";
		<%} else {%>	
			msgObjID = "<%= emlTypeDstObj%>";
		<%}%>
		var field = {"MsgLngRef" : $("#langageID").val(), "MsgAttFileName" : fileName, "MsgAttID" : file, "MsgCode" : f.EmlCode.value, "MsgType" : msgType, "MsgObjID" : msgObjID};
		var res = [];
		res[0] = {"type" : "Messages", "id" : "msgID", "fields" : field};
		var jsondata = JSON.stringify(res);
		$.ajax({
		   data: jsondata,
		   type: "POST",
		   url: '<fl:webapp/>/save_message.fl?id=' + $("input[name='id']").val() + '&langageID=' + $("#langageID").val(),
		   timeout: 20000,
		   contentType: "application/json;charset=utf-8",
		   dataType: 'json',
		   async: false,
		   success: analyseResponse
		});
		function analyseResponse(data) {
			if (data != null){
			  if (data.EmmID != ''){
			    //ID du nouveau massemailing créé
			  	$("input[name='id']").val(data.EmmID);
			  }
			  if (data.MsgID != ''){
			  	//ID du nouveau message créé
			  	$("#msgID").val(data.MsgID);
			  }
			  if (data.status != '' && msgType == "<%= codeMsgModele %>") {
			  	//ID du nouveau message créé
			  	if (data.status == "OK") alert('<fl:getMessage code="M9023" alt="Le modèle a été bien enregistré" js="true"/>')
			  	if (data.status == "NO") alert('<fl:getMessage code="M9024" alt="Erreur lors de l\\\'enregistrement du modèle" js="true"/>')
			  }
			}
		}
	}  
		  
	var isMassEmailingSaved = false;	  
	
	//Sauver la partie commune et le premier onglet
	function saveMassEmailing() {
		var rtn = true;
		var f = document.forms[0];	

		//partie commune
		var emlName = f.EmlName.value;
		var emlCode = f.EmlCode.value;
		var emlRegroupement = f.EmlRegroupement.value;
		var emlType = f.EmlType.value;
		var emlStatus = "<%= emlStatus %>";
		var emlOwner = f.EmlOwner.value;
		
		var field = {"EmlName" : emlName, "EmlCode" : emlCode, "EmlRegroupement" : emlRegroupement, "EmlType" : emlType, "EmlStatus" : emlStatus, "EmlOwner" : emlOwner};
		var res = [];
		res[0] = {"type": "MassEmailing", "id": "emlIDempty", "fields": field};
		var jsondata = JSON.stringify(res);
		$.ajax({
		   data: jsondata,
		   type: "POST",
		   url: '<fl:webapp/>/save_massemailing_ajax.fl',
		   timeout: 20000,
		   contentType: "application/json;charset=utf-8",
		   dataType: 'json',
		   async: false,
		   success: analyseResponse
		});
		function analyseResponse(data) {
			if ((data != null) && (data.status == "OK")){
			  if (data.EmlID != ''){
			    //ID du nouveau massemailing créé
			  	$("input[name='id']").val(data.EmlID);
			  }
			} else {
				rtn = false;
			}
		}
		
		if (rtn) 
			isMassEmailingSaved = true;
		else
			alert('<fl:getMessage code="L70BA" alt="Erreur lors de la création de l\\\'emailing" js="true"/>'); 
		
		return rtn;
	}  
		  
	var isMessageLoaded = false;
	
	function setMessageLoaded() {
		isMessageLoaded = true;
	}
	function saveMessageContent() {
		if (isMessageLoaded){
			saveMessage();
			isMessageLoaded = false;
		} 
	}
	
	function communsFieldsConditions() {
		var f = document.forms[0];	
		if (f.EmlName.value == '') {
			document.getElementById('EmlName_msg').style.display = "inline";
			alert('<fl:getMessage code="L63B1" alt="Veuillez saisir un nom" js="true"/>');
			f.EmlName.focus();
			return;
		}
		if (f.EmlCode.value == '') {
			document.getElementById('EmlCode_msg').style.display = "inline";
			alert('<fl:getMessage code="L6144" alt="Veuillez saisir un code" js="true"/>');
			f.EmlCode.focus();
			return;
		}
		if (f.EmlRegroupement.value == '') {
			document.getElementById('EmlRegroupement_msg').style.display = "inline";
			alert('<fl:getMessage code="M9007" alt="Veuillez saisir un code de regroupement" js="true"/>');
			f.EmlCode.focus();
			return;
		}
		if (f.EmlOwner.value == '') {
			document.getElementById('EmlOwner_msg').style.display = "inline";
			alert('<fl:getMessage code="L7019" alt="Veuillez saisir un auteur" js="true"/>');
			f.EmlOwner.focus();
			return;
		}
		return true;
	}
	function doSubmit() {
		//conditions sur les champs partagés
		var f = document.forms[0];	
		
		if (!communsFieldsConditions())
			return;

		//EmlDstSubsSil
		if (($('#EmlDstSubsPer').val() != '') && ($('#checkDstSubsSil').is(':checked'))) {
			$('#EmlDstSubsSil').val($('#EmlDstSubsPer').val());
		}

		//save sender type 
		$('#EmlSndType').val($('input[type=radio][name=exp]:checked').attr('value'));
		//save linksSelectBox value
		$('#EmlFltLinkElnID').val($('#linksSelectBox option:selected').val());
		//save date and time email send
		setDateAndTimeEmailSend();
		
		var msgAttIDs = $("input[name='MsgAttID']").val()
		if (msgAttIDs != '') {
			saveMessage();
		}	
			
		return true;
	}

	function setDateAndTimeEmailSend(){
		if($("#lblDate").val() != '') {
			if($("#lblTime").val() == '') {
				$("#lblTime").val('00:00');
			}
			$("#EmlSndDate").val($("#lblDate").val() + ' ' + $("#lblTime").val());
		}
	}
	
	function doOnLoad() {
		loadMessage($('#langageID').val());
		setMessageLoaded();
	}
</script>
<fl:form action="/save_bulkfaxing.fl" bean="MassEmailing">
	<fl:bigTabs
		objectTitle="<%= Utils.getMessage(session, \"L80C3\", \"Faxing en masse\") %>"
		listTitle="<%= Utils.getMessage(session, \"L80C3\", \"Faxing en masse\") %>"
		ou="<%= \"/edit_bulkfaxing.fl\" + (id != null ? \"?id=\" + id : \"\") %>">
		<input type="hidden" value="" name="EmlMailSendField" id="EmlMailSendField">
		<%-- date and time  --%>
		<input type="hidden" value="" name="EmlSndDate" id="EmlSndDate">
		<%-- type de destination --%>
		<input type="hidden" name="EmlTypeDst" id="EmlTypeDst" value="<%= codeDestSil %>"/>

		<input type="hidden" name="msgID" id="msgID">
		<input type="hidden" name="langageID" id="langageID" value="<%= langageID %>">

		<input type="hidden" name="EmlStatus" id="EmlStatus" value="<%= emlStatus %>">

		<input type="hidden" name="EmlType" id="EmlType" value="<%= emlTypeID %>">

		<table class="container" cellpadding="0">
			<tr>
				<td colspan="3">
					<table class="container" cellpadding="0">
						<tr class="fieldline">
							<td class="labelTitreFiche">
								<fl:label field="EmlName" labelClassName="titreFiche" />
							</td>
							<td class="fieldTitreFiche">
								<fl:input property="EmlName" mandatoryMsgCode="L63B1"/>
							</td>
						</tr>
					</table>
				</td>
			</tr>
			<tr>
				<td colspan="3" class="ligne_separation" />
			</tr>
			<tr>
				<td class="column2">
					<table class="data_column" cellpadding="0">
						<fl:fieldEdit property="EmlCode" mandatoryMsgCode="L6144" unicityMsgCode="M60E3"/>
						<fl:fieldEdit property="EmlRegroupement" mandatoryMsgCode="M9007">
							<fl:suggest table="MassEmailing" field="EmlRegroupement" caseSensitive="false" maxLimit="20" trigger="1" />
						</fl:fieldEdit>
					</table>
				</td>
				<td class="separation">
					<div class="separation"></div>
				</td>
				<td class="column2">
					<table class="data_column" cellpadding="0">
						<tr class="fieldline">
							<td class="dataLabel" id="EmlStatus_label">
								<div>
									<fl:label forInput="EmlStatusForDisplay" field="EmlStatus" />
								</div>
							</td>
							<td class="dataValue" id="EmlStatus_value">
								<div class="input text">
									<input readonly disabled class="input text"
										name="EmlStatusForDisplay" id="EmlStatusForDisplay"
										value="<fl:getProperty name="MassEmailing" property="EmlStatus" alt="<%= emlStatusDisp %>"/>">
								</div>
							</td>
						</tr>
						<fl:fieldEdit property="EmlOwner" mandatoryMsgCode="L7019" />
					</table>
				</td>
			</tr>
		</table>
		<link href="<fl:webapp/>/css/smalltabs_css.jsp" rel="stylesheet"
			type="text/css">
		<fl:smallTabs name="MassMailingTabs">
			
			<fl:sTab id="MESSAGE"
				title="<%= Utils.getMessage(session, \"F6002\", \"Message\") %>"
				onselect="javascript:loadMessage($('#langageID').val());setMessageLoaded();">
				<div id="message-editor" class="message-editor">
					<table border="0" cellspacing="0" cellpadding="0">
						<tr>
							<td width="80%"></td>
							<td width="20%">
								<div id="div_language"></div>
							</td>
						</tr>
					</table>
					<div id="div_attachement"></div>
				</div>
			</fl:sTab>
			<fl:sTab id="SENDING"
				title="<%= Utils.getMessage(session, \"L700F\", \"Envoi\") %>">
				<table class="container" cellpadding="0">
					<tr class="fieldline">
						<td class="column2">
							<table class="container" cellpadding="0">
								<tr class="fieldline">
									<td class="column2" colspan="2">
										<fieldset class="fieldset">
											<legend class="legend">
												<fl:getMessage code="L7036" alt="Expéditeur" />
											</legend>
											<br>
											<table class="container" cellpadding="0">
												<tr class="fieldline">
													<td class="column2" colspan="2">
														<table class="container" cellpadding="0">
															<tr class="fieldline">
																<td class="dataLabel" id="fixe_label">
																	<div>
																		<label title="<fl:getMessage code="L7039" alt="fixe"/>" for="fixe">
																			<input type="radio" name="exp" id="exp_fixe" value="fixe" checked>
																			<fl:getMessage code="L7039" alt="fixe" />
																		</label>
																	</div>
																</td>
																<td class="dataValue" id="fixe_value">
																	<div>
																		<fl:input property="EmlSndEnsID" comboFobThreshold="0" />
																	</div>
																</td>
															</tr>
														</table>
													</td>
												</tr>
												<tr class="fieldline">
													<td class="column2" colspan="2">
														<span
															style="font-size: 11px; font-family: Arial, Verdana, sans-serif; font-style: italic">
															<fl:getMessage code="L7034"
																alt="avec gestion des retours en erreur" /> </span>
													</td>
												</tr>
											</table>
										</fieldset>
									</td>
								</tr>							
							</table>
						</td>
						<td class="separation">
							<div class="separation"></div>
						</td>
						<td class="column2">
							<table class="container" cellpadding="0">
								
								<tr class="fieldline">
									<td id="EmlSndDate_label" class="dataLabel">
										<div>
											<label for="EmlSndDate"
												title="<fl:getMessage code="F700E" alt="Date d'envoi"/>">
												<fl:getMessage code="F700E" alt="Date d'envoi" />
											</label>
										</div>
									</td>
									<td style="white-space: nowrap; width: 50%;" class="dataValue">
										<input type="text"
											onblur="ctrlDateField(this, 'Veuillez saisir une date correcte du type jj/mm/aaaa.');"
											maxlength="10" size="10" value="<%= strDate %>"
											name="lblDate" id="lblDate" class="input Date">
										<a onmouseout="window.status=' '; return true"
											onmouseover="window.status='Afficher le calendrier';return true;"
											href="JavaScript:openCalendar(document.forms[0].lblDate)">
											<img class="icon"
												src="<fl:webapp/>/icons/ico/clock_neutre.gif"> </a>
										&nbsp;&nbsp;&nbsp;
										<input type="text" onblur="ctrlHourField(this, 'Veuillez saisir une heure correcte.');" maxlength="5" size="5" value="<%= strTime %>" class="input Time" name="lblTime" id="lblTime">
									</td>
								</tr>
								<fl:fieldEdit property="EmlSndEosID" comboFobThreshold="0"
									mandatoryMsgCode="L703A" />

							</table>
						</td>
					</tr>
				</table>
			</fl:sTab>			
		</fl:smallTabs>
	</fl:bigTabs>
</fl:form>