/// <reference path="../../typings/jquery/jquery.d.ts"/>

var global_columns_goals = []; //Holds column names for goals, and selected state
var global_columns_phases = []; //Holds column names for phases, and selected state

var deferredOpenElem = null;
var srVersion = false;
var preFetchImages = true;

var creditDict = {};
var G_projectCreditCountApplicable = 100;
var G_projectCreditCountEarned = 0;
var G_projectSolutionsTowardsBonusCount = 0;
var G_projectAwardPercentage = 0.0;
var G_h1CreditsArrString = '';
var G_h1CreditsArrEarnedString = '';
var G_h1CreditsArrApplicableString = '';
var G_h1CreditsArr = [];
var G_h1CreditsArrEarned = [];
var G_isud_status = 0;
var G_IS_PROJECT_OWNER = true;
var G_IS_PROJECT_REVIEWER = false;
var d_visibility = "deleted";
var s_visibility = "self";
var a_visibility = "all";
var pre_id="prelim";
var full_id="full";
var cert_id="cert";
var summary_id = "summary";
// Project scope : Building and Site =1 and Building only =0
// used to hide and show Chapter 5 based on scope.
var G_project_scope = 0;

var editMode = false;
var initialPopulationMode = true;
var params={};
var pbar;
var initialFetchChapterCount = 0;

var loadingMsgContainer = null;
var loadingMsgSpan = null;
var G_PROJECT_ID;
String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}
//

$(document).ready(function () {

    var user_email = "";

    window.location.search.replace(/[?&;#]+([^=&]+)=([^&]*)/gi,function(str,key,value){params[key] = value;});

    $("img").unveil();
    $("img").trigger("unveil");
    /*replace the browse icon in the navigation bar to active browse icon.*/
    $("#id-img-navbar-p-browse").attr("src","images/browsesolutions_icon_active.fde41802.png");


    // TODO : Fix this temp //////////
    if(typeof params.edit !== "undefined" && params.edit ==="true" && (typeof params.id !== "undefined")){
        editMode = true;
        //$(".icon-holder").css("margin-right","5%");
        G_PROJECT_ID=params.id;
        $(".cl-div-chapter-sub-title").hide();
        $(".cl-div-nav-image-holder-solution_l").css("display","flex");
        $(".cl-div-nav-project-award-details-holder").css("display","flex");
        $(".cl-div-nav-project-award-details-holder").css("max-width","100%");
        $(".cl-div-nav-project-award-details-holder").css("min-width","14.5%");
        $(".cl-div-nav-project-award-details-holder").css("height","100%");
        $(".cl-div-nav-project-award-details-holder").css("background-color","#e8e8e8");
        $(".icon-holder").css("max-width","27%");
        $(".cl-div-site-breadcrumb").addClass("hide");
        process_solution_summary();
    } else {
        $(".cl-div-chapter-sub-title").show();
        $(".cl-div-nav-image-holder-solution_l").css("display","none");
        $(".cl-div-nav-project-award-details-holder").css("display","none");
        $(".cl-form-solution-checkbox").hide();
        $(".cl-div-hx-item-title-edit-status").hide();
        $(".cl-div-chapter-credit-implemented-ratio-holder").hide();
        $("#id-div-chapter-content-top-info").hide();
        $(".cl-div-hx-footer").hide();
        $(".cl-div-nav-image-holder-solution_l").addClass("hide");
        $(".cl-div-nav-project-award-details-holder").addClass("hide");
    }
});
function process_solution_summary(){
  // Call api to get all comments and their corresponding solution text
  // Populate the solution comments and solution text as heading
  $.post("API.php",{comment:"GET_ALL",project_id:G_PROJECT_ID},function(data){
    if(data.success){
      var comments = data.comments;
      if(comments.length==0) return;
      var chat_thread="";
      var prev_id=comments[0].sub_id;
      var element = null;
      var parentElement = $("#fb-sol-summary");
      parentElement.html("");
      var clone = $("#sol-cmnts-thread-template").clone();
      var rev_ele=$("#rev_comment_clone").clone();
      rev_ele.attr("id","");
      var cli_ele=$("#cli_comment_clone").clone();
      cli_ele.attr("id","");
      var c_clone=null;
      var comment_div_ele=null;
      for(var i=0;i<comments.length;i++){
          var comment = comments[i];
          var curr_id = comment.sub_id;

          if(curr_id!=prev_id){
            if(prev_id=="summary" || prev_id == pre_id || prev_id == full_id || prev_id == cert_id || comment.visibility==d_visibility)
            {
              prev_id=curr_id;
              continue;
            }

            comment = comments[i-1];
            var text = comment.standard_text != null ? comment.standard_text : "";
            element = clone.clone();
            comment_div_ele=element.find(".sol-comments-threadCSS");
            element.attr("id","");
            element.find(".sol-cmnts-title").html(prev_id+" "+ text);
            element.find(".collapse-threadTxt").attr("data-target",prev_id);
            if(comment.user_status=="other"){
              c_clone=rev_ele.clone();
              if(!G_IS_PROJECT_REVIEWER)
                c_clone.find(".comment-checkbox").remove();
             }
            else{
              c_clone=cli_ele.clone();
              if(G_IS_PROJECT_REVIEWER)
                c_clone.find(".comment-checkbox").remove();
            }
            var frmtDate = return_formatted_timestamp(comment.timestamp);
            var timestamp="";
            c_clone.find(".comment-info-divCss").css("color","grey");

            if(comment.visibility==a_visibility){
              timestamp="Sent on: "+frmtDate;
              c_clone.find(".comment-checkbox").remove();
            }
            else if(comment.visibility==s_visibility){
              timestamp="Saved on: "+frmtDate;
            }
            c_clone.find(".comment-info-divCss").html(timestamp);
            c_clone.find(".comment-txt-divCSS").html(comment.comment);
            c_clone.removeClass("hide");
            comment_div_ele.append(c_clone);
            parentElement.append(element);
            parentElement.append("<hr style='margin:0px;'/>");
            element.removeClass('hide');
          }
          prev_id=curr_id;
          // Build a function to separate comments based on if the comment belongs to client or reviewer

      }

    }
    else{
      show_splash_popup("Failed to get comments");
    }
  },"json")
}
$(document).on("click",".collapse-threadTxt",function(ev){
  ev.stopPropagation();

  var sub_id = $(this).attr("data-target");
  var sol_text = $(this).parent().parent().find(".sol-cmnts-title").text();
  var ms = Date.now();
  $.post("API.php",{comment:"GET",project_id:G_PROJECT_ID,solution_id:sub_id},function(data){
    if(data.success){
      var parentElement=$("#comments-thread-div");
      parentElement.empty();
      var comments = data.comments;
      var chat_thread="";
      var rev_ele=$("#rev_comment_clone").clone();
      rev_ele.attr("id","");
      var cli_ele=$("#cli_comment_clone").clone();
      cli_ele.attr("id","");
      var clone;
      for(var i=0;i<comments.length;i++){
          var comment = comments[i];
          if(comment.visibility==d_visibility)
           continue;
          // This is just to demonstrate conversation between user and reviewer, write login to segregate comments based on whom it belongs to
          if(comment.user_status=="other"){
           clone=rev_ele.clone();
           }
          else{
            clone=cli_ele.clone();
          }
          clone.find(".comment-checkbox").remove();
          clone.find(".comment-txt-divCSS").html(comment.comment);
          var clone_id = "comments_"+comment.sl_no+"_"+Date.now();
          clone.attr("id",clone_id);
          var frmtDate = return_formatted_timestamp(comment.timestamp);
          var timestamp;
          if(comment.visibility==a_visibility){
            timestamp="Sent on: "+frmtDate;
            clone.find(".comment-info-divCss").remove();

          }
          else if(comment.visibility==s_visibility){
            timestamp="Saved on: "+frmtDate;
          }
          clone.find(".comment-timestamp-divCss").html(timestamp);
          clone.removeClass("hide");
          parentElement.append(clone);
      }
      parentElement.show();
      parentElement.scrollTop(parentElement.height());
      var cm_modal_id="#id-sol-comments-modal";
      $("#solution-comments-text").val("");
      $("#solution-comments-text").focus();
      
      if (data.review_checkbox_value == "-1" )
      {
        $("#solution-comments-text").hide();
        $("#cmnt-file-upload-btn").hide();
        $("#id-send-cmnts").hide();
        $("#id-save-cmnts").hide();
        $("#id-close-cmnts").show();
      }
      else
      {
        $("#solution-comments-text").show();
        $("#cmnt-file-upload-btn").show();
        $("#id-send-cmnts").show();
        $("#id-save-cmnts").show();
        $("#id-close-cmnts").hide();
      }

      $(cm_modal_id).modal("show"); //Displaying solution comments modal
      $(cm_modal_id).attr("data-target",sub_id);
      $(cm_modal_id).attr("sol_id",sub_id);
      // $("#id-comment-header").html(sol_text); // Dynamically adding item number and title to the modal header
      $("#id-comment-solution").html(sol_text); // Dynamically adding solution text to modal content

    }
    else{
      show_splash_popup("Failed to get comments");
    }
  },"json");
});

function preprocess_comments_modal_buttons(cm_modal_id){ // Function that is common to all button handlers of comments modal

  var attr = $(cm_modal_id).attr("data-target");
  $(cm_modal_id).modal("hide");
  return attr;
}
function validate_modal_comments(){
    var comment = $("#solution-comments-text").val();
    if(comment.trim().length==0)
     return false;
    return true;
}
$("#id-save-cmnts").unbind().click(function(){
  var cm_modal_id="#id-sol-comments-modal";
  if(validate_modal_comments()){
    var attr = preprocess_comments_modal_buttons(cm_modal_id);
    // Save comments to the database and pop notification that the input has been saved
    // Function to save comments to database

    var comment = $("#solution-comments-text").val();
    save_comment_indb(attr,comment);


}
});
$("#id-send-cmnts").unbind().click(function(){
  var comment = $("#solution-comments-text").val();
  if(comment.trim()=="") return;
  var cm_modal_id="#id-sol-comments-modal";
  var attr = $(cm_modal_id).attr("data-target");
  var sol_id=$(cm_modal_id).attr("sol_id");
  // Open a new popup showing send this comment or send all comments
  var popup_id="#popup-modal";
  $(popup_id).attr("data-target",attr);
  $(popup_id).attr("sol_id",sol_id);
  $("#id-popup-modal-title").html("Notification");
  $("#send-this-radio-btn").prop('checked', false);
  $("#send-all-radio-btn").prop('checked', false);
  $(popup_id).modal("show");
});

// File upload icon that navigates user to file upload page
$("#cmnt-file-upload-btn").on("click",function(){
  // if(G_IS_PROJECT_REVIEWER){
    var target = "submitProject.php?pid=" + G_PROJECT_ID;
    var win = window.open(target,"_blank");
    win.focus();
  // }
});
function save_comment_indb(sol_id,comment){
  // update_checkbox_value_in_db(1,sol_id);
  $.post("API.php",{comment:"SET",project_id:G_PROJECT_ID,solution_id:sol_id,text:comment,visibility:s_visibility},
  function (data) {
      if (data.success == true)
      {
        process_solution_summary();
        show_splash_popup("Your input was saved","",2); // Popup to display the message
      }
    },"json");
}
$("#id-cancel-cmnts").unbind().click(function(){
  var cm_modal_id="#id-sol-comments-modal";
  var attr = preprocess_comments_modal_buttons(cm_modal_id);
  // Exit out of solution comments box
});

$("#id-close-cmnts").unbind().click(function(){
  var cm_modal_id="#id-sol-comments-modal";
  var attr = preprocess_comments_modal_buttons(cm_modal_id);
  // Exit out of solution comments box
});

// Comment modification handlers
$("#comments-thread-div").on("click",".comment-delete-btn-id",function(ev){
  ev.stopPropagation();
  var clone = $(this).parent().parent().parent();
  var clone_id = clone.attr("id");
  var temp_arr = clone_id.split("_");
  var cmnt_sl_no = temp_arr[1];
  $.post("API.php",{comment:"DELETE",sl_no:cmnt_sl_no},function(data){
    if(data.success){
      process_solution_summary();
      show_splash_popup("Comment Deleted Successfully","",2);
      clone.remove();
    }
  },"json");
});
// Comment Edit handler
$("#comments-thread-div").on("click",".comment-edit-btn-id",function(ev){

  var clone = $(this).parent().parent().parent();
  clone.find(".comment-txt-divCSS").attr("contentEditable",true);
  clone.find(".comment-save-btn-id").removeClass("hide");
  $(this).addClass("hide");
});
// Comment Save handler
$("#comments-thread-div").on("click",".comment-save-btn-id",function(ev){

  var clone = $(this).parent().parent().parent();
  var clone_id = clone.attr("id");
  var temp_arr = clone_id.split("_");
  var cmnt_sl_no = temp_arr[1];
  clone.find(".comment-txt-divCSS").attr("contentEditable",false);
  clone.find(".comment-edit-btn-id").removeClass("hide");
  $(this).addClass("hide");
  var updated_comment = clone.find(".comment-txt-divCSS").text();
  $.post("API.php",{comment:"UPDATE_TEXT",sl_no:cmnt_sl_no,text:updated_comment},function(data){
    if(data.success){
      process_solution_summary();
      show_splash_popup("Comment updated Successfully","",2);
    }
  },"json");
});
// Till here
function return_formatted_timestamp(rawDate){
    var date1 = new Date(rawDate);
    var day = date1.getDate();
    var month = date1.getMonth()+1;
    var year = date1.getFullYear();
    var hours = date1.getHours();
    var mins = date1.getMinutes();
    var ampm="am";
    if(hours==12){
      ampm="pm";
    }
    if(hours>12){
      ampm="pm";
      hours=hours-12;
    }
    var formattedDate=month+"/"+day+"/"+year+" "+hours+":"+mins+ampm;
    return formattedDate;
}
$("#send-this-radio-btn").on("click",function(){
  if($(this).prop("checked")=="false") return;
  var popup_id="#popup-modal";
  var sol_id= $(popup_id).attr("sol_id");
  var comment = $("#solution-comments-text").val();
  // console.log("Send this radio button clicked for solution id: "+sol_id);
  $.post("API.php",{comment:"SET",project_id:G_PROJECT_ID,solution_id:sol_id,text:comment,visibility:a_visibility},
  function (data) {
      if (data.success == true)
      {
        var cm_modal_id="#id-sol-comments-modal";
        $(popup_id).modal("hide");
        show_splash_popup("Your input was sent","",2); // Popup to display the message
        process_solution_summary();
      }
    },"json");

});
$("#send-all-radio-btn").on("click",function(){
  if($(this).prop("checked")=="false") return;
  var target = "projectfullreview.php?edit=true&id=" + G_PROJECT_ID;
  var win = window.open(target,"_self");
});
// Handling send all and send selected
$("#sendallsavedcmnts").on("change",function(){
  if($(this).prop("checked")==true){
    $(".comment-checkbox").prop("checked",true);
    $("#sendselectedcmnts").prop("checked",false);
  }
  else{
    $(".comment-checkbox").prop("checked",false);
  }
});
$("#fb-sol-summary").on("change",".comment-checkbox",function(ev){
  if($(this).prop("checked")==false){
    $("#sendallsavedcmnts").prop("checked",false);
  }
});
$("#sendselectedcmnts").on("change",function(){
  if($(this).prop("checked")==true){
    $("#sendallsavedcmnts").prop("checked",false);
  }
});
$("#sendFinalComments").on("click",function(){
  if($("#sendallsavedcmnts").prop("checked")==true){
    $.post("API.php",{comment:"SET_VISIBILITY",project_id:G_PROJECT_ID,solution_id:"%",visibility:a_visibility},
    function (data) {
        if (data.success == true)
        {
          show_splash_popup("All your saved comments have been sent","",2); // Popup to display the message

          process_solution_summary();
          $("#sendallsavedcmnts").prop("checked","false");
        }
      },"json");
  }
  else if($("#sendselectedcmnts").prop("checked")==true){
    // write a function to send only the selected comments
  }
});
;