<%@ include file="/jsp/init.jsp" %>

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

<div class="span10 context-pane">

	<%  
		String cabecalho = StringPool.BLANK;
		String rodape = StringPool.BLANK;
		String corpo = StringPool.BLANK;
		
		Template template = null;
	    long templateId = ParamUtil.getLong(request, "templateId");
	    
	    if (templateId > 0) {
	    	template = TemplateLocalServiceUtil.getTemplate(templateId);
	    } else {
	    	template = (Template) request.getAttribute("template");
	    }
	    
	    if (template != null){
	    	//preencher variaveis que serao utilizadas em funcoes com scriptlet
	        cabecalho = template.getCabecalho();
	        rodape = template.getRodape();
	        corpo = template.getCorpo();
	        pageContext.setAttribute("template", template);
	    }
		
	%>	
	
	<aui:model-context bean="<%= template %>" model="<%= Template.class %>" />
	
	<liferay-ui:header title="template.header.formulario.edicao"/>
	
	<div class="formulario-template">
	
		<liferay-ui:error key="template.nome.existe" message="template.nome.existe"/>
	
		<liferay-portlet:renderURL var="redirect">
			<liferay-portlet:param name="mvcPath" value="/jsp/admin/template/listagem.jsp"/>
			<liferay-portlet:param name="rascunho" value="${param.rascunho}"/>
			<liferay-portlet:param name="wizard" value="${param.wizard}"/>
		</liferay-portlet:renderURL>
		
		<liferay-portlet:actionURL var="gravarURL">
			<liferay-portlet:param name="<%= ActionRequest.ACTION_NAME %>" value='TemplateAlterarIncluir'/>
			<liferay-portlet:param name="mvcPath" value="/jsp/admin/template/edicao.jsp"/>
			<liferay-portlet:param name="rascunho" value="${param.rascunho}"/>
			<liferay-portlet:param name="wizard" value="${param.wizard}"/>
			<liferay-portlet:param name="redirect" value="${param}"/>
		</liferay-portlet:actionURL>
		
		<c:if test="${param.wizard eq true}">
			<liferay-portlet:renderURL var="proximaPaginaURL">
				<liferay-portlet:param name="mvcPath" value="/jsp/admin/mensagem/formulario.jsp"/>
				<liferay-portlet:param name="wizard" value="${param.wizard}"/>
				<liferay-portlet:param name="passoAtual" value="2"/>
				<liferay-portlet:param name="exibirProximoPasso" value="true"/>
				<liferay-portlet:param name="rascunho" value="${param.rascunho}"/>
			</liferay-portlet:renderURL>	
		</c:if>
	
		<aui:form action="${gravarURL}" name="fmDados" method="post" enctype="multipart/form-data">
			<aui:input name="redirect" value="${redirect}" type="hidden"/>
			<aui:input name="rascunho" value="${param.rascunho}" type="hidden"/>
			<aui:input name="wizard" value="${param.wizard}" type="hidden"/>
			<aui:input name="templateId" value="<%=template.getTemplateId()%>" type="hidden"/>
			
			<aui:input name="nome" label="template.nome" required="true"/>
		
			<aui:field-wrapper label="template.estilo">
				<aui:input name="estilo" 
					value="0" 
					type="radio" 
					label="template.estilo.cabecalho-rodape" 
					checked="${empty template or template.estilo == 0 ? true : false}" 
					required="true" 
					onClick="exibirEditor(this.value);previewConteudo()"/>
					
				<aui:input name="estilo" 
					value="1" 
					type="radio" 
					label="template.estilo.corpo"
					checked="${template.estilo == 1 ? true : false}" 
					required="true" 
					onClick="exibirEditor(this.value);previewConteudo()"/>	
			</aui:field-wrapper>	
			
			<aui:field-wrapper label="template.cabecalho" cssClass="cabecalho-wrapper">
				<div class="alert alert-error validacao cabecalho"><liferay-ui:message key="template.validacao.erro.cabecalho"/></div>
				<liferay-ui:input-editor 
						editorImpl="<%= EDITOR_WYSIWYG_IMPL_KEY %>" 
						initMethod='<%= "initEditorCabecalho" %>' 
						toolbarSet="liferay-article" 
						name="editorCabecalho"
						onChangeMethod="previewConteudoEventoEditor"/>
				<aui:input name="cabecalho" type="hidden" value="${template.cabecalho}" />
			</aui:field-wrapper>
			
			<aui:field-wrapper label="template.rodape" cssClass="rodape-wrapper">
				<div class="alert alert-error validacao rodape"><liferay-ui:message key="template.validacao.erro.rodape"/></div>
				<liferay-ui:input-editor 
						editorImpl="<%= EDITOR_WYSIWYG_IMPL_KEY %>" 
						initMethod='<%= "initEditorRodape" %>' 
						toolbarSet="liferay-article" 
						name="editorRodape"
						onChangeMethod="previewConteudoEventoEditor"/>	
				<aui:input name="rodape" type="hidden" value="${template.rodape}"/>
			</aui:field-wrapper>
			
			<aui:field-wrapper label="template.corpo" cssClass="corpo-wrapper">
				<div class="alert alert-error validacao corpo"><liferay-ui:message key="template.validacao.erro.corpo"/></div>
				<liferay-ui:input-editor 
						editorImpl="<%= EDITOR_WYSIWYG_IMPL_KEY %>" 
						initMethod='<%= "initEditorCorpo" %>' 
						toolbarSet="liferay-article" 
						name="editorCorpo"
						onChangeMethod="previewConteudoEventoEditor"/>	
				<aui:input name="corpo" type="hidden" value="${template.corpo}"/>
			</aui:field-wrapper>
			
			<aui:field-wrapper label="template.imagem-miniatura">
			<liferay-ui:message key="template.imagem-miniatura.instrucoes"/>
			
				<aui:input name="imgThumb" type="file" label="">
					<aui:validator name="acceptFiles">'jpg,png'</aui:validator>
				</aui:input>
				
				<c:if test="${not empty template.thumbnailURL}">
					<div id="preview-thumbnail">
						<img alt="Imagem de thumbnail" src='<%=ImagemUtil.getUrlThumbnailTemplate(renderRequest, template.getThumbnailURL())%>'>
					</div>
				</c:if>
			</aui:field-wrapper>
			
			<!-- DIV que sera utilizado como 'corpo' no preview, quando o estilo
			cabecalho e rodape for selecionado, para simular um espaçamento entre
			o topo e rodape. -->
			<div id="preview-corpo-container">
				<div style="height:50px;"></div>
			</div>
			
			<!-- componente de preview -->
			<c:set var="tituloPreview">
				<liferay-ui:message key='template.titulo-preview'/>
			</c:set>
			<liferay-util:include 
					page="/jsp/admin/includes/componente-preview-html.jsp" 
					servletContext="<%=this.getServletContext()%>">
				<liferay-util:param name="tituloPreview" value="${tituloPreview}"/>
			</liferay-util:include>
		</aui:form>

		<!-- Definir botoes de acordo com o tipo de acao que oroginou o formulario. -->
		<c:choose>
			<c:when test="${param.wizard eq true}">
				<div class="botoes-acao-wizard-wrapper clearfix">
					<div class="botao-wizard-wrapper lado-esquerdo">
						<a href="javascript:" id="<portlet:namespace/>btAnterior" class="botao-wizard anterior">
							<i class="icon-circle-arrow-left"></i>
							<liferay-ui:message key="wizard.navegacao.botao.template.selecionar"/>
						</a>
					</div>		
					<div class="botao-wizard-wrapper lado-direito">
						<a href="javascript:" id="<portlet:namespace/>btProximo" class="botao-wizard proximo">
							<liferay-ui:message key="wizard.navegacao.botao.template.criar"/>
							<i class="icon-circle-arrow-right"></i>
						</a>
					</div>
				</div>						
			</c:when>
			<c:otherwise>
				<aui:button-row>
					<aui:button type="button" cssClass="btn-primary" value="save" name="btGravar" />
					<input type="button" value="Cancelar" class="btn btn-cancel" onclick="javascript:window.location.href = $('#<portlet:namespace/>redirect').val()"/>
				</aui:button-row>				
			</c:otherwise>
		</c:choose>		
		
	</div>
</div>

<aui:script use="node">
	var hiddenCabecalho = A.one("#<portlet:namespace />cabecalho");
	var hiddenRodape = A.one("#<portlet:namespace />rodape");
	var hiddenCorpo = A.one("#<portlet:namespace />corpo"); 

	
	A.one("#<portlet:namespace />btGravar").on("click", function() {
		<portlet:namespace />gravar();
	});
	

	function atualizarInputsHTML() {
		//atualizar o valor dos campos hidden com o que estiver informado no CKEditor HTML
		hiddenCabecalho.val(window.<portlet:namespace />editorCabecalho.getHTML());
		hiddenRodape.val(window.<portlet:namespace />editorRodape.getHTML());
		hiddenCorpo.val(window.<portlet:namespace />editorCorpo.getHTML());
	}
	
	//funcao que sera utilizada pelo Editor HTML para carregar o valor inicial
	Liferay.provide(
		window,
		'<portlet:namespace />initEditorCabecalho',
		function() {
			window.<portlet:namespace />editorCabecalho.setHTML("<%= UnicodeFormatter.toString(cabecalho) %>");
		}
	);
	Liferay.provide(
		window,
		'<portlet:namespace />initEditorRodape',
		function() {
			<portlet:namespace />editorRodape.setHTML("<%= UnicodeFormatter.toString(rodape) %>");
		}
	);
	Liferay.provide(
		window,
		'<portlet:namespace />initEditorCorpo',
		function() {
			window.<portlet:namespace />editorCorpo.setHTML("<%= UnicodeFormatter.toString(corpo) %>");
		}
	);		
	//
	Liferay.provide(
		window,
		'<portlet:namespace />gravar',
		function(urlRedirect) {
			atualizarInputsHTML();

			exibirMsgValidadaoEditor(false);

			var estilo = A.one("input[name='<portlet:namespace />estilo']:checked").val();
			var erro = false;
			
			if (estilo == '0') {
				if (hiddenCabecalho.val() == '') {
					exibirMsgValidadaoEditor(true, 'cabecalho');
					erro = true;
				}
				if (hiddenRodape.val() == '') {
					exibirMsgValidadaoEditor(true, 'rodape');
					erro = true;
				}
			}
			else {
				if (hiddenCorpo.val() == '') {
					exibirMsgValidadaoEditor(true, 'corpo');
					erro = true;
				}
			}

			if (!erro) {
				//redefinir o redirecionamento apos o processamento do formulario, quando necessario
				if (urlRedirect != undefined) {
					A.one("#<portlet:namespace/>redirect").val(urlRedirect);
				}
				submitForm(document.<portlet:namespace />fmDados);
			}
			else {
				window.scroll(0,0);
			}	
		}
	);

	Liferay.provide(
		window,
		'exibirEditor',
		function(estilo) {
			A.one(".cabecalho-wrapper").setStyle("display", (estilo == '0' ? 'block' : 'none'));
			A.one(".rodape-wrapper").setStyle("display", (estilo == '0' ? 'block' : 'none'));
			A.one(".corpo-wrapper").setStyle("display", (estilo == '1' ? 'block' : 'none'));
		}
	);

	//define a funcao que sera utilizada pelo componente de pre-visualizacao do dispositivo
	Liferay.provide(
		window,
		'definirConteudoPreview',
		function() {
			atualizarInputsHTML();
			var conteudo = '';
			//obtem o radio button do estilo selecionado
			var estilo = A.one("input[name='<portlet:namespace />estilo']:checked");
			if (estilo != null) {
				estilo = estilo.val();
				if (estilo == 0) {
					conteudo += hiddenCabecalho.val();
					//obter o 'corpo' para simular o espacamento entre o topo e rodape
					conteudo += A.one("#preview-corpo-container").html();
					conteudo += hiddenRodape.val();
				}
				else {
					conteudo += hiddenCorpo.val();
				}
			}
			else {
				console.error("Estilo nao selecionado!");
			}
			return conteudo;
		}
	);

	A.one("#<portlet:namespace/>nome").focus();

	exibirEditor('${template.estilo}');
	definirConteudoPreview();
	previewConteudo();
</aui:script>	