<%= csrf_meta_tag %> 
<% content_for :page_specific_css do %>
  <%= stylesheet_link_tag "client_management/dashboard" %>
  <%= stylesheet_link_tag "select2/select2" %>
<% end %>
<% content_for :page_specific_javascript do %>
  <%= javascript_include_tag "lib/jquery.form.js" %>
  <%= javascript_include_tag "validator" %>
  <%= javascript_include_tag "select2/select2.min" %>
  <%= javascript_include_tag "jquery.viewport" %>
<% end %>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div class="dashboard-wrapper">
	<div class="left-side">
		<div id="url-box">
			<span class="site-title"><%= @site_request.site_title %></span>
			<span class="site-url">
				<span id="edit-url-box">
					<% if @site_request.new_site_url.nil? || @site_request.new_site_url == "" %>
						<a href="" id="site-url-tag">Not Available</a>
					<% else %>
						<a href="<%= @site_request.new_site_url %>" target="_blank" id="site-url-tag"><%= @site_request.new_site_url %></a>
					<% end %>
					<a href="" id="edit-url-btn"><i class="icons-pencil"></i></a>
				</span>
				<span id="site-url-edit-box" style="display:none;">
					<%= form_for @site_request, :url => {:action => "update_site_request"} do |f| %>
						<%= f.text_field :new_site_url, :placeholder => "http://site-abbr.pending.rulingcom.com" %>
						<button role="submit"><i class="icons-checkmark"></i></button>
					<% end %>
				</span>
				
			</span>
			<span class="pull-right request-type">
				<%= @site_request.get_request_type %>
				<% if @site_request.type == "upgrade" %>
					<a href="<%= @site_request.upgrade_r2_site %>" target="_blank"><i class="icons-popup"></i></a>
				<% end %>
			</span>
		</div>
		<div id="timeline-box" class="collapsed">
			<%= render :partial => "timeline_box" %>
		</div>
		<div id="dashboard">
			<div class="conversations">
				<% if @site_request.project_posts.count > 0 %>
					<%= render :partial => "conversation", :collection => @site_request.project_posts.asc(:created_at) %>
				<% else %>
					<h3>No posts found</h3>
				<% end %>
			</div>
			<div class="editor-wrapper">
			  <div id="post-loader" style="display:none;">
          <%= image_tag("preloader.gif", size: "50")  %>
          <div>Posting your response.</div>
        </div>
				<%= form_for @project_post, :url => {:action => "create_project_post"}, :html => {:id => "dashboard-post"} do |f| %>
          <textarea class="ckeditor" name="project_post[content]" data-fv-validation="required;" data-fv-messages="Cannot be empty;"></textarea>
          <div class="ticket-internal-response-wrap">
	          <div class="ticket-internal-response">
	            <%= f.check_box :internal_response %>
	            <%= f.hidden_field :site_request_id , :value => @site_request.id.to_s %>
	            <%= f.hidden_field :user_id , :value => current_user.id.to_s %>
	            <span class="ticket-internal-response">Internal Response</span>
	          </div>
	          <div class="ticket-tag-member">
	            <!-- <h4 class="ticket-tag-mebmer-heading">Tag member</h4> -->
	            <select class="member_tags" multiple="multiple" name="project_post[user_tags][]">
                <% @members.each do |member| %>
	                <%
	                  name = member["name"][I18n.locale.to_s] == "" ? member["name"]["zh_tw"] : member["name"][I18n.locale.to_s]
	                  name = "" if name.nil?
	                  user_name = "(#{member["user_name"]})"
	                  text = " #{name} #{user_name}"
	                %>
                  <option value="<%= member["id"] %>" data-member="<%= member.to_json %>"><%= text %></option>
                <% end %>
	            </select>
	          </div>
	          <div class="submit-form-btn">
	          	<input type="submit" class="btn btn-primary" id="dashboard-post-submit-btn" value="Submit">
	          </div>
	        </div>
        <% end %>
			</div>
		</div>
	</div>
	<div class="right-side">
		<%= render :partial => "progress_tracker" %>
	</div>
</div>

<script type="text/javascript">
	var locale = "<%= I18n.locale.to_s %>";
	$("#edit-url-btn").on("click",function(){
		$("#edit-url-box").hide();
		$("#site-url-edit-box").show();
		$("#site-url-edit-box input[type=text]").focus();
		return false;
	})
	$("#site-url-edit-box form").on("submit",function(){
		var form = $(this);
		$.ajax({
			url : form.attr("action"),
			data : form.serialize(),
			type : "post",
			dataType : "json"
		}).done(function(data){
			$("#site-url-tag").attr("href", data.url).text(data.url);
			$("#site-url-edit-box").hide();
			$("#edit-url-box").show();
		})
		return false;
	})
	$(".member_tags").select2({
    formatResult: function (el) {
      var $el = $(el.element),
          member = $el.data("member"),
          name = (member.name[locale] == "" ? member.name.zh_tw : member.name[locale]),
          user_name = "(" + member.user_name + ")",
          text = name + " " + user_name;
      if (!el.id) { return el.text; }
      var $state = $(
        '<span><img src="' + member.avatar + '" class="img-avatar" /> ' + text + '</span>'
      );
      return $state;
    },
    placeholder: "Tag Members"
  });
  var fv = new FormValidator($("#dashboard-post"));
  $("#dashboard-post-submit-btn").on("click",function(){
  	 for (instance in CKEDITOR.instances) {
      CKEDITOR.instances[instance].updateElement();
    }
    if(fv.isFormValidated()){
      $("#dashboard-post").hide();
      $("#post-loader").show();
      fv.form.ajaxSubmit({
        success : function(data){
          setTimeout(function(){
            fv.reset();
            $(".member_tags").select2("val","");
            for (instance in CKEDITOR.instances) {
               CKEDITOR.instances[instance].setData("");
            }
            $("#dashboard-post").show();
            $(".conversations").find("h3").remove();
            $(".conversations").append(data);
            $("#post-loader").hide();
          },500)
        },
        error : function(){
          $("#post-loader").find("img").hide();
          $("#post-loader").find("div").text("There was some error.");
        }
      });
    }
    return false;
  })
  $(document).on("click", ".progress-checkbox", function(){
  	var el = $(this),
  			value = el.attr("name"),
  			checked = el.prop("checked");
  	$.ajax({
  		url : "<%= timeline_update_admin_client_management_path(@site_request.site_timeline) %>",
  		data : {"field" : value, "checked" : checked},
  		dataType : "json",
  		type : "post",
  		beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
  	}).success(function(data){
  		var span = el.parent().find("span"),
  				label = el.parent().find("label");
  		if(checked){
  			span.removeClass("deadline");
  			span.addClass("completed");
  			label.addClass("strikethrough");
  			span.text(data.time + " by " + data.name);
  		}else{
  			span.removeClass("completed");
  			span.addClass("deadline");
  			label.removeClass("strikethrough");
  			span.text(data.time);
  		}
  	})
  })
  var timelineBox = $("#timeline-box"),
  		expandBtn = $("#timeline-expand-btn");
  expandBtn.on("click",function(){
  	if(timelineBox.hasClass("collapsed")){
  		timelineBox.removeClass("collapsed");
  		expandBtn.find("i").removeClass("icons-plus");
  		expandBtn.find("i").addClass("icons-minus");
  		$("#timeline-chart").show();
  	}else{
  		timelineBox.addClass("collapsed");
  		expandBtn.find("i").removeClass("icons-minus");
  		expandBtn.find("i").addClass("icons-plus");
  		$("#timeline-chart").hide();
  	}
  })
  var timelineHash = <%= @timeline.to_json.html_safe %>,
  		dataTable = null,
  		chart = null,
  		counter = 0,
  		titles = {
				"test_site_creation_start" : "Test Site Creation",
				"template_design_images_start" : "Template Images",
				"template_html_css_start" : "Template HTML & CSS",
				"customized_module_start" : "Customized Module",
				"data_migration_start" : "Data Migration",
				"site_structure_start" : "Structure & Data Finalizing ",
				"site_migration_start" : "Site Migration"
			}

	google.charts.load("current", {packages:["timeline"]});
  google.charts.setOnLoadCallback(drawChart);
  var timelineOptions = {
    timeline: { showRowLabels: true }
  };

  function drawChart() {
    var container = document.getElementById('timeline-chart');
  	chart = new google.visualization.Timeline(container);
  	dataTable = new google.visualization.DataTable();
    dataTable.addColumn({ type: 'string', id: 'Term' });
    dataTable.addColumn({ type: 'string', id: 'Name' });
    dataTable.addColumn({ type: 'date', id: 'Start' });
    dataTable.addColumn({ type: 'date', id: 'End' });
    $.each(timelineHash,function(i, tm){
			var hs = tm[0],
					keys = Object.keys(hs),
					enddt = new Date(hs[keys[1]]),
					startdt = new Date(hs[keys[0]]);
	  	counter++;
	  	console.log(hs[keys[1]]);
	  	dataTable.addRow([counter.toString(), titles[keys[0]], startdt, enddt]);
		})
    chart.draw(dataTable, timelineOptions);
    $("#timeline-chart").hide();
  }
</script>



