<% content_for :page_specific_css do %>
  <%= stylesheet_link_tag "lib/main-forms" %>
<% end %>
<% content_for :page_specific_javascript do %>
<% end %>
<%#= f.error_messages %>
<fieldset>
<!-- Input Area -->
  <div class="input-area">

    <!-- Module Tabs -->
    <div class="nav-name"><strong><%= t(:module) %></strong></div>
    <ul class="nav nav-pills module-nav">
        <li class="active">
          <a href="#basic" data-toggle="tab"><%= t(:basic) %></a>
        </li>
    </ul>

    <!-- Module -->
    <div class="tab-content module-area">
      <!-- Basic Module -->
      <div class="tab-pane fade in active" id="basic">
        <% copy_source = SiteConstruct.find(params[:copy_id]) rescue nil %>
        <% if copy_source %>
          <div class="control-group">
              <label class="control-label muted"><%= t("client_management.copy_source") %></label>
              <div class="controls">
                <a title="<%= copy_source.site_name %>" href="<%= copy_source.get_domain_name %>" style="font-weight: bold; font-size: 1.3em;"><%= copy_source.site_name %></a>
              </div>
              <%= f.hidden_field :copy_id, :value => params[:copy_id] %>
          </div>
          <div class="control-group">
              <label class="control-label muted"><%= t("client_management.only_copy_installed_module") %></label>
              <div class="controls">
                <%= f.check_box :only_copy_installed_module %>
              </div>
              <%= f.hidden_field :copy_id, :value => params[:copy_id] %>
          </div>
        <% end %>
        <% server_types = SiteConstruct.server_types %>
        <div class="control-group">
          <%= f.label :server_type ,"Server", :class => "control-label muted" %>
          <div class="controls">
            <%= f.select :server_type, server_types %>
          </div>
        </div>

        <div class="control-group">
          <%= f.label :root_domain ,"Root Domain", :class => "control-label muted" %>
          <div class="controls" id="root_domain_group">
            <div class="root_domain_group">
              <%= select_tag :root_domain, 
                    options_for_select((SiteServer.where(:server_name=>server_types.first).first.domain_names.collect{ |u| [u, u] } rescue [])), 
                    :class => "root_domain" %>
            </div>
            <%= button_tag 'add root domain',:type => 'button', :id => 'add_root_domain',class: 'btn btn-info',:style => 'margin-top: 1em;' %>
          </div>
        </div>

        <div class="control-group">
          <%= f.label :site_type ,"Site Type", :class => "control-label muted" %>
          <div class="controls">
            <%= f.select :site_type, SiteConstruct::SITE_TYPES, :id => "site_type" %>
          </div>
        </div>

        <div class="control-group">
          <%= f.label :school_name ,"School Name", :class => "control-label muted" %>
          <div class="controls">
            <%= f.text_field :school_name, :id => "school_name", :placeholder => "XXXX" %>
            <div class="hint">Eg: NCTU</div>
          </div>
        </div>

        <div class="control-group">
          <%= f.label :site_name ,"Site Name", :class => "control-label muted" %>
          <div class="controls">
            <%= f.text_field :site_name, :id => "site_name", :placeholder => "xxx_xxx", :oninput=> "replace_input(this)" %>
            <div class="hint">schoolname_deptname eg: nctu_eed</div>
          </div>
        </div>

        <div class="control-group">
          <%= f.label :domain_name ,"Domain Name", :class => "control-label muted", :oninput=> "replace_input(this)" %>
          <div class="controls">
            <div class="domain_group">
              <input type="text" onchange="change_domain_input(this)" oninput="replace_domain_input(this)">
              <span class="root_domain_text"><%= SiteServer.first.domain_names[0] rescue nil %></span>
              <%= hidden_field_tag nil,nil, :class => "domain_name",:id=>nil %>
            </div>
            <%= f.hidden_field :domain_name %>
            <!--<div class="hint">schoolname-deptname.pending.rulingcom.com eg: nctu-eed.pending.rulingcom.com</div>-->
          </div>
        </div>

        <div class="control-group">
          <%= f.label :db_name ,"Database Name", :class => "control-label muted" %>
          <div class="controls">
            <%= f.text_field :db_name, :id => "db_name" %>
            <div class="hint">schoolname_deptname eg: nctu_eed</div>
          </div>
        </div>

        <div class="control-group">
          <%= f.label :port ,"Port Number", :class => "control-label muted" %>
          <div class="controls">
            <div class="port_block">
              <%= number_field_tag("#{f.object_name}[port][]",f.object.port.first, :min => 1, :id => nil) %>
              <div style="clear: both;"></div>
            </div>
            <div id="append_port_block"></div>
            <button class="btn btn-primary" id="add_port" type="button">Add Port</button>
          </div>
        </div>

        <div class="control-group">
          <%= f.label :path ,"Path", :class => "control-label muted" %>
          <div class="controls">
            <%= f.text_field :path, :disabled => true, :id => "path" %>
          </div>
        </div>
      </div>
    </div>
    <div class="form-actions">
      <%= f.submit t('submit'), class: 'btn btn-primary' %>
    </div>
  </div>
</fieldset>
<style type="text/css">
  .remove_btn{
    float: left;
    color: red;
    line-height: 2rem;
    cursor: pointer;
    font-weight: bold;
  }
  .remove_btn:hover{
    font-size: 1.3em;
  }
</style>
<script type="text/javascript">
  var user_name_relations = {};
  var domain_name_relations = {};
  var pre_site_name = '';
  var active_user_name = '<%= SiteServer.first.account rescue 'rulingcom' %>';
  <% SiteServer.all.each do |server_server| %>
    domain_name_relations['<%= server_server.server_name %>'] = <%= server_server.domain_names.inspect.html_safe %>;
    user_name_relations['<%= server_server.server_name %>'] = <%= server_server.account.inspect.html_safe %>;
  <% end %>
  function unique(array) {
      return $.grep(array, function(el, index) {
          return index == $.inArray(el, array);
      });
  }
  function change_domain_name(index){
    if (index=='all'){
      for (var i=0;i<$('.domain_group').length;i++){
        change_domain_name(i)
      }
    }else{
      var $input = $('.domain_group').eq(index).find('input[type="text"]');
      var current_root_domain_text = $('.root_domain_group').eq(index).find('select').val()
      if ($input.val()==pre_site_name){
        if($("#site_name").val() != ""){
          $input.val($("#site_name").val().replaceAll("_","-") + ".");
        }
      }
      $('.domain_group').eq(index).find('input[type="hidden"]').val($('.domain_group').eq(index).find('input[type="text"]').val()+current_root_domain_text)
      $('.root_domain_text').eq(index).html(current_root_domain_text)
    }
  }
  $("#school_name").on("blur",function(){
    var school = $(this).val().toLowerCase();
    if($("#site_name").val() == ""){
      $("#site_name").val(school + "_");
    }
  })
  $("#site_construct_site_type").on("change",function(){
    var type = $(this).val();
    if(type == "School"){
      $("#school_name").parents(".control-group").show();
    }else{
      $("#school_name").parents(".control-group").hide();
      $("#school_name").val("");
    }
    var school = $("#school_name").val();
    type = (type == "School" ? "school_sites" : "orbit_sites" );
    if(school != ""){
      $("#path").val("/home/"+active_user_name+"/" + type + "/" + school);
    }else{
      $("#path").val("/home/"+active_user_name+"/" + type);
    }
  })
  function add_change_event_for_root_domain(){
    $(".root_domain").off('change');
    $(".root_domain").each(function(i,root_domain){
      change_domain_name($(root_domain).index('.root_domain'));
    })
    $(".root_domain").change(function(){
      change_domain_name($(this).index('.root_domain'));
    })
  }
  add_change_event_for_root_domain()
  $('#site_construct_server_type').change(function(){
    var server_name = $(this).val();
    active_user_name = user_name_relations[server_name];
    var domain_name = domain_name_relations[server_name][0];
    var domain_names = domain_name_relations[server_name];
    $(".root_domain").find('option').remove()
    $.each(domain_names,function(i,v){
      var o = new Option(v, v);
      /// jquerify the DOM object 'o' so we can use the html method
      $(o).html(v);
      for(var idx=0;idx<$(".root_domain").length;idx++){
        var option = $(o.outerHTML);
        $(".root_domain").eq(idx).append(option);
      }
    })
    if(domain_name == undefined){
      $(".root_domain_text").html("");
    }else{
      $(".root_domain_text").html(domain_name);
    }
    if ($("#site_name").val()!=''){
      change_domain_name(0);
    }
    add_change_event_for_root_domain();
    //$('#domain_name').siblings('.hint').html('schoolname-deptname.'+domain_name+' eg: nctu-eed.'+domain_name);
  })
  $("#site_name").on("blur",function(){
    var val = $(this).val(),
        type = $("#site_construct_site_type").val(),
        school = $("#school_name").val();

    //$('#domain_name').siblings('.hint').html('schoolname-deptname.'+domain_name+' eg: nctu-eed.'+domain_name);
    change_domain_name('all');
    pre_site_name = val.replaceAll("_","-")+'.';
    $("#db_name").val(val);
    type = (type == "School" ? "school_sites" : "orbit_sites" );
    if(school != ""){
      $("#path").val("/home/"+active_user_name+"/" + type + "/" + school);
    }else{
      $("#path").val("/home/"+active_user_name+"/" + type);
    }
  })
  $("#school_name").on("input",function(){
    replace_input(this);
    var school = $(this).val();
    if(school != ""){
      $("#path").val("/home/"+active_user_name+"/school_sites/" + school);
    }
  })
  function replace_input(ele){
    var correct_val = $(ele).val().match(/([0-9]||[a-z]||[-_])*/gi).join("");
    $(ele).val(correct_val);
  }
  function replace_domain_input(ele){
    var correct_val = $(ele).val().match(/([0-9]||[a-z]||[-_.])*/gi).join("");
    $(ele).val(correct_val.replaceAll("_","-"));
  }
  function change_domain_input(ele){
    replace_domain_input(ele);
    change_domain_name($(ele).parents('.domain_group').index('.domain_group'))
  }
  $("#site_construct_site_type").val("School");
  function delete_domain(ele){
    $('.domain_group').eq($(ele).parents('.root_domain_group').index('.root_domain_group')).remove();
    $(ele).parents('.root_domain_group').remove();
  }
  $('#add_root_domain').click(function(){
    var first_domain_group = $('#root_domain_group .root_domain_group').first();
    var clone_domain_group = $(first_domain_group).clone();
    clone_domain_group.find('select').val(clone_domain_group.find('select option:first').val());
    clone_domain_group.append("<button class=\"btn btn-danger\" onclick=\"delete_domain(this)\">delete domain</button>");
    $('#root_domain_group .root_domain_group').last().after(clone_domain_group);
    var clone_input_group = $('.domain_group').last().clone();
    clone_input_group.find('input[type="text"]').val(pre_site_name);
    clone_input_group.find('input[type="hidden"]').val(pre_site_name+clone_domain_group.find('select').val());
    clone_input_group.find('.root_domain_text').val(clone_domain_group.find('select').val())
    $('.domain_group').last().after(clone_input_group);
    add_change_event_for_root_domain();
  })
  $("form.main-forms").submit(function(){
    $("#domain_name").removeAttr('disabled');
    $("#path").removeAttr("disabled");
    var type = $("#site_construct_site_type").val();
    type = (type == "School" ? "school_sites" : "orbit_sites" );
    var school = $("#school_name").val();
    if(school != ""){
      $("#path").val("/home/"+active_user_name+"/" + type + "/" + school);
    }else{
      $("#path").val("/home/"+active_user_name+"/" + type);
    }
    $('#site_construct_domain_name').val(unique(
      $.map($('.domain_name'),function(v,i){
        return $(v).val()
      })
    ).join(' '))
    console.log($("#path").val());
  })
  $(document).on("click",".remove_btn",function(event){
    $(this).parent().remove();
  })
  $("#add_port").click(function(){
    var clone_input = $(this).siblings(".port_block").eq(0).clone();
    var $div = $("<div></div>");
    $div.append("<span class=\"remove_btn\">X</span>").append(clone_input);
    $(this).siblings("#append_port_block").append($div)
  })
</script>