<style type="text/css">
  ul.no_list_style li{
    list-style: none;
  }
  ul.no_list_style li label {
    font-weight: bold;
  }
  #info_texts{
    white-space: pre;
  }
</style>
<table class="table main-list default footable-loaded">
  <thead>
    <tr>
      <th><%=t('client_management.server_name')%></th>
      <th><%=t('client_management.domain_name')%></th>
      <th>Port</th>
      <th><%=t('client_management.status')%></th>
      <th><%=t('client_management.action')%></th>
    </tr>
  </thead>
  <tbody>
    <% status_relation = {"creating"=>"<span style=\"color: skyblue;\">creating</span>".html_safe,"error"=>"<span style=\"color: red;\">error</span>".html_safe,"finish"=>"<span style=\"color: darkseagreen;\">finish</span>".html_safe,"closed"=>"<span style=\"color: red;\">closed</span>".html_safe}%>
    <% time_now = Time.now %>
    <% @sites.each do |site|%>
      <tr>
        <td><%=site.server_type%></td>
        <td>
        <% site.domain_name.split(" ").each_with_index do |domain_name,i| %>
          <% domain_link = ((site.get_port.to_s == "443") ? "https" : "http") + '://' + domain_name + ((site.get_port.to_s != '80' && site.get_port.to_s != '443') ? ':'+site.get_port.to_s : '') %>
          
            <% if i!=0 %>
              <br>
            <% end %>
            <%= link_to domain_name, domain_link, :title => "Open #{domain_link} in new window", :target=>"_blank" %>
        <% end %>
        </td>
        <td><%=site.display_port%></td>
        <td class="site_status"><%= (site.status.blank? ? "not yet create" : status_relation[site.status]) %></td>
        <td>
          <a href="javascript:void(0)" title="<%=t("client_management.see_logs_for_site",{:site=>site.domain_name})%>" class="btn btn-primary see_infos" data-id="<%=site.id.to_s%>"><%=t('client_management.see_logs')%></a>
          <% if site.status.blank? || (site.status == 'creating' && (time_now - site.updated_at > 60)) %>
            <a href="javascript:void(0)" title="create <%=site.domain_name%>" class="btn btn-primary create_site" data-id="<%=site.id.to_s%>"><%=t('client_management.create_site')%></a>
          <% elsif site.status == "error" || site.status == "finish" %>
            <% if site.created_at > Time.now - 3.day %>
              <a href="javascript:void(0)" title="recreate <%=site.domain_name%>" class="btn btn-primary recreate_site" data-id="<%=site.id.to_s%>"><%=t('client_management.recreate_site')%></a>
            <% end %>
            <a href="javascript:void(0)" title="<%=t("client_management.delete_site_for_site",{:site=>site.domain_name})%>" class="btn btn-primary delete_site" data-id="<%=site.id.to_s%>"><%=t('client_management.delete_site')%></a>
            <a href="javascript:void(0)" title="<%=t("client_management.close_site_for_site",{:site=>site.domain_name})%>" class="btn btn-danger close_site" data-id="<%=site.id.to_s%>"><%=t('client_management.close_site')%></a>
            <a href="javascript:void(0)" title="Restart <%=site.domain_name%>" class="btn btn-primary open_site btn-success" data-id="<%=site.id.to_s%>"><%=t('client_management.restart_site')%></a>
          <% elsif site.status == "closed" %>
            <a href="javascript:void(0)" title="<%=t("client_management.delete_site_for_site",{:site=>site.domain_name})%>" class="btn btn-primary delete_site" data-id="<%=site.id.to_s%>"><%=t('client_management.delete_site')%></a>
            <a href="javascript:void(0)" title="<%=t("client_management.start_site_for_site",{:site=>site.domain_name})%>" class="btn btn-success open_site" data-id="<%=site.id.to_s%>"><%=t('client_management.start_site')%></a>
          <% end%>
          <% if site.status.present? %>
            <% if site.rails_env == "production" %>
              <a href="javascript:void(0)" title="<%=t("client_management.switch_to_development")%>" class="btn btn-primary open_site btn-success" data-id="<%=site.id.to_s%>" data-env="development"><%=t('client_management.switch_to_development')%></a>
            <% else %>
              <a href="javascript:void(0)" title="<%=t("client_management.switch_to_production")%>" class="btn btn-primary open_site btn-success" data-id="<%=site.id.to_s%>" data-env="production"><%=t('client_management.switch_to_production')%></a>
            <% end %>
          <% end %>
          <a href="javascript:void(0)" title="<%=t("client_management.exec_commands_on_site",{:site=>site.domain_name})%>" class="btn btn-primary exec_commands" data-id="<%=site.id.to_s%>"><%=t('client_management.exec_commands')%></a>
          <a href="<%=admin_site_panel_edit_site_path+"?id=#{site.id}&type=detail"%>" title="<%=t("client_management.see_detail_for_site",{:site=>site.domain_name})%>" class="btn btn-info see_detail" data-id="<%=site.id.to_s%>"><%=t('client_management.detail')%></a>
          <a href="<%=admin_site_panel_edit_site_path+"?id=#{site.id}&type=delete_from_list"%>" title="<%=t("client_management.delete_from_list_for_site",{:site=>site.domain_name})%>" class="btn btn-danger" data-id="<%=site.id.to_s%>"><%=t('client_management.delete_from_list')%></a>
          <% if site.status == "finish" || site.status == "closed" %>
            <a href="<%=admin_site_panel_path+"?copy_id=#{site.id}"%>" title="<%=t('client_management.copy_site_hint')%>" class="btn btn-primary"><%=t('client_management.copy_site')%></a>
            <a data-id="<%= site.id %>" title="<%=t('client_management.edit_cert_setting')%>" class="btn btn-primary open-cert-form"><%=t('client_management.edit_cert_setting')%></a>
            <div id="<%= "cert-form-#{site.id}" %>" class="cert-form" style="display: none;">
              <%= form_for site, as: 'site', url: "/#{I18n.locale}/admin/site_panel/update_cert_setting",method: "post" do |f| %>
                <div>
                  CSR txt path:&nbsp;
                  <%= f.text_field 'cert_ver_location_path',style: 'width: calc(100% - 8em);margin: 0;',:id=>nil %>
                </div>
                <div>
                  CSR txt content:&nbsp;
                  <%= f.text_area 'cert_ver_file_content',class: 'ckeditor',value: site.cert_ver_file_content.to_s.gsub("\n",'<br>'),:id=>nil %>
                </div>
                <%= f.hidden_field 'id',:id=>nil %>
                <%= f.submit 'edit',class: 'btn btn-primary' %>
              <% end %>
            </div>
          <% end %>
          <% if site.status != "" %>
            <a data-id="<%= site.id %>" title="<%=t('client_management.https_setting')%>" class="btn btn-primary https_setting"><%=t('client_management.https_setting')%></a>
            <a title="<%=t('client_management.super_manager_management')%>" class="btn btn-primary super_manager_management" href="<%=super_manager_management_for_site_admin_site_panel_path(:id=>site.id) %>"><%=t('client_management.super_manager_management')%></a>
          <% end %>
          </td>
      </tr>
    <% end %>
  </tbody>
</table>
<div class="bottomnav clearfix">
  <div class="pagination pagination-centered"><%=paginate(@sites)%></div>
  <a class="btn btn-primary pull-right" href="<%=admin_site_panel_path%>" title="Create new web"><%=t(:add)%></a>
</div>
<script type="text/javascript">
  var close_info = false;
  var timeout_id;
  var status_relation = {"creating":"<span style=\"color: skyblue;\">creating</span>","error":"<span style=\"color: red;\">error</span>","finish": "<span style=\"color: darkseagreen;\">finish</span>","closed":"<span style=\"color: red;\">closed</span>"};
  var need_close_info = false;
  $(document).on("change", "input[data-key=\"{{create_super_manager}}\"]", function() {
    if ($(this).prop('checked')){
      $('#super_manager_div').show()
    }else{
      $('#super_manager_div').hide()
    }
  });
  $(document).ready(function(){
    function see_infos(id){
      if(!close_info){
        var request = $.post("<%=admin_site_panel_site_infos_path%>",{"id":id});
        request.done(function(data){
          var infos = request.responseJSON.infos;
          var status = request.responseJSON.status;
          if($("#info_texts").length == 0)
            return infos.join("\n")
          else{
            $("#info_texts").html(infos.join("\n"));
            if(status == "")
              var status_text = "not yet create";
            else
              var status_text = status_relation[status];
            if(status == "finish"){
              var params = {}
              var params_text = window.location.search.split(/[?&]/).slice(1);
              params_text.forEach(function(text){
                if(text.split("=")[0] != "")
                  params[text.split("=")[0]] = text.split("=")[1].split("#")[0].split("&")[0];
              });
              var new_params_text = "?";
              Object.keys(params).forEach(function(key){
                var value = params[key];
                if(key == "id"){
                  if(value != id){
                    new_params_text += (key+"="+value+"&")
                  }
                }else
                  new_params_text += (key+"="+value+"&")
              });
              if(new_params_text[new_params_text.length -1] == "&")
                new_params_text = new_params_text.substr(0,new_params_text.length - 1)
              if(params["id"] == id || window.refresh_flag || need_close_info){
                close_info = true;
                window.setTimeout(function(){
                  var current_location_search = window.location.search;
                  if(current_location_search == ''){
                    current_location_search = '?';
                  }
                  if(window.confirm("<%=t('client_management.finished_reload_page')%>")){
                    if(new_params_text == current_location_search){
                      window.location.reload();   
                    }else{
                      window.location.search = new_params_text;
                    }
                  }
                }, 1000);
              }
            }else if(status == "changing"){
              window.refresh_flag = true
            }else{
              need_close_info = true;
            }
            $(".see_infos[data-id="+id+"]").parent().siblings(".site_status").html(status_text);
            //msg_end.scrollIntoView();
            timeout_id = window.setTimeout(see_infos(id),1000);
          }
        }).fail(function() {
          window.location.reload();
        })
      }else{
        window.clearTimeout(timeout_id);
      }
    };
    function show_infos_dialog(item){
      close_info = true;
      window.clearTimeout(timeout_id);
      close_info = false;
      var id = item.data("id");
      if($("#dialog-confirm").length == 0){
        $("#main-wrap").before("<div id='dialog-confirm' title='site infos'>"+
                      "<div style='clear:both;'></div><div id='info_texts'>"+see_infos(id)+"</div><div id='msg_end' style='height:0px; overflow:hidden'></div>"+
                      "</div>");
      }else{
        see_infos(id);
      };
      $( "#dialog-confirm" ).dialog({
        resizable: true,
        minHeight: 300,
        maxHeight: 400,
        modal: true,
        width: '80%',
        close: function(){
          close_info = true;
          need_close_info = false;
        },
        buttons: {
          "<%= t('client_management.confirm') %>": function(){
            $( this ).dialog( "close" );
          },
          "stop update": function(){
            close_info = true;
          }
        }
      });
    }
    $('.see_infos').click(function(){show_infos_dialog($(this));});
    $('.create_site').click(function(){
      close_info = true;
      window.clearTimeout(timeout_id);
      close_info = false;
      var item = $(this);
      var id = item.attr("data-id");
      $.post("<%= admin_site_panel_create_site_path %>",{'id': id}).done(function(){
        show_infos_dialog(item);
      }).fail(function() {
        window.location.reload();
      })
    });
    $('.recreate_site').click(function(){
      if(window.confirm("Do you really want to recreate this site?")){
        if(window.confirm("Do you really want to recreate this site?")){
          var _this = $(this);
          if($("#dialog-confirm").length == 0){
            $("#main-wrap").before("<div id='dialog-confirm' title='site infos'>"+
                          "<div style='clear:both;'></div><div id='info_texts'>"+"Do you really want to "+$(this).attr('title')+"?</div>"+"<input id=\"confirm_input\"/ placeholder=\"<%= t('client_management.please_input_confirm_recreate') %>\" style=\"width: 17em;\">"+"<div id='msg_end' style='height:0px; overflow:hidden'></div>"+
                          "</div>");
          }else{
            $("#info_texts").html("Do you really want to "+_this.attr('title')+".");
            if($('#confirm_input').length == 0){
              $('#info_texts').after("<input id=\"confirm_input\"/ placeholder=\"<%= t('client_management.please_input_confirm_recreate') %>\" style=\"width: 17em;\">");
            }else{
              $('#confirm_input').css('display','block');
              $('#confirm_input').val('');
            }
          }
          $( "#dialog-confirm" ).dialog({
            resizable: true,
            minHeight: 200,
            maxHeight: 400,
            modal: true,
            width: '80%',
            open: function(){
              $('#confirm_input').blur();
            },
            close: function(){
              $('#confirm_input').css('display','none');
              $( this ).dialog( "close" );
            },
            buttons: {
              "<%= t('client_management.confirm') %>": function(){
                if($('#confirm_input').val().match(/<%= t('client_management.confirm_recreate') %>/gi)){
                  $('#confirm_input').val('');
                  $('#confirm_input').css('display','none');
                  close_info = true;
                  window.clearTimeout(timeout_id);
                  close_info = false;
                  var id =_this.attr("data-id");
                  var item = _this;
                  $.post("<%= admin_site_panel_create_site_path %>",{'id': id}).done(function(){
                    show_infos_dialog(item);
                  }).fail(function() {
                    window.location.reload();
                  })
                }else{
                  alert("<%= t('client_management.please_input_confirm_recreate').html_safe %>");
                  $('#confirm_input').focus();
                }
              },
              "<%= t('client_management.cancel') %>": function(){
                $('#confirm_input').css('display','none');
                $( this ).dialog( "close" );
              }
            }
          });
        }
      }
    });
    $('.delete_site').click(function(){
      var item = $(this);
      if(window.confirm("Do you really want to delete this site?")){
        if(window.confirm("Do you really want to delete this site?")){
          if($("#dialog-confirm").length == 0){
            $("#main-wrap").before("<div id='dialog-confirm' title='site infos'>"+
                          "<div style='clear:both;'></div><div id='info_texts'>"+"Do you really want to "+$(this).attr('title')+"?</div>"+"<input id=\"confirm_input\"/ placeholder=\"<%= t('client_management.please_input_confirm_delete') %>\" style=\"width: 17em;\">"+"<div id='msg_end' style='height:0px; overflow:hidden'></div>"+
                          "</div>");
          }else{
            $("#info_texts").html("Do you really want to "+$(this).attr('title')+".");
            if($('#confirm_input').length == 0){
              $('#info_texts').after("<input id=\"confirm_input\"/ placeholder=\"<%= t('client_management.please_input_confirm_recreate') %>\" style=\"width: 17em;\">");
            }else{
              $('#confirm_input').css('display','block');
              $('#confirm_input').val('');
            }
          }
          $( "#dialog-confirm" ).dialog({
            resizable: true,
            minHeight: 200,
            maxHeight: 400,
            modal: true,
            width: '80%',
            open: function(){
              $('#confirm_input').blur();
            },
            close: function(){
              $('#confirm_input').css('display','none');
              $( this ).dialog( "close" );
            },
            buttons: {
              "<%= t('client_management.confirm') %>": function(){
                if($('#confirm_input').val().match(/<%= t('client_management.confirm_delete') %>/gi)){
                  $('#confirm_input').val('');
                  $('#confirm_input').css('display','none');
                  $.post("<%=admin_site_panel_edit_site_path%>",{'id':item.attr("data-id"),'type':'delete'}).done(function(data){
                      show_infos_dialog(item);
                      item.remove();
                  });
                }else{
                  alert("<%= t('client_management.please_input_confirm_delete').html_safe %>");
                  $('#confirm_input').focus();
                }
              },
              "<%= t('client_management.cancel') %>": function(){
                $('#confirm_input').css('display','none');
                $( this ).dialog( "close" );
              }
            }
          });
        }
      }
    });
    $(".https_setting").click(function(){
      var item = $(this);
      var id = item.data("id");
      if($("#https_setting-dialog-confirm").length == 0){
        $("#main-wrap").before("<div id='https_setting-dialog-confirm' title='<%=t("client_management.https_setting")%>'>"
                    +"<div id='https_setting_area'></div>"+
                      "</div>");
      }
      $('#https_setting_area').attr('data-id',id);
      $.get("<%=get_certs_for_site_admin_site_panel_index_path%>",{id: id}).done(function(html){
        $('#https_setting_area').html(html);
        $( "#https_setting-dialog-confirm" ).dialog({
          resizable: true,
          minHeight: 300,
          maxHeight: 400,
          modal: true,
          width: '80%',
          close: function(){$( this ).dialog( "close" );},
          buttons: {
          "<%= t(:submit) %>": function(){
            var redirect_to_https = ($('#https_setting_area [name="redirect_to_https"]:checked').length != 0);
            var site_cert_id = $('#https_setting_area [name="site_cert"]:checked').eq(0).val();
            if(site_cert_id != undefined){
              $.post("<%=admin_site_panel_edit_site_path%>",{'id': id,'type':'select_cert','site_cert_id': site_cert_id,'redirect_to_https': redirect_to_https}).done(function(response){
                show_infos_dialog(item);
              });
            }
            $( this ).dialog( "close" );
          },
          }
        });
      })
    })
    $('.close_site').click(function(){
      var item = $(this);
      $.post("<%=admin_site_panel_edit_site_path%>",{'id':$(this).attr("data-id"),'type':'close'}).done(function(){
        show_infos_dialog(item);
        item.remove();
      });
    });
    $('.open_site').click(function(){
      var item = $(this);
      var env = item.data("env");
      if( env == undefined )
        env = "";
      $.post("<%=admin_site_panel_edit_site_path%>",{'id':$(this).attr("data-id"),'type':'open','env': env}).done(function(){
        show_infos_dialog(item);
        item.remove();
      });
    });
    $('.exec_commands').click(function(){
      show_exec_commands_block($(this).attr('data-id'));
    });
    function show_exec_commands_block(id){
      if($("#exec-commands-dialog-confirm").length == 0){
        var built_in_commands = "<div><ul class='no_list_style'>"
        <% render :partial => "get_commands_list" %>
        var command_trans = <%= @command_trans.to_json.html_safe %>;
        Object.keys(command_trans).forEach(function(k){
          built_in_commands += "<li><label><input class='built_in_commands' type='checkbox' data-key='{{"+ k +"}}'>" + command_trans[k] + "</label></li>"
        })
        built_in_commands += "</ul></div>"
        $("#main-wrap").before("<div id='exec-commands-dialog-confirm' title='Commands to Exec'>" +
          "<div style='clear:both;'></div>"+
          built_in_commands+
          "<div style=\"display: none;\" id=\"super_manager_div\"><input type=\"text\" placeholder=\"account\" name=\"account\"><br><input type=\"password\" placeholder=\"password\" name=\"password\" minlength=\"8\"></div>"+
          "<textarea style='height: 200px;width: 100%;' id='commands_area' data-id='"+id+"'></textarea>"+
          "</div>");
      }else{
        $('#commands_area').attr('data-id',id);
      };
      $( "#exec-commands-dialog-confirm" ).dialog({
        resizable: true,
        minHeight: 300,
        maxHeight: 400,
        modal: true,
        width: '80%',
        close: function(){$( this ).dialog( "close" );},
        buttons: {
        "<%= t(:submit) %>": function(){$( this ).dialog( "close" );exec_commands()},
        }
      });
    }
    function exec_commands(){
      var commands = "";
      var built_in_commands_selected = [];
      $("input.built_in_commands:checked").each(function(i,v){
        built_in_commands_selected.push($(v).data("key"));
      })
      commands += built_in_commands_selected.join("////");
      commands += $('#commands_area').val().replace(/(\r\n|\n)/g,"////");
      var id = $('#commands_area').attr('data-id');
      $.post("<%=admin_site_panel_edit_site_path%>",{'id':id,'commands':commands,'account': $('input[name="account"]').val(),'password': $('input[name="password"]').val()}).done(function(){
        show_infos_dialog($('.see_infos[data-id="'+id+'"]').eq(0));
      });
    }
    <% if !params[:id].blank? %>
      see_infos("<%=params[:id]%>");
      $( "#dialog-confirm" ).dialog({
          resizable: true,
          minHeight: 300,
          maxHeight: 400,
          width: '80%',
          modal: true,
          close: function(){$( this ).dialog( "close" );close_info = true;},
          buttons: {
          "<%= t('client_management.confirm') %>": function(){$( this ).dialog( "close" );close_info = true;},
          "stop update": function(){close_info = true;}
          }
      });
    <% end %>
    $(".cert-form").dialog({
        autoOpen: false,
        show: "blind",
        modal: true,
        width: '90vw',
        maxHeight: '80vh',
        open: function() {
            $(this).css("max-height", '80vh');
        }
    });
    $('.open-cert-form').click(function(){
      $('#cert-form-'+$(this).data('id')).dialog('open')
    })
  })
</script>
<style type="text/css">
  .delete_site, .recreate_site{
    background: #7d1a23;
  }
  .delete_site:hover, .delete_site:focus, .recreate_site:hover, .recreate_site:focus{
    background: #eb1d30;
  }
</style>