<%@ page buffer="8kb" autoFlush="true" %>
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="zm" uri="com.zimbra.zm" %>
<%@ taglib prefix="app" uri="com.zimbra.htmlclient" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="com.zimbra.i18n" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<app:handleError>
<zm:getMailbox var="mailbox"/>
<c:choose>                                                                                                   
    <c:when test="${not empty mailbox.prefs.locale}">
        <fmt:setLocale value='${mailbox.prefs.locale}' scope='request' />
    </c:when>
    <c:otherwise>
        <fmt:setLocale value='${pageContext.request.locale}' scope='request' />
    </c:otherwise>
</c:choose>
<fmt:setBundle basename="/messages/ZhMsg" scope='request' />
<fmt:message var="title" key="compose"/>
<zm:composeUploader var="uploader"/>
<c:set var="compose" value="${uploader.compose}"/>
<c:set var="composeformat" value="${mailbox.prefs.composeFormat}" />
<c:if test="${mailbox.prefs.forwardReplyInOriginalFormat && !empty param.rf && (param.rf eq 'html' || param.rf eq 'text')}">
    <c:set var="composeformat" value="${param.rf}"/>
</c:if>
<c:set var="isHtml" value="${composeformat eq 'html'}"/>
</app:handleError>

<app:handleError>
<c:choose>
    <c:when test="${!empty param.id or !empty compose.draftId or !empty requestScope.draftid}">
        <c:choose>
            <c:when test="${!empty compose.draftId or !empty requestScope.draftid}">
                <zm:getMessage var="message" id="${empty requestScope.draftid ? compose.draftId : requestScope.draftid}" wanthtml="${(isHtml ? true : false)}"/>
            </c:when>
            <c:otherwise>
                <zm:getMessage var="message" id="${param.id}" part="${param.part}" wanthtml="${(isHtml ? true : false)}"/>
            </c:otherwise>
        </c:choose>
    </c:when>
    <c:otherwise>
        <c:set var="message" value="${null}"/>
    </c:otherwise>
</c:choose>

<c:choose>
    <c:when test="${empty compose }">
        <zm:messageCompose var="compose" message="${message}" action="${message.isDraft ? 'draft' : param.op}"/>
    </c:when>
    <c:when test="${uploader.isUpload and !empty message}">
        <c:if test="${!requestScope.uploadError}">
            <zm:fixupMessageCompose message="${message}" compose="${compose}" newattachments="${uploader.isContactDone or uploader.isContactCancel
                                                        or uploader.isAttachCancel or uploader.compose.hasFileItems
                                                        or not empty uploader.compose.uploadedAttachment
                                                        or uploader.isDraft}"/>
        </c:if>
    </c:when>
</c:choose>

<c:set var="priority" value=""/>
<c:if test="${not empty message and message.isDraft}">
    <c:choose>
        <c:when test="${message.isHighPriority}">
            <c:set var="priority" value="!"/>
        </c:when>
        <c:otherwise>
            <c:if test="${message.isLowPriority}">
                <c:set var="priority" value="?"/>
            </c:if>
        </c:otherwise>
    </c:choose>
</c:if>

</app:handleError>

<c:set var="focusField" value="${param.op eq 'reply' or param.op eq 'replyAll' ? 'bodyField' : 'toField'}"/>
<app:view mailbox="${mailbox}" title="${not empty compose.subject ? compose.subject : title}" selected='compose' folders="true" tags="true" searches="true" context="${null}" keys="false"
          onload="var e=document.getElementById('${focusField}'); if (e) {e.focus(); if (e.setSelectionRange) e.setSelectionRange(0,0);}" >
<body class="yui-skin-sam">
<form action="" method="post" name="composeForm" enctype="multipart/form-data" accept-charset="utf-8">
<table width="100%">
<tr>
    <td class='TbTop'>
        <table width="100%">
            <tr valign='middle'>
                <td align=left class="TbBt">
                    <table class='Tb'>
                        <tr>
                            <app:button id="OPSEND" name="actionSend" src="mail/ImgSend.png" tooltip="send" text="send"/>
                            <td><div class='vertSep'></div></td>
                            <app:button id="OPCANCEL" name="actionCancel" src="common/ImgCancel.png" tooltip="cancel" text="cancel"/>
                            <td><div class='vertSep'></div></td>
                            <app:button id="OPDRAFT" name="actionDraft" src="startup/ImgDraftFolder.png" tooltip="saveDraft" text="saveDraft"/>
                            <td><div class='vertSep'></div></td>
                            <app:button id="OPATTACH" name="actionAttachAdd" src="startup/ImgAttachment.png" tooltip="addAttachments" text="addAttachments"/>
                            <c:if test="${mailbox.features.contacts or mailbox.features.gal}">
                                <td><div class='vertSep'></div></td>
                                <app:button id="OPADDRECIP" name="actionContactAdd" src="contacts/ImgContactsPicker.png" tooltip="addFromContacts" text="addFromContacts"/>
                            </c:if>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </td>
</tr>
<tr>
<td class='ZhAppContent'>
<div>
<table style="height:80%;" width="100%" class='ZPropertySheet' cellspacing="6">
<tr>
    <app:button id="tobutton" name="actionContactAdd" width="1%" clazz="tobutton" tooltip="addFromContacts" text="to"/>
    <td colspan="2" nowrap>
        <div class="ZhAC ZhACTo">
            <textarea id="toField" rows="2" style='width:99%;height:40px;position:relative;' cols="80" onkeydown="return handleEnter(event, this);"
                       onkeypress="return handleEnter(event, this);" name="to" >${compose.to eq 'toAddresses' ? (fn:escapeXml(sessionScope.toAddresses)):(fn:escapeXml(compose.to))}</textarea>
            <br><div class='ZhACCont' id="toContainer" style='width:99%;top:3em;'></div></div>
    </td>
</tr>
<tr>
    <app:button id="ccbutton"  name="actionContactAdd" width="1%" clazz="tobutton" tooltip="addFromContacts" text="cc"/>
    <td nowrap>
        <div class="ZhAC ZhACCc">
            <textarea id="ccField" rows="2" style='width:99%;height:40px;position:relative;' cols='80' name="cc">${fn:escapeXml(compose.cc)}</textarea>
            <br><div class='ZhACCont' id="ccContainer" style='width:99%;'></div>
        </div>
    </td>
    <td nowrap="nowrap" style='width:5%; padding:4px 10px;'>
        <div id="show_bcc" style="display:block;"><a id="a_shbcc" href="javascript:showHideBcc();"><fmt:message key="showBcc"/></a></div>
        <div id="hide_bcc" style="display:none;"><a id="a_hdbcc" href="javascript:showHideBcc();"><fmt:message key="hideBcc"/></a></div>
    </td>
</tr>
<tr id="bcc_tr" style="display:none">
    <app:button id="bccbutton" name="actionContactAdd" width="1%" clazz="tobutton" tooltip="addFromContacts" text="bcc"/>
    <td colspan="2" nowrap>
        <div class="ZhAC ZhAcBcc">
            <textarea id="bccField" rows="2" style='width:99%;height:40px;position:relative;' cols='80' name="bcc" >${fn:escapeXml(compose.bcc)}</textarea>
            <br><div class='ZhACCont' id="bccContainer" style='width:99%;'></div>
        </div>
    </td>
</tr>
<tr>
    <td valign='top' align="right" nowrap  style='padding-top:4px;'> <label for="subjectField"><fmt:message key="subject"/>: </label></td>
    <c:choose>
        <c:when test="${mailbox.features.mailPriority}">
            <td nowrap style='padding-top:4px;'><input style='width:99%; height:18px;' type="text" size="100" name="subject" id="subjectField" onkeydown="return handleEnter(event);" onkeypress="return handleEnter(event);" value="${fn:escapeXml(compose.subject)}"></td>
            <td nowrap align='right' style='width:5%; padding:4px 10px;'>
                <c:if test="${mailbox.features.mailPriority}">
                    <fmt:message key="priority"/>:
                    <select name="priority">
                        <option id="OPPRIORITYHIGH" value="!"<c:if test="${priority eq '!'}"> selected</c:if>> <fmt:message key="high"/>
                        <option id="OPPRIORITYNORMAL" value="" <c:if test="${priority eq ''}"> selected</c:if>><fmt:message key="normal"/>
                        <option id="OPPRIORITYLOW" value="?"<c:if test="${priority eq '?'}"> selected</c:if>><fmt:message key="low"/>
                    </select>
                </c:if>
            </td>
        </c:when>
        <c:otherwise>
            <td colspan="2" nowrap><input style='width:99%' type="text" size="100" onkeydown="return handleEnter(event);"
                                          onkeypress="return handleEnter(event);" name="subject" id="subjectField" value="${fn:escapeXml(compose.subject)}"></td>
        </c:otherwise>
    </c:choose>
</tr>
<c:set var="firstAttachment" value="${true}"/>
<c:if test="${not empty compose.messageAttachments and empty compose.draftId and empty requestScope.draftid}">
    <c:forEach var="ma" items="${compose.messageAttachments}" varStatus="status">
        <tr>
            <td align='right'>
                <c:if test="${firstAttachment}">
                    <app:img altkey="ALT_ATTACHMENT" src="startup/ImgAttachment.png"/>
                    <c:set var="firstAttachment" value="${false}"/>
                </c:if>
            </td>
            <td colspan="2">
                <c:choose>
                    <c:when test="${empty ma.subject}"><fmt:message var="subj" key="noSubject"/></c:when>
                    <c:otherwise><c:set var="subj" value="${zm:truncate(ma.subject,100,true)}"/></c:otherwise>
                </c:choose>
                ${fn:escapeXml(subj)}
                <input type="hidden" name="messageAttachment" value="${ma.id}:${fn:escapeXml(ma.subject)}"/>
            </td>
        </tr>
    </c:forEach>
</c:if>
<c:if test="${!empty compose.originalAttachments}">
    <c:forEach var="part" items="${compose.originalAttachments}" varStatus="status">
        <c:set var="cid" value="${fn:replace(part.contentId,'<' ,'')}"/>
        <c:set var="cid" value="${fn:replace(cid,'>' ,'')}"/>
        <c:if test="${not (part.isImage and not empty part.contentId and fn:contains(cid,'DWT'))}">
            <app:attachment firstAttachment="${firstAttachment}" url="/service/home/~/?id=${message.id}&part=${part.partName}&auth=co"
                            displayName="${part.displayName}" contentType="${part.contentType}"
                            checked="${compose.checkedAttachmentNames[part.partName] != null or (part.isMssage and not empty compose.messageAttachments)}" displaySize="${zm:displaySize(pageContext,part.size)}"
                            value="${part.partName},${empty cid ? compose.checkedAttachmentNames[part.partName] : cid }" name="originalAttachment"/>
            <c:set var="firstAttachment" value="${false}"/>
        </c:if>
        <c:if test="${(part.isImage and not empty part.contentId and fn:contains(part.contentId,'DWT'))}">
            <input type="hidden" value="${part.partName},${empty cid ? compose.checkedAttachmentNames[part.partName] : cid}" name="originalAttachment"/>
        </c:if>    
    </c:forEach>
</c:if>
<c:if test="${(not empty param.attachId) and (not empty param.attachUrl) and (not empty param.attachName)}">
    <app:attachment firstAttachment="${firstAttachment}" url="${param.attachUrl}"
                    displayName="${param.attachName}"
                    checked="true"
                    value="${zm:cook(param.attachId)}" name="uploadedAttachment"/>
</c:if>
<tr>
    <td colspan="3"  width="100%" <c:if test="${isHtml}">style="background-color: #FFFFFF;"</c:if>>
        <c:set var="isHTMLContType" value="${compose.contentType eq 'text/html'}" />
        <c:set var="isHtmlCont" value="${not empty compose.htmlContent}" />
        <c:set var="theBody" value="${fn:escapeXml(isHtml ? (empty compose.htmlContent ? (isHTMLContType or isHtml ? compose.content : zm:cook(compose.content)) : compose.htmlContent) : compose.content)}"/>
        <c:if test="${not empty message}">
            <c:forEach var="part" items="${message.attachments}">
               <c:if test="${part.isImage}"> <%-- SWAP the inline images dfsrc and src from the attached parts to display the images. --%>
                   <c:set var="cid" value="${fn:replace(part.contentId,'<' ,'')}"/>
                   <c:set var="cid" value="cid:${fn:replace(cid,'>' ,'')}"/>
                   <c:set var="cidUrl" value=" src=\"${cid}\""/>
                   <c:set var="imgUrl" value=" dfsrc=\"${cid}\" src=\"/service/home/~/?id=${message.id}&amp;part=${part.partName}&amp;auth=co\""/>
                   <c:set var="theBody" value="${fn:replace(theBody,fn:escapeXml(cidUrl),fn:escapeXml(imgUrl))}"/>
               </c:if>
            </c:forEach>
        </c:if>
        <c:if test="${isHtml}">
            <c:set var="find" value="&gt;([\s\n\t ])+&lt;"/>
            <c:set var="theBody" value="${zm:replaceAll(theBody, find,'&gt;&lt;' )}"/>
            <c:set var="find" value="\r\n"/>
            <c:set var="theBody" value="${zm:replaceAll(theBody, find,'<br>')}"/>  <%--  Needed otherwise YUI rich text editor in IE has two <br>'s for \r\n --%>
            <c:set var="find" value="\n"/>
            <c:set var="theBody" value="${zm:replaceAll(theBody, find,'<br>')}"/>
        </c:if>
        <textarea class='MsgCompose' name="body" id="body" rows="20" cols="80" style='<c:if test="${isHtml}">visibility:hidden;</c:if>width:100%'>${theBody}</textarea>
        <input type="hidden" id="bodyText" class='MsgCompose' name="bodyText" value="" style='width:100%' />

    </td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
    <td class='TbBottom'>
        <table width="100%">
            <tr valign='middle'>
                <td align=left class="TbBt">
                    <table class='Tb'>
                        <tr>
                            <app:button id="DOPSEND" name="actionSend" src="mail/ImgSend.png" tooltip="send" text="send"/>
                            <td><div class='vertSep'></div></td>
                            <app:button id="DOPCANCEL" name="actionCancel" src="common/ImgCancel.png" tooltip="cancel" text="cancel"/>
                            <td><div class='vertSep'></div></td>
                            <app:button id="DOPDRAFT" name="actionDraft" src="startup/ImgDraftFolder.png" tooltip="saveDraft" text="saveDraft"/>
                            <td><div class='vertSep'></div></td>
                            <app:button id="DOPATTACH" name="actionAttachAdd" src="startup/ImgAttachment.png" tooltip="addAttachments" text="addAttachments"/>
                            <c:if test="${mailbox.features.contacts or mailbox.features.gal}">
                                <td><div class='vertSep'></div></td>
                                <app:button id="DOPADDRECIP" name="actionContactAdd" src="contacts/ImgContactsPicker.png" tooltip="addFromContacts" text="addFromContacts"/>
                            </c:if>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </td>
</tr>
</table>
<input type="hidden" name="sendUID" value="${fn:escapeXml(compose.sendUID)}"/>
<input type="hidden" name="replyto" value="${fn:escapeXml(compose.replyTo)}"/>
<input type="hidden" name="from" value="${fn:escapeXml(compose.from)}"/>
<input type="hidden" name="inreplyto" value="${fn:escapeXml(compose.inReplyTo)}"/>
<input type="hidden" name="messageid" value="${fn:escapeXml(compose.messageId)}"/>
<input type="hidden" name="compNum" value="${fn:escapeXml(compose.compNum)}"/>
<input type="hidden" name="instCompNum" value="${fn:escapeXml(compose.instanceCompNum)}"/>
<input type="hidden" name="replytype" value="${fn:escapeXml(compose.replyType)}"/>
<input type="hidden" name="inviteReplyVerb" value="${fn:escapeXml(compose.inviteReplyVerb)}"/>
<input type="hidden" name="inviteReplyInst" value="${fn:escapeXml(compose.inviteReplyInst)}"/>
<input type="hidden" name="inviteReplyAllDay" value="${fn:escapeXml(compose.inviteReplyAllDay)}"/>
<input type="hidden" name="crumb" value="${fn:escapeXml(mailbox.accountInfo.crumb)}"/>
<%--input element used to set the draftid during autosave--%>
<c:choose>
    <c:when test="${zm:boolean(message.isDraft)}">
       <input type="hidden" name="draftid" value="${message.id}"/>
    </c:when>
    <c:otherwise>
        <input type="hidden" name="draftid" value=""/>
    </c:otherwise>
</c:choose>
    
</form>
<form id="SpellCheckForm">
    <input type="hidden" id="SpellCheckData" name="SpellCheckData" value=""/>
</form>

<iframe style="visibility:hidden" name="targetFrame">
</iframe>

<app:autoComplete>
    initAuto("toField","toContainer");
    initAuto("ccField","ccContainer");
    initAuto("bccField","bccContainer");
</app:autoComplete>

<c:if test="${isHtml}" >
<app:htmlCompose isHtmlCont="${isHtmlCont}" mailbox="${mailbox}" />
</c:if>

<script type="text/javascript">
<!--
var AUTO_SAVE_DRAFT_INTERVAL = 30;
var timer;
timer = setTimeout(autoSaveTimer, AUTO_SAVE_DRAFT_INTERVAL*1000);

function autoSaveTimer()
{
    //send saveDraft request only if there is a change in the content
    if(checkForChanges())
    {
        grabFieldValues();
        var formElement = document.forms["composeForm"];
        //set iframe as the form target
        formElement.target = 'targetFrame';
        //create an input element used to set the autoSave flag
        var elem = document.createElement('input');
        elem.type = 'hidden';
        elem.name = 'actionAutoSave';
        elem.id = 'OPAUTOSAVE';
        formElement.appendChild(elem);
        formElement.submit();
    }
    setTimeout(autoSaveTimer, AUTO_SAVE_DRAFT_INTERVAL*1000 );
}

var showHideBcc = function(){
    var bcc = document.getElementById("bcc_tr");
    var showBcc = document.getElementById("show_bcc");
    var hideBcc = document.getElementById("hide_bcc");
    var bccField = document.getElementById('bccField');

    bcc.style.display=(bcc.style.display=="none"?"":"none");
    showBcc.style.display=(showBcc.style.display=="block"?"none":"block") ;
    hideBcc.style.display=(hideBcc.style.display=="block"?"none":"block") ;
}

var showBccWhenNotNull = function() {
    var bcc = document.getElementById("bcc_tr");
    var showBcc = document.getElementById("show_bcc");
    var hideBcc = document.getElementById("hide_bcc");
    var bccField = document.getElementById('bccField');
    if(trim(bccField.value) != "") {
        bcc.style.display=(bcc.style.display=="none"?"":"none");
        showBcc.style.display=(showBcc.style.display=="block"?"none":"block") ;
        hideBcc.style.display=(hideBcc.style.display=="block"?"none":"block") ; 
    }
}

var trim = function(strVal){
    return strVal.replace(/^\s*/, "").replace(/\s*$/, "");
}

var handleEnter= function(ev, _field) {
    var keyCode = ev.keyCode ? ev.keyCode : ev.which ? ev.which : ev.charCode;
    if (keyCode == 13){
        if(_field){
            if (trim(_field.value) == "") { return false } else return true ;
        }else
            return false;
    }
    else return true;
}

var zclick = function(id) { var e = document.getElementById(id); if (e) e.click(); }
var zselect = function(id) { var e = document.getElementById(id); if (e) { e.selected = true; }}

showBccWhenNotNull();        
// -->
</script>
<app:composeValidation isHtml="${isHtml}" />

<app:keyboard cache="mail.compose" globals="false" passspecial="true" mailbox="${mailbox}">
    <zm:bindKey message="compose.Send" func="function() { zclick('SOPSEND')}"/>
    <zm:bindKey message="compose.Save" func="function() { zclick('SOPDRAFT')}"/>
    <zm:bindKey message="compose.Attachment" func="function() { zclick('SOPATTACH')}"/>
    <zm:bindKey message="compose.AddressPicker" func="function() { zclick('SOPADDRECIP')}"/>
    <zm:bindKey message="compose.HighPriority" func="function() { zselect('OPPRIORITYHIGH')}"/>
    <zm:bindKey message="compose.NormalPriority" func="function() { zselect('OPPRIORITYNORMAL')}"/>
    <zm:bindKey message="compose.LowPriority" func="function() { zselect('OPPRIORITYLOW')}"/>
</app:keyboard>
</body>
</app:view>

