/// <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";
// 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");
        load_project_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 load_project_summary(){
  $.post("API.php",{comment:"GET",project_id:G_PROJECT_ID,solution_id:"summary"},
  function (data) {
      if (data.success == true)
      {
        var comments = data.comments;
        if(comments.length==0) return;
        var comment = comments[0];
        var summary = comment.comment;
        var txt_id = "#id-summary-txt";
        var summary = $(txt_id).val(summary);

      }
    },"json");
}

// $(".cl-edit-summary-btn").on("click",function(){
//   var txt_id = "#id-summary-txt";
//   $(txt_id).attr("readonly", false);
//   $(txt_id).css('background','white');
// });
// $(".cl-save-summary-btn").on("click",function(){
//   var txt_id = "#id-summary-txt";
//   var summary = $(txt_id).val();
//   if(summary.trim()=="") return;
//   $.post("API.php",{comment:"SET",project_id:G_PROJECT_ID,solution_id:"summary",text:summary,visibility:s_visibility},
//   function (data) {
//       if (data.success == true)
//       {
//         show_splash_popup("Your input was saved","",2); // Popup to display the message
//         $(txt_id).attr("readonly", true);
//         $(txt_id).css('background','none');
//       }
//     },"json");
// });
// $(".cl-send-summary-btn").on("click",function(){
//   var txt_id = "#id-summary-txt";
//   var summary = $(txt_id).val();
//   if(summary.trim()=="") return;
//   $.post("API.php",{comment:"SET",project_id:G_PROJECT_ID,solution_id:"summary",text:summary,visibility:a_visibility},
//   function (data) {
//       if (data.success == true)
//       {
//         show_splash_popup("Your input was saved","",2); // Popup to display the message
//         $(txt_id).attr("readonly", true);
//         $(txt_id).css('background','none');
//       }
//     },"json");
// });

// Reply Button Related Functions
$(".cl-reply-summary-btn").on("click",function(){
  var sub_id = "summary";
  var sol_text = "Preliminary Feedback";
  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();
      var cm_modal_id="#id-sol-comments-modal";
      $("#solution-comments-text").val("");
      $("#solution-comments-text").focus();
      $(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 = preprocess_comments_modal_buttons(cm_modal_id);
var sol_id=$(cm_modal_id).attr("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)
    {
      load_project_summary();
      show_splash_popup("Your input was sent","",2); // Popup to display the message
    }
  },"json");
});

// 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)
    {
      load_project_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
});
// 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){
    load_project_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){
    load_project_summary();
    show_splash_popup("Comment updated Successfully","",2);
  }
},"json");
});

$('.modal').on('shown.bs.modal', function () {
    $("#comments-thread-div").scrollTop($("#comments-thread-div")[0].scrollHeight);
});

// 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;
};