/// <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 pre_id="prelim";
var full_id="full";
var cert_id="cert";

var pre_review_allow_edit = true;
var full_review_allow_edit = true;
var cert_review_allow_edit = true;

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");
        $.post("API.php", {project: "DETAILS", id :G_PROJECT_ID}, function (data) {
            var d = data[0];
            G_IS_PROJECT_OWNER = d.is_requesting_user_owner;
            G_IS_PROJECT_REVIEWER = d.is_requesting_user_reviewer;
            if(!G_IS_PROJECT_REVIEWER){
              // Delete all review divs if the project reviewer is not the current user
              $(".cl-identifier-summary-btn-div").remove();
              $(".cl-feedback-text").css("background-color","#fafaf9");
            }
            // Updating textarea with the data if present
            $.post("API.php",{comment:"GET",project_id:G_PROJECT_ID,solution_id:pre_id},function(data){
              if(data.success){
                var comments = data.comments;
                if(comments.length!=0){

                  var comment = comments[comments.length-1];
                  var comment_text = comment.comment;
                  if(comment.visibility==a_visibility){                      
                    $("#id-preliminary-summary-txt").val(comment_text);
                    disable_review_textarea_editing("#cl-preliminary-review-holder");
                  }
                  else if(comment.visibility==s_visibility) $("#id-preliminary-summary-txt").val(comment_text);
                }

              }
            },"json");
            $.post("API.php",{comment:"GET",project_id:G_PROJECT_ID,solution_id:full_id},function(data){
              if(data.success){

                var comments = data.comments;
                if(comments.length!=0){
                  var comment = comments[comments.length-1];
                  var comment_text = comment.comment;
                  if(comment.visibility==a_visibility){
                      $("#id-full-summary-txt").val(comment_text);
                      disable_review_textarea_editing("#cl-full-summary-holder");
                  }
                  else if(comment.visibility==s_visibility) $("#id-full-summary-txt").val(comment_text);
                }
              }
            },"json");
            
            $.post("API.php",{comment:"GET",project_id:G_PROJECT_ID,solution_id:cert_id},function(data){
              if(data.success){

                var comments = data.comments;
                if(comments.length!=0){
                  var comment = comments[comments.length-1];
                  var comment_text = comment.comment;
                  if(comment.visibility==a_visibility) {
                      $("#id-certification-summary-txt").val(comment_text); 
                      disable_review_textarea_editing("#cl-certification-summary-holder");
                  }
                  else if(comment.visibility==s_visibility) $("#id-certification-summary-txt").val(comment_text);
                }
              }
            },"json");


        },"json");
    } else {
        $(".cl-identifier-summary-btn-div").remove();
        $(".cl-feedback-text").css("background-color","#fafaf9cl");
        $(".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");
    }


});

$("#id-preliminary-summary-txt").on("click",function(){
    if(pre_review_allow_edit && G_IS_PROJECT_REVIEWER)
        $("#id-preliminary-summary-txt").attr("readonly",false);        
});
$("#id-full-summary-txt").on("click",function(){
    if(full_review_allow_edit && G_IS_PROJECT_REVIEWER)
        $("#id-full-summary-txt").attr("readonly",false);
});
$("#id-certification-summary-txt").on("click",function(){
    if(cert_review_allow_edit && G_IS_PROJECT_REVIEWER)
        $("#id-certification-summary-txt").attr("readonly",false);
});

$(".cl-full-review-plusminus-togglebtn").on("click",function(){
  $(".cl-feedback-text").addClass("hide");
  $(".cl-identifier-summary-btn-div").addClass("hide");
  if($(this).text()=="—"){
    $(this).html("+");
  }
  else{
    $(".cl-full-review-plusminus-togglebtn").text("+");
    $(this).html("—");
    $(this).parent().parent().find(".cl-feedback-text").removeClass("hide");
    $(this).parent().parent().find(".cl-identifier-summary-btn-div").removeClass("hide");
  }
});
// Review button handlers

$("#cmnt-file-upload-btn").on("click",function(){
  var target = "submitProject.php?pid=" + G_PROJECT_ID;
  var win = window.open(target,"_blank");
});
$(".cl-edit-final-summary-btn").on("click",function(){
  var parent_div = $(this).parent().parent();
  parent_div.find(".cl-feedback-text").attr("readonly", false);
});

$(".cl-send-final-summary-btn").on("click",function(){
  var parent_div = $(this).parent().parent();
  var letter_heading = parent_div.find(".cl-feedback-heading").text();
  var letter_desc = parent_div.find(".cl-feedback-text").val();
  var sol_id=get_sol_id(letter_heading);
  if(sol_id == full_id)
  {
    $.post("API.php",{project:"SUBMIT_DISCUSSION",project_id:G_PROJECT_ID},
    function (data) {
        if (data.success == true)
        {
          save_comment(sol_id, letter_desc, parent_div);
        }
        else
        {
          // console.log(data);
          var msg = data.message == "not_in_review_state" ? "Project not in expected review State" : "Please review all the solutions before submitting Review letter";
          show_review_status_popup(msg, data.review_status , sol_id);
        }
      },"json");
  }

  else if(sol_id == cert_id)
  {
    $.post("API.php",{project:"SUBMIT_COMPLETION",project_id:G_PROJECT_ID},
    function (data) {
        if (data.success == true)
        {
          save_comment(sol_id, letter_desc, parent_div);
        }
        else
        {
          // console.log(data);
          var msg = data.message == "not_in_review_state" ? "Project not in expected review State" : "Please review and accept all the solutions before submitting Review letter";
          show_review_status_popup(msg,data.review_status, sol_id);
        }
      },"json");
  }
  else
  {
    save_comment(sol_id, letter_desc, parent_div);
  }
});


var show_review_status_popup = function (msg, review_status, review_type){
  $("#id-review-status-msg").html(msg);
  var modal = $("#id-modal-review-status-popup");
  $(modal).modal('show');
  if(typeof review_status != "undefined")
    show_solutions(modal, review_status, review_type);
}

function show_solutions(modal, review_status, review_type )
{
  var list_control = $(modal).find("#id-ul-review-solution");
  list_control.empty();

  var color1="yellow";
  var color2= review_type == cert_id ? "red":"yellow";
  
  $.each( review_status, function(h1_key, h1_value)
    {
        if (typeof h1_value === 'object' )
        {
            $.each( h1_value, function(h2_key, h2_value)
            {
                if(typeof h2_value === 'object')
                {
                    $.each(h2_value, function(h3_key, h3_value)
                    {
                        $.each(h3_value, function(h4_key, h4_value)
                        {
                          var color="grey";
                          if(h4_key=="status")
                          {
                            var section = h1_key + "." + h2_key + "." +h3_key;
                            color = h4_value;                            
                          }
                          else
                          {
                            var section = h1_key + "." + h2_key + "." +h3_key + "."+h4_key;
                            color = h4_value.status;
                          }
                          if(color == color1 || color==color2)
                          {
                              // console.log(section);
                              list_control.append('<li>'+section+'</li>');
                          }
                        });                       
                    });
                }
            });
        }
    });
}

function save_comment(sol_id, letter_desc, parent_div)
{
  $.post("API.php",{comment:"SET",project_id:G_PROJECT_ID,solution_id:sol_id,text:letter_desc,visibility:a_visibility},
  function (data) {
      if (data.success == true)
      {
        show_splash_popup("Your input was sent","",2); // Popup to display the message
        disable_review_textarea_editing("#" + parent_div.attr('id'))
      }
    },"json");
}


$(".cl-save-final-summary-btn").on("click",function(){
  var parent_div = $(this).parent().parent();
  var letter_heading = parent_div.find(".cl-feedback-heading").text();
  var letter_desc = parent_div.find(".cl-feedback-text").val();
  var sol_id=get_sol_id(letter_heading);
  $.post("API.php",{comment:"SET",project_id:G_PROJECT_ID,solution_id:sol_id,text:letter_desc,visibility:s_visibility},
  function (data) {
      if (data.success == true)
      {
        show_splash_popup("Your input was saved","",2); // Popup to display the message
      }
    },"json");
});

function get_sol_id(letter_heading){
  var sol_id="";
  if(letter_heading.indexOf("Preliminary Review Letter")==0){
    sol_id=pre_id;
  }
  else if(letter_heading.indexOf("Full Review Letter")==0){
    sol_id=full_id;
  }
  else if(letter_heading.indexOf("Certification Letter")==0){
    sol_id=cert_id;
  }
  return sol_id;
}

function disable_review_textarea_editing(div){
    if(div === "#cl-preliminary-review-holder") pre_review_allow_edit = false;        
    else if(div === "#cl-full-summary-holder")  full_review_allow_edit = false;
    else if(div === "#cl-certification-summary-holder") cert_review_allow_edit = false;            
    $(div).find(".cl-identifier-summary-btn-div").remove();
    $(div).find(".cl-feedback-text").attr("readonly",true);
}


$("#id-btn-review-solutions").on("click",function()
{
  var target = "solutions_l.php?edit=true&id=" + G_PROJECT_ID;
  window.open(target,"_self");
});