<% if authorize_for(:issues, :send_helpdesk_response) && @issue.customer && @issue.customer.primary_email %>
<script type="text/javascript" charset="utf-8">
  function emailTagResult (opt) {
    if (opt.name){
      var formated_tag = $('<span>' + opt.avatar + '&nbsp;' + opt.text + '</span>');;
    } else {
      var formated_tag = opt.text;
    }
    return formated_tag
  };
  function emailTagSelection (opt) {
    if (opt.name){
      var formated_tag = opt.name + ' <' + opt.email + '>';
    } else {
      var formated_tag = opt.text;
    }
    return formated_tag
  };
  $(document).ready(function() {
    toggleSendMail($('#helpdesk_is_send_mail').get(0));
    var select2_fields = ['#helpdesk_to', '#helpdesk_cc', '#helpdesk_bcc'];
    $.each(select2_fields, function(index, field){
      $(field).select2({
        ajax: {
          url: '<%= auto_complete_contacts_path(:project_id => (ContactsSetting.cross_project_contacts? ? nil : @project), :is_company => nil) %>',
          dataType: 'json',
          delay: 250,
          data: function (params) {
            return { q: params.term };
          },
          processResults: function (data, params) {
            return { results: $.grep(data, function(elem){ elem.id = elem.email; return elem }) };
          },
          cache: true
        },
        tags: true,
        placeholder: ' ',
        minimumInputLength: 1,
        width: '60%',
        templateResult: emailTagResult,
        templateSelection: emailTagSelection,
      }).on('select2:open', function (e) {
        $(field).closest('.cc-list-edit').find('.select2-search__field').val(' ').trigger($.Event('input', { which: 13 })).val('');
      });
    });

    $('#email_footer').insertAfter($('#helpdesk_is_send_mail').parents().eq(1).find('.jstEditor'));
    $('#email_header').insertBefore($('#helpdesk_is_send_mail').parents().eq(1).find('>legend'));
    $('#email_canned_responses').insertBefore($('#helpdesk_is_send_mail').parents().eq(1).find('>legend'));
  });

  var issue_status = $('#issue_status_id').val();

  function toggleSendMail(element) {
    if (element.checked) {
      $('.email-template').show();
      <% unless HelpdeskSettings["helpdesk_answered_status", @project].blank? %>
        issue_status = $('#issue_status_id').val();
        $('#issue_status_id').val("<%= HelpdeskSettings["helpdesk_answered_status", @project] %>");
      <% end %>
      <% if @issue.assigned_to.blank? %>
        $('#issue_assigned_to_id').val("<%= User.current.id %>");
      <% end %>

    } else {
      $('.email-template').hide();
      $('#cc_list_edit').hide();
      $('#helpdesk_is_cc').val("");
      <% unless HelpdeskSettings["helpdesk_answered_status", @project].blank? %>
        $('#issue_status_id').val(issue_status);
      <% end %>
    }

  }

function updateCannedResposeFrom(url, value) {
  $.ajax({
    url: url,
    type: 'post',
    data: {id: value}
  });
}


</script>
<% canned_responses = CannedResponse.visible.in_project_or_public(@project) %>
<% if canned_responses.any? %>
  <span id="email_canned_responses" style="display: none; float:right;" class="email-template">
    <%= select_tag 'helpdesk[canned_response]', options_for_select([[ "--- #{l(:label_helpdesk_canned_response_plural)} ---", '' ]] + canned_responses.order("#{CannedResponse.table_name}.name").map{|cr| [cr.name, cr.id]}), :onchange => "updateCannedResposeFrom('#{escape_javascript add_canned_responses_path(:project_id => @project, :issue_id => @issue, :format => 'js')}', $(this).val())"  %>
  </span>
<% end %>

<% unless HelpdeskSettings["helpdesk_emails_header", @project].blank? %>
  <div id="email_header" style="display: none;" class="email-template">
    <%= textilizable(HelpdeskMailer.apply_macro(HelpdeskSettings["helpdesk_emails_header", @project], @issue.customer, @issue, User.current)).html_safe  %>
  </div>
<% end %>

<% unless HelpdeskSettings["helpdesk_emails_footer", @project].blank? %>
  <div id="email_footer" style="display: none;" class="email-template">
    <%= textilizable(HelpdeskMailer.apply_macro(HelpdeskSettings["helpdesk_emails_footer", @project], @issue.customer, @issue, User.current)).html_safe  %>
  </div>
<% end %>

<p id="helpdesk_send_response">
  <%= check_box_tag 'helpdesk[is_send_mail]', 1, HelpdeskSettings["send_note_by_default", @project], :onclick => "toggleSendMail(this);" %>
  <%= label_tag :helpdesk_is_send_mail, l(:label_is_send_mail), :class => "icon icon-email-to", :style => "" %>

  <span id="journal_contacts" style="display: none;" class="email-template">
      <span id="customer_to_email" class="email-template">
        <%= render :partial => "issues/customer_to_email", :locals => {:contact => Contact.where(:email => @issue.helpdesk_ticket.default_to_address).first || @issue.customer, :contact_email => @issue.helpdesk_ticket.default_to_address } %>
      </span>
      <a href="#" class="inline-edit email-template" onclick="$('#customer_to_email').hide(); $(this).hide(); $('#cc_list_edit').show(); return false;"><img alt="Edit" src="/images/edit.png" style="vertical-align:middle;" ></a>
  </span>
</p>

<div id="cc_list_edit" style="display:none;">
  <% contact_emails = ((@issue.helpdesk_ticket.cc_address.to_s.split(',') + @issue.helpdesk_ticket.response_addresses).uniq.map { |email| [email, email] } + (@issue.contacts + [@issue.customer]).uniq.map{ |contact| [contact.email_name, contact.primary_email] }).uniq(&:last) %>
  <%= hidden_field_tag 'helpdesk[is_cc]' %>
  <p class="cc-list-edit">
    <span class="is-cc">
    <%= label_tag l(:label_helpdesk_to) %>
    </span>
    <%= select_tag 'journal_message[to_address]', options_for_select(contact_emails, @issue.helpdesk_ticket.default_to_address), :id => "helpdesk_to", :multiple => true %>
  </p>
  <p class="cc-list-edit">
    <span class="is-cc">
    <%= label_tag l(:label_helpdesk_cc) %>
    </span>
    <%= select_tag 'journal_message[cc_address]', options_for_select(contact_emails, @issue.customer.primary_email != @issue.helpdesk_ticket.default_to_address ? @issue.customer.primary_email : @issue.helpdesk_ticket.cc_addresses), :id => "helpdesk_cc", :multiple => true %>
  </p>
  <div style="clear: both;"></div>
  <p class="cc-list-edit">
    <span class="is-cc">
    <%= label_tag l(:label_helpdesk_bcc) %>
    </span>
    <%= select_tag 'journal_message[bcc_address]', nil, :id => "helpdesk_bcc", :multiple => true %>
  </p>
  <div style="clear: both;"></div>
</div>

<% end %>

<% content_for :header_tags do %>
  <%= javascript_include_tag :redmine_helpdesk, :plugin => 'redmine_contacts_helpdesk'  %>
  <%= stylesheet_link_tag :helpdesk, :plugin => 'redmine_contacts_helpdesk' %>
<% end %>

<% if authorize_for(:issues, :send_helpdesk_response) && @issue.customer && @issue.customer.primary_email %>
  <%= javascript_tag do %>
    $('#content .contextual:first a:first').before('<%= helpdesk_reply_link %>')
    $('#content .contextual:last a:first').before('<%= helpdesk_reply_link %>')
  <% end %>
<% end %>
