<%@page import="br.mp.mprj.portal.portlet.gestaomensagens.search.UserSearch"%>
<%@page import="br.mp.mprj.portal.portlet.gestaomensagens.service.service.EmailDestinatarioLocalServiceUtil"%>
<%@page import="br.mp.mprj.portal.portlet.gestaomensagens.service.model.GrupoDestinatario"%>
<%@page import="java.util.Calendar" %>
<%@page import="java.util.Date" %>
<%@ include file="/jsp/init.jsp" %>

<%@ include file="/jsp/admin/includes/menu-lateral-principal.jspf" %>

<%  

	//pagina (fragmento) utilizada para definir variaveis e atributos utilizados pelo modulo.
    GrupoDestinatario grupoDestinatario = (GrupoDestinatario) request.getAttribute("grupoDestinatario");
	if (grupoDestinatario == null) {
	    long grupoDestinatarioId = ParamUtil.getLong(request, "grupoDestinatarioId");
	    if (grupoDestinatarioId > 0) {
	    	grupoDestinatario = GrupoDestinatarioLocalServiceUtil.getGrupoDestinatario(grupoDestinatarioId);
	        pageContext.setAttribute("grupoDestinatario", grupoDestinatario );
	    }
	}
	
	Boolean isEdit = false;
	Calendar cal = Calendar.getInstance();
	 
	Calendar c = Calendar.getInstance();
	
	if (grupoDestinatario != null && grupoDestinatario.getDataFinalListaTemporaria() != null) {
		c.setTime(grupoDestinatario.getDataFinalListaTemporaria());
	} else {
		c.setTime(new Date());
	}
	
	int day = c.get(Calendar.DAY_OF_MONTH);
	int month = c.get(Calendar.MONTH);
	int year = c.get(Calendar.YEAR);
	int hourOfDay = c.get(Calendar.HOUR_OF_DAY);
	int minute = c.get(Calendar.MINUTE);
	
	//Lista utilizadas para a carga das tabelas durante o processo de edicao
	List<UserVO> listaModeracao =   null;
	List<UserVO> listaResponsaveis = null;
	List<UserVO> listaEmNome = null;
    List<String> dynamicListEmail = new ArrayList<String>();
	
    if (grupoDestinatario != null) {
	    List<EmailDestinatario> listaEmail =
	    				EmailDestinatarioLocalServiceUtil.findByGrupoDestinatarioId(grupoDestinatario.getGrupoDestinatarioId());
	   
	    for (EmailDestinatario email : listaEmail){
	        dynamicListEmail.add(email.getEmail());
	   	}
	}
%>

<liferay-portlet:renderURL var="redirect">
	<liferay-portlet:param name="mvcPath" value="/jsp/admin/destinatario/listagem.jsp"/>
</liferay-portlet:renderURL>

<liferay-portlet:actionURL var="gravarURLInclusao">
	<liferay-portlet:param name="<%= ActionRequest.ACTION_NAME %>" value='GrupoDestinatarioAlterarIncluir'/>
	<liferay-portlet:param name="mvcPath" value="/jsp/admin/destinatario/formulario.jsp"/>
</liferay-portlet:actionURL>

<div class="span10 context-pane">
	<div class="formulario-mensagem-dados">
		<liferay-ui:header title="destinatario.header.listagem"/>
		
		<div class="alert alert-error email-invalido" style="display:none"><liferay-ui:message key="destinarario.email.invalido"/></div>
		<div class="alert alert-error email-error" style="display:none"><liferay-ui:message key="destinarario.email.obrigatorio"/></div>
		<div class="alert alert-error email-one" style="display:none"><liferay-ui:message key="destinarario.email.one"/></div>

        <aui:model-context bean="<%= grupoDestinatario %>" model="<%= GrupoDestinatario.class %>" />

		<aui:form action="${gravarURLInclusao}" name="fmDestinatario" method="post">
			<aui:input name="redirect" value="${redirect}" type="hidden"/>
			<aui:input name="grupoDestinatarioId" value="${grupoDestinatario.grupoDestinatarioId}" type="hidden"/>
			<!--  <input id="" type="hidden" value="true"/>-->
	
			<% if (grupoDestinatario == null ) { %>
				<div>
				    <spam id="radioDestinatario">
					    <aui:input
                            name="tipoLista"
                            id="tipoDestinatario"
                            value="0"
                            label="destinatario.lista"
                            type="radio"
                            inlineField="true"
                            checked="${grupoDestinatario.tipoLista == 0}"
                            inlineLabel="left"
                            onClick="defineTipoLista(this);">
							<aui:validator name="required"/>
						</aui:input>
					</spam>
	  				<spam id="radioConta">
			    		<aui:input
			    		    name="tipoLista"
			    		    id="contaSaida"
			    		    value="1"
			    		    label="destinatario.conta"
			    		    type="radio"
			    		    inlineField="true"
			    		    checked="${grupoDestinatario.tipoLista == 1}"
			    		    inlineLabel="left"
			    		    onClick="defineTipoLista(this);">
							<aui:validator name="required"/>
						</aui:input>
					</spam>	
				</div>
			<% } else if (grupoDestinatario.getTipoLista() == 0) { %>
			    <style>
			        .visivel-ambos, .visivel-destinatario {
			            display: block !important;
			        }
			        .visivel-conta {
                        display: none !important;
                    }
			    </style>
				<p><liferay-ui:message key="destinatario.lista"/></p>
			<% } else if (grupoDestinatario.getTipoLista() == 1){ %>
			    <style>
                    .visivel-ambos, .visivel-conta {
                        display: block !important;
                    }
                    .visivel-destinatario {
                        display: none !important;
                    }
                </style>
				<p><liferay-ui:message key="destinatario.conta"/></p>
			<% } %>
	
			<div class="visivel-ambos" style="display:none">
				<aui:input
				    name="nome" 
					type="text"
					label="destinatario.nome" 
					required="true" 		
					inlineLabel="left"
					showRequiredLabel="false"
					cssClass="span6">
					<aui:validator name="maxLength">255</aui:validator>
				</aui:input>	
	
				<aui:input
					name="finalidade" 
					type="textarea"
					label="destinatario.finalidade" 
					rows="7"
					required="true" 
					showRequiredLabel="false" 
					cssClass="span7" />
							
                <div>
    				<liferay-ui:message key="destinatario.responsaveis"/>
                </div>
				
				<liferay-ui:icon
					iconCssClass="icon-search"
					id="selectUsuarioLinkResponsaveis"
					label="<%= true %>"
					linkCssClass="btn"
					message="destinatario.responsavel.selecionar"
					url="javascript:;" />
					
				<div class="alert alert-info responsaveis-user"><liferay-ui:message key="search.empty.responsaveis.associados"/></div>
				<%
					RowChecker ckResponsavel = new RowChecker(renderResponse);
					ckResponsavel.setAllRowIds("allRowIdsR");
					ckResponsavel.setRowIds("rowIdsR");
				%>
				<liferay-ui:search-container
				    id="userResponsaveis"
				    var="userSearchContainer"
				    headerNames="Nome,Email" 
			        rowChecker="<%= ckResponsavel %>">
				    <liferay-ui:search-container-results>
					    <% if (grupoDestinatario != null && grupoDestinatario.getUserIdResponsaveis() != null &&
					    				   !"".equals(grupoDestinatario.getUserIdResponsaveis())){
		        				UserSearch userSearch = new UserSearch();
								listaResponsaveis = UserSearch.pesquisar(renderRequest , grupoDestinatario.getUserIdResponsaveis());
								userSearchContainer.setResults(listaResponsaveis);
								userSearchContainer.setTotal(listaResponsaveis.size());
							}
						%> 	 
				    </liferay-ui:search-container-results>
				    <liferay-ui:search-container-row 
				        className="br.mp.mprj.portal.portlet.gestaomensagens.search.vo.UserVO"
				        escapedModel="true" 
				        keyProperty="userId"
				        modelVar="usuarios"
				        rowIdProperty="userId">
				        <liferay-ui:search-container-column-text
				            name="Nome"
				            property="fullName" />
				        
				        <liferay-ui:search-container-column-text
				            name="Email"
				            property="emailAddress" />
				        
				    </liferay-ui:search-container-row>
				
				    <liferay-ui:search-iterator />
			    
				</liferay-ui:search-container>
				
				<liferay-util:buffer var="htmlBtRemoverResponsaveis"> 
					<div>
						<aui:button
                            cssClass="remover-responsaveis"
                            type="button"
                            value="delete"
                            onClick="javascript:excluirResponsaveis()"/>
					</div>
				</liferay-util:buffer>
	
				${htmlBtRemoverResponsaveis}
			
				<p>
				    <br/>
					<liferay-ui:message key="destinatario.temporaria"/>			
				</p>
				
				<div>	
				    <aui:input
				        name="temporaria"
				        id="temporariaSim"
				        value="Sim"
				        label="destinatario.sim"
				        type="radio"
				        inlineField="true"
				        inlineLabel="left"
				        onClick="exibirCalendario();"
				        checked="${grupoDestinatario.listaTemporaria}">
						<aui:validator name="required"/>
					</aui:input>
		    		<aui:input
		    		    name="temporaria"
		    		    id="temporariaNao"
		    		    value="Não"
		    		    label="destinatario.nao"
		    		    type="radio"
		    		    inlineField="true"
		    		    inlineLabel="left"
		    		    onClick="exibirCalendario();"
		    		    checked="${grupoDestinatario.listaTemporaria == null or grupoDestinatario.listaTemporaria eq false}">
						<aui:validator name="required"/>
					</aui:input>
				</div>		
			
				<div id="divCalendario">
					<liferay-ui:message key="destinatario.datafim"/>
					<liferay-ui:input-date
					   cssClass="calendario"
					   formName="date"
					   yearValue="<%=year%>"
					   monthValue="<%=month%>"
					   dayValue="<%=day%>"
					   dayParam="d1"
					   monthParam="m1"
					   yearParam="y1"/>
				</div>
			</div>
			
			<div class="visivel-destinatario" style="display:none">
				<div>
	                <liferay-ui:message key="destinatario.moderada"/>
				</div>
	  	   
	            <aui:input
                    name="moderada"
                    id="moderadaSim"
                    value="Sim"
                    label="destinatario.sim"
                    type="radio"
                    inlineField="true"
                    inlineLabel="left"
                    onClick="exibirModerada();"
                    checked="${grupoDestinatario.listaModerada}">
	                <aui:validator name="required"/>
	            </aui:input>
	            
	            <aui:input
                    name="moderada"
                    id="moderadaNao"
                    value="Não"
                    label="destinatario.nao"
                    type="radio"
                    inlineField="true"
                    inlineLabel="left"
                    onClick="exibirModerada();"
                    checked="${grupoDestinatario.listaModerada == null or grupoDestinatario.listaModerada eq false}">
                    <aui:validator name="required"/>
                </aui:input>
		
	            <div id="divModerada">	
	
					<div>
						<liferay-ui:icon
							iconCssClass="icon-search"
							id="selectUsuarioLinkModeracao"
							label="<%= true %>"
							linkCssClass="btn"
							message="destinatario.moderada.selecionar"
							url="javascript:;" />
					</div>			
					<%
						RowChecker ckModerada = new RowChecker(renderResponse);
						ckModerada.setAllRowIds("allRowIdsM");
						ckModerada.setRowIds("rowIdsM");
					%>
					<liferay-ui:search-container
					    id="userModeracao"
					    var="userSearchModeracao"
						headerNames="Nome,Email" 
					    rowChecker="<%= ckModerada %>">
					    
					    <liferay-ui:search-container-results>
						    <% if (grupoDestinatario!= null && grupoDestinatario.getUserIdListaModerada() != null &&
						    				  !"".equals(grupoDestinatario.getUserIdListaModerada())){
			        				UserSearch userSearch = new UserSearch();
									listaModeracao = UserSearch.pesquisar(renderRequest , grupoDestinatario.getUserIdListaModerada() );
									userSearchModeracao.setResults(listaModeracao);
									userSearchModeracao.setTotal(listaModeracao.size());
			      			   }
			      			%> 	
			      			 
	                    </liferay-ui:search-container-results> 
					
					    <liferay-ui:search-container-row 
					        className="br.mp.mprj.portal.portlet.gestaomensagens.search.vo.UserVO"
					        escapedModel="true" 
					        keyProperty="userId"
					        modelVar="usuarios"
					        rowIdProperty="userId">
					        <liferay-ui:search-container-column-text
					            name="Nome"
					            property="fullName" />
					        
					        <liferay-ui:search-container-column-text
					            name="Email"
					            property="emailAddress" />
					        
					    </liferay-ui:search-container-row>
					
					    <liferay-ui:search-iterator />
					    
					</liferay-ui:search-container>
					
					<div class="alert alert-info moderacao-user"><liferay-ui:message key="search.empty.moderacao.associados"/></div>
					
					<liferay-util:buffer var="htmlBtRemoverModeracao">
						<div>
							<aui:button cssClass="remover-moderacao" type="button" value="delete" onClick="javascript:excluirModeracao()"/>
						</div>
					</liferay-util:buffer>
	
					${htmlBtRemoverModeracao}
					
				</div>
			</div>

			<div class="visivel-conta" style="display:none">
				<p>
					<br/>
				  	<liferay-ui:message key="destinatario.em.nome.lista"/>
				</p>
			  
			    <aui:input
                    name="emNome"
                    id="emNomeSim"
                    value="Sim"
                    label="destinatario.sim"
                    type="radio"
                    inlineField="true"
                    inlineLabel="left"
                    onClick="exibirEmNome();"
                    checked="${grupoDestinatario.envioEmNomeLista}">
                    <aui:validator name="required"/>
				</aui:input>
				
				<aui:input
                    name="emNome"
                    id="emNomeNao"
                    value="Não"
                    label="destinatario.nao"
                    type="radio"
                    inlineField="true"
                    inlineLabel="left"
                    onClick="exibirEmNome();"
                    checked="${grupoDestinatario.envioEmNomeLista == null or grupoDestinatario.envioEmNomeLista eq false}">
                    <aui:validator name="required"/>
                </aui:input>
						
				<div id="divEmNome">
					<div>
						<liferay-ui:icon
							cssClass="selecionar-usuarios"
							iconCssClass="icon-search"
							id="selectUsuarioLinkEmNome"
							label="<%= true %>"
							linkCssClass="btn"
							message="destinatario.emnome.selecionar"
							url="javascript:;" />
					</div>
					<%
						RowChecker ckEmNome = new RowChecker(renderResponse);
						ckEmNome.setAllRowIds("allRowIdsE");
						ckEmNome.setRowIds("rowIdsE");
					%>	
					
					<liferay-ui:search-container
			                     id="userEmNome"
						headerNames="Nome,Email" 
					    rowChecker="<%= ckEmNome %>"
					    var="userSearchEmNome">
					    
					    <liferay-ui:search-container-results>
						    <% 
						        if (grupoDestinatario != null && grupoDestinatario.getUserIdNomesLista() != null &&
						        				  !"".equals(grupoDestinatario.getUserIdNomesLista())){
			        				UserSearch userSearch = new UserSearch();
									listaEmNome = UserSearch.pesquisar(renderRequest , grupoDestinatario.getUserIdNomesLista() );
									userSearchEmNome.setResults(listaEmNome);
									userSearchEmNome.setTotal(listaEmNome.size());
			      			 	}
			      			%> 	 
					    </liferay-ui:search-container-results>
					    
					    <liferay-ui:search-container-row 
					        className="br.mp.mprj.portal.portlet.gestaomensagens.search.vo.UserVO"
					        escapedModel="true" 
					        keyProperty="userId"
					        modelVar="usuarios"
					        rowIdProperty="userId">
					        <liferay-ui:search-container-column-text
					            name="Nome"
					            property="fullName" />
					        
					        <liferay-ui:search-container-column-text
					            name="Email"
					            property="emailAddress" />
					    </liferay-ui:search-container-row>
					    <liferay-ui:search-iterator />
					</liferay-ui:search-container>
					
					<div class="alert alert-info emnome-user"><liferay-ui:message key="search.empty.emnome.associados"/></div>			
					
					<liferay-util:buffer var="htmlBtRemoverEmNome">
						<div>
							<aui:button cssClass="remover-emnome" type="button" value="delete" onClick="javascript:excluirEmNome()"/>
						</div>
					</liferay-util:buffer>
			
					${htmlBtRemoverEmNome}
					
					<br/>
	 				<br/>
				</div>
			</div>
		
		    <div>
		    	<p></p>
		    </div>
		    
			<div class="visivel-ambos" style="display:none">
			
				<p class="visivel-destinatario" >
					<liferay-ui:message key="destinatario.inserir.email"/>:
				</p>
				
				<p class="visivel-conta">
					<liferay-ui:message key="saida.inserir.email"/>:
				</p>
															
				<aui:input name="destinatario" 
							type="text"
							label="destinatario.email" 
							required="false" 
							inlineLabel="left"
							inlineField="false"
							showRequiredLabel="false"
							cssClass="span6">
					<aui:validator name="email"/>
					<aui:validator name="maxLength">75</aui:validator>
				</aui:input>
						
				<liferay-ui:icon
					cssClass="selecionar-usuarios"
					id="btnEmailDestinatario"
					label="<%= true %>"
					linkCssClass="btn"
					message="destinatario.adicionar.email"
					url="javascript:;" />
				
				<div class="alert alert-info emails-user"><liferay-ui:message key="search.empty.emails.associados"/></div>	
				<%
					RowChecker ckEmailDest = new RowChecker(renderResponse);
					ckEmailDest.setAllRowIds("allRowIdsD");
					ckEmailDest.setRowIds("rowIdsD");
				%>
				
				<liferay-ui:search-container
                    id="emailDestinatarios"
                    var="userSearchEmail"
					headerNames="email" 
				    rowChecker="<%= ckEmailDest %>">
				
				    <liferay-ui:search-container-row 
				        className="br.mp.mprj.portal.portlet.gestaomensagens.search.vo.UserVO"
				        escapedModel="true">
				        <liferay-ui:search-container-column-text
				            name="Email"
				            property="emailAddress" />
				    </liferay-ui:search-container-row>
				    <liferay-ui:search-iterator />
				    
				</liferay-ui:search-container>
				
				<liferay-util:buffer var="htmlBtRemoverEmailDestinatarios">
					<div>
						<aui:button
                            cssClass="remover-emaildestinatarios"
                            type="button"
                            value="delete"
                            onClick="javascript:excluirEmailDestinatarios()"/>
					</div>
				</liferay-util:buffer>
		
				${htmlBtRemoverEmailDestinatarios}	
			</div>
	
			<aui:button-row>
		        <aui:button type="button" cssClass="btn-primary" onClick="gravar();" value="Salvar" name="btDadosGrupos" />
				<input
				    type="button"
				    value="Cancelar"
				    class="btn btn-cancel"
				    onClick="javascript:window.location.href = $('#<portlet:namespace/>redirect').val()" />
			</aui:button-row>	
        </aui:form>
    </div>
</div>

<liferay-portlet:renderURL var="selUsuariosURLR" windowState="<%=LiferayWindowState.POP_UP.toString()%>">
	<liferay-portlet:param name="mvcPath" value="/jsp/admin/destinatario/user-popup.jsp"/>
	<liferay-portlet:param name="tipoSelecao" value="R"/>
</liferay-portlet:renderURL>

<liferay-portlet:renderURL var="selUsuariosURLM" windowState="<%=LiferayWindowState.POP_UP.toString()%>">
	<liferay-portlet:param name="mvcPath" value="/jsp/admin/destinatario/user-popup.jsp"/>
	<liferay-portlet:param name="tipoSelecao" value="M"/>
</liferay-portlet:renderURL>	

<liferay-portlet:renderURL var="selUsuariosURLN" windowState="<%=LiferayWindowState.POP_UP.toString()%>">
	<liferay-portlet:param name="mvcPath" value="/jsp/admin/destinatario/user-popup.jsp"/>
	<liferay-portlet:param name="tipoSelecao" value="N"/>
</liferay-portlet:renderURL>
		
<script>

function exibirCalendario(){
	var temporariaSim = $("#<portlet:namespace />temporariaSim:checked");
	var calendario = $("#divCalendario");
	if (temporariaSim.val() == "Sim"){
		calendario.css("display", "block");
	} else{
		calendario.css("display", "none");
	}
}
function exibirModerada(){
	var moderadaSim = $("#<portlet:namespace />moderadaSim:checked");
	var moderada = $("#divModerada");
	if (moderadaSim.val() == "Sim"){
		moderada.css("display", "block");
	} else{
		moderada.css("display", "none");
	}
}

function exibirEmNome(){
	var emNomeSim = $("#<portlet:namespace />emNomeSim:checked");
	var emNome = $("#divEmNome");
	if (emNomeSim.val() == "Sim"){
		emNome.css("display", "block");
    } else{
    	emNome.css("display", "none");
	}
}

</script>

<aui:script use="node, liferay-search-container">

var dialogId = 'dialogSelUser';
var searchContainerResponsaveis = Liferay.SearchContainer.get('<portlet:namespace />userResponsaveis');
var searchContainerModeracao = Liferay.SearchContainer.get('<portlet:namespace />userModeracao');
var searchContainerEmNome = Liferay.SearchContainer.get('<portlet:namespace />userEmNome');
var searchContainerEmailDestinatarios= Liferay.SearchContainer.get('<portlet:namespace />emailDestinatarios');

var templateChkBoxSearchR = "<input name='<portlet:namespace/>rowIdsR' type='checkbox' value='_ID_' onclick='Liferay.Util.checkAllBox(AUI().one(this).ancestor('.table'), '<portlet:namespace/>rowIdsR', '<portlet:namespace/>allRowIdsR');AUI().one(this).ancestor('tr:not(.lfr-template)').toggleClass('info');'>";
var templateChkBoxSearchM = "<input name='<portlet:namespace/>rowIdsM' type='checkbox' value='_ID_' onclick='Liferay.Util.checkAllBox(AUI().one(this).ancestor('.table'), '<portlet:namespace/>rowIdsM', '<portlet:namespace/>allRowIdsM');AUI().one(this).ancestor('tr:not(.lfr-template)').toggleClass('info');'>";
var templateChkBoxSearchE = "<input name='<portlet:namespace/>rowIdsE' type='checkbox' value='_ID_' onclick='Liferay.Util.checkAllBox(AUI().one(this).ancestor('.table'), '<portlet:namespace/>rowIdsE', '<portlet:namespace/>allRowIdsE');AUI().one(this).ancestor('tr:not(.lfr-template)').toggleClass('info');'>";
var templateChkBoxSearchD = "<input name='<portlet:namespace/>rowIdsD' type='checkbox' value='_ID_' onclick='Liferay.Util.checkAllBox(AUI().one(this).ancestor('.table'), '<portlet:namespace/>rowIdsD', '<portlet:namespace/>allRowIdsD');AUI().one(this).ancestor('tr:not(.lfr-template)').toggleClass('info');'>";

A.one('#<portlet:namespace />btnEmailDestinatario').on(
		'click',
		function(event) {
			adicionarEmailDestintarios();
		}
	);

A.one('#<portlet:namespace />selectUsuarioLinkResponsaveis').on(
	'click',
	function(event) {
		exibirSelUserPopupResponsaveis();
	}
);

A.one('#<portlet:namespace />selectUsuarioLinkModeracao').on(
		'click',
		function(event) {
			exibirSelUserPopupModeracao();
		}
	);

A.one('#<portlet:namespace />selectUsuarioLinkEmNome').on(
		'click',
		function(event) {
			exibirSelUserPopupEmNome();
		}
	);

Liferay.provide(
        window,
        'associarUsuariosResponsaveis',
        function(usuarios) {
			Liferay.Util.getWindow(dialogId).hide();

			if (usuarios != undefined && usuarios != null) {
				for (var i = 0; i < usuarios.length; i++) {
					var usu = usuarios[i];
					
					if (possuiUsuarioResponsaveis(usu.id)) continue;

		            var rowColumns = [];

		            rowColumns.push(templateChkBoxSearchR.replace("_ID_", usu.id));
		            rowColumns.push(usu.fullName);
		            rowColumns.push(usu.emailAddress);
		            searchContainerResponsaveis.addRow(rowColumns, usu.id);
		            searchContainerResponsaveis.updateDataStore();
		         
		         }
				
				ocultarMensagemResponsaveis(true);	
				ocultarExibirBtExclusaoResponsaveis(searchContainerResponsaveis.getData() != '');
			}

        }
    );

Liferay.provide(
        window,
        'associarUsuariosModeracao',
        function(usuarios) {
			Liferay.Util.getWindow(dialogId).hide();

			if (usuarios != undefined && usuarios != null) {
				for (var i = 0; i < usuarios.length; i++) {
					var usu = usuarios[i];
					
					if (possuiUsuarioModeracao(usu.id)) continue;

		            var rowColumns = [];

		            rowColumns.push(templateChkBoxSearchM.replace("_ID_", usu.id));
		            rowColumns.push(usu.fullName);
		            rowColumns.push(usu.emailAddress);

		            searchContainerModeracao.addRow(rowColumns, usu.id);
		            searchContainerModeracao.updateDataStore();
				}

				ocultarMensagemModeracao(true);
				ocultarExibirBtExclusaoModeracao(searchContainerModeracao.getData() != '');
			}

        }
    );

Liferay.provide(
        window,
        'associarUsuariosEmNome',
        function(usuarios) {
			Liferay.Util.getWindow(dialogId).hide();

			if (usuarios != undefined && usuarios != null) {
				for (var i = 0; i < usuarios.length; i++) {
					var usu = usuarios[i];

					if (possuiUsuarioEmNome(usu.id)) continue;

		            var rowColumns = [];

		            rowColumns.push(templateChkBoxSearchE.replace("_ID_", usu.id));
		            rowColumns.push(usu.fullName);
		            rowColumns.push(usu.emailAddress);

		            searchContainerEmNome.addRow(rowColumns, usu.id);
		            searchContainerEmNome.updateDataStore();
				}

				ocultarMensagemEmNome(true);
				ocultarExibirBtExclusaoEmNome(searchContainerEmNome.getData() != '');
			}
        }
    );


Liferay.provide(
        window,
        'adicionarEmailDestintarios',
        function() {
				ocultarMensagemEmailInvalido(true);
        	
               if (codigoTipoLista != 0 && codigoTipoLista!= 1 && <%=(grupoDestinatario == null)%>) return;

        		var email = A.one('#<portlet:namespace />destinatario').val();       

        		email = $.trim(email);

        		if (email != ""){

            		if (possuiEmail(email)){
						   return;										
                		}

        			<% if (grupoDestinatario == null ) { %>

            		 if (codigoTipoLista == '1' && searchContainerEmailDestinatarios.getData() != '') {
            			  ocultarMensagemSomenteUmEmail(false);
            			  window.scroll(0,0);
                		  return;
            		 } 

            		<% } else {  %>
						
            			if (<%=grupoDestinatario.getTipoLista()%>  == 1 && searchContainerEmailDestinatarios.getData() != ''){

            				  ocultarMensagemSomenteUmEmail(false);
                			  window.scroll(0,0);
                    		  return;

                			} 

            		<% } %>		  

            		if (!is_email(email)){
            			ocultarMensagemEmailInvalido(false);
            			 window.scroll(0,0);
            			return;
                	}
                		 

        		    var rowColumns = [];

       	            rowColumns.push(templateChkBoxSearchD.replace("_ID_", email));
       	            rowColumns.push(email);
       	            
       	            searchContainerEmailDestinatarios.addRow(rowColumns, email);
       	            searchContainerEmailDestinatarios.updateDataStore();

       	            ocultarMensagemEmails(true);
       	            ocultarExibirBtExclusaoEmailDestintarios(searchContainerEmailDestinatarios.getData() != '');

       	           var emailComponent = A.one('#<portlet:namespace />destinatario');
       	           emailComponent.val("");
            	}
        	 
        }
);



Liferay.provide(
        window,
        'adicionarEmailsDinamicos',
        function() {

        		<% if (dynamicListEmail.size() > 0) { 

					for (String email : dynamicListEmail){
            	%>
        		    var rowColumns = [];

       	            rowColumns.push(templateChkBoxSearchD.replace("_ID_", '<%=email%>'));
       	            rowColumns.push('<%=email%>');
       	            
       	            searchContainerEmailDestinatarios.addRow(rowColumns, '<%=email%>');
       	            searchContainerEmailDestinatarios.updateDataStore();

       	            ocultarMensagemEmails(true);
    	            ocultarExibirBtExclusaoEmailDestintarios(searchContainerEmailDestinatarios.getData() != '');
       	            
        		<% }} %>

        		   
        }
);
	
Liferay.provide(
        window,
        'exibirSelUserPopupResponsaveis',
        function() {
            Liferay.Util.openWindow({ 
       	     dialog: { 
       	             centered: true, 
       	             modal: true
       	             }, 
       	     id: dialogId, 
       	     title: "<liferay-ui:message key='mensagem.selecionar-usuarios' />", 
       	     uri: '${selUsuariosURLR}'
            });				
        }
);
var codigoTipoLista;
Liferay.provide(
    window,
    'defineTipoLista',
    function(radio) {
    	codigoTipoLista = radio.value;
    	$('.visivel-ambos').css('display', 'block');
     	if (codigoTipoLista == 0) {
         	$('#radioConta').css('display', 'none');

         	$('.visivel-destinatario').css('display', 'block');
            $('.visivel-conta').css('display', 'none');

        } else {
            
        	//$("#validaEmailDestinatario").val(false);
         	$('#radioDestinatario').css('display', 'none');

         	$('.visivel-conta').css('display', 'block');
            $('.visivel-destinatario').css('display', 'none');
        }
    }
);

Liferay.provide(
        window,
        'exibirSelUserPopupModeracao',
        function() {
            Liferay.Util.openWindow({ 
       	     dialog: { 
       	             centered: true, 
       	             modal: true
       	             }, 
       	     id: dialogId, 
       	     title: "<liferay-ui:message key='mensagem.selecionar-usuarios' />",
       	     uri: '${selUsuariosURLM}'
            });				
        }
);


Liferay.provide(
        window,
        'exibirSelUserPopupEmNome',
        function() {
            Liferay.Util.openWindow({ 
       	     dialog: { 
       	             centered: true, 
       	             modal: true
       	             }, 
       	     id: dialogId, 
       	     title: "<liferay-ui:message key='mensagem.selecionar-usuarios' />",
       	     uri: '${selUsuariosURLN}'
            });				
        }
);

function possuiUsuarioResponsaveis(userId) {
    var ids = searchContainerResponsaveis.getData(true); //retorna um array (parametro true)
    var index = A.Array.indexOf(ids, userId.toString());
    return (index > -1);
}

function possuiUsuarioModeracao(userId) {
    var ids = searchContainerModeracao.getData(true); //retorna um array (parametro true)
    var index = A.Array.indexOf(ids, userId.toString());
    return (index > -1);
}

function possuiUsuarioEmNome(userId) {
    var ids = searchContainerEmNome.getData(true); //retorna um array (parametro true)
    var index = A.Array.indexOf(ids, userId.toString());
    return (index > -1);
}

function possuiEmail(userId) {
    var ids = searchContainerEmailDestinatarios.getData(true); //retorna um array (parametro true)
    var index = A.Array.indexOf(ids, userId.toString());
    return (index > -1);
}

function ocultarExibirBtExclusaoResponsaveis(exibir)	{
	var div = A.one("button.remover-responsaveis");
	if (div != null) {
    	if (exibir) {
    		div.show();
    	}
    	else {
			div.hide();
		}
	}
}	

function ocultarExibirBtExclusaoModeracao(exibir)	{
	var div = A.one("button.remover-moderacao");
	if (div != null) {
    	if (exibir) {
    		div.show();
    	}
    	else {
			div.hide();
		}
	}
}	

function ocultarExibirBtExclusaoEmNome(exibir)	{
	var div = A.one("button.remover-emnome");
	if (div != null) {
    	if (exibir) {
    		div.show();
    	}
    	else {
			div.hide();
		}
	}
}	

function ocultarExibirBtExclusaoEmailDestintarios(exibir)	{
	var div = A.one("button.remover-emaildestinatarios");
	if (div != null) {
    	if (exibir) {
    		div.show();
    	}
    	else {
			div.hide();
		}
	}
}	

Liferay.provide(
        window,
        'excluirResponsaveis',
        function() {

			var idsSel = Liferay.Util.listChecked(document.<portlet:namespace/>fmDestinatario).split(',');
			if (idsSel != null) {
				for (var i = 0; i < idsSel.length; i++) {
					var id = idsSel[i];
					
					if (id == 'on' || id == '') continue;

					//obter o elemento TR relacionado com o checkbox, para exclusao
					var tr = A.one("input[name='<portlet:namespace/>rowIdsR'][value='" +  id + "']").ancestor("tr");
		            
		            searchContainerResponsaveis.deleteRow(tr, id);						
				}
			}

			ocultarMensagemResponsaveis(searchContainerResponsaveis.getData() != '');
			ocultarExibirBtExclusaoResponsaveis(searchContainerResponsaveis.getData() != '');
        },
        ['liferay-util-list-fields']
);

Liferay.provide(
        window,
        'excluirModeracao',
        function() {

			var idsSel = Liferay.Util.listChecked(document.<portlet:namespace/>fmDestinatario).split(',');
			if (idsSel != null) {
				for (var i = 0; i < idsSel.length; i++) {
					var id = idsSel[i];
					
					if (id == 'on' || id == '') continue;

					//obter o elemento TR relacionado com o checkbox, para exclusao
					var tr = A.one("input[name='<portlet:namespace/>rowIdsM'][value='" +  id + "']").ancestor("tr");
		            
		            searchContainerModeracao.deleteRow(tr, id);						
				}
			}

			ocultarMensagemModeracao(searchContainerModeracao.getData() != '');
			ocultarExibirBtExclusaoModeracao(searchContainerModeracao.getData() != '');
        },
        ['liferay-util-list-fields']
);

Liferay.provide(
        window,
        'excluirEmNome',
        function() {

			var idsSel = Liferay.Util.listChecked(document.<portlet:namespace/>fmDestinatario).split(',');
			if (idsSel != null) {
				for (var i = 0; i < idsSel.length; i++) {
					var id = idsSel[i];
					
					if (id == 'on' || id == '') continue;

					//obter o elemento TR relacionado com o checkbox, para exclusao
					var tr = A.one("input[name='<portlet:namespace/>rowIdsE'][value='" +  id + "']").ancestor("tr");
		            
		            searchContainerEmNome.deleteRow(tr, id);						
				}
			}
			ocultarMensagemEmNome(searchContainerEmNome.getData() != '');
			ocultarExibirBtExclusaoEmNome(searchContainerEmNome.getData() != '');
        },
        ['liferay-util-list-fields']
);

Liferay.provide(
        window,
        'excluirEmailDestinatarios',
        function() {

			var idsSel = Liferay.Util.listChecked(document.<portlet:namespace/>fmDestinatario).split(',');
			if (idsSel != null) {
				for (var i = 0; i < idsSel.length; i++) {
					var id = idsSel[i];
					
					if (id == 'on' || id == '') continue;

					//obter o elemento TR relacionado com o checkbox, para exclusao
					var tr = A.one("input[name='<portlet:namespace/>rowIdsD'][value='" +  id + "']").ancestor("tr");
		            
					searchContainerEmailDestinatarios.deleteRow(tr, id);
				}
			}
			ocultarMensagemEmails(searchContainerEmailDestinatarios.getData() != '');
			ocultarExibirBtExclusaoEmailDestintarios(searchContainerEmailDestinatarios.getData() != '');
        },
        ['liferay-util-list-fields']
);


Liferay.provide(
        window,
        'ocultarMensagemResponsaveis',
        function(ocultar) {

        	var div = A.one(".alert-info.responsaveis-user");
        	if (div != null) {
            	if (ocultar) {
            		div.hide();
            	}
            	else {
            		div.show();
        		}
        	}
        }
);



Liferay.provide(
        window,
        'ocultarMensagemEmailObrigatorio',
        function(ocultar) {

        	var div = A.one(".alert.alert-error.email-error"); 
        	if (div != null) {
            	if (ocultar) {
            		div.hide();
            	}
            	else {
            		div.show();
        		}
        	}
        }
);

Liferay.provide(
        window,
        'ocultarMensagemSomenteUmEmail',
        function(ocultar) {

        	var div = A.one(".alert.alert-error.email-one"); 
        	if (div != null) {
            	if (ocultar) {
            		div.hide();
            	} else {
            		div.show();
        		}
        	}
        }
);

Liferay.provide(
        window,
        'ocultarMensagemModeracao',
        function(ocultar) {

        	var div = A.one(".alert-info.moderacao-user");
        	if (div != null) {
            	if (ocultar) {
            		div.hide();
            	} else {
            		div.show();
        		}
        	}
        }
);

Liferay.provide(
        window,
        'exibirOcultarEmailObrigatorio',
        function(ocultar) {

        	var div = A.one(".alert-info.moderacao-user");
        	if (div != null) {
            	if (ocultar) {
            		div.hide();
            	} else {
            		div.show();
        		}
        	}
        }
);

Liferay.provide(
        window,
        'ocultarMensagemEmNome',
        function(ocultar) {

        	var div = A.one(".alert-info.emnome-user");
        	if (div != null) {
            	if (ocultar) {
            		div.hide();
            	} else {
            		div.show();
        		}
        	}
        }
);


Liferay.provide(
        window,
        'ocultarMensagemEmails',
        function(ocultar) {

        	var div = A.one(".alert-info.emails-user");
        	if (div != null) {
            	if (ocultar) {
            		div.hide();
            	} else {
            		div.show();
        		}
        	}
        }
);

Liferay.provide(
        window,
        'ocultarMensagemEmailInvalido',
        function(ocultar) {

        	var div = A.one(".email-invalido");
        	if (div != null) {
            	if (ocultar) {
            		div.hide();
            	} else {
            		div.show();
        		}
        	}
        }
);


/*
Liferay.provide(
        window,
        'isEmail',
        function(email) {

        	var exclude=/[^@-.w]|^[_@.-]|[._-]{2}|[@.]{2}|(@)[^@]*1/;
            var check=/@[w-]+./;
            var checkend=/.[a-zA-Z]{2,3}$/;
            if(((email.search(exclude) != -1)||(email.search(check)) == -1)||(email.search(checkend) == -1)){return false;}
            else {return true;}
        }
);*/

Liferay.provide(
        window,
        'gravar',
        function() {
        	/*<% if (grupoDestinatario != null && grupoDestinatario.getTipoLista() == 1) { %>
        	    codigoTipoLista = 1;
        	    $("#validaEmailDestinatario").val(false);
        	<% } %>*/

          //  if (searchContainerEmailDestinatarios.getData() == '' && codigoTipoLista == 0){
          if (searchContainerEmailDestinatarios.getData() == ''){
            	ocultarMensagemEmailObrigatorio(false);
            	window.scroll(0,0);
            } else {
                submitForm(document.<portlet:namespace/>fmDestinatario);
            }

        }
);
	ocultarExibirBtExclusaoResponsaveis(searchContainerResponsaveis.getData() != '');
	ocultarExibirBtExclusaoModeracao(searchContainerModeracao.getData() != '');
	ocultarExibirBtExclusaoEmNome(searchContainerEmNome.getData() != '');
	ocultarExibirBtExclusaoEmailDestintarios(searchContainerEmailDestinatarios.getData() != '');
	ocultarMensagemEmails(searchContainerEmailDestinatarios.getData() != ''); 
	
	exibirCalendario();
	exibirModerada();
	exibirEmNome();
	ocultarMensagemEmailObrigatorio(true);
	ocultarMensagemSomenteUmEmail(true);
	adicionarEmailsDinamicos();

	<% if (listaResponsaveis != null) { %>
	ocultarMensagemResponsaveis(true);
	<% } %>	

	<% if (listaModeracao != null) { %>
	ocultarMensagemModeracao(true);
	<% } %>	

	<% if (listaEmNome != null) { %>
	ocultarMensagemEmNome(true);
	<% } %>	


</aui:script>	    

<script type="text/javascript">


	function is_email(email) {

	    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	    return re.test(email);
	}
	
	document.getElementById("<portlet:namespace />nome").focus();
</script>
	    