<% the_current_user = current_user%>
<script>
    
  function submit_custom_form() { 
    $.ajax({
           type: "POST",
           url: url,
           data: form.serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
      });
  }
  
  function cancel_allocation(build_id, allocation_id) {
    $.ajax({
         type: "POST",
         url: "/builds/" + build_id + "/cancel-allocation/" + allocation_id,
         success: function(data)
         {
         }
    });
  }
  
  window.onbeforeunload = function() {
	var custom_test_execution_modal_shown =  $('#test_execution_output_dialog').is(':visible');
	if (custom_test_execution_modal_shown == true)
        return "Are you sure to exit?";
  }
</script>

<input id="project_local_ui_test_dir" type="hidden" value="<%= @project.ui_test_local_working_dir rescue nil %>"/>

<div class="modal fade modal-wide" tabindex="-1" role="dialog" id="custom_test_execution_modal">
</div>

<div class="modal fade modal-wide" tabindex="-1" role="dialog" id="deploy_output_modal">
  <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
           <div class="modal-header">
               <h5 class="modal-title">Deploy Output</h5>
               <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<%= I18n.t(:close) %>"></button>
          </div>
           <div class="modal-body">
             
             <div>
               <b>Stdout:</b>
               <pre id="deploy-stdout" style="margin-top: 5px; margin-bottom: 15px;"></pre>
              </div>

             <div>
               <b>Stderr:</b>
               <pre id="deploy-stderr" style="margin-top: 5px; margin-bottom: 10px;"></pre>
              </div>
              
          </div>
      </div>
  </div>
</div>


<!-- Modal With Warning -->
<div id="Warning" class="modal modal-medium fade" role="dialog" data-backdrop="false">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-body">
                <p style="margin-top: 10px; margin-bottom: 10px;">Are you sure?</p>
            </div>
        </div>
    </div>
</div>




<% if @build.is_load_testing && !@build.incomplete? %>
  <%=  partial(:'builds/load_test_results_modal', :locals => {:build => @build}) %>
  <%=  partial(:'builds/load_operation_errors_modal', :locals => {:build => @build}) %>
<% end %>


<input type="hidden" id="is_parallel_build_in_progress"  value="<%= (@build && @build.incomplete?).to_s rescue 'false' %>"/>


<% if @build && @build.incomplete? %>

    <div id="banner" style="<% unless @build.is_waiting_mode %>display:none;
      <% end %>">
      <div id="notifications_banner" class="banner_content">
				<%= I18n.t(:buildwise_extend_wait_for_completion)%>         
        <a style="margin-left: 5px;" href="javascript:void(0)" class="btn btn-light btn-sm" onclick="$.getScript('/builds/<%= @build.id%>/unwait')"><%= I18n.t(:continue) %></a>
        <a class="cursor_pointer bold dismiss" href="#" onclick="$('#banner').hide();" style="margin-top: 6px; font-size: 20px;"> &times; </a>
      </div>
    </div>

<% end %>
	
	
<script type="text/javascript" charset="utf-8">

    function set_error_file_line() {
        var aux = document.getElementById("error_line_hidden");
        var error_file_line = $("#error_line").text();
        aux.setAttribute("value", error_file_line);
    }

    // somehow not working as intended, but OK with clipbpard.js
    function copyErrorLineToClipboard() {
        setTimeout()
        copyToClipboard("error_line_hidden");
    }


    function copyToClipboard(elem_id) {
        // Highlight its content
        // document.getElementById(elem_id).focus();
        document.getElementById(elem_id).select();
        try {
            var successful = document.execCommand("copy");
            console.log("copy OK");
        } catch (err) {
            console.log("copy failed: " + err);
        }
    }

    function execute_test_file(test_file_id) {
        $("#execute_test_file_spin_" + test_file_id).show();
        $("#execute_test_file_" + test_file_id).hide();
        $.getScript("/test_files/" + test_file_id + "/execute");
    }

    function execute_test_case(test_case_id) {
        $("#execute_test_case_spin_" + test_case_id).show();
        $("#execute_test_case_" + test_case_id).hide();
        $.getScript("/test_files/execute_test/" + test_case_id);
    }

    function show_test_case_execution_modal(test_case_id) {
      $.getScript("/test_files/prepare_test_execution/" + test_case_id);
    }

    function confirm_deployment()  {
      bootbox.confirm({
          message: "Are you sure to call deploy Rake task (configured in the project settings)?",
          buttons: {
              confirm: {
                  label: 'Yes',
                  className: 'btn-success'
              },
              cancel: {
                  label: 'No',
                  className: 'btn-danger'
              }
          },
          callback: function (result) {
            if (result) {
              $.ajax({
                type: "POST",
                url: "/builds/<%= @build.id %>/confirm-deploy",
                success: function(res) {
                      // $("#result").append(res);
                      console.log(res);
                }
               });
             }
          }
      });
    }
    

    function escapeHtml(text) {
        'use strict';
        return text.replace(/[\"&'\/<>]/g, function (a) {
            return {
                '"': '&quot;', '&': '&amp;', "'": '&#39;',
                '/': '&#47;', '<': '&lt;', '>': '&gt;'
            }[a];
        });
    }

    function show_test_failure(test_file_name, test_case_name, test_file_index, test_case_screenshot,active_tab) {
        $("#test_script_filename").html(test_file_name);
        // console.log("before test case name: " + test_case_name);
        var escaped_test_case_name = test_case_name;
        // console.log("after  test case name: " + test_case_name);

        $("#test_case_name").html(escaped_test_case_name);
        var failed_test_line = ""; // to be used in open in testwise link

        var data = $("#test_error_details_" + test_file_index).html();
		if (data) { 
	        var arrayOfLines = data.match(/[^\r\n]+/g);
	        if (arrayOfLines) { 
	          var arrayLength = arrayOfLines.length;
	          var formatted_data = ""

	          var regex_rspec = /\w[\w|\d|_]+_spec\.rb:\d+/; // for rspec
            var regex_junit = /\w[\w|\d|_]+Test\.java:\d+/; // for JUnit
            var regex_mocha = /\w[\w|\d|_]+_spec\.js:\d+/; // for Mocha
            var regex_pytest = /\w[\w|\d|_]+_test\.py:\d+/; // for Pytest
	          
            var found_spec_line = false;
	          var normalized_error_line;
	          for (var i = arrayLength - 1; i >= 0; i--) {
	              normalized_error_line = arrayOfLines[i];

	              if (!found_spec_line && regex_rspec.test(normalized_error_line)) {
								    var highlighted_line = normalized_error_line.replace(regex_rspec, function highline_error_line(x) {
	                    failed_test_line = x;
	                    return "<span id='error_line' class='marked-text'>" + x + "</span>";
	                  });
	                  formatted_data =  highlighted_line + "\r\n" + formatted_data;
	                  found_spec_line = true;
	               
								} else if (!found_spec_line && regex_junit.test(normalized_error_line)) {
									
							    var highlighted_line = normalized_error_line.replace(regex_junit, function highline_error_line(x) {
                    failed_test_line = x;
                    return "<span id='error_line' class='marked-text'>" + x + "</span>";
                  });
                  formatted_data =  highlighted_line + "\r\n" + formatted_data;
                  found_spec_line = true;
								
								} else if (!found_spec_line && regex_mocha.test(normalized_error_line)) {
									
							    var highlighted_line = normalized_error_line.replace(regex_mocha, function highline_error_line(x) {
                    failed_test_line = x;
                    return "<span id='error_line' class='marked-text'>" + x + "</span>";
                  });
                  formatted_data =  highlighted_line + "\r\n" + formatted_data;
                  found_spec_line = true;
								
								} else if (!found_spec_line && regex_pytest.test(normalized_error_line)) {
									
							    var highlighted_line = normalized_error_line.replace(regex_pytest, function highline_error_line(x) {
                    failed_test_line = x;
                    return "<span id='error_line' class='marked-text'>" + x + "</span>";
                  });
                  formatted_data =  highlighted_line + "\r\n" + formatted_data;
                  found_spec_line = true;

	              } else {
	                  formatted_data =  normalized_error_line + "\r\n" + formatted_data;
	              }
	          }
	      }
					
        } else {
          var formatted_data = "[No data returned]"
        }
        
        <% if defined?(settings) && settings.testwise_integration %>
        var test_file_path_line = $("#project_local_ui_test_dir").val() + "/" + failed_test_line;
        $("#open_in_testwise_link").attr("href", "testwise://" + test_file_path_line);
        <% end %>
        
        $("#test_failure_content_pre").html(formatted_data);
        $("#error_line_hidden").val($("#error_line").text());
        
        $("#test_case_screenshot").attr("src", test_case_screenshot);
        
        if (active_tab == "screenshot") {
          $("#test_failure_modal_tabs a:last").tab('show');                    
        } else {
          // $('#test_failure_content_pre').scrollTop($('#test_failure_content_pre')[0].scrollHeight);
          $("#test_failure_modal_tabs a:first").tab('show');          
        }
        $("#test_failure_modal").modal("show");
    }

    function show_test_failure_output(test_file_name, test_case_name, test_file_index, test_case_screenshot) {
      show_test_failure(test_file_name, test_case_name, test_file_index, test_case_screenshot, "test_failure");
    }

    function show_test_failure_screenshot(test_file_name, test_case_name, test_file_index, test_case_screenshot) {
      show_test_failure(test_file_name, test_case_name, test_file_index, test_case_screenshot, "screenshot");
    }


    function edit_summary() {
        <% if (the_current_user && the_current_user.is_member?(@project))  %>
      
      bootbox.prompt({ 
          size: "large",
          title: "<%= I18n.t(:change_build_summary) %>",
          value: "<%= @build.summary rescue nil %>",
          callback: function(value){ 
			if (value == null) {
				return;
			}
			
              $.post("/builds/<%= @build.id%>/summary", {summary: value}, function (json) {
                $("#build_summary_link").text(value);
                $("#build_summary_link").show();
			  })
          }
      });
      
                    
        <% end %>              
    }

    function update_test_file_priority(test_file_name, test_file_id, current_priority) {

      bootbox.prompt({ 
          size: "medium",
          title: "Update test file priority: " + test_file_name,
          value: current_priority,
          inputType: "number",
          callback: function(value){ 
            if (value) {
              $.getScript("/test_files/" + test_file_id + "/update_priority?priority=" + value);		  
			}
          }
      });      
    }

    /*  onclick='$("#test_details_1").slideToggle("slow");' */

    $(function () {

        // new Clipboard('#copy-button');
        var clipboard = new Clipboard("#orgin-copy-button");

        clipboard.on('success', function (e) {
            console.info('Action:', e.action);
            console.info('Text:', e.text);
            //alert('Text:', e.text);
            e.clearSelection();
        });

        $("#copy-button").on("click", function () {
            $("#orgin-copy-button").trigger('click');
        });

        $("#orgin-copy-button").on('click', function () {
            // without the statement below, strangely, copy does not work
            $("#test_failure_modal").modal('hide');
        });



        $(".test-file-link").click(function () {
          <% if RACK_ENV == "showcase" %>
            event.preventDefault();
            bootbox.alert("This feature 'displaying test script content' is disabled in ShowCase mode");

          <% elsif (@project.config.show_test_scripts_to_public || (the_current_user && the_current_user.is_member?(@project))  ) %>

            var item_id = $(this).attr('data-id');
            var item_name = $(this).attr('data-name');
            if (item_id == "") {
                var scriptUrl = "/builds/<%= @build.id%>/test_files/" + item_name;
            } else {
                var scriptUrl = "/test_files/" + item_id;
            }

            console.log(scriptUrl);
            $.get(scriptUrl, function (data) {
                $("#test_script_header").html(item_name);
                $("#test_script_content").html(data);
                $("#dialog").modal("show");
            });

          <% else %>
            event.preventDefault();
            bootbox.alert("You are not allowed to view the test script content, which is set to be accessible to project team members only.");
          <% end %>
            // });
        });
/*
        $(".test-history-link").click(function () {

            var item_id = $(this).attr('data-id');
            var item_name = $(this).attr('data-name');
            if (item_id == "") {
                // ignore
            } else {
                var scriptUrl = "/test_files/" + item_id + "/history";
                $.getScript(scriptUrl);
            }
        });
*/
    });

			
		<% if the_current_user  && (the_current_user.is_admin? || the_current_user.has_role?(:builder, @build.project) ) %>
		function build_again() {
	    // send request
	    $.post("/projects/<%= @build.project.id%>/start_build", function(json) {
				var data = JSON.parse(json);
				if (data["build_id"]) {
					// redirect to the build page
					window.location = "/builds/" + data["build_id"];
				
				} else {
					alert("Failed to start a build");
				}
	    });
		}
		<% end %>
		
</script>

<script type="text/javascript" charset="utf-8">
    function toggle_test_cases() {
        $("tr.test_case_row").toggle();
        $(".test_file_result").toggle();
    }

    function show_test_file_results() {
        $("tr.test_case_row").hide();
        $(".test_file_result").show();
        $("#test_results_table").addClass("table-striped");
    }

    function show_test_case_results() {
        $("tr.test_case_row").show();
        $(".test_file_result").hide();
        $("#test_results_table").removeClass("table-striped");
    }
</script>

<div style="position:absolute; left: -3000px;">
  <input id="error_line_hidden" value=""/>
  <button id="orgin-copy-button" class="copy" type="button" style="display:none;" data-clipboard-target="#error_line_hidden">Test</button>
</div>

<% if @build.incomplete? %>
    <%
      error_count_so_far = 0;
      build_test_files = @test_files.to_a || @build.test_files.to_a || []
      build_test_files.uniq.each {|x|
        error_count_so_far += x.error_count
      }
    %>
    <div id="ui_test_summary"
         <% if error_count_so_far <= 0 %> style="<% if @build.is_waiting_mode %>position:fixed;<% end %> background-color: rgb(56, 182, 3);"
         <% else %> style="<% if @build.is_waiting_mode %>position:fixed;<% end %> background-color: rgb(255, 0, 0);"
         <% end %> >
		
      <% if error_count_so_far <= 0 %>
          <div class="ui_test_ok hidden-print" ><%= I18n.t(:so_far_so_good) %></div>
      <% else %>
          <div class="ui_test_failed hidden-print">
		<span id="failed_test_count" class="ui_test_error_count"><%= error_count_so_far rescue 0 %></span> <%= I18n.t(:failures) %>
          </div>
      <% end %>
    </div>
<% else %>
    <div id="ui_test_summary" class="hidden-print"
         <% if @build.successful %> style="background-color: rgb(56, 182, 3);"
         <% else %> style="background-color: rgb(255, 0, 0);"
         <% end %>>
      <% if @build.successful %>
        <% if @build.is_parallel && @build.is_load_testing %>          
          <div class="ui_test_ok"><a style="color: white;" href="javascript:void(0);"  onclick="$.getScript('/builds/<%= @build.id %>/load-testing-errors')"><%= I18n.t(:ok) %></a></div>    
        <% else  %>
          <div class="ui_test_ok"><%= I18n.t(:ok) %></div>
        <% end %>
      <% elsif @build.is_parallel && @build.is_load_testing %>
          <div class="ui_test_failed"><a style="color: white;" href="javascript:void(0);"  onclick="$.getScript('/builds/<%= @build.id %>/load-testing-errors')">Failed</a></div>
      <% else %>
          <div class="ui_test_failed">
            <span id="failed_test_count" class="ui_test_error_count"><%= @build.ui_test_error_count rescue 0 %></span>
            <%= I18n.t(:failures) %>
          </div>
      <% end %>

    </div>
<% end %>


<div id="builds_list" class="hidden-print">

  <div class="build-history-chart-container" id="project-chart-<%= @project.id %>" style=""></div>

  <div id="left_tabs" style="padding-right: 6px;">

    <ul id="myTab" class="nav nav-tabs">
      <li class="nav-item"><a class="nav-link active" href="#tab-steps" data-toggle="tab"><%= I18n.t(:build_steps) %></a></li>
      <% unless @autorefresh %>
          <li class="nav-item"><a class="nav-link" href="#tab-history" data-toggle="tab"><%= I18n.t(:history) %></a></li>
      <% end %>
    </ul>

    <div class="tab-content">

      <div id="tab-steps" class="tab-pane show active fade" style="padding: 0px; padding-top: 10px;">
        <div class="card" style="margin-top: 0px;">
          <div class="card-heading" style="padding: 10px 10px 6px 6px;">
            <% if @build.incomplete? %>
                <div class="build_nav_heading"><a href="/builds/<%= @build.id %>?step=all">Build #<%= @build.id %></a>
                </div>
            <% else %>
                <div class="build_nav_heading"><a href="/builds/<%= @build.id %>">Build #<%= @build.id %></a></div>
            <% end %>
          </div>
          <div classs="card-block">
            <table class="table" id="build_step_list">
              <tbody>

              <tr>
                <td class="step-group">
                  <div class="pull-right">
                    <% if @build.incomplete? && (@build.stage.nil? || @build.build_step_executions.empty?) %>
                        <i class="fa fa-spinner fa-spin"></i>
                    <% end %>
                  </div>
                  <i class="fa fa-chevron-down" aria-hidden="true"></i> <%= I18n.t(:build_prepare) %>
                </td>
              </tr>
              <% @build.prepare_steps(true).each do |step| %>
                  <tr
                  <% if @step && @step.id == step.id %>class="active"
                  <% end %> >
                    <td class="step-actual">
                      <div class="pull-right">
                        <% if step.end_time %>
                            <% if step.successful %>
                                <i class="fa fa-check green" aria-hidden="true"></i>
                            <% else %>
                                <i class="fa fa-times red" aria-hidden="true"></i>
                            <% end %>
                        <% elsif @build.incomplete? && step.task_name == @build.stage %>
                            <i class="fa fa-spinner fa-spin"></i>
                        <% end %>
                      </div>

                      <% if step.id %>
                          <a href="/builds/<%= @build.id %>?step=<%= step.id %>"><%= step.display_task_name %></a>
                      <% else %>
                          <span class="planned"><i><%= step.display_task_name %></i></span>
                      <% end %>

                    </td>
                  </tr>
              <% end %>

              <% if @build.user_steps(true).any? %>
                  <tr>
                    <td class="step-group"><i class="fa fa-chevron-down" aria-hidden="true"></i>
                      Build Steps
                    </td>
                  </tr>
                  <% @build.user_steps(true).each do |step| %>
                      <tr
                      <% if @step && @step.id == step.id %>class="active"
                      <% end %> >
                        <td class="step-actual">

                          <% if step.id && step.is_ui_test? %>
                              <div class="pull-left" style="margin-left: 4px; margin-top: 1px;">
                                <i class="fa fa-star-o" aria-hidden="true"></i></div>
                          <% end %>

                          <div class="pull-right">
                            <% if step.end_time %>
                                <% if step.successful %>
                                    <i class="fa fa-check green" aria-hidden="true"></i>
                                <% else %>
                                    <i class="fa fa-times red" aria-hidden="true"></i>
                                <% end %>
                            <% elsif @build.incomplete? && step.task_name == @build.stage %>
                                <i class="fa fa-spinner fa-spin"></i>
                            <% end %>
                          </div>

                          <% if step.id %>
                              <a
                              <% if step.is_ui_test? %> style="padding-left: 4px !important;"
                              <% end %>href="/builds/<%= @build.id %>?step=<%= step.id %>"><%= step.display_task_name %></a>
                          <% else %>
                              <span class="planned"><i><%= step.display_task_name %></i></span>
                          <% end %>


                        </td>
                      </tr>
                  <% end %>
              <% end %>

			 <% build_finalize_steps = @build.finalize_steps(false)   %>
              <% if build_finalize_steps.any? %>
                  <tr>
                    <td class="step-group"><i class="fa fa-chevron-down" aria-hidden="true"></i>
                      Finalize Build
                    </td>
                  </tr>

                  <% build_finalize_steps.each do |step| %>
                      <tr
                      <% if @step && @step.id == step.id %>class="active"
                      <% end %> >
                        <td class="step-actual">
                          <div class="pull-right">
                            <% if step.end_time %>
                                <% if step.successful %>
                                    <i class="fa fa-circle-o green" aria-hidden="true"></i>
                                <% else %>
                                    <i class="fa fa-circle-o red" aria-hidden="true"></i>
                                <% end %>
                            <% elsif @build.incomplete? && step.task_name == @build.stage %>
                                <i class="fa fa-spinner fa-spin"></i>
                            <% end %>
                          </div>

                          <% if step.id %>
                              <a href="/builds/<%= @build.id %>?step=<%= step.id %>"><%= step.task_name %></a>
                          <% else %>
                              <span class="planned"><i><%= "UI Test" %></i></span>
                          <% end %>

                        </td>
                      </tr>
                  <% end %>

              <% end %>


              </tbody>
            </table>
          </div>
        </div>					
		
      </div>

      <% unless @autorefresh %>
          <!-- build in progress, don not show previous build -->
          <div id="tab-history" class="tab-pane">

            <div id="navigate_build" style="padding-top: 5px;">
              <% prev_build, next_build = @project.previous_build(@build), @project.next_build(@build) %>

              <% if prev_build %>
                  <a href="/builds/<%= prev_build.id %>">&lt; <%= I18n.t(:prev) %></a>
                  <!--  :accesskey => 'k' -->
              <% end %>
              <b style="font-size: 120%; color: #356AA0"><%= @build.label %></b>

              <% if next_build %>
                  <a href="/builds/<%= next_build.id %>"><%= I18n.t(:next) %> &gt;</a>
                  <!--  :accesskey => 'k' -->
              <% end %>
            </div>

            <% @project_recent_builds.each do |build| %>
                <% next if build.status == "unchanged" %>
                <% if @build.label == build.label %>
                    <div style="float:left; margin-left: -18px;"><i class="fa fa-hand-o-right" aria-hidden="true"></i>
                    </div>
                <% end %>
                <div class="build-link<%= ' selected' if @build.label == build.label %>">
                  <a href="/builds/<%= build.id %>?tab=history" class="<%= build.status_css_for_display %>"
                     data-toggle="tooltip" data-placement="right" title="<%= build.pretty_duration rescue nil %>"
                  >
                    <span data-localtime-format="MM-dd HH:mm"><%= build.start_time.iso8601 rescue nil %></span> <%= build_list_label(build) %>
                  </a>
                </div>
            <% end %>

          </div>

      <% end %>
    </div>
  </div>
</div>


<% unless settings.hide_test_script_content %>
    <div class="modal" tabindex="-1" role="dialog" id="dialog">
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header">
            <h5 id="test_script_header">Test script</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<%= I18n.t(:close) %>"></button>
          </div>
          <div class="modal-body" id="test_script_content">
          </div>
        </div>
      </div>
    </div>
<% end %>

<div class="modal fade modal-wide" tabindex="-1" role="dialog" id="test_execution_output_dialog">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h4 id="test_script_header">Test Execution: <span id="test_file_or_case"></span></h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<%= I18n.t(:close) %>"></button>
      </div>
      <div class="modal-body" id="test_execution_output_div">
        <div style="margin-bottom: 0.5rem;">
            <b id="test_execution_time"></b> <%= I18n.t(:seconds) %>
		     </div>
        <pre id="test_execution_output">
				</pre>
      </div>
    </div>
  </div>
</div>


<div class="modal fade modal-wide" tabindex="-1" role="dialog" id="test_failure_modal">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <div>
          <b id="test_script_filename" class="test_script_filename"></b> :
          "<b id="test_case_name" class="test_case_name"></b>"
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<%= I18n.t(:close) %>"></button>
      </div>
      <div class="modal-body" id="test_failure_content">

        <ul class="nav nav-tabs" id="test_failure_modal_tabs">
          <li class="nav-item"><a class="nav-link active" data-toggle="tab" href="#output"><%= I18n.t(:test_output) %></a></li>
          <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#screenshot"><%= I18n.t(:screenshot)%></a></li>
        </ul>

        <div class="tab-content">
          <div id="output" class="tab-pane fade show active">
            <pre id="test_failure_content_pre"></pre>
          </div>
          <div id="screenshot" class="overview tab-pane fade">
            <img id="test_case_screenshot" src=""/>
          </div>
        </div>
      </div>

      <div class="modal-footer">
          <% if defined?(settings) && settings.testwise_integration %>
          <div style="float:left;">
            <a id="open_in_testwise_link"  style="float:left;" href="testwise://" class="btn btn-default btn-sm"><%= t(:open_in_testwise) %></a>
          </div>
          <% end %>
            
          <button type="button" id="copy-button" class="btn btn-info btn-sm" data-clipboard-target="#error_line_hidden"><%= t(:copy_error_line_to_clipboard) %>        </button>
          <button type="button" class="btn btn-default btn-sm" data-dismiss="modal" data-bs-dismiss="modal"><%= t(:close) %></button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade modal-wide" tabindex="-1" role="dialog" id="test_history_dialog">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h4 id="test_history_header">Test </h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<%= I18n.t(:close) %>"></button>    
      </div>
      <div class="modal-body" id="test_history_content">
        <div id="test_history_chart" class="tab-pane" style="height: 80%; margin-left: 0px;"></div>
      </div>
    </div>
  </div>
</div>


<div class="modal fade modal-wide" tabindex="-1" role="dialog" id="performance_test_history_dialog">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h4 id="performance_test_history_header"><%= I18n.t(:performance_test) %></h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<%= I18n.t(:close) %>"></button>    
      </div>
      <div class="modal-body" id="test_history_content">
        <div id="performance_test_history_chart" class="tab-pane" style="height: 80%; margin-left: 0px;"></div>
      </div>
    </div>
  </div>
</div>
			
<div class="modal fade modal-wide" tabindex="-1" role="dialog" id="load_test_history_dialog">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h4 id="load_test_history_header"><%= I18n.t(:load_test) %></h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<%= I18n.t(:close) %>"></button>    
      </div>
      <div class="modal-body" id="test_history_content">
        <div id="load_test_history_chart" class="tab-pane" style="height: 80%; margin-left: 0px;"></div>
      </div>
    </div>
  </div>
</div>
            

<div class="modal fade modal-wide" tabindex="-1" role="dialog" id="agent_charts_dialog">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h5 id="agents_header">Agents </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<%= I18n.t(:close) %>"></button>            
      </div>
      <div class="modal-body" id="test_history_content">
        <div class="row">
          <div id="left_chart" class="col-md-9">
            <div id="agent_execution_time_chart" style="width:660px;  margin-left: 0px;"></div>
          </div>
          <div id="agent_test_count_div" class="col-md-3" style="height: 480px; margin-left: 0px;">

          </div>
        </div>
      </div>
    </div>
  </div>
</div>


<div class="modal fade modal-wide" tabindex="-1" role="dialog" id="agent_allocations_dialog">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h4 id="agents_header"><%= I18n.t(:agent_allocations) %></h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<%= I18n.t(:close) %>"></button>
      </div>
      <div class="modal-body" id="agent_allocations_content">

        <div id="agent_allocations_table">
        </div>

      </div>
    </div>
  </div>
</div>

<% build_false_alarms = (@build_false_alarms || @build.false_alarms) rescue [] %>

<div class="modal fade" tabindex="-1" role="dialog" id="false_alarms_modal">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h4><%= t(:false_alarms).capitalize %></h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<%= I18n.t(:close) %>"></button>
      </div>
      <div class="modal-body" id="false_alarms_content">
        <% if @build && build_false_alarms.count > 0 %>
            
            <table class="table  table-condensed striped highlight">
              <thead>
                <tr>
                 <th><%= I18n.t(:test_file).capitalize %></th>
                 <th><%= I18n.t(:failed_on) %></th>
                 <th><%= I18n.t(:passed_on) %></th>
                </tr>
              </thead>
              <tbody>              
              <% build_false_alarms.each do |tf| %>
              <tr>
                <td><%= tf.filename %></td>
                <td><span class="red"><%= tf.past_agents %></span></td>
                <td><span class="green"><%= tf.agent %></span></td>
              </tr>
              <% end %> 
              </tbody>
            </table> 
            
        <% end %>
        
      </div>

      <div class="modal-footer">            
          <button type="button" class="btn btn-default btn-sm" data-dismiss="modal" data-bs-dismiss="modal"><%= t(:close) %></button>
      </div>
    </div>
  </div>
</div>
            
		
<div id="build_details">

    <% if (the_current_user && the_current_user.is_member?(@project)) %>
			<div id="action_dropdown">
          <%= partial(:'builds/action_dropdown', :locals => {:build => @build}) %>        
			</div>
    <% end %>
		

  <h2 class="build_heading <% if @build.incomplete? %> in_progress_build<% else %> completed_build<% end %>">

    <%= @project.name %> &nbsp;

    <a href="/projects/<%= @project.id %>/edit" class="hidden-print" style="margin-top: 2px;"><i class="fa fa-pencil-square-o fa-lg" aria-hidden="true" style="font-size: 1.22em;"></i></a>

    
    <% unless @build.incomplete? %>

        <a href="/projects/<%=@build.project.identifier%>/report" class="hidden-print" style="margin-top: 2px;" data-toggle='tooltip' data-placement='top' title='<%= I18n.t(:project_chart)%>'><i class="fa fa-line-chart" class="orange" aria-hidden="true"></i></a>

  			<span class="label <% if @build.successful %> label-success <% elsif @build.status == 'complete' %> label-failed <% else %> label-<%= @build.status %> <% end %>" style="font-size: 16px; margin-right: 5px; padding: 4px;"><a href="/builds/<%= @build.id %>" style="color: white;">
						Build #<%= @build.id %>
          <% if @build.successful %>
							OK
						<% elsif @build.status == 'complete' %>
		          <%= I18n.t(:failed) %>
						<% else %>
							<%= I18n.t(@build.status.downcase) rescue nil  %>
						<% end %></a>
				</span>

        <% if @build.build_agents.any? %>
            <button class="btn btn-info btn-sm" type="button" style="margin-top: -2px; padding: 4px;" onclick="$.getScript('/builds/<%= @build.id %>/agent_charts')">
              <%= I18n.t(:agents) %> <span class="badge badge-dark"><%= @build.build_agents.size %></span>
            </button>
        <% end %>

				<% if !@building_in_progress && the_current_user  && (the_current_user.is_admin? || the_current_user.has_role?(:builder, @project) ) %>
              <button class="btn btn-default btn-sm not-for-showcase" id="build_project_<%= @build.project.id %>" style="margin-top: -1px;" type="button" onclick="build_again();"><%= I18n.t(:build_now)%></button>
				<% end %>


        <label class="label label-warning" id="valid_status_label" style="padding: 6px; <% unless @build.is_invalid %> display:none;
          <% end %>"><%= I18n.t(:invalid) %></label>

    <% else %>
        <span class="label label-info" id="build-status" style="font-size: 14px;"><a href="/builds/<%= @build.id %>" style="color:white;">Build #<%= @build.id %>
          building ...</a></span> &nbsp;

        <% if @build.is_parallel && @build.build_agents.any? %>
            <button class="btn btn-info btn-sm" type="button" onclick="$.getScript('/builds/<%= @build.id %>/allocations')" style="padding: 4px;">
              <%= I18n.t(:agents) %> <span class="badge badge-dark"><%= @build.current_agent_allocations.size %></span>
            </button>
        <% end %>

    <% end %>
    <!-- status: <%= @build.status %>-->


    <% unless @build.incomplete? %>
        <!-- do not show for in-progress build-->
        <span class="build_summary">
        <a href="javascript:void(0);" id="build_summary_link" onclick="edit_summary();"
           <% if @build.summary.nil? || @build.summary.empty? %> style="display:none"
           <% end %>
           class="label label-info"><%= @build.summary %></a>
		</span>
    <% end %>

  </h2>

  <% if @build.incomplete? %>
      <div class="bar-container hidden-print" style="width: 100%; margin-top: 10px;">
        <div class="progress" style="width: 100%">
          <div class="progress-bar  progress-bar-striped progress-bar-animated active " id="progressbar"
               style="width: 0%; <% if @project.build_progress_percentage.nil? || @project.build_progress_percentage.to_i < 4 %> padding-left: 10px; font-weight: 700;
                 <% end %>">
          </div>
        </div>
      </div>
      <script type="text/javascript" charset="utf-8">
          $(function () {
              var $bar = $('#progressbar');
              $bar.width("<%= @project.build_progress_percentage.to_i %>%");
              $bar.text("<%= @project.build_progress_percentage.to_i %>" + '%');
          });
      </script>
  <% end %>

  <!-- DETAILS -->

  <% if $troubled_agents && $troubled_agents.any? %>
      <div id="agent_warning">
        Agents experiencing errors:
        <ul>
          <% $troubled_agents.each {|key, val| %>
              <li><%= key %></li>
          <% } %>
        </ul>
      </div>
  <% end %>

  <!-- help with first build -->
  <%
    build_test_files = @test_files || []
  %>

  <% if !@build.incomplete? && @build.test_files.any? %>
  	<% if @build.project.config && @build.project.config.is_load_testing %>
       <!-- ignore duplicate suite name check for load testing -->
    <% else  %>
		<% if @build.test_files.count !=  @build.test_files.collect{|x| x.filename}.uniq.count %>
      <div class="alert alert-warning" style="margin-top: 5px; font-size: 14px;">
         Duplicate <code>describe('...')</code> detected, which cause showing duplicate test file names.
	    </div>
	  <% end %>
    <% end %>
  <% end %>

  <% if @build.incomplete? && (Time.now - @build.start_time) > 120 && @build.project.total_ui_test_count == 0 && @build_test_files && @build_test_files.empty? %>
      <div class="alert alert-info" style="margin-top: 5px; font-size: 14px;">
        <p style="margin-top: 3px; margin-bottom: 10px;">Looks like there are some configurations issues prevent tests
          being run. Here are common reasons: </p>
        <ul>
          <li>The <code>BUILD PROJECT IDENTIFER</code> set in the <code>Rakefile</code> shall be the same as this one:
            <code><%= @build.project.identifier rescue nil %></code></li>
          <li>The <code>BUILDWISE_MASTER</code> environment value in this BuildWise project configuration, and it shall
            be accessible by the server and all build agents.
          </li>
          <li>Make sure the code/test scripts are checked out (from Git) correctly at
            <code><%= @build.project.checkout_dir %></code></li>
        </ul>
      </div>
  <% end %>


  <% if @step && @step.id %>
      <div id="step_detail">
        <%= partial "/builds/step_detail".to_sym %>
      </div>
  <% else %>
      <div id="full_detail">
        <%= partial "/builds/full_detail".to_sym %>
            
    		<div style="margin-top: 10px; margin-bottom: 10px; margin-left: 2px;" class="hidden-print">          
    	    <span class="hint" style="font-weight: 100;">
            <i class="fa fa-clock-o" aria-hidden="true"></i>
            <i><%= I18n.t(:triggered_by) %></i> <b style='color:#4885ed;'><%= @build.triggered_user %></b> <%=I18n.t(:at) %> <%= @build.created_at.localtime.strftime('%Y-%m-%d %H:%M:%S') %>
          </span>
    		</div>
          
      </div>
  <% end %>


  <% unless @build.incomplete? %>

      <script type="text/javascript">

          var fuse;

          $(document).ready(function () {

              var list = <%= raw @build.all_test_cases_in_json %>;

              var options = {
                  shouldSort: true,
                  includeScore: true,
                  threshold: 0.6,
                  location: 0,
                  distance: 100,
                  maxPatternLength: 32,
                  minMatchCharLength: 2,
                  keys: [
                      "test_file",
                      "test_case"
                  ]
              };

              fuse = new Fuse(list, options); // "list" is the item array

              $("#searchTextbox").bind("mouseup", function(e){
                 var $input = $(this);
                 var oldValue = $input.val();

                 if (oldValue == "") return;

                 // When this event is fired after clicking on the clear button
                 // the value is not cleared yet. We have to wait for it.
                 setTimeout(function(){
                   var newValue = $input.val();

                    if (newValue == ""){
                       // capture the clear
                      onSearch();
                    }
                  }, 1);
              });
              
          });

          function onSearch() {

              $("#search_spinner").show();
              $("#match_results_count").html("");
              $("#match_results_count").hide();

              var pattern = $("#searchTextbox").val();
              if (pattern.length < 2) {
                  $("#test_results_table tbody tr.test_file_row").show();
                  $("#test_results_table tbody tr.test_case_row").show();
              } else {
                  var result = fuse.search(pattern)
                  // console.log(result);
                  $("#test_results_table tbody tr").hide();
                  for (var i = 0; i < result.length; i++) {
                      var match_test_file_id = result[i]["item"]["test_file_id"];
                      var match_test_case_id = result[i]["item"]["test_case_id"];
                      $("#test_results_table tbody tr#test_file_" + match_test_file_id).show();
                      $("#test_results_table tbody tr#test_case_" + match_test_case_id).show();
                  }

                  $("#match_results_count").html(result.length + " matches");
                  $("#match_results_count").show();

              }
              $("#search_spinner").hide();

          }
      </script>
  <% end %>
          
          

				              
          
</div>


        
<script type="text/javascript">

    $(document).ready(function () {

      $('#myTab a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
      });

      $('#test_failure_modal_tabs a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
      });
       
        <% if params && params['tab'] == "history" %>
        $('#myTab a:last').tab('show');
        <% else %>
        $('#myTab a:first').tab('show');
        <% end %>

        Highcharts.chart('project-chart-<%= @project.id%>', {
            chart: {
                type: 'column',
                backgroundColor: null

            },
            title: {
                text: ''
            },
            credits: {
                enabled: false
            },
            xAxis: {
                labels: {
                    enabled: false
                },
                title: {
                    text: null
                },
                startOnTick: false,
                endOnTick: false,
                tickPositions: []
            },
            yAxis: {
                endOnTick: false,
                startOnTick: false,
                labels: {
                    enabled: false
                },
                title: {
                    text: null
                },
                tickPositions: [0]
            },
            legend: {
                enabled: false
            },
            tooltip: {
                // positioner: function () {
                //    return { x: 0, y: 0 };
                // },
                formatter: function () {
                    return '<span style="font-size:10px">#' + this.point.id + ' </span> <span style="font-size:10px;"><b>' + this.point.duration + '</b></span>'+ 
					    '  <label style="font-size:10px;"><i> ' +  this.point.pass_rate + '</i></label>' + 					
					'<br/>' + '<span style="font-size:10px">' + this.point.time + '</span>';
                }
            },
            plotOptions: {
                column: {
                    pointPadding: 0.15,
                    borderWidth: 0
                },
                series: {
                    animation: false,
                    cursor: 'pointer',
                    point: {
                        events: {
                            click: function () {
                                window.location.href = "/builds/" + this.id;
                            }
                        }
                    }
                }
            },
            series: [{
                name: 'time',
                maxPointWidth: 10,
                data: <%= raw  @project.last_builds(15, @build.id).reverse.collect{|x| x.chart_data}.to_json %>
            }]
        });


				// highlight code in test output
				$('pre code').each(function(i, block) {
				    hljs.highlightBlock(block);
				});

        <% if @build.is_load_testing || @build.is_performance_testing %>
          // no searching for performance/load testing
        <% else %>
        if ($("#searchTextbox").length) {
          $("#searchTextbox").focus();
        }
        <% end %>

    });

</script>
