<?python from worktime.utils import *
from worktime.dateutils import * 

start_week, days_thismonth = calendar.monthrange(current.year, current.month)
weekdays_css = {}
holiday_css = {}
today_css = {}
for x in range(days_thismonth):
	weekdays_css[x]='weekdays_'+str((start_week+x)%7)
	holiday_css[x]=is_holiday(current.year, current.month, x+1, holidays) and 'holiday' or ''
	today_css[x]=is_today(current.year, current.month, x+1) and 'today' or ''
?>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:py="http://genshi.edgewall.org/"
      xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="layout.html" />
  <xi:include href="macros.html" />
  <head>
    <title>Work Time Management</title>
    <link href="${href.chrome('common/css/report.css')}" rel="stylesheet" type="text/css" />
    <link href="${href.chrome('worktime/treetable/stylesheets/jquery.treeTable.css')}" rel="stylesheet" type="text/css" />
    <link href="${href.chrome('worktime/css/worktime.css')}" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="${chrome.htdocs_location}js/folding.js"></script>
    <script type="text/javascript" src="${href.chrome('worktime/js/editinplace/jquery.editinplace.js')}"></script>
    <script type="text/javascript" src="${href.chrome('worktime/treetable/javascripts/jquery.treeTable.js')}"></script>
    <script type="text/javascript" src="${href.chrome('worktime/js/jquery.calculation.js')}" ></script>
    <script type="text/javascript" src="${href.chrome('worktime/js/jquery.alphanumeric.js')}"></script>
    <script type="text/javascript">
      jQuery(document).ready(function($) {
        $("fieldset legend.foldable").enableFolding(false);
        $(".worktime").editInPlace({
          url: "${href.worktime('update')}",
          show_buttons: ${show_save_buttons.lower()},
          params: "__FORM_TOKEN=${req.form_token}&amp;selected_user="+jQuery("#selected_user").text(),
          success: recalcTotal,
          default_text: ''
        });
  	    $("#tree").treeTable({
    	  initialState: "expanded"
  	    });
  	    // Make visible that a row is clicked
        $("table#tree tbody tr").mousedown(function() {
          $("tr.selected").removeClass("selected"); // Deselect currently selected rows
          $(this).addClass("selected");
        });
        
        // Make sure row is selected when span is clicked
        $("table#tree tbody tr span").mousedown(function() {
          $($(this).parents("tr")[0]).trigger("mousedown");
        });
        //recalc();
      });
      var date_map = {};
      <py:for each="x in range(days_thismonth)">
      date_map[${x}] = '${date_map[x]}';
      </py:for>
      function recalcTotal() {
        //<![CDATA[
        jQuery("#t_total").text(jQuery("span[id$=_sum]").sum());
        jQuery("#t_alltotal").text(jQuery("span[id$=_allsum]").sum());
        jQuery("#t_estimatedtotal").text(jQuery("span[id$=_estimated]").sum());
        //]]>
      }
      function updateCalendar(year, month) {
        var form = jQuery('#worktime_form');
        form.each(function() {
          this.elements['year'].value = year;
          this.elements['month'].value = month;
        });
        form.attr('action', '${javascript_quote(href.worktime() + "#update_button")}');
        jQuery('#update_button input').click();
      }
      var group_count = ${len(group_fields)-1};
      function addGroup() {
        newGroup = jQuery('#group_template').clone();
        newGroup.attr({id:'group_field' + (group_count)});
        newGroup.find('th').text('Level' + (group_count+1));
        newGroup.find('select').attr({name:'group_field' + (group_count+1)});
        newGroup.show();
    	jQuery('#add_group').before(newGroup);
    	group_count++;
      }
      function removeGroup() {
        //<![CDATA[
        if (group_count > 0) {
       	  jQuery('#group_field' + (group_count-1)).remove();
      	   group_count--;
        }
        //]]>
      }
    </script>

  </head>
  <body py:with="nodes=to_ticket_group_nodes(tickets,group_fields)">
    <div id="content">
      <h1>作業時間入力</h1>
      <form id="worktime_form" action="${href.worktime()}">
        <!-- Filter Setting -->
        <fieldset id="filter" class="collapsed">
          <legend class="foldable">Filter</legend>
          <table class="list">
            <tr>
              <td>
                <select name="selected_user">
                <py:for each="i in users">
                    <option selected="${selected_user==i or None}" value="${i}">
                    ${i}
                    </option>
                </py:for>
                </select>
                <span id="selected_user" style="display: none;">${selected_user}</span>
                さんの作業時間を表示
              </td>
            </tr>
            <tr>
              <td>
                <label>クローズしたチケットの表示</label>
                <select name="selected_closed_month">
                  <option selected="${selected_closed_month=='0' or None}" value="0">今月分だけ表示</option>
                  <py:for each="i in range(3)">
                    <option selected="${selected_closed_month==str(i+1) or None}" value="${i+1}">${i+1}ヶ月前まで表示する</option>
                  </py:for>
                  <option selected="${selected_closed_month=='-1' or None}" value="-1">全て表示する</option>
                  <option selected="${selected_closed_month=='-2' or None}" value="-2">表示しない</option>
                </select>
              </td>
            </tr>
            <tr>
              <td>
                <label>チケット登録日時によるフィルタリング</label>
                <select name="selected_created_month">
                  <option selected="${selected_created_month=='1' or None}" value="1">翌月以降に登録されたチケットを表示しない</option>
                  <option selected="${selected_created_month=='2' or None}" value="2">翌月に登録されたチケットを表示する</option>
                  <option selected="${selected_created_month=='-1' or None}" value="-1">全て表示する</option>
                </select>
              </td>
            </tr>
            <tr>
              <td>
                <input type="checkbox" name="show_cc_ticket" checked="${show_cc_ticket or None}" />&nbsp;関係者チケットを表示する<br/>
                <input type="hidden" name="show_cc_ticket" value="off" />
                <input type="hidden" name="year" value="${current.year}" />
                <input type="hidden" name="month" value="${current.month}" />
              </td>
            </tr>
          </table>
        </fieldset>
  
        <!-- Group Setting -->
        <fieldset id="group" class="collapsed">
          <legend class="foldable">Group</legend>
          <table class="list">
            <tbody id="group_template" style="display: none">
              <tr>
                <th style="width: 10px">Level1</th>
                <td py:with="selectable_ticket_fields=[x for x in ticket_fields if x.name not in ('summary', 'description')]">
                  <select>
                    <option value="" selected="selected"></option>
                    <option py:for="x in selectable_ticket_fields" value="${x.name}">${x.label}</option>
                  </select>
                </td>
              </tr>
            </tbody>
            <py:for each="index, group_field in enumerate(group_fields)">
            <tbody py:if="index &lt; len(group_fields)-1" id="group_field${index}">
              <tr>
                <th style="width: 10px">Level${index+1}</th>
                <td py:with="selectable_ticket_fields=[x for x in ticket_fields if x.name not in ('summary', 'description')]">
                  <select name="group_field${index}">
                    <option value="" selected="${group_field is None or None}"></option>
                    <option py:for="x in selectable_ticket_fields" value="${x.name}" selected="${group_field==x.name or None}">${x.label}</option>
                  </select>
                </td>
              </tr>
            </tbody>
            </py:for>
            <tbody id="add_group">
              <tr>
                <td class="actions" style="text-align: right;" colspan="4">
                  <input type="button" value="追加" onclick="addGroup()" />
                  <input type="button" value="削除" onclick="removeGroup()" />
                </td>
              </tr>
            </tbody>
          </table>
        </fieldset>
        
        <div id="update_button">
          <input type="submit" value="更新" />
        </div>
        <hr/>
      </form>
       
      <!-- worktime calendar -->
      <div py:if="len(nodes)==0">該当のチケットはありません。<br/><br/></div>
      <table id="tree">
        <thead>
          <tr>
            <!-- 
            <th py:for="index, group_field in enumerate(group_fields)" rowspan="4" nowrap="nowrap">
              <py:for each="x in ticket_fields">
                <py:if test="x.name==group_field">${x.label}</py:if>
              </py:for>
            </th>
            -->
            <th rowspan="4" class="ticket" nowrap="nowrap">チケット</th>
            <th rowspan="3" nowrap="nowrap">合計時間(総合計時間)<br/>/見積り時間</th>
            <!-- month -->
            <th colspan="${days_thismonth}">
              <div id="calender_selector">
                <form action="${href.worktime()}" onsubmit="return false">
                  <input class="left" type="button" value="&lt;&lt;${prev.month}月"
                         onclick="updateCalendar(${prev.year}, ${prev.month}); return false" />
                  <select id="year_selector" name="year"
                          onchange="updateCalendar(jQuery(this.form.year).val(),
                                                   jQuery(this.form.month).val());
                                    return false">
                    <option py:for="y in range(current.year-3,current.year+4)"
                           value="$y"
                           selected="${y==current.year or None}">$y</option>
                  </select>年
                  <select id="month_selector" name="month"
                          onchange="updateCalendar(jQuery(this.form.year).val(),
                                                   jQuery(this.form.month).val());
                                    return false">
                    <option py:for="m in xrange(1, 13)"
                           value="$m" selected="${m==current.month or None}">$m</option>
                  </select>月
                  <input class="right" type="button" value="${next.month}月&gt;&gt;"
                         onclick="updateCalendar(${next.year}, ${next.month}); return false" />
                </form>
              </div>
            </th>
          </tr>
          <!-- day -->
          <tr>
            <th py:for="x in range(days_thismonth)"
                class="day ${weekdays_css[x]} ${holiday_css[x]} ${today_css[x]}">${x+1}</th>
          </tr>
          <!-- weekday -->
          <tr>
            <th py:for="x in range(days_thismonth)"
                class="${weekdays_css[x]} ${holiday_css[x]} ${today_css[x]}">${num_to_weekday((start_week+x)%7)}</th>
          </tr>
          <tr>
            <th>
              <span id="t_total">${num_format(sum_all)}</span>
              (<span id="t_alltotal">${num_format(sum_workers_all)}</span>)<br/>/
              <span id="t_estimatedtotal">${num_format(sum_estimatedhours)}</span>
            </th>
            <th py:for="x in range(days_thismonth)" id="t_total_${date_map[x]}"
                class="${weekdays_css[x]} ${holiday_css[x]} ${today_css[x]}">${num_format(date_sum.get(date_map[x],0))}</th>
          </tr>
        </thead>
        <tbody>
          <py:for each="index, node in enumerate(nodes)">
          <tr py:with="ticket=node.ticket" id="${node.get_node_id()}"
              class="${node.get_parent_node_id()}">
            <!-- Ticket Group -->
            <td class="group" >
              <py:for each="g_index, group_field in enumerate(group_fields)">
                <py:if test="node.is_ticket() is False">${node.get_label(group_field)}</py:if>
                <py:if test="node.is_ticket() is True">
                  <a py:if="group_field=='summary'" style="z-index: ${9999-(index*g_index)}"
                     class="ticket ${is_closed(ticket) and 'closed' or ''}" href="${req.href.ticket(ticket.id)}">#${ticket.id}:${omit(ticket.summary,30)}
                    <span class="popup" style="text-decoration: none">
                      <strong>ID</strong>: #${ticket.id}<br/>
                      <strong>${ticket_field_map['type']}</strong>: ${ticket.type}<br/>
                      <strong>${ticket_field_map['summary']}</strong>: ${ticket.summary}<br/>
                      <strong>${ticket_field_map['reporter']}</strong>: ${format_author(ticket.reporter)}<br/>
                      <strong>${ticket_field_map['owner']}</strong>: ${format_author(ticket.owner)}<br/>
                      <strong>${ticket_field_map['cc']}</strong>: ${format_author(ticket.cc)}<br/>
                      <strong>登録日時</strong>: ${to_localtime(req, ticket.time)}<br/>
                      <strong>最終更新日時</strong>: ${to_localtime(req, ticket.changetime)}<br/>
                      <strong>${ticket_field_map['status']}</strong>: ${ticket.status}
                      <py:if test="is_closed(ticket)">
                      (${ticket.resolution})
                      </py:if>
                      <br/>
                      <strong>${ticket_field_map['description']}</strong>: <pre class="description">${omit_line(ticket.description,5)}</pre>
                    </span>
                  </a>
                </py:if>
              </py:for>
            </td>
            <py:if test="node.is_ticket()">
            <!-- sum for this ticket -->
            <td>
              <span id="${ticket.id}_sum">${num_format(ticket_sum.get(ticket.id, 0))}</span>
              <span id="${ticket.id}_allsum">(${num_format(ticket.worktime_sum)})</span>
              /
              <span id="${ticket.id}_estimated">${num_format(ticket.estimatedhours)}</span>
            </td>
            <!-- worktime -->
            <td py:for="x in range(days_thismonth)" id="${ticket.id}:${date_map[x]}" 
                class="worktime ${weekdays_css[x]} ${holiday_css[x]} ${today_css[x]}"
                tabindex="${1+index+(len(nodes)*x)}">
              <py:with vars="worktime=ticket['worktimes'][date_map[x]]">
                <py:if test="str(worktime) != 'undefined'">
                  ${worktime}
                </py:if>
              </py:with>
            </td>
            </py:if>
            <py:if test="not node.is_ticket()">
            <td>
            </td>
            <!-- worktime -->
            <td py:for="x in range(days_thismonth)" 
                class="${weekdays_css[x]} ${holiday_css[x]} ${today_css[x]}">
            </td>
            </py:if>
          </tr>
          </py:for>
        </tbody>
      </table>
    </div>
    <div id="help"></div>
  </body>
</html>
