<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" th:lang="${#ctx.getLocale().toLanguageTag()}" >
    <head>
        <title>Renkan</title>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>

        <link rel="shortcut icon" href="../../static/img/favicon.ico" th:href="@{/static/img/favicon.ico}"/>
        
        <script th:remove="all" type="text/javascript" src="../../static/lib/jquery.min.js"></script>
        <script th:remove="all" type="text/javascript" src="../../static/js/thymol.js"></script>
        
        <script src="../../static/lib/jquery.min.js" th:src="@{/static/lib/jquery.min.js}" ></script>
        <script src="../../static/lib/jquery-ui/jquery-ui.min.js" th:src="@{/static/lib/jquery-ui/jquery-ui.min.js}" ></script>
        <script src="../../static/lib/underscore-min.js" th:src="@{/static/lib/underscore-min.js}" ></script>
        <script src="../../static/lib/URI.js" th:src="@{/static/lib/URI.js}" ></script>

        <link href="../../static/lib/jquery-ui/css/ui-lightness/jquery-ui.min.css" rel="stylesheet" th:href="@{/static/lib/jquery-ui/css/ui-lightness/jquery-ui.min.css}"/>
        <link href="../../static/css/style.css" rel="stylesheet" th:href="@{/static/css/style.css}"/>
        <link href="../../static/css/index.css" rel="stylesheet" th:href="@{/static/css/index.css}"/>

    </head>
    <body>
      <div id="container">
        <div id="wrapper">
            <header id="header">
                <h1><a href="renkanIndex.html" th:href="@{'/'}" id="home-link" th:text="#{renkanIndex.renkan_space}">Renkan Space</a>: <span th:text="${space.title}">Titre</span></h1>
                <div id="headerNav" th:include="fragment/pageFragment :: headerNavFragment"></div>
            </header>
            <div id="inner">
                <div id="label" class="translate" th:text="#{renkanIndex.renkan_exp}">Create a Renkan</div> 
                <form action="#" id="new-renkan-form">
                    <fieldset id="form-fields">
                        <div id="title-field"><label th:text="#{renkanIndex.renkan_title}" for="renkantitle">title</label><input type="text" id="renkantitle" autofocus="autofocus" x-webkit-speech="x-webkit-speech"/></div>
                        <div id="file-field"><label th:text="#{renkanIndex.renkan_file}" for="renkanfile">file</label><input type="file" id="renkanfile"/></div> 
                    </fieldset>
                    <div id="form-submit"><button type="submit">OK</button></div>
                </form>
            </div>
            <div id="project-list-container">
              <h2 th:text="#{renkanIndex.project_list}">Project list</h2>
              <div id="project-filter-container">
                  <form method="get"> 
                      <input type="text" id="project-filter" name="filter" placeholder="filter title" th:placeholder="#{renkanIndex.project_filter}" th:value="${param['filter']}?${param['filter'][0]}:''" /> 
                      <button type="submit">OK</button>
                  </form>
              </div>
              <div th:include="fragment/paginationFragment :: paginationFragment" class="pagination-container">
                  <div>
                      <a href="#?p.page=1">&lt;&lt;</a>
                      <a href="#?p.page=3">&lt;</a>
                      <span>...</span>
                      <a href="#?p.page=2">2</a>
                      <a href="#?p.page=3">3</a>
                      <span>4</span>
                      <a href="#?p.page=5">5</a>
                      <a href="#?p.page=6">6</a>
                      <span>...</span>
                      <a href="#?p.page=5">&gt;</a>
                      <a href="#?p.page=7">&gt;&gt;</a> 
                  </div>
              </div>
              <table th:with="columnSort=${param['p.sort']}?${param['p.sort'][0]}:'updated',sortDir=${param['p.sort.dir']}?${param['p.sort.dir'][0]}:'desc'">
                <thead th:with="sortDirInv=${sortDir}=='desc'?'asc':'desc'">
                  <tr>
                      <th th:with="sorted=(${columnSort}=='title')"><span th:text="#{renkanIndex.project_name}">Name</span><form method="get" class="proj-sort-form"><input type="hidden" name="p.sort" value="title"/><input type="hidden" name="p.sort.dir" th:value="${sorted}?${sortDirInv}:'desc'"/><input th:if="${param['filter']}" name="filter" type="hidden" th:value="${param['filter'][0]}"/><input type="submit" class="proj-sortable-col" th:class="${sorted}?'proj-sort-'+${sortDir}+'-col':'proj-sortable-col'" value=""/></form></th>
                      <th th:with="sorted=(${columnSort}=='updated')"><span th:text="#{renkanIndex.project_updated}">Updated</span><form method="get" class="proj-sort-form"><input type="hidden" name="p.sort" value="updated"/><input type="hidden" name="p.sort.dir" th:value="(${sorted})?${sortDirInv}:'desc'"/><input th:if="${param['filter']}" name="filter" type="hidden" th:value="${param['filter'][0]}"/><input type="submit" class="proj-sort-desc-col" th:class="${sorted}?'proj-sort-'+${sortDir}+'-col':'proj-sortable-col'" value=""/></form></th>
                      <th th:with="sorted=(${columnSort}=='created')"><span th:text="#{renkanIndex.project_creation}" >Creation</span><form method="get" class="proj-sort-form"><input type="hidden" name="p.sort" value="created"/><input type="hidden" name="p.sort.dir" th:value="${sorted}?${sortDirInv}:'desc'"/><input th:if="${param['filter']}" name="filter" type="hidden" th:value="${param['filter'][0]}"/><input type="submit" class="proj-sort-asc-col" th:class="${sorted}?'proj-sort-'+${sortDir}+'-col':'proj-sortable-col'" value=""/></form></th>
                      <th th:text="#{renkanIndex.project_commands}">Comm.</th>
                  </tr>
                </thead>
                <tbody>
                  <tr th:each="project: ${page}">
                    <th th:text="${project.title}">title</th>
                    <td th:text="${project.updated}?${#dates.format(project.updated, #messages.msg('date.format'))}:''">update</td>
                    <td th:text="${#dates.format(project.created, #messages.msg('date.format'))}">date</td>
                    <td>
                        <a href="#" th:href="@{'/p/'+${project.id}(cowebkey=${project.getKey(2)})}" th:title="#{renkanIndex.project_edit_link}"><span class="ui-icon ui-icon-pencil renkan-basic-action"></span></a>
                        <a href="#" th:href="@{'/p/pub/'+${project.id}(cowebkey=${project.getKey(1)})}" th:title="#{renkanIndex.project_render_link}"><span class="ui-icon renkan-icon-eye renkan-basic-action"></span></a>
                        <span class="ui-icon ui-icon-triangle-1-e renkan-basic-action renkan-action-button" th:id="'renkan-action-button-'+${project.id}" th:attr="data-project_id=${project.id}"></span>
                    </td>
                  </tr>
                </tbody>
              </table>
              <ul th:each="project: ${page}" class="action-menu" id="action-menu-" th:id="'action-menu-'+${project.id}">
                 <li><a href="#" th:href="@{'/p/'+${project.id}(cowebkey=${project.getKey(2)})}"><span class="ui-icon ui-icon-pencil"></span><span th:text="#{renkanIndex.project_edit_link}">Edit project</span></a></li>
                 <li><a href="#" th:attr="data-project_id=${project.id}" class="copy-project"><span class="ui-icon ui-icon-copy"></span><span th:text="#{renkanIndex.project_copy_link}">Copy project</span></a></li>
                 <li><a href="#" th:attr="data-project_id=${project.id},data-project_title=${project.title}" class="delete-project"><span class="ui-icon ui-icon-trash"></span><span th:text="#{renkanIndex.project_delete_link}">Delete project</span></a></li>
                 <li><a href="#" th:href="@{'/p/pub/'+${project.id}(cowebkey=${project.getKey(1)})}"><span class=" ui-icon renkan-icon-eye"></span><span th:text="#{renkanIndex.project_render_link}">View project</span></a></li>
                 <li><a href="#" th:href="@{'/p/exp/'+${project.id}}"><span class="ui-icon ui-icon-arrowthickstop-1-s"></span><span th:text="#{renkanIndex.project_export_link}">Export project</span></a></li>
             </ul>
              
            </div>
        </div>
        <footer id="footer" th:include="fragment/pageFragment :: footerFragment">
            <div id="version">© <span class="version-date">2014</span> <a href="http://www.iri.centrepompidou.fr" target="_blanck">IRI</a> - Version <span class="version-version">0.0</span></div>
        </footer>        
      </div>
      <script th:inline="javascript" >
      /*<![CDATA[*/
          'use strict';
          function go2Title()
          {
              var renkantitle = $("#renkantitle").val(),
                  renkanfiles = $("#renkanfile").prop("files");
              
              if(renkantitle.length === 0 && renkanfiles.length === 0) {
              	var alert_message = /*[[#{renkanIndex.js.empty_form_error}]]*/"Please enter a title or a file"; 
              	alert(alert_message);
              	return false;
              }
              var post_url = /*[[@{/rest/projects/}]]*/"/rest/projects/",
                  deferred = $.Deferred();
              
              deferred.done(function(new_renkan) {
                  new_renkan.space_id = /*[[${space.id}]]*/"_";
                  $.ajax(post_url, {
                      data:JSON.stringify(new_renkan),
                      type: "POST",
                      dataType: "json",
                      contentType: "application/json; charset=UTF-8"
                  }).done(function(project){
                      var uri = new URI(window.location);
                      window.location = uri.setSearch("p.sort","created").setSearch("p.sort.dir", "desc").href();
                  });
              });

              if(renkanfiles.length === 0) {
                  deferred.resolve({
                      title: renkantitle,
                      description: "",
                      uri: null,
                  });
              }
              else {
                  fr = new FileReader();
                  fr.onload = function() {
                      var new_renkan = JSON.parse(fr.result);
                      if(renkantitle.length > 0) {
                          new_renkan.title = renkantitle;
                      }
                      if(typeof new_renkan.created !== "undefined") {
                          delete new_renkan.created;
                      }
                      if(typeof new_renkan.updated !== "undefined") {
                          delete new_renkan.updated;
                      }
                      deferred.resolve(new_renkan);
                  };
                  fr.readAsText(renkanfiles[0]);
              }
          }

          function copyProject(project_id)
          {
          	var post_url = /*[[@{/p/copy}]]*/"#";
              $.post(post_url, {"project_id": project_id})
                  .done(function(p){
                      window.location.reload();
              });
          }
      
          function deleteProject(project_id, project_title)
          {
          	var message = /*[[#{renkanIndex.project_delete_confirm}]]*/"Delete project \"<%= title %>\"";
          	if(confirm(_.template(message, {title: project_title}))) {
                  var delete_url = /*[[@{/rest/projects}]]*/"#";
                  $.ajax(delete_url+"/"+project_id, {
                      type: "DELETE"	
                  }).done(function(){
                  	window.location.reload();
                  });
          	}
          }
          
          function createMenuHandler(menu, timeoutCallback) {
              return function(e) {
                  menu.toggle();
                  $(e.target).toggleClass("ui-icon-triangle-1-e").toggleClass("ui-icon-triangle-1-se");
                  $('.renkan-action-button').each(function() {
                      if($(this).prop('id') !== $(e.target).prop('id')) {
                          $(this).removeClass("ui-icon-triangle-1-se").addClass("ui-icon-triangle-1-e");
                          $("#action-menu-"+$(this).data('project_id')).hide();
                          var timeout = $("#action-menu-"+$(this).data('project_id')).data('blurtimeout');
                          if(typeof timeout !== 'undefined') {
                              clearTimeout(menu.data('blurtimeout'));
                              menu.removeData('blurtimeout');
                          }
                      }
                  });
                  if(menu.is(":visible")) {
                      menu.data('blurtimeout', setTimeout( timeoutCallback,5000));
                  } 
              }
          }
          
          $(function(){
             
              $(".copy-project").click(function(event) {
                  var project_id = $(event.currentTarget).data("project_id");
                  copyProject(project_id);
              });

              $(".delete-project").click(function(event) {
                  deleteProject($(event.currentTarget).data("project_id"), $(event.currentTarget).data("project_title"));
              });

              
              $("#new-renkan-form").submit(function(e) {
                  e.preventDefault();
                  go2Title();
                  return false;
              });
              
              $("#import-renkan-form").submit(function(e) {
                  e.preventDefault();
                  console.log("import form event :", e);
              });
              
              $('.renkan-action-button').each(function() {
                  var projectId = $(this).data('project_id');
                  var menu = $('#action-menu-'+projectId).menu().position({ my: "left top", at: "right top", of: this }).hide();
                  var that = this;
                  
                  var timeoutCallback = function() {
                      menu.hide();
                      $(that).removeClass("ui-icon-triangle-1-se").addClass("ui-icon-triangle-1-e");
                      menu.removeData('blurtimeout');
                  };
                  
                  menu.on('menufocus', function() {
                      clearTimeout(menu.data('blurtimeout'));
                      menu.removeData('blurtimeout');
                  });
                  menu.on('menublur',function(e) {
                      menu.data('blurtimeout', setTimeout( timeoutCallback,200));
                  });
                  
                  $(this).click(createMenuHandler(menu, timeoutCallback));
              });
          });

      /*]]>*/
      </script>
    </body>
</html>
