<%@ 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" %>
<app:handleError>
    ${zm:clearMessageCache(mailbox)}
    <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="newTask"/>
    <zm:composeUploader var="uploader"/>
    <c:set var="compose" value="${uploader.compose}"/>
    <fmt:message var="hourFmt" key="CAL_APPT_EDIT_HOUR_FORMAT"/>
</app:handleError>

<app:handleError>
    <c:choose>
        <c:when test="${param.useInstance eq '1' and not empty param.exInvId}">
            <c:set var="id" value="${param.exInvId}"/>
            <c:set var="compNum" value="${empty param.exCompNum ? 0 : param.exCompNum}"/>
            <zm:getMessage var="message" id="${id}" markread="true" neuterimages="${empty param.xim}" wanthtml="false"/>
        </c:when>
        <c:when test="${not empty param.id}">
            <c:set var="id" value="${param.id}"/>
            <c:set var="compNum" value="${empty param.invCompNum ? 0 : param.invCompNum}"/>
            <zm:getMessage var="message" id="${id}" markread="true" neuterimages="${empty param.xim}" wanthtml="false"/>
        </c:when>
        <c:otherwise>
            <c:set var="message" value="${null}"/>
        </c:otherwise>
    </c:choose>

    <c:set var="appt" value="${empty message ? null : message.invite.component}"/>

    <c:set var="canEditRecurrence" value="${(empty appt or not appt.exception) and not compose.useInstance}"/>
    <c:set var="canDelete" value="${not empty appt}"/>
    <c:set var="hasAttendees" value="${not empty appt and not empty appt.attendees}"/>


    <c:choose>
        <c:when test="${empty compose}">
            <zm:messageCompose var="compose" message="${message}" action="${empty message ? 'apptnew' : 'apptedit'}"
                               date="${requestScope.dateContext}"
                               inviteId="${param.id}"
                               exceptionInviteId="${empty param.exInvId? null : param.exInvId}"
                               useInstance="${param.useInstance eq '1'}"
                               istask="${true}"
                               instanceStartTime="${zm:nonNull(param.instStartTime)}"
                               instanceDuration="${zm:nonNull(param.instDuration)}"/>
        </c:when>
        <c:when test="${uploader.isUpload and not empty message}">
            <zm:fixupMessageCompose message="${message}" compose="${compose}" newattachments="${uploader.compose.hasFileItems}"/>
        </c:when>
    </c:choose>

    <c:choose>
        <c:when test="${empty compose.inviteId}">
            <c:set var="apptImage" value="tasks/ImgNewTask.png"/>
            <c:set var="apptImageAlt" value="ALT_NEW_TASK"/>
            <fmt:message var="apptSubject" key="newTask"/>
            <c:set var="isNewAppt" value="${true}"/>
        </c:when>
        <c:otherwise>
            <c:set var="apptImage" value="tasks/ImgTask.png"/>
            <c:set var="apptImageAlt" value="ALT_EDIT_TASK"/>
            <c:set var="apptSubject" value="${compose.subject}"/>
            <c:set var="closeImage" value="common/ImgClose.png"/>
            <c:set var="isNewAppt" value="${false}"/>
        </c:otherwise>
    </c:choose>

    <c:set var="isInstance" value="${not empty appt and (appt.exception or not empty appt.recurrence) and compose.useInstance}"/>
    
</app:handleError>

<app:view mailbox="${mailbox}" title="${not empty compose.subject ? compose.subject : title}" selected='tasks' tasks="true" context="${null}" keys="false" date="${requestScope.dateContext}" tags="true"
     onload="var e=document.getElementById('subject'); if (e) e.focus();">

    <form action="" name="taskForm" method="post" enctype="multipart/form-data" accept-charset="utf-8">
        <table width="100%" style='height:100%;'>
            <tr>
                <td class='TbTop'>
                    <table width="100%" class='Tb'>
                        <tr valign='middle'>
                            <td align="left" class="TbBt">
                                <table class='Tb'>
                                    <tr>
                                        <app:button id="OPSAVE" name="actionSave" src="common/ImgSave.png" tooltip="save" text="save"/>
                                        <td><div class='vertSep'></div></td>
                                        <c:choose>
                                            <c:when test="${zm:boolean(isNewAppt)}">
                                                <app:button id="OPCANCEL" name="actionCancel" src="common/ImgCancel.png" tooltip="cancel" text="cancel"/>
                                            </c:when>
                                            <c:otherwise>
                                                <app:button id="OPCANCEL" name="actionCancel" src="common/ImgClose.png" tooltip="close" text="close"/>
                                            </c:otherwise>
                                        </c:choose>

                                        <c:if test="${canDelete}">
                                            <td><div class='vertSep'></div></td>
                                            <c:choose>
                                                <c:when test="${hasAttendees}">
                                                    <app:button name="actionApptCancel"  src="common/ImgCancel.png" tooltip="actionTaskCancelTT" text="cancel"/>
                                                </c:when>
                                                <c:when test="${isInstance}">
                                                    <app:button name="actionApptDelete" src="startup/ImgDelete.png" tooltip="actionTaskDeleteInstTT" text="deleteInst"/>
                                                </c:when>
                                                <c:otherwise>
                                                    <app:button name="actionApptDelete" src="startup/ImgDelete.png" tooltip="actionTaskDeleteTT" text="delete"/>
                                                </c:otherwise>
                                            </c:choose>
                                        </c:if>
                                        <c:if test="${canDelete and not isInstance}">
                                            <td><div class='vertSep'></div></td>
                                            <td  nowrap valign=middle>
                                                <select name="actionOp">
                                                    <option value="" selected/><fmt:message key="moreActions"/>
                                                    <app:tagOptions mailbox="${mailbox}" keys="${true}"/>
                                                </select>
                                            </td>
                                            <app:button name="actionGo" tooltip="actionTaskListGoTT" text="actionGo"/>
                                            <td><div class='vertSep'></div></td>
                                        </c:if>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td class='ZhAppContent'>
                    <table width="100%" class='Compose'>
                    <c:set var="folder" value="${zm:getFolder(pageContext, empty compose ? 15 : compose.apptFolderId)}"/>
                    <fmt:message var="colorMsg" key="${folder.rgbColorMsg}"/>
                        <tr  class='${folder.styleColor}Bg'>
                            <td colspan="2" class='ZhBottomSep'>
                                <table width="100%">
                                    <tr class='apptHeaderRow' style="background-color:${zm:lightenColor(not empty folder.rgb ? folder.rgb : colorMsg)}">
                                        <td width="24"><center><app:img src="${apptImage}" altkey="${apptImageAlt}"/></center></td>
                                        <td class='apptHeader'>
                                            ${fn:escapeXml(apptSubject)}
                                        </td>
                                        <td width="1%" nowrap align='right' class='Tags' style='padding-right:5px'>
                                            <c:if test="${(message.hasTags and mailbox.features.tagging) or (message.isFlagged)}">
                                                <c:set var="tags" value="${zm:getTags(pageContext, message.tagIds)}"/>
                                                <c:forEach items="${tags}" var="tag">
                                                    <span style='white-space:nowrap;'>
                                                        <app:img altkey="${fn:escapeXml(tag.name)}" src="${tag.miniImage}"/>${fn:escapeXml(tag.name)} </span>
                                                </c:forEach>
                                                <c:if test="${message.isFlagged}">
                                                    <span style='white-space:nowrap;'>
                                                        <app:flagImage flagged="${message.isFlagged}"/>
                                                    </span>
                                                </c:if>
                                            </c:if>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                        <td colspan="2">
                            <table width="100%">
                                <tr>
                                    <td valign='top' width="50%">
                                        <fieldset>
                                            <legend><fmt:message key="details"/></legend>
                                            <table class="ZPropertySheet" cellspacing="6">
                                                <tr>
                                                    <td class="editViewLabel"><label for="subject"><fmt:message key="subject"/>:</label></td>
                                                    <td><input style="width:99%" type="text" size="100" id="subject" name="subject" value="${fn:escapeXml(compose.subject)}"></td>
                                                </tr>
                                                <tr>
                                                    <td class="editViewLabel"><label for="location"><fmt:message key="location"/>:</label></td>
                                                    <td><input style="width:99%" id="location" type="text" size="100" name="location" value="${fn:escapeXml(compose.location)}"></td>
                                                </tr>
                                                <tr>
                                                    <td class="editViewLabel"><label for="priority"><fmt:message key="priority"/>:</label></td>
                                                    <td>
                                                        <table>
                                                            <tr>
                                                                <td>
                                                                    <select name="taskPriority" id="priority">
                                                                        <option <c:if test="${compose.taskPriority eq '9'}">selected </c:if>value="9"><fmt:message key="taskPrioLow"/>
                                                                        <option <c:if test="${compose.taskPriority eq '5'}">selected </c:if>value="5"><fmt:message key="taskPrioNormal"/>
                                                                        <option <c:if test="${compose.taskPriority eq '1'}">selected </c:if>value="1"><fmt:message key="taskPrioHigh"/>
                                                                    </select>
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                </tr>

                                                <c:set var="numTaskLists" value="0"/>
                                                <zm:forEachFolder var="folder">
                                                    <c:if test="${folder.isTaskView and folder.isTaskMoveTarget}">
                                                        <c:set var="numTaskLists" value="${numTaskLists+1}"/>
                                                    </c:if>
                                                </zm:forEachFolder>
                                                <c:choose>
                                                    <c:when test="${numTaskLists gt 1}">
                                                        <tr>
                                                            <td nowrap width="1%" align="right"><label for="apptFolderId"><fmt:message key="taskList"/>:</label></td>
                                                            <td>
                                                                <select name='apptFolderId' id="apptFolderId">
                                                                    <zm:forEachFolder var="folder">
                                                                        <c:if test="${folder.isTaskView and folder.isTaskMoveTarget}">
                                                                            <option value="${folder.id}" <c:if test="${compose.apptFolderId eq folder.canonicalId}">selected </c:if>/>
                                                                            ${zm:getFolderName(pageContext, folder.id)}
                                                                        </c:if>
                                                                    </zm:forEachFolder>
                                                                </select>
                                                            </td>
                                                        </tr>
                                                    </c:when>
                                                    <c:otherwise>
                                                        <tr>
                                                            <td colspan="2">&nbsp;</td>
                                                        </tr>
                                                    </c:otherwise>
                                                </c:choose>
                                            </table>
                                        </fieldset>
                                    </td>
                                    <td valign='top' width="50%">
                                        <fieldset>
                                            <legend><fmt:message key="date"/></legend>
                                            <table class="ZPropertySheet" cellspacing="6">
                                            <tr>
                                                <td align="right">
                                                    <input id="completed" type=checkbox onclick="completedCheckbox(this)" name="completed" <c:if test="${compose.taskStatus eq 'COMP'}">checked</c:if> value="1">
                                                </td>
                                                <td>
                                                    <table>
                                                        <tr>
                                                            <td>
                                                                <select name="taskStatus" id="status" onchange="statusChanged(this.options[this.selectedIndex].value)">
                                                                    <option id="NEED" <c:if test="${compose.taskStatus eq 'NEED'}">selected </c:if>value="NEED"><fmt:message key="TASK_NEED"/>
                                                                    <option id="COMP" <c:if test="${compose.taskStatus eq 'COMP'}">selected </c:if>value="COMP"><fmt:message key="TASK_COMP"/>
                                                                    <option id="INPR" <c:if test="${compose.taskStatus eq 'INPR'}">selected </c:if>value="INPR"><fmt:message key="TASK_INPR"/>
                                                                    <option <c:if test="${compose.taskStatus eq 'WAITING'}">selected </c:if>value="WAITING"><fmt:message key="TASK_WAITING"/>
                                                                    <option <c:if test="${compose.taskStatus eq 'DEFERRED'}">selected </c:if>value="DEFERRED"><fmt:message key="TASK_DEFERRED"/>
                                                                </select>
                                                            </td>
                                                            <td>&nbsp;</td>
                                                            <td>
                                                                <select name="taskPercentComplete" id="percent" onchange="percentChanged(this.options[this.selectedIndex].value)">
                                                                    <option id="percent0" <c:if test="${compose.taskPercentComplete eq '0'}">selected </c:if>value="0">0%
                                                                    <option <c:if test="${compose.taskPercentComplete eq '10'}">selected </c:if>value="10">10%
                                                                    <option <c:if test="${compose.taskPercentComplete eq '20'}">selected </c:if>value="20">20%
                                                                    <option <c:if test="${compose.taskPercentComplete eq '30'}">selected </c:if>value="30">30%
                                                                    <option <c:if test="${compose.taskPercentComplete eq '40'}">selected </c:if>value="40">40%
                                                                    <option <c:if test="${compose.taskPercentComplete eq '50'}">selected </c:if>value="50">50%
                                                                    <option <c:if test="${compose.taskPercentComplete eq '60'}">selected </c:if>value="60">60%
                                                                    <option <c:if test="${compose.taskPercentComplete eq '70'}">selected </c:if>value="70">70%
                                                                    <option <c:if test="${compose.taskPercentComplete eq '80'}">selected </c:if>value="80">80%
                                                                    <option <c:if test="${compose.taskPercentComplete eq '90'}">selected </c:if>value="90">90%
                                                                    <option id="percent100" <c:if test="${compose.taskPercentComplete eq '100'}">selected </c:if>value="100">100%
                                                                </select>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td width="1%" align="right" nowrap><label for="start"><fmt:message key="startDate"/>:</label></td>
                                                <td>
                                                    <table>
                                                        <tr>
                                                            <td>
                                                                <input id="start" type=text size="12" maxlength="20" name="startDate" value="${fn:escapeXml(compose.startDate)}">
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td width="1%" align="right" nowrap><label for="end"><fmt:message key="taskDueDate"/>:</label></td>
                                                <td>
                                                    <table>
                                                        <tr>
                                                            <td>
                                                                <input id="end" type=text size="12" maxlength="20" name="endDate" value="${fn:escapeXml(compose.endDate)}">
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                            </tr>
                                            </table>
                                        </fieldset>
                                    </td>
                                </tr>
                            </table>
                        </td>

                        </tr>
                        <c:set var="firstAttachment" value="${true}"/>
                        <c:if test="${!empty compose.messageAttachments}">
                                <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">
                                    <tr class="CompOrigAtt" valign="middle">
                                        <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>
                                        <c:set var="url" value="/service/home/~/?id=${message.id}&part=${part.partName}&auth=co"/>
                                        <c:set var="pname" value="${part.displayName}"/>
                                        <c:if test="${empty pname}">
                                            <fmt:message key="unknownContentType" var="pname">
                                                <fmt:param value="${part.contentType}"/>
                                            </fmt:message>
                                        </c:if>
                                        <td>
                                            <table>
                                                <tr valign="middle">
                                                    <td>
                                                        <input <c:if test="${compose.checkedAttachmentNames[part.partName]}">checked </c:if>type=checkbox name="originalAttachment" value="${part.partName}">
                                                    </td>
                                                    <td>&nbsp;</td>
                                                    <td>
                                                        <a target="_blank" href="${url}&disp=i">${fn:escapeXml(pname)}</a>&nbsp;(${part.displaySize})
                                                    </td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                </c:forEach>
                        </c:if>
                        <tr>
                            <td colspan="3" style='padding:10px'>
                                <textarea class='MsgCompose' rows="30" cols="80" style='width:100%'
                                              name="body">${fn:escapeXml(empty compose.content ? compose.description : compose.content)}</textarea>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td class='TbBottom'>
                    &nbsp;
                        <c:if test="${not empty param.debug}">
                            <pre>${fn:escapeXml(appt)}</pre>
                        </c:if>
                </td>
            </tr>
        </table>
        <input type="hidden" name="apptFolderId" value="${fn:escapeXml(compose.apptFolderId)}"/>
        <input type="hidden" name="invId" value="${fn:escapeXml(compose.inviteId)}"/>
        <input type="hidden" name="crumb" value="${fn:escapeXml(mailbox.accountInfo.crumb)}"/>
        <input type="hidden" name="origOrganizer" value="${fn:escapeXml(compose.origOrganizer)}"/>
    </form>

    <SCRIPT TYPE="text/javascript">
    <!--
    var zclick = function(id) { var e = document.getElementById(id); if (e) e.click(); }
    function completedCheckbox(box) {
        if (box.checked) {
            document.getElementById("COMP").selected = true;
            document.getElementById("percent100").selected = true;
        } else {
            document.getElementById("NEED").selected = true;
            document.getElementById("percent0").selected = true;
        }
    }
    function statusChanged(value) {
        if (value != 'COMP') {
            document.getElementById("completed").checked = false;
            if(document.getElementById("percent").value == "100") {
                document.getElementById("percent0").selected = true;
            }
        } else {
            document.getElementById("completed").checked = true;
            document.getElementById("percent100").selected = true;
        }
    }
    function percentChanged(value) {
        if (value == "100") {
            document.getElementById("completed").checked = true;
            document.getElementById("COMP").selected = true;
        } else {
            var statusEl = document.getElementById("status");
            if (statusEl.options[statusEl.selectedIndex].value == "COMP")
                document.getElementById("INPR").selected = true;
            document.getElementById("completed").checked = false;
        }
    }

    /* dirty check */
    var _fields = {} ;
    grabFieldValues = function(){
        var form = document.forms["taskForm"];
        var _el = form.elements;
        for ( var _i=0;_i < _el.length; _i++){
            if((_el[_i].type == "hidden") || (_el[_i].type == "submit")){
                // do nothing
            }else if(_el[_i].type == "text"){
                _fields[_el[_i].name] = _el[_i].value;
            }else if(_el[_i].type == "radio"){
                if(_el[_i].checked){
                    _fields[_el[_i].name] = _el[_i].value+"::"+_el[_i].checked;
                }
            }else if(_el[_i].type == "checkbox"){
                _fields[_el[_i].name] = _el[_i].checked;
            }else if(_el[_i].type == "select-one"){
                _fields[_el[_i].name] = _el[_i].options[_el[_i].selectedIndex].value;
            }else if(_el[_i].type == "textarea"){
                _fields[_el[_i].name] = _el[_i].value;
            }
        }
    }
    grabFieldValues();
    var _form = document.forms["taskForm"];

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

    checkForChanges = function(){
        var _el = _form.elements;
        var _checkFail = false;
        for ( var _i=0;_i < _el.length; _i++){
            if(_el[_i].name != null && _el[_i].name != ""){
                if((_el[_i].type == "hidden") || (_el[_i].type == "submit")){
                    // do nothing
                }else if(_el[_i].type == "text"){
                    if(_fields[_el[_i].name] != _el[_i].value) { _checkFail = true; }
                }else if(_el[_i].type == "radio"){
                    if(_el[_i].checked){
                        if(_fields[_el[_i].name] != _el[_i].value+"::"+_el[_i].checked) { _checkFail = true; }
                    }
                }else if(_el[_i].type == "checkbox"){
                    if(_fields[_el[_i].name] != _el[_i].checked) {_checkFail = true; }

                }else if(_el[_i].type == "select-one"){
                    if(_fields[_el[_i].name] != _el[_i].options[_el[_i].selectedIndex].value) {_checkFail = true; }

                }else if(_el[_i].type == "textarea"){
                    if(_fields[_el[_i].name] != _el[_i].value) {_checkFail = true; }
                }
            }
        }

        if(_checkFail){
            return (confirm("<fmt:message key="optionsExitConfirmation"/>"));
        } else {
            return true;
        }
    }

    /* List of elements that has to be handled for send */
    var sendElemts = new Array("SOPCANCEL", "IOPCANCEL");
    var y;
    for (y in sendElemts){
        var _elemA = document.getElementById(sendElemts[y]);
        _elemA.onclick = function () {
           return cancelOnbeforeUnload();
        }
    }

    var cancelOnbeforeUnload = function(){
        window.onbeforeunload = null;
        return checkForChanges();
    }
            
    /* end */
    //-->
   </SCRIPT>

    <app:keyboard cache="cal.eappt" globals="false" passspecial="true" mailbox="${mailbox}">
        <zm:bindKey message="editAppointment.Save" func="function() { zclick('SOPSAVE')}"/>
    </app:keyboard>
</app:view>
