
/// <reference path="../../typings/jquery/jquery.d.ts"/>
//var pbar;
var OngoingContainer = null;
var CompletedContainer = null;
var PendingContainer = null;
var loadingMsgContainer = null;
var loadingMsgSpan = null;

var HABITABLE_FLOOR_AREA_THRESHOLD = 100000;
var statuses = ['Ongoing', 'Completed', 'InReview', 'Pending', 'Inactive'];

// string constant
HABITABLE_FLOOR_AREA_1 = "<50,000";
HABITABLE_FLOOR_AREA_2 = "50,000-100,000";
HABITABLE_FLOOR_AREA_3 = ">100,000";

// str parameters for constructing string messgaes
// these appears in parameterized string
STR_PARAM_PROJECT_SUBMISSION_TYPE = "%PROJECT_SUBMISSION_TYPE%";
STR_PARAM_PROJECT_SUBMISSION_TYPE_C = "%PROJECT_SUBMISSION_TYPE_C%";
STR_PARAM_EARNED_CREDITS = "%EARNED_CREDITS%";
STR_PARAM_PERCENTAGE = "%PERCENTAGE%";
STR_PARAM_BONUS_CREDITS = "%BONUS_CREDITS%";
STR_PARAM_APPLICABLE_SECTIONS ="%APPLICABLE_SECTIONS%";
STR_PARAM_MIN_AVAILABLE_CREDITS = "%MINIMUM_AVAILABLE_CREDITS%";
STR_PARAM_WITHOUT_WITH = "%WITHOUT_WITH%";

STR_PROJECT_SUBMISSION_TYPE_ISUD = "isUD Certification";
STR_PROJECT_SUBMISSION_TYPE_SELF = "self-assessment";
STR_PROJECT_SUBMISSION_TYPE_SELF_C = "Self-assessment"; // at the begining of the sentence
STR_AVAILABLE_CREDITS_SUCCESS_MSG = "You selected enough sections to qualify for %PROJECT_SUBMISSION_TYPE%.";
STR_EARNED_CREDITS_SUCCESS_MSG = "Based on your selected solutions, you earned %EARNED_CREDITS% credits. Your projected final score is %PERCENTAGE%%, which qualifies for %PROJECT_SUBMISSION_TYPE%.";
STR_REVIEW_CHECK_MSG = "*Pre-submission checklist results do not guarantee final %PROJECT_SUBMISSION_TYPE%.";

STR_EARNED_CREDITS_SUCCESS_WARN_MSG = "Based on the solutions selected, you earned %EARNED_CREDITS% credits and %BONUS_CREDITS% bonus credits. Your projected final score is %PERCENTAGE%%.";
STR_EARNED_CREDITS_SUCCESS_WARN_WARNING ="Although this is sufficient to qualify for %PROJECT_SUBMISSION_TYPE%, some sections did not earn any credit. To ensure a well-balanced design, please consider reviewing the sections below and implementing additional solutions.";

STR_EARNED_CREDITS_FAILURE_MSG = "This is insufficient to qualify for %PROJECT_SUBMISSION_TYPE%. This project requires a minimum score of  %APPLICABLE_SECTIONS%%. The sections listed below did not earn any credit. Please review these sections and implement additional solutions.";
STR_AVAILABLE_CREDITS_FAILURE_MSG= "Based on the sections marked “yes,” there are %APPLICABLE_SECTIONS% available credits in your project. This is insufficient to qualify for %PROJECT_SUBMISSION_TYPE%. A project %WITHOUT_WITH% a site requires a minimum of %MINIMUM_AVAILABLE_CREDITS% available credits. The sections listed below are currently marked “no.” Please review these sections to ensure all relevant sections are marked “yes” and the applicable solutions are selected.";
STR_PROJECT_TITLE = "A-Z";
STR_PROJECT_SCORE = "Score";

// Cached List of the project used for sorting n all
var PROJECT_LIST = ""; // returned from API
var PROJECT_LIST_FILTERED = "" // Filtered project list
var PROJECT_DOM; // storing project DOM structure so that we can clear containers and attach again

var SORT_BY_JSON = [ {
	"value": "project_title",
	"text": STR_PROJECT_TITLE
}, {
	"value": "award_percentage",
	"text": STR_PROJECT_SCORE
}];

var FILTER_BY_JSON = [ {
	"value": "0",
	"text": STR_PROJECT_SUBMISSION_TYPE_SELF_C
}, {
	"value": "1",
	"text": STR_PROJECT_SUBMISSION_TYPE_ISUD
}];
// Cached List of the project used for sorting n all
var PROJECT_DETAILS = "";


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";

//Subscription Related Data
var upgradeMsg = "";
var activeTeamSize = 0;
// 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 () {

    // if(userRole == 1 || userRole == 2){
    //     window.location.replace("projectAdminDashboard.php");
    // }

    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.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;

        // $('#id-btn-notify-upgrade').click(function(ev){
        //     var target = "profileMemberShipAfterReg.php";
        //     window.location.href = target;
        // });

        // $("#id-btn-notify-close").click(function(){
        //     $("#id-modal-upgrade-membership-popup").modal('hide');
        // });


        // $.post("API.php",{ projectTeam: "CHECK_SESSION_STATUS", project_id:G_PROJECT_ID}, function(data){
        //     if(data.length>4) {
        //         // alert(data);
        //     } else {
        //         $.post("API.php", { projectTeam: "UPDATE_SESSION_STATUS",project_id: G_PROJECT_ID, user_id:  userID, edit_status: 1}, function (data) {
        //             if(data.response == true){
        //                 console.log("Success setting to 1");
        //             }else{
        //                 console.log("Failure setting to 1");
        //                 console.log("hi" + data);
        //             }
        //           });
        //     }
        // });

        // function inactiveUserStatus() {
        //     document.body.classList.add('inactive');
        //     alert("You can edit");
        //     $.post("API.php", { projectTeam: "UPDATE_SESSION_STATUS",project_id: G_PROJECT_ID, user_id:  userID, edit_status: 0}, function (data) {
        //         alert("Inside inactiveUserStatus");
        //         if(data.response == true){
        //             component.alert("Success setting to 0");
        //         }else{
        //             component.alert("Failure setting to 0");
        //             console.log("hi" + data);
        //         }
        //       });
        //   }
          
          // function activeUserStatus() {
          //   document.body.classList.remove('inactive');
          //   alert("You cannot edit");
          //   $.post("API.php", { projectTeam: "UPDATE_SESSION_STATUS",project_id: G_PROJECT_ID, user_id:  userID, edit_status: 1}, function (data) {
                
          //       alert("Inside activeUserStatus");
          //       if(data.response == true){
          //           component.alert("Success setting to 1");
          //       }else{
          //           component.alert("Failure setting to 1");
          //           console.log("hi" + data);
          //       }
          //     });
          // }
    
        // const component = document.getElementById('containerFuild');
        // component.addEventListener('blur', inactiveUserStatus);
        // component.addEventListener('focus', activeUserStatus);
        
        // $(window).addEventListener('beforeunload', function () {
        //     // e.preventDefault();
        //     // e.returnValue = '';
        //     alert("Are you sure?");
        //     $.post("API.php", { projectTeam: "UPDATE_SESSION_STATUS",project_id: G_PROJECT_ID, user_id:  userID, edit_status: 0}, function (data) {
        //     if(data.response == true){
        //         console.log("Success");
        //     }else{
        //         console.log("Failure");
        //         console.log("hi" + data);
        //     }
        //   });
        // });
       console.log(G_PROJECT_ID);
        $.post("API.php",{project: "DETAILS", id:G_PROJECT_ID}, function(data){
        displayServiceCheckBox(data[0].service_type);
        displayRadioOption(data[0].certification_type)

        if(data){
            PROJECT_DETAILS = data[0];
            console.log(PROJECT_DETAILS);
            $('#project-status-id').html(statuses[PROJECT_DETAILS.isud_status]);
            $('#id-btn-notify-upgrade').click(function(ev){
                // if(PROJECT_DETAILS.subscription_type == 'free'){
                //     var target = "profileMemberShip.php";
                // }else{
                    var target = "profileMemberShipAfterReg.php";
                // }
                
                window.location.href = target;
            });

            $("#id-btn-notify-close").click(function(){
                $("#id-modal-upgrade-membership-popup").modal('hide');
            });

            var projTitle = $(".project-overview-container").find('.cl-span-site-title').html(' '+PROJECT_DETAILS.project_title);

            // alert(PROJECT_DETAILS.is_actively_editing);
            // if(PROJECT_DETAILS.supporter_expiry_date != null && new Date(PROJECT_DETAILS.supporter_expiry_date) < new Date()){
            //   $(".project-overview-container").find('#id-expiry-notification').html('Expired on '+PROJECT_DETAILS.supporter_expiry_date).show();
            // }
            // else if(PROJECT_DETAILS.innovator_expiry_date != null && new Date(PROJECT_DETAILS.innovator_expiry_date) < new Date()){
            //   $(".project-overview-container").find('#id-expiry-notification').html('Expired on '+PROJECT_DETAILS.innovator_expiry_date).show();
            // }
            // else if(PROJECT_DETAILS.free_trial_expiry_date != null && new Date(PROJECT_DETAILS.free_trial_expiry_date) < new Date()){
            //   $(".project-overview-container").find('#id-expiry-notification').html('Expired on '+PROJECT_DETAILS.free_trial_expiry_date).show();
            // }

            var projectOverviewTemplate = $(".projectOverview");

            $(projectOverviewTemplate).attr("id","id-"+PROJECT_DETAILS._id);
            $(projectOverviewTemplate).attr("data-project-id",PROJECT_DETAILS._id);
            $(projectOverviewTemplate).attr("project-isUD-status",PROJECT_DETAILS.isud_status);
            $(projectOverviewTemplate).attr("project-submission-type",PROJECT_DETAILS.project_submission_type);
            // $(projectOverviewTemplate).css("display","flex");
            $(projectOverviewTemplate).attr("demo_project",PROJECT_DETAILS.demo_project);
           

            var projectInfoTemplete = $(".projectInfoClass");
            var projectScoreTemplate = $(projectOverviewTemplate).find(".projectScoreClass");
            var projectReqTemplate = $(".projRequirementClass");
            var chapterProgressTemplate = $(".chapterSectionProgress");

            var projDate = PROJECT_DETAILS.project_a_end_date != null ? PROJECT_DETAILS.project_a_end_date : new Date();

            console.log(projDate)


            if(projDate && projDate != "0000-00-00"){

                var end = new Date(projDate);
                var start   = new Date();
                var diff  = new Date(end - start);
                var days  = diff/1000/60/60/24;
                var result = Math.ceil(days);
                // alert(result);
                var estDays = $(".estDate").find('#estdays').html(result+' Days');


                const d = new Date(projDate);
                const dtf = new Intl.DateTimeFormat('en-US', { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric' });
                const [{ value: day },,{ value: month },,{ value: date },,{ value: year }] = dtf.formatToParts(d) ;
                var estDate = `${day}, ${month} ${date} ${year}`;
                $(".estDate").find('#estdate').html(estDate);

            }

            else{
                $(".estDate").find('#estdate').html('Update Project End Date');
                $(".estDate").find('#estdays').html('Nan Days');
            }

            
            
            UpdateProjectInfoList(projectOverviewTemplate, PROJECT_DETAILS);

            UpdateRightContainer(projectOverviewTemplate, PROJECT_DETAILS);

            UpdateProjectButtons(projectOverviewTemplate, PROJECT_DETAILS);
            UpdateChapterProgressContainer(chapterProgressTemplate, PROJECT_DETAILS);
            UpdateDocumentStatus(projectOverviewTemplate);
            // $(projectOverviewTemplate).find(".documentStatus").find("id-modal-document").find("input[type=checkbox]").prop("checked", true);
           
            // console.log(PROJECT_DETAILS);
            
            

            if(PROJECT_DETAILS.project_permission_id){
              var authLevel =  PROJECT_DETAILS.project_permission_id
            }
            else{
              var authLevel =  1;
            }
            
            
            //update the project requirement UI. This is new UI update where we place project progress check indicators in top container
            var btn = $(projectOverviewTemplate).find(".cl-img-project-requirement-expand");

            var project_id = $(projectOverviewTemplate).attr("data-project-id");
            var project_submission_type = $(projectOverviewTemplate).attr("project-submission-type");
            var isud_status = $(projectOverviewTemplate).attr("project-isUD-status");

            //For enabling the submit project button
            $.post("API.php", {project: "PRE_CHECK_SUBMIT_REVIEW", project_id: project_id, submit_type: project_submission_type }, function(data)
            {
                if ( data.success )
                {
                    if(parseInt(isud_status,10) === 0)
                    {
                        attachSubmitEventListener(projectOverviewTemplate, true);
                    }
                }
                else
                {
                    attachSubmitEventListener(projectOverviewTemplate, false);
                }


            },"json");

            updateProjectRequirementUI(projectOverviewTemplate,btn);
            UpdateRecentMessages(projectOverviewTemplate);
            // UpdateProjectTeamList(projectOverviewTemplate, data); 

           $.post("API.php",{projectTeam:"LIST",project_id:G_PROJECT_ID},
               function (data) {
                   if (data)
                   {
                    //  var activeTeamSize = $(data).filter(function (i,n){return n.status==='1'});
                    //  if(activeTeamSize.length >= 3){
                    //     upgradeMsg = "Sorry, you are limited to 3 members per project. If you would like to add a dierent team member, you will have to remove an existing team member. If you would like additional members added to your project, please contact us at info@thisidud.com.";
                        
                    // }
                    
                     UpdateProjectTeamList(projectOverviewTemplate, data); 
                     
                   }
                   else{
                     alert("error in fetching team details.");
                   }
                  
                  attachEventListeners(projectOverviewTemplate, authLevel);
             },"json");
            
            ////////////////////////////////////////////////////////
            $(projectOverviewTemplate).find(".cl-comment-icon").css('visibility','visible');
            var sol_id_overview = "overview";
            //For Check Boxes in Project Phases
            // $(projectElem).find(".cl-i-project-compose").css("cursor", "pointer");
            
            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;
             }

             $("#id-see-all-cmnts").unbind().click(function(){
               var cm_modal_id="#id-sol-comments-modal";
               var attr = preprocess_comments_modal_buttons(cm_modal_id);
               
             });
            
             $("#id-cancel-cmnts").unbind().click(function(){
               var cm_modal_id="#id-sol-comments-modal";
               var attr = preprocess_comments_modal_buttons(cm_modal_id);
               var slider = $("#"+attr);
             });

             function validate_modal_comments(){
                 var comment = $("#solution-comments-text").val();
                 if(comment.trim().length==0)
                  return false;
                 return true;
             }
             $("#id-save-cmnts").hide();
             $("#id-close-cmnts").hide();

             $("#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);
                 var comment = $("#solution-comments-text").val();
                 // console.log("Comments:"+comment);
                 save_comment_indb(attr,comment);
             }
             });

             function enable_comment_icon(id){
               var p_div = $("#"+id).parent().parent();
               var c_icon_div = p_div.find(".cl-comment-icon");
               c_icon_div.css('visibility','visible');
             }

             $("#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");
               // console.log("Solution id:"+sol_id_overview);
               // Open a new popup showing send this comment or send all comments
               var popup_id="#popup-modal";
               $(popup_id).attr("data-target",attr);
               
               $("#id-popup-modal-title").html("Notification");
               $("#send-this-radio-btn").prop('checked', false);
               $("#send-all-radio-btn").prop('checked', false);
               $(popup_id).modal("show");
             });
             // Functions invoked by button on popup-modal
             $("#id-cancel-all-cmnts").unbind().click(function(){
               var cm_modal_id="#popup-modal";
               var attr = preprocess_comments_modal_buttons(cm_modal_id);
               $("#"+attr).prop("checked",false);
               // Exit out of solution comments box
             });

             $("#id-send-final-cmnts").unbind().click(function(){
               var cm_modal_id="#popup-modal";
               var attr = preprocess_comments_modal_buttons(cm_modal_id);

               var radio_value=$('input[name=comment-radio]:checked').val();
               // Send comments to project owner

             });

             $("#id-save-final-cmnts").unbind().click(function(){
               var cm_modal_id="#popup-modal";
               var attr = preprocess_comments_modal_buttons(cm_modal_id);
               save_comment_indb(attr);

               // enable_comment_icon(attr);
               // Save comments to project owner
             });
             // 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(sliderId,comment){
               
               $.post("API.php",{comment:"SET",project_id:G_PROJECT_ID,solution_id:sol_id_overview,text:comment,visibility:s_visibility},
               function (data) {
                   if (data.success == true)
                   {
                     show_splash_popup("Your input was saved","",2); // Popup to display the message
                   }
                 },"json");
             }

             $(".sol-comment-img").unbind().click(function(ev){
               ev.stopPropagation();
               $(".comment-checkbox").remove(); // this is utilized in full review page

               $.post("API.php",{comment:"GET",project_id:G_PROJECT_ID,solution_id:sol_id_overview},function(data){
                 if(data.success){
                   var parentElement=$("#comments-thread-div").empty();
                   var comments = data.comments;
                   var chat_thread="";
                   var rev_ele=$("#rev_comment_clone").clone();
                   var cli_ele=$("#cli_comment_clone").clone();
                   var clone;
                   
                   for(var i=0;i<comments.length;i++){
                       var comment = comments[i];
                       // console.log(comment);
                       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-txt-divCSS").html(comment.comment);
                       // console.log(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();
                   $(cm_modal_id).modal("show"); //Displaying solution comments modal
                   // $(cm_modal_id).attr("data-target",ms);
                   $(cm_modal_id).attr("sol_id",sol_id_overview);
                   $("#id-comment-header").html(""+" Project Inbox"); // Dynamically adding item number and title to the modal header
                   // $("#id-comment-solution").html(text); // Dynamically adding solution text to modal content
                   $(".modal-title").html("Inbox");
                 }
                 else{
                   show_splash_popup("Failed to get comments");
                 }
               },"json");

             });

             $("#send-this-radio-btn").off('click').on("click",function(){
               if($(this).prop("checked")=="false") return;
               var popup_id="#popup-modal";
               var comment = $("#solution-comments-text").val();
               // console.log("Send this radio button clicked for solution id: "+sol_id_overview);
               $.post("API.php",{comment:"SET",project_id:G_PROJECT_ID,solution_id:sol_id_overview,text:comment,visibility:a_visibility},
               function (data) {
                   if (data.success == true)
                   {
                     var cm_modal_id="#id-sol-comments-modal";
                     $(popup_id).modal("hide");
                     var attr = preprocess_comments_modal_buttons(cm_modal_id);
                     
                     show_splash_popup("Your input was sent","",2); // Popup to display the message
                   }
                 },"json");

             });


             $("#send-all-radio-btn").off('click').on("click",function(){
                if($(this).prop("checked")=="false") return;
                ///////////////////////
                var popup_id="#popup-modal";
                
                var comment = $("#solution-comments-text").val();
                // console.log("Send this radio button clicked for solution id: "+sol_id_overview);
                // $(popup_id).modal("hide");
 
                $.post("API.php",{comment:"SET",project_id:G_PROJECT_ID,solution_id:sol_id_overview,text:comment,visibility:a_visibility},
                function (data) {
                     if (data.success == true)
                     {
                            var cm_modal_id="#id-sol-comments-modal";
                            $(popup_id).modal("hide");
                            var attr = preprocess_comments_modal_buttons(cm_modal_id);
                     
                            show_splash_popup("Your input was sent","",2);
                     }
                  },"json");               
              });

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

            ///////////////////////////////////////////////////////////////
            phases = PROJECT_DETAILS.project_phase.split(";");
            $.each(phases, function(index, phase){
                        $("#id-project-phase-checkboxes").find("input[type=checkbox]").filter(function()
                        {
                            return this.value === phase;
                        }).prop('checked', true);
                });
            
            var phaseSavebtn = $(projectOverviewTemplate).find("#id-btn-project-phase-save");
            $(phaseSavebtn).css("cursor", "pointer");
            
            $(phaseSavebtn).click(function(){
                
                var projectPhase = "";

                $.each($(".form-check-input"), function(index, elem){
                        if( $(elem).prop("checked") ){
                            projectPhase += ";"+$(elem).val();
                        }
                });

                projectPhase = projectPhase.replace(/([;]+)/, ";").replace(/^;/, "").replace(/;$/, "");
                
                updateProjectPhase(projectPhase);
            });
            

            // $(".form-check-input").change(function(){
            //     var val = $(this).val();
            //     var parentHeaderElem = $(this).parent().parent().parent().find("span");
               
            //     var parentVal = $(parentHeaderElem).attr("data-checked-vals");
            //     parentVal = typeof parentVal === "undefined" ? "": parentVal;
            //     var parentValArr = parentVal === ""? [] : parentVal.split(",");
            //     if(parentValArr.includes(val)){
            //         parentValArr = parentValArr.filter(function(v){
            //             return (v !== val);                
            //         });
            //     }
    
            //     if($(this).prop("checked")){
            //         parentValArr.push(val);
            //     }
            
            //     $(parentHeaderElem).attr("data-checked-vals",parentValArr.toString());
            // });
        }
        else{

            alert('Please wait for the data to load. If it takes too long try again in a while.');
        }

        },"json");

    } else {
        alert("Direct acess not allowed.");
    }  

});

function displayServiceCheckBox(SelectedServices){
    if(SelectedServices){
        arrSelectedServices=SelectedServices.split(",")
        arrSelectedServices.pop()    
        // Display the checkboxItems where the value matches with fetched Services    
        arrSelectedServices.forEach(Service=>{
            // console.log("The Fetched Service:",Service)
            // console.log('corresponding elem',document.getElementsByClassName(Service)[0])
            // console.log('corresponding elem class Before',document.getElementsByClassName(Service)[0].style.display)
            document.getElementsByClassName(Service)[0].classList.remove('HideService')
            // console.log('corresponding elem class After',document.getElementsByClassName(Service)[0].style.display)
        })
    }
}

function displayRadioOption(SelectedCertifications){
    if(SelectedCertifications){
        arrSelectedCertification = SelectedCertifications.split(",")
        arrSelectedCertification.pop()    
        document.getElementsByClassName(arrSelectedCertification)[0].classList.remove('HideService')        
    }
}

var updateProjectPhase = function(phase)
{
     $.post("API.php", {project: "PHASE_UPDATE", id: G_PROJECT_ID, projectPhase: phase}, function(data){
        // console.log("Project Phase Details : " + data.success);
        alert('Successfully Saved.');
     },"json");
}

var UpdateChapterProgressContainer = function (projectChapterTemplete,elem)
{

    var h1_credits_earned = elem.h1_credits_earned.substr(0,elem.h1_credits_earned.length-1);
    var h1_credits_applicable = elem.h1_credits_applicable.substr(0,elem.h1_credits_applicable.length-1);
    var h1applicable = elem.h1_credits_applicable.split(",");
    var h1earned = elem.h1_credits_earned.split(",");
    // h1applicable.length
    for(var i=0;i<5;i++){

        
        var chapterContainer = $(projectChapterTemplete).find('.containChapters');
       
        var chapterProgressContainer = $(chapterContainer).find(".cl-div-project-award").clone(true);

        $(chapterContainer).append(chapterProgressContainer);

        $(chapterProgressContainer).attr("class",$(chapterProgressContainer).attr("class")+i);
        // console.log($(chapterContainer).attr("class"));
        // console.log($(chapterProgressContainer).attr("class"));
       
        var chapterProgressChart = $(chapterProgressContainer).find(".cl-div-project-award-progress-container");
       
        $(chapterProgressChart).attr("class",$(chapterProgressChart).attr("class")+i);

        $(chapterProgressChart).attr("id",$(chapterProgressChart).attr("id")+i);

        var chapterProgressTitle = $(chapterProgressContainer).find(".cl-div-project-award-progress-title");
       
        $(chapterProgressTitle).attr("class",$(chapterProgressTitle).attr("class")+i);

        $(chapterProgressTitle).attr("id",$(chapterProgressTitle).attr("id")+i);

        var titles = ['Design Process', 'Space Clearences', 'Circulation', 'Environmental Quality', 'Site'];

        $(chapterProgressTitle).html(titles[i]);

        var pbar = new ProgressBar.Circle("#"+chapterProgressChart.attr("id"), {
            color: '#F7941E',
            strokeWidth: 10,
            trailColor: '#f4f4f4',
            trailWidth: 10,
            outlineColor: '#444444',
            outlineWidth: 2,
            text: {
                autoStyleContainer: false
            }
        });

        pbar.setText("0%");
        pbar.set(0.0);
        pbar.text.style.fontSize = '0.7em';
        pbar.text.style.color = 'black';
        pbar.text.style.fontWeight = '1000';
        var percentage = (elem.earned_credits) * 100 / elem.applicable_credits;
        // alert(h1applicable[i]+"--"+h1earned[i]);
        var percentage = h1earned[i]*100/h1applicable[i];
        // alert(percentage+" %");
        
        var percentage_completion = Math.floor(parseFloat(percentage)); // + (parseInt(elem.bonus_credits,10) > 50 ? 10 : elem.bonus_credits/5));
        var chapText = h1earned[i] + "/" + h1applicable[i];
        pbar.setText(chapText);
        // pbar.setText(percentage_completion);
        percentage_completion = percentage_completion >100?100:percentage_completion;
        pbar.set(percentage_completion/100.0);

    }
    console.log(h1applicable);
    for(var i=5;i<h1applicable.length;i++){

       
        var chapterContainer = $(projectChapterTemplete).find('.containChapters2');
       

        var chapterProgressContainer = $(chapterContainer).find(".cl-div-project-award").clone(true);

        $(chapterContainer).append(chapterProgressContainer);

        $(chapterProgressContainer).attr("class",$(chapterProgressContainer).attr("class")+i);
        // console.log($(chapterContainer).attr("class"));
        // console.log($(chapterProgressContainer).attr("class"));
       
        var chapterProgressChart = $(chapterProgressContainer).find(".cl-div-project-award-progress-container");
       
        $(chapterProgressChart).attr("class",$(chapterProgressChart).attr("class")+i);

        $(chapterProgressChart).attr("id",$(chapterProgressChart).attr("id")+i);

        var chapterProgressTitle = $(chapterProgressContainer).find(".cl-div-project-award-progress-title");
       
        $(chapterProgressTitle).attr("class",$(chapterProgressTitle).attr("class")+i);

        $(chapterProgressTitle).attr("id",$(chapterProgressTitle).attr("id")+i);

        var titles = ['Rooms and Spaces','Furnishings and Equipment', 'Services', 'Policies'];

        $(chapterProgressTitle).html(titles[i-5]);

        var pbar = new ProgressBar.Circle("#"+chapterProgressChart.attr("id"), {
            color: '#F7941E',
            strokeWidth: 10,
            trailColor: '#f4f4f4',
            trailWidth: 10,
            outlineColor: '#444444',
            outlineWidth: 2,
            text: {
                autoStyleContainer: false
            }
        });

        pbar.setText("0%");
        pbar.set(0.0);
        pbar.text.style.fontSize = '0.7em';
        pbar.text.style.color = 'black';
        pbar.text.style.fontWeight = '1000';
        var percentage = (elem.earned_credits) * 100 / elem.applicable_credits;
        // alert(h1applicable[i]+"--"+h1earned[i]);
        var percentage = h1earned[i]*100/h1applicable[i];
        // alert(percentage+" %");
        
        var percentage_completion = Math.floor(parseFloat(percentage)); // + (parseInt(elem.bonus_credits,10) > 50 ? 10 : elem.bonus_credits/5));
        var chapText = h1earned[i] + "/" + h1applicable[i];
        pbar.setText(chapText);
        // pbar.setText(percentage_completion);
        percentage_completion = percentage_completion >100?100:percentage_completion;
        pbar.set(percentage_completion/100.0);

    }

    $(projectChapterTemplete).find('.containChapters').find(".cl-div-project-award").hide();
    $(projectChapterTemplete).find('.containChapters2').find(".cl-div-project-award").hide();


    // Fuction to hide an element on adminDashboard if the project is demo and has no progress
    // console.log("User role :"+userRole);
    // console.log("Project Title :"+elem.project_title);
    // console.log("Is Demo Project :"+elem.demo_project);
    // console.log("Score :"+percentage_completion);
    // if(userRole == 1){
    //     if(percentage_completion==0){
    //         $(projectTemplete).hide();
    //     }
    // }
}

var UpdateDocumentStatus = function(projectOverviewTemplate){

        $.post("API.php", {document: "GET_DETAILS", project_id: G_PROJECT_ID, document_id: -1}, function(document_info){
            console.log("Proj ID : ",G_PROJECT_ID);
            console.log(document_info);
            // $("#id-inp-document-file-rename").val(document_info.true_name);
            var document_types = [];
            $.each(document_info, function(i, doc){
                try{
                    console.log("Documents : ",doc.document_type);
                    var doc_type_list =  doc.document_type;
                    doc_type_list = doc_type_list.replace("document:","");
                    doc_type_list = doc_type_list.split(";");
                    document_types = document_types.concat(doc_type_list);
                    console.log(document_types);
                }
                catch(err){
                    // console.log(err);
                }
            })

            // console.log("Document types are : ",document_info['0'].document_type);
            // var document_types =  document_info['0'].document_type;
            // document_types = document_types.replace("document:","");
            // document_types = document_types.split(";");
            
            var finalDrawingsMandatory = ["Site Plan", "Building Plans", "Building Sections", "Building Elevations", "Details / Shop Drawings"]
            var result = finalDrawingsMandatory.every(val => document_types.includes(val));
            if(result){
              $("#final-drawings").find("#success").removeClass('hide');
              $("#final-drawings").find("#fail").addClass('hide');
            }

            $.each(document_types,function(index,document_type){
                console.log(document_type);

                // var matches = docStatus.querySelectorAll("div.note, div.alert");
                // document.getElementById("myLabel").htmlFor
                // var $element = $(this);
                // if ($element.val() == '') {
                //     var $label = $("label[for='"+this.id+"']")
                //     alert($label.text())    
                // }

                var elem = $(projectOverviewTemplate).find(".documentStatus").find("#id-document-status").find("label[for='"+document_type+"']");
                elem.find("#success").removeClass('hide');
                elem.find("#fail").addClass('hide');
                console.log(elem);

                // $(projectOverviewTemplate).find(".documentStatus").find("#id-document-status").find("label[for='"+document_type+"']").filter(function()
                // {
                //     return this.value === document_type;
                //     // if(this.for === document_type){
                //     // console.log('yes');
                //     // console.log(this.for);
                //     // }
                //     // return (this.for === document_type);
                // })
                // .css( "border", "3px double red" ); //input[type=checkbox]
            })
         },"json");

}

var UpdateRecentMessages = function(){

        $.post("API.php",{comment:"GET",project_id:G_PROJECT_ID, solution_id:"overview"},function(data){

                if(data.success && data.comments.length != 0){

                    var comments = data.comments;
                    var len = comments.length;
                    // console.log("printing lengt");
                    // console.log(len);
                    for(var i=len-1;i>len-6;i--){
                       var comment = comments[i];
                       // console.log(i);
                       if(comment){
                            var commentSpace = $(".recentMessages").find('#recentMessages').clone();
        
                             $(".recentMessages").find(".messagesDashContainer").append(commentSpace);
                             $(commentSpace).attr("id",$(commentSpace).attr("id")+i);
        
                            commentSpace.html(((len-1)-i+1)+ ". " +comment.comment);
                            // console.log(comment);
                        }

                    }

                    $(".recentMessages").find('#recentMessages').hide();


                }
                else{
                     $(".recentMessages").find('#recentMessages').html("Empty Inbox.");
                }
        },"json");
}


var UpdateProjectInfoList = function (projectTemplete,elem)
{


    
    var projectSummaryContainer = $(projectTemplete).find(".projectInfoClass").find(".cl-div-project-info-left");
    var list_control = $(projectSummaryContainer).find("#id-ul-unchecked-project-info-item");

  
    list_control.empty();
    
    var title = "<b>Title: </b>"+elem.project_title
    var address = "<b>Address: </b>"+elem.project_address_line_1;
    var city = "<b>City: </b>"+elem.project_city;
    var state = "<b>State: </b>"+elem.project_state;
    var country = "<b>Country: </b>"+elem.project_country;
    var zip = "<b>ZIP Code: </b>"+elem.project_zipcode;   
    var site_area = "<b>Site Area: </b>"+elem.site_area+ " acres";
    area_string = get_area_string(elem.habitable_floor_area);
    var building_area = "<b>Building Area: </b>"+elem.habitable_floor_area+" sq.ft.";
    // var building_type_string = elem.project_scope ==="0" ? "Building" : "Building and Site";
    // var project_scope = "<b>Project Scope: </b>"+building_type_string;

    // project_types = ["Entirely New Facility", "Addition to Existing Facility", "Alteration to Existing Facility", "Existing Facility As-Built", "Facility Registered as Historic"];
    // var building_type = "<b>Project Type: </b>"+project_types[elem.project_type+1];

    // Submission Type
    if ( parseInt(elem.project_submission_type,10) == 0 )
    {
        var project_submission_type = ""+STR_PROJECT_SUBMISSION_TYPE_SELF_C+"";
        $(".certification").find('#id-recognition-type').html(STR_PROJECT_SUBMISSION_TYPE_SELF_C);
    }
    else
    {
        var project_submission_type = ""+STR_PROJECT_SUBMISSION_TYPE_ISUD+"";
        $(".certification").find('#id-recognition-type').html(STR_PROJECT_SUBMISSION_TYPE_ISUD);
    }

    // var project_cost = "<b>Cost: </b> $"+elem.project_cost;


    var contact_person = "<b>Name : </b>"+elem.project_contact_person;
    var contact_email = "<b>Email: </b>"+elem.project_contact_email;
    var contact_telephone = "<b>Telephone: </b>"+elem.project_contact_telephone;
    var project_owner = "<b>Project Owner: </b>"+ elem.project_owner;
    var project_architect = "<b>Architect: </b>"+elem.project_architect;

    append_to_list(list_control,title,elem.project_title);
    append_to_list(list_control,address,elem.project_address_line_1);
    append_to_list(list_control,city,elem.project_city);
    append_to_list(list_control,state,elem.project_state);
    append_to_list(list_control,country,elem.project_country);
    append_to_list(list_control,zip,elem.project_zipcode);
    append_to_list(list_control,site_area,elem.site_area);
    append_to_list(list_control,building_area,area_string);
    // append_to_list(list_control,project_scope,building_type_string);
    // append_to_list(list_control,building_type,building_type_string);
    // append_to_list(list_control,project_cost,building_type);
   

    //for contact info in project overview page
    var projectContactContainer = $(projectTemplete).find(".projectContactInfoClass").find(".cl-div-project-info-left");
    var list_control_contactInfo = $(projectContactContainer).find("#id-ul-unchecked-project-info-item");

    list_control_contactInfo.empty();

    append_to_list(list_control_contactInfo,contact_person,elem.contact_person);
    append_to_list(list_control_contactInfo,contact_email,elem.contact_email);
    append_to_list(list_control_contactInfo,contact_telephone,elem.contact_telephone);
    append_to_list(list_control_contactInfo,project_owner,elem.project_owner);
    append_to_list(list_control_contactInfo,project_architect,elem.project_architect);

}


var UpdateProjectTeamList = function (projectTemplete,team_list)
{
    
    var projectTeamContainer = $(projectTemplete).find(".projectTeamMembers").find(".cl-div-project-info-left");
    var list_control = $(projectTeamContainer).find("#id-ul-unchecked-project-team-member-item");

    list_control.empty();
    
    $.each(team_list, function(index, elem){
        var name = ""+elem.name;
        var roles = ['Admin', 'Editor', 'Viewer'];
        var role = roles[parseInt(elem.project_permission_id) + 1];
        if(elem.status == 1){
          append_to_list(list_control,name, elem.name);
        }
    });
}


var UpdateRightContainer = function (projectTemplete,elem)
{
    var projectRightContainer = $(projectTemplete);

    var projectAwardDetailsHolder = $(projectRightContainer).find(".cl-div-project-award-details-holder");
    var projectEarnedCredits = $(projectAwardDetailsHolder).find(".cl-span-project-award-credit-earned");
    var projectApplicableCredits = $(projectAwardDetailsHolder).find(".cl-span-project-award-credit-applicable");
    var projectBonusCredits = $(projectAwardDetailsHolder).find(".cl-span-project-award-credit-bonus");
    
    var projectAwardChart = $(projectRightContainer).find(".cl-div-project-award-progress-container");

    projectEarnedCredits.html(elem.earned_credits);
    projectApplicableCredits.html(elem.applicable_credits);
    var bonus = parseInt(elem.bonus_credits,10);
    bonus = bonus > 50 ? 10 : Math.floor(bonus/5);
    projectBonusCredits.html(bonus);

    $(projectAwardChart).attr("id",$(projectAwardChart).attr("id")+elem._id);

    var pbar = new ProgressBar.Circle("#"+projectAwardChart.attr("id"), {
        color: '#F7941E',
        strokeWidth: 10,
        trailColor: '#f4f4f4',
        trailWidth: 10,
        outlineColor: '#444444',
        outlineWidth: 2,
        text: {
            autoStyleContainer: false
        }
    });
    pbar.setText("0%");
    pbar.set(0.0);
    pbar.text.style.fontSize = '2.1em';
    pbar.text.style.color = 'black';
    pbar.text.style.fontWeight = '700';
    var percentage_completion = Math.floor(parseFloat(elem.award_percentage)); // + (parseInt(elem.bonus_credits,10) > 50 ? 10 : elem.bonus_credits/5));
    //pbar.setText(percentage_completion+"%");
    pbar.setText(percentage_completion);
    percentage_completion = percentage_completion >100?100:percentage_completion;
    pbar.set(percentage_completion/100.0);
        // Fuction to hide an element on adminDashboard if the project is demo and has no progress
        // console.log("User role :"+userRole);
        // console.log("Project Title :"+elem.project_title);
        // console.log("Is Demo Project :"+elem.demo_project);
        // console.log("Score :"+percentage_completion);
        // if(userRole == 1){
        //     if(percentage_completion==0){
        //         $(projectTemplete).hide();
        //     }
        // }
}


var append_to_list = function(list_control,display_str,check_str)
{
    // alert('inside appnd func');
    // alert(display_str);
    if (check_str == "")
    {
        list_control.append('<li style="color:red">'+display_str+'</li>');
    }
    else
    {
        list_control.append('<li>'+display_str+'</li>');
    }
}


// var show_project_details = function(project_details)
// {
//     // alert('inside show');
//     // alert(JSON.stringify(PROJECT_DETAILS));
//     //var project = $(OngoingContainer).find(".cl-div-project").clone();

//     // hide the success and failure section of expanded project requirement section
//     // I added this to clear the corruption of icons while expanding sections
//     $(".cl-project-requirement-success").hide();
//     $(".cl-project-requirement-failure").hide();


//     $.each(project_list, function(index, elem){
//         var projectTemplete = $(PROJECT_DOM).clone();
//         var projectTitle = $(projectTemplete).find(".cl-span-project-title-text");

//         $(projectTemplete).attr("id","id-"+elem._id);
//         $(projectTemplete).attr("data-project-id",elem._id);
//         $(projectTemplete).attr("project-isUD-status",elem.isud_status);
//         $(projectTemplete).attr("project-submission-type",elem.project_submission_type);
//         $(projectTemplete).css("display","flex");
//         // type of the project for identifying the demo project
//         $(projectTemplete).attr("demo_project",elem.demo_project);
//         $(projectTitle).html(elem.project_title);

//         // Add project to the specific container
//         if(parseInt(elem.isud_status,10) === 0){
// 					 // Check if it is demo project
//             $(OngoingContainer).append(projectTemplete);
//         } else if(parseInt(elem.isud_status,10) === 1){
//             $(CompletedContainer).append(projectTemplete);
//             hide_unnecessary_controls(projectTemplete);
//         } else if(parseInt(elem.isud_status,10) === 2 || parseInt(elem.isud_status,10) === 3){
//             $(PendingContainer).append(projectTemplete);
//             hide_unnecessary_controls(projectTemplete);
//         }

//         UpdateProjectButtons(projectTemplete,elem);
//         // UpdateLeftContainer(projectTemplete,elem);
//         UpdateProjectInfoList(projectTemplete,elem);
//         UpdateRightContainer(projectTemplete,elem);
//         // UpdateExpandedSection(projectTemplete ,elem);
//         UpdateProjectSummaryBlock(projectTemplete,elem);

//         attachEventListeners(projectTemplete);

//         //update the project requirement UI. This is new UI update where we place project progress check indicators in top container
//         var btn = $(projectTemplete).find(".cl-img-project-requirement-expand");
//         updateProjectRequirementUI(projectTemplete,btn);
//     });
//     updateEmptyContainers();
// }

// sort the given project list on field prop in ascending=true order
function sortResults(project_list, prop, asc) {
    if(prop == "award_percentage")
        asc = false;

    var project_list;
    if(prop == "award_percentage")
    {
        project_list = project_list.sort(function(a, b) {
            int_a = parseInt(a[prop]);
            int_b = parseInt(b[prop]);
            if (asc) {
                return ( int_a > int_b ) ? 1 :((int_a < int_b) ? -1 : 0);
            } else {
                return (int_b > int_a) ? 1 : ((int_b < int_a) ? -1 : 0);
            }
        });
    }
    else
    {
        project_list = project_list.sort(function(a, b) {
            if (asc) {
                return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
            } else {
                return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
            }
        });
    }
    return project_list;
}

// filter out the passed list with given prop and value
function filter_list_equql(project_list,prop,val)
{
    var as=$(project_list).filter(function (i,n){return n[prop]===val});
    return as;
}

// Tab Switch logic - start
  $("#on-projects-title").click(function(){
    $("#pend-projects-title").removeClass('cl-div-p-holder-title');
    $("#comp-projects-title").removeClass('cl-div-p-holder-title');
    $("#pend-projects-title").addClass('cl-div-p-holder-title-inactive');
    $("#comp-projects-title").addClass('cl-div-p-holder-title-inactive');

    $("#on-projects-title-div").show();
    $("#pend-projects-title-div").hide();
    $("#comp-projects-title-div").hide();

    $(this).removeClass("cl-div-p-holder-title-inactive");
    $(this).addClass("cl-div-p-holder-title");
    $(this).css([])
  })

  $("#pend-projects-title").click(function(){
    $("#on-projects-title").removeClass('cl-div-p-holder-title');
    $("#comp-projects-title").removeClass('cl-div-p-holder-title');
    $("#on-projects-title").addClass('cl-div-p-holder-title-inactive');
    $("#comp-projects-title").addClass('cl-div-p-holder-title-inactive');

    $("#on-projects-title-div").hide();
    $("#pend-projects-title-div").show();
    $("#comp-projects-title-div").hide();

    $(this).removeClass("cl-div-p-holder-title-inactive");
    $(this).addClass("cl-div-p-holder-title");
  })

  $("#comp-projects-title").click(function(){
    $("#on-projects-title").removeClass('cl-div-p-holder-title');
    $("#pend-projects-title").removeClass('cl-div-p-holder-title');
    $("#on-projects-title").addClass('cl-div-p-holder-title-inactive');
    $("#pend-projects-title").addClass('cl-div-p-holder-title-inactive');

    $("#on-projects-title-div").hide();
    $("#pend-projects-title-div").hide();
    $("#comp-projects-title-div").show();

    $(this).removeClass("cl-div-p-holder-title-inactive");
    $(this).addClass("cl-div-p-holder-title");
  })
// Tab Switch login - end

var hide_unnecessary_controls = function(projectTemplete)
{
    var instruction_control = $(projectTemplete).find(".cl-span-project-submission-requirement-instruction");
    $(instruction_control).hide();

    var submit_button = $(projectTemplete).find(".cl-div-project-submit-button-holder");
    $(submit_button).hide();

    var edit_icon = $(projectTemplete).find(".cl-i-project-edit");
    $(edit_icon).hide();

    var edit_profile_button = $(projectTemplete).find(".cl-project-edit-btn");
    $(edit_profile_button).hide();

    var upload_doc_icon = $(projectTemplete).find(".cl-i-project-upload-doc");
    $(upload_doc_icon).hide();

    var delete_icon = $(projectTemplete).find(".cl-i-project-delete");
    $(delete_icon).hide();

    var large_area_message = $(projectTemplete).find("#id-large-habitable-area-notice");
    $(large_area_message).hide();

    var submit_button = $(projectTemplete).find(".cl-project-submit-btn");
    $(submit_button).val("Under Review");

    var edit_button = $(projectTemplete).find(".cl-project-update-btn");
    $(edit_button).val("View Solutions")

}

// Show empty div if no projects in container
function updateEmptyContainers(){
    $(".cl-div-pending-p-holder").find(".cl-div-p-empty-holder").css("display", $(PendingContainer).children().length <= 0 ? "flex" : "none");
    $(".cl-div-ongoing-p-holder").find(".cl-div-p-empty-holder").css("display", $(OngoingContainer).children().length <= 0 ? "flex" : "none");
    $(".cl-div-completed-p-holder").find(".cl-div-p-empty-holder").css("display", $(CompletedContainer).children().length <= 0 ? "flex" : "none");
}

function attachEventListeners(projectElem, roleid){
  //Expand actions. Common events.
    attachRequirementExpandEventListener(projectElem, true);
    attachDocUploadExpandListener(projectElem, true);
    attachAccordianListener(projectElem, true);

    if(userRole == 1 && PROJECT_DETAILS.isud_status != 4){
      //      alert('1st if');  
            attachEditEventListener(projectElem, true);
            attachProjectDocumentUploadEventListener(projectElem, true);
            attachGoInboxEventListener(projectElem, true);
            //attachSubmitEventListener(projectElem, false);
            attachUpdateEventListener(projectElem, true);
            if(activeTeamSize.length >= 3){
              attachEditTeamEventListener(projectElem, false, "", "Sorry, you are limited to 3 members per project.");
            }
            else{
              attachEditTeamEventListener(projectElem, true);
            }
    }

    else if(PROJECT_DETAILS.isud_status != 0){
        //alert('else if');  
          attachEditEventListener(projectElem, false,"", "You can't edit the project. This project is in "+statuses[PROJECT_DETAILS.isud_status]+" status.");
          attachProjectDocumentUploadEventListener(projectElem, false, "", "You can't edit the project. This project is in "+statuses[PROJECT_DETAILS.isud_status]+" status.");
          attachGoInboxEventListener(projectElem, false);
         // attachSubmitEventListener(projectElem, false);
          attachUpdateEventListener(projectElem, false, "You can't edit the project. This project is in "+statuses[PROJECT_DETAILS.isud_status]+" status.");
          attachEditTeamEventListener(projectElem, false,"", "You can't edit the project. This project is in "+statuses[PROJECT_DETAILS.isud_status]+" status.");
    } else{
        // if(PROJECT_DETAILS.subscription_type == "free"){ 
        //     if(new Date(PROJECT_DETAILS.free_trial_expiry_date) >= new Date()){
        //         // alert('Not expired');
        //         //var msg = "Upgrade to Innovator/Supporter Membership to {Upload Documents}{Add Team Members}";
        //         attachEditEventListener(projectElem, true);
        //         attachProjectDocumentUploadEventListener(projectElem, false, "", "Thank you for using isUD. Please upgrade to Innovator membership to upload project documents. If you have any questions, please contact us at info@thisisud.com");
        //         attachGoInboxEventListener(projectElem, true);
        //         attachSubmitEventListener(projectElem, false);
        //         attachUpdateEventListener(projectElem, true);
        //         attachEditTeamEventListener(projectElem, false, "", "Thank you for using isUD. Please upgrade to Innovator Membership to add up to 3 team member per project. If you would like to switch the primary member on your current project, please contact us at info@thisisud.com");
                
        //     }
        //     else if(new Date(PROJECT_DETAILS.free_trial_expiry_date) < new Date()){
        //         //alert('Expired');
        //       // alert('in else');
        //       // $(".project-overview-container").find('#id-expiry-notification').html('Expired on '+PROJECT_DETAILS.free_trial_expiry_date).show();
        //         var msg = "Thank your for using isUD. Your 30-day free trial has ended. Please upgrade to the Supporter or Innovator membership to continue working on your project. If you have any questions, please contact us at info@thisisud.com";
        //         attachEditEventListener(projectElem, true);
        //         attachProjectDocumentUploadEventListener(projectElem, false, "", msg);
        //         attachGoInboxEventListener(projectElem, true);
        //         attachSubmitEventListener(projectElem, false);
        //         attachUpdateEventListener(projectElem, false, msg);
        //         attachEditTeamEventListener(projectElem, false,"", "", msg);
        //     }
        // }


        // else if(PROJECT_DETAILS.subscription_type == "Supporter"){  
        //     if(new Date(PROJECT_DETAILS.supporter_expiry_date) >= new Date()){
        //        // alert('in if');
        //        // console.log('type '+PROJECT_DETAILS.subscription_type);
        //         attachEditEventListener(projectElem, true);
        //         attachProjectDocumentUploadEventListener(projectElem, true);
        //         attachGoInboxEventListener(projectElem, true);
        //         //attachSubmitEventListener(projectElem, false);
        //         attachUpdateEventListener(projectElem, true);
        //         attachEditTeamEventListener(projectElem, false,"", "Thank you for using isUD. You are limited to 1 team member per project. If you would like to add a team member, please upgrade your Membership. If you would like additional members added to your project, please contact us at info@thisisud.com");
                
        //     }
        //     else if(new Date(PROJECT_DETAILS.supporter_expiry_date) < new Date()){
        //       // alert('in else');
        //       // $(".project-overview-container").find('#id-expiry-notification').html('Expired on '+PROJECT_DETAILS.supporter_expiry_date).show();
        //         var msg = "Thank you for using isUD. Your Supporter membership has expired! To continue working on your project(s), please renew today."
        //         attachEditEventListener(projectElem, true);
        //         attachProjectDocumentUploadEventListener(projectElem, false,"", "Thank you for using isUD. Your Supporter membership has expired! To continue working on your project(s), please [upgrade/renew] today.");
        //         attachGoInboxEventListener(projectElem, false);
        //         //attachSubmitEventListener(projectElem, false);
        //         attachUpdateEventListener(projectElem, false, "Thank you for using isUD. Your Supporter membership has expired! To continue working on your project(s), please [upgrade/renew] today.");
        //         attachEditTeamEventListener(projectElem, false, "", msg);
        //     }
        // }

        // else if(PROJECT_DETAILS.subscription_type == "Innovator" || PROJECT_DETAILS.subscription_type == "Collaborator"){
           // alert('Innovator'); 
        //   if(new Date(PROJECT_DETAILS.innovator_expiry_date) >= new Date()){
             // alert('in if');
              // attachEditEventListener(projectElem, true);
              // attachProjectDocumentUploadEventListener(projectElem, true);
              // attachGoInboxEventListener(projectElem, true);
              // attachSubmitEventListener(projectElem, false);
              // attachUpdateEventListener(projectElem, true);
              // attachEditTeamEventListener(projectElem, true);
              if(roleid == 1){
                attachEditEventListener(projectElem, true);
                attachProjectDocumentUploadEventListener(projectElem, true);
                attachGoInboxEventListener(projectElem, true);
                //attachSubmitEventListener(projectElem, false);
                attachUpdateEventListener(projectElem, true);
                if(activeTeamSize.length >= 3){
                  attachEditTeamEventListener(projectElem, false, "", "Sorry, you are limited to 3 members per project. If you would like to add a different team member, you will have to remove an existing team member. If you would like additional members added to your project, please contact us at info@thisidud.com.");
                }
                else{
                  attachEditTeamEventListener(projectElem, true);
                }
                
              }else if(roleid == 2){
                attachEditEventListener(projectElem, true);
                attachProjectDocumentUploadEventListener(projectElem, true, "Project Permission");
                attachGoInboxEventListener(projectElem, true);
                // attachDeleteEventListener(projectElem, false);
                attachSubmitEventListener(projectElem, false);
                attachUpdateEventListener(projectElem, true);
                attachEditTeamEventListener(projectElem, false, "Project Permission", "Thank you for using isUD. Only Project Manager can Add or Edit team members. Please contact the Project Manager if you have any questions.");
              }else if(roleid == 3){
                var msg = "Thank you for using isUD. You are limited to View Only permission on this project. Please contact the Project Manager for if you need editing capabilities. ";
                attachEditEventListener(projectElem, false, "Project Permission", msg);
                attachProjectDocumentUploadEventListener(projectElem, false, "Project Permission", msg);
                attachGoInboxEventListener(projectElem, false);
                // attachDeleteEventListener(projectElem, false);
                attachSubmitEventListener(projectElem, false);
                attachUpdateEventListener(projectElem, true, msg);
                attachEditTeamEventListener(projectElem, false, "Project Permission", msg);
              }
              // alert(activeTeamSize.length);
              // alert(PROJECT_DETAILS.number_of_allowed_team_members);
              // if(activeTeamSize.length >= PROJECT_DETAILS.number_of_allowed_team_members){
              //     alert('true');
              //     attachEditTeamEventListener(projectElem, false);
              //     upgradeMsg = "Please contact isUD team to add additional team members. ";
              // }
        //   }
        //   else if(new Date(PROJECT_DETAILS.innovator_expiry_date) < new Date()){
        //     // alert('in else');
        //     // $(".project-overview-container").find('#id-expiry-notification').html('Expired on '+PROJECT_DETAILS.innovator_expiry_date).show();
        //       var msg = "Thank you for using isUD. Your Innovator membership has expired! To continue working on your project(s), please renew today."
        //       attachEditEventListener(projectElem, true);
        //       attachProjectDocumentUploadEventListener(projectElem, false,"", "Thank you for using isUD. Your Innovator membership has expired! To continue working on your project(s), please [upgrade/renew] today.");
        //       attachGoInboxEventListener(projectElem, false);
        //       attachSubmitEventListener(projectElem, false);
        //       attachUpdateEventListener(projectElem, false, "", "Thank you for using isUD. Your Innovator membership has expired! To continue working on your project(s), please [upgrade/renew] today.");
        //       attachEditTeamEventListener(projectElem, false, "", msg);
              
        //   }
        // }
        
    }
    // alert('last line');

}

function attachAccordianListener(projectElem, attach){

        var btn = $(projectElem).find(".cl-img-credits-earned-expand");

        if(!attach){
            $(btn).css("cursor", "no-drop");
            $(btn).click(function(ev){
                return false;
            });
        } else {
            $(btn).css("cursor", "pointer");
            $(btn).click(function(ev){
                $(btn).toggleClass("expanding");
                $(btn).children("i").toggleClass("fa-plus fa-minus");
                if($(btn).hasClass("expanding")){                
                    $(btn).parent().parent().find(".cl-div-credits-earned-expanded-holder").slideDown();
                } else {
                    $(btn).attr("src","images/plus.png");
                    $(btn).parent().parent().find(".cl-div-credits-earned-expanded-holder").slideUp();
                }
            });
        }
}

function attachDocUploadExpandListener(projectElem, attach){

    var btn = $(projectElem).find(".cl-doc-upload-expand");

    if(!attach){
        $(btn).css("cursor", "no-drop");
        $(btn).prop("disabled",true);
        $(btn).click(function(ev){
          
            return false;
        });
    } else {
        $(btn).css("cursor", "pointer");
        $(btn).click(function(ev){
            $(btn).toggleClass("expanding");
            $(btn).children("i").toggleClass("fa-plus fa-minus");
            if($(btn).hasClass("expanding")){                
                // $(btn).parent().parent().find(".cl-div-project-requirement-expanded-holder").find(".cl-div-project-requirement-item").css("max-height","100%");
                $(btn).parent().parent().find(".cl-div-doc-upload-expanded-holder").slideDown();
                // $(btn).parent().parent().find(".cl-div-project-requirement-available-credit-section").css("max-width","100%");
                // $(btn).parent().parent().find(".cl-div-project-requirement-item").css("max-width","100%");

            } else {
                $(btn).attr("src","images/plus.png");
                $(btn).parent().parent().find(".cl-div-doc-upload-expanded-holder").slideUp();
                // $(btn).parent().parent().find(".cl-div-project-requirement-expanded-holder").find(".cl-div-project-requirement-item").css("max-height","4em");
                // $(btn).parent().parent().find(".cl-div-project-requirement-available-credit-section").css("max-width","250px");
                // $(btn).parent().parent().find(".cl-div-project-requirement-item").css("max-width","250px");
            }
        });
    }

}



function attachRequirementExpandEventListener( projectElem, attach){
    var btn = $(projectElem).find(".cl-img-project-requirement-expand");
    if(!attach){
        $(btn).css("cursor", "no-drop");
        $(btn).prop("disabled",true);
        $(btn).click(function(ev){
            return false;
        });
    } else {
        $(btn).css("cursor", "pointer");
        $(btn).click(function(ev){
            $(btn).toggleClass("expanding");
            $(btn).children("i").toggleClass("fa-plus fa-minus");
            if($(btn).hasClass("expanding")){                
                // $(btn).parent().parent().find(".cl-div-project-requirement-expanded-holder").find(".cl-div-project-requirement-item").css("max-height","100%");
                $(btn).parent().parent().find(".cl-div-project-requirement-expanded-holder").slideDown();
                // $(btn).parent().parent().find(".cl-div-project-requirement-available-credit-section").css("max-width","100%");
                // $(btn).parent().parent().find(".cl-div-project-requirement-item").css("max-width","100%");
                updateProjectRequirementUI(projectElem, btn);


            } else {
                $(btn).attr("src","images/plus.png");
                $(btn).parent().parent().find(".cl-div-project-requirement-expanded-holder").slideUp();
                // $(btn).parent().parent().find(".cl-div-project-requirement-expanded-holder").find(".cl-div-project-requirement-item").css("max-height","4em");
                // $(btn).parent().parent().find(".cl-div-project-requirement-available-credit-section").css("max-width","250px");
                // $(btn).parent().parent().find(".cl-div-project-requirement-item").css("max-width","250px");
            }
        });
    }
}

function attachEditEventListener(projectElem, attach, title="", upgradeMsg=''){
    var btn = $(projectElem).find(".cl-project-edit-btn");
    var iconBtn = $(projectElem).find(".cl-i-project-edit");
    
    if(!attach){
        $(btn).css("cursor", "no-drop");
        // $(btn).prop("disabled",true);
        $(btn).css("background-color", "#555");
        $(btn).css("border", "1px solid #555");
        $(btn).css("opacity", ".65");
        $(btn).click(function(ev){
          if(upgradeMsg != ""){
              show_upgrade_popup(upgradeMsg, title);
            }
            return false;
        });
        $(iconBtn).css("cursor", "no-drop");
        $(iconBtn).prop("disabled",true);
        $(iconBtn).click(function(ev){
          if(upgradeMsg != ""){
              show_upgrade_popup(upgradeMsg,title);
            }
            return false;
        });
       
        
    } else {
        $(btn).css("cursor", "pointer");
        $(btn).click(function(ev){
            var target = "createProject.php?edit=true&p=" + $(this).attr("data-project-id");
            window.location.href = target;
        });
        $(iconBtn).css("cursor", "pointer");
        $(iconBtn).click(function(ev){
            var target = "createProject.php?edit=true&p=" + $(this).attr("data-project-id");
            window.location.href = target;
        });
       
    }
}

function attachEditTeamEventListener(projectElem, attach, title="", upgradeMessage=''){
    // alert('Entered');
    var projectTeamiconBtn = $(projectElem).find(".cl-i-project-team-edit");
    var projectTeamAddiconBtn = $(projectElem).find(".cl-i-project-team-add");
    if(!attach){
        console.log(upgradeMsg);
        $(projectTeamiconBtn).css("cursor", "no-drop");
        $(projectTeamiconBtn).prop("disabled",true);
        // alert('Before');
        // alert('Upgrade msg' +  upgradeMessage);
        $(projectTeamiconBtn).click(function(ev){
            // alert('Entered click');
            if(upgradeMessage != ""){
              show_upgrade_popup(upgradeMessage,title);
            }
            return false;
        });
        $(projectTeamAddiconBtn).css("cursor", "no-drop");
        $(projectTeamAddiconBtn).prop("disabled",true);
        $(projectTeamAddiconBtn).click(function(ev){
            if(upgradeMessage != ""){
              show_upgrade_popup(upgradeMessage,title);
            }
            return false;
        });
        
    } else {
    //    alert('Else');
        $(projectTeamiconBtn).css("cursor", "pointer");
        $(projectTeamiconBtn).click(function(ev){
            var target = "projectTeam.php?edit=true&id=" + $(this).attr("data-project-id");
            window.location.href = target;
        });
        $(projectTeamAddiconBtn).css("cursor", "pointer");
        $(projectTeamAddiconBtn).click(function(ev){
            var target = "projectTeam.php?edit=true&id=" + $(this).attr("data-project-id");
            window.location.href = target;
        });
    }
}

function attachGoInboxEventListener(projectElem, attach){
    var btn = $(projectElem).find(".cl-i-project-inbox");
    var composeBtn = $(projectElem).find(".cl-i-project-compose");
    if(!attach){
        $(btn).css("cursor", "no-drop");
        $(btn).click(function(ev){
            return false;
        });
    } else {
        $(btn).css("cursor", "pointer");
        $(composeBtn).css("cursor", "pointer");
        $(btn).click(function(ev){
            var target = "projectfullreview.php?edit=true&id=" + G_PROJECT_ID; //$(this).attr("data-project-id");
            window.location.href = target;
        });
    }
}


function attachDeleteEventListener(projectElem, attach){
    var btn = $(projectElem).find(".cl-i-project-delete");
    var is_demo_project = $(projectElem).attr("demo_project");

    // if attach is false or it is a demo project then Disable delete Button for the project
    if(!attach || is_demo_project === "1"){
        $(btn).css("cursor", "no-drop");
        $(btn).click(function(ev){
            return false;
        });
    } else {
        $(btn).css("cursor", "pointer");
        $(btn).click(function(ev){
            var clickedIcon = $(this);
            var modal = $("#id-modal-project-dashboard-delete-popup");
            $(modal).find("#id-btn-project-delete-yes").attr("project_id",$(this).attr("data-project-id"));
            $(modal).modal('show');
        });
    }

}

function attachSubmitEventListener(projectElem, attach)
{
    //alert('Entered');
    var btn = $(projectElem).find(".cl-project-submit-btn");
    if(!attach)
    {
        $(btn).css("cursor", "no-drop");
        $(btn).prop("disabled",true);
        
        if(btn[0]){
            btn[0].addEventListener("click", function(ev)
            {
                return false;
            }, {capture: true})
        };
    }
    else
    {
       // alert('Entered Else');
        $(btn).css("cursor", "pointer");
        $(btn).prop("disabled",false);
        btn[0].addEventListener("click", function(ev)
        {
            submit_project_button_clicked($(this).attr("data-project-id"));
            var applicableThreshold = parseInt($(this).attr("data-scope"), 10) == 0? 50 : 55;
            if (((parseFloat($(this).attr("data-perc")) < 60) && (parseInt($(this).attr("data-applicable"), 10) >= applicableThreshold)))
            {
                // alert("Project cannot be submitted because it doesn't meet the minimum threshold of completion.");
                 // $("#id-modal-project-submit-error").modal('show');
            }
            else
            {
                // launch_project_submit_dialog($(this).attr("data-project-id"));
            }
        }, {once: false});
    }
}

function attachUpdateEventListener(projectElem, attach,upgradeMsg=''){
    var btn = $(projectElem).find(".cl-project-update-btn");
    var ibtn = $(projectElem).find(".cl-project-solutions-update-btn");
    if(!attach){
        $(btn).css("cursor", "no-drop");
        $(btn).css("background-color", "#555");
        $(btn).css("border", "1px solid #555");
        $(btn).css("opacity", ".65");
        // $(btn).prop("disabled",true);
        $(btn).click(function(ev){
          if(upgradeMsg != ""){
              show_upgrade_popup(upgradeMsg);
            }
            return false;
        });

        $(ibtn).css("cursor", "no-drop");
        $(ibtn).prop("disabled",true);
        $(ibtn).click(function(ev){
          if(upgradeMsg != ""){
              show_upgrade_popup(upgradeMsg);
            }
            return false;
        });

    } else {
        $(btn).css("cursor", "pointer");
        $(btn).click(function(ev){
            var target = "solutions_l.php?edit=true&id=" + G_PROJECT_ID; //$(this).attr("data-project-id");
            window.location.href = target;
        });

        $(ibtn).css("cursor", "pointer");
        $(ibtn).click(function(ev){
            var target = "solutions_l.php?edit=true&id=" + G_PROJECT_ID;  //$(this).attr("data-project-id");
            window.location.href = target;
        });
    }
}



function attachProjectDocumentUploadEventListener(projectElem, attach, title="",upgradeMsg='')
{
    var btn = $(projectElem).find(".cl-i-project-upload-doc");
    if(!attach)
    {
        $(btn).css("cursor", "no-drop");
        $(btn).prop("disabled",true);
        $(btn).click(function(ev){
          if(upgradeMsg != ""){
              show_upgrade_popup(upgradeMsg, title);
            }
            return false;
        });
    }
    else
    {
        $(btn).css("cursor", "pointer");
        $(btn).click(function(ev)
        {
            var target = "submitProject.php?pid=" + $(this).attr("data-project-id");
            window.location.href = target;
        });
    }
}


function updateProjectRequirementUI(projectElem, btn)
{
    var project_id = $(projectElem).attr("data-project-id");
    //console.log('Project Id '+project_id);
    var isud_status = $(projectElem).attr("project-isUD-status");
    var project_submission_type = $(projectElem).attr("project-submission-type");
    project_submission_type = parseInt(project_submission_type,10) == 0 ? "self_certification" : "isUD_certification";
    $.post("API.php", {project: "PRE_CHECK_SUBMIT_REVIEW", project_id: project_id, submit_type: project_submission_type }, function(data)
    {
        // if ( data.success )
        // {
        //     if(parseInt(isud_status,10) === 0)
        //     {
        //         alert('True');
        //         attachSubmitEventListener(projectElem, true);
        //     }
        // }
        // else
        // {
        //     alert('False');
        //     attachSubmitEventListener(projectElem, false);
        // }

        UpdateAvailableCreditCheck(data.project_dict, data.status.available_credit_threshold_check, btn);

        UpdatePercentageCompletedCheck(data.project_dict, data.status, btn);

        UpdateRequiredSolutionsCheck(data.project_dict, data.status.required_solutions_check, btn);

        UpdateMinimumCreditCheck(data.project_dict, data.status.minimum_credit_check, btn);

        UpdateRequiredDocumentCheck(data.project_dict, data.status.required_doc_types_check, btn);

        updateReviewCheckMessage(data.project_dict,btn);

    },"json");

}

var UpdateProjectButtons= function (projectTemplete,elem)
{
    var projectEditIcon = $(projectTemplete).find(".cl-i-project-edit");
    var projectProfileEditButton = $(projectTemplete).find(".cl-project-edit-btn");
    var projectDocumentUploadIcon = $(projectTemplete).find(".cl-i-project-upload-doc");
    var projectDeleteIcon = $(projectTemplete).find(".cl-i-project-delete");
    var projectUpdateButton = $(projectTemplete).find(".cl-project-update-btn");
    var projectSubmitButton = $(projectTemplete).find(".cl-project-submit-btn");
    var projectTeamEditIcon = $(projectTemplete).find(".cl-i-project-team-edit");
    var projectTeamAddIcon = $(projectTemplete).find(".cl-i-project-team-add");

    $(projectUpdateButton).attr("data-project-id",elem._id);
    $(projectSubmitButton).attr("data-project-id",elem._id);
    $(projectEditIcon).attr("data-project-id",elem._id);
    $(projectProfileEditButton).attr("data-project-id",elem._id);
    $(projectDocumentUploadIcon).attr("data-project-id",elem._id);
    $(projectDeleteIcon).attr("data-project-id",elem._id);
    $(projectTeamEditIcon).attr("data-project-id",elem._id);
    $(projectTeamAddIcon).attr("data-project-id",elem._id);

    var percentage_completion = Math.floor(parseFloat(elem.award_percentage));
    projectSubmitButton.attr("data-perc", percentage_completion);
    projectSubmitButton.attr("data-applicable", elem.applicable_credits);
    projectSubmitButton.attr("data-scope", elem.project_scope);
}

var UpdateLeftContainer =  function(projectTemplete,elem)
{
    var projectLeftContainer = $(projectTemplete).find(".cl-div-project-info-left");
    var projectInfoItem = $(projectLeftContainer).find(".cl-div-project-info-item");
    $(projectLeftContainer).empty();

    //Project Number
    var projectInfoItemClone = $(projectInfoItem).clone();
    $(projectInfoItemClone).find(".cl-span-project-info-item-header-text").html("Number");
    $(projectInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.sl_pr_no);
    $(projectInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.sl_pr_no);
    $(projectLeftContainer).append(projectInfoItemClone);

    //Project Owner
    var projectInfoItemClone = $(projectInfoItem).clone();
    $(projectInfoItemClone).find(".cl-span-project-info-item-header-text").html("Owner");
    $(projectInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.project_owner);
    $(projectInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.project_owner);
    $(projectLeftContainer).append(projectInfoItemClone);

    //Architect
    var projectInfoItemClone = $(projectInfoItem).clone();
    $(projectInfoItemClone).find(".cl-span-project-info-item-header-text").html("Architect");
    $(projectInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.project_architect);
    $(projectInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.project_architect);
    $(projectLeftContainer).append(projectInfoItemClone);

    //Floor Area
    var projectInfoItemClone = $(projectInfoItem).clone();
    $(projectInfoItemClone).find(".cl-span-project-info-item-header-text").html("Floor Area");
    $(projectInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.habitable_floor_area);
    $(projectInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.habitable_floor_area);
    $(projectLeftContainer).append(projectInfoItemClone);

    //Site Area
    var projectInfoItemClone = $(projectInfoItem).clone();
    $(projectInfoItemClone).find(".cl-span-project-info-item-header-text").html("Site Area");
    $(projectInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.site_area);
    $(projectInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.site_area);
    $(projectLeftContainer).append(projectInfoItemClone);

    //Building Type
    var building_type_string = elem.building_type.replace(new RegExp(";{2,}","g"), "").replace(new RegExp(";","g"),",").replace(new RegExp("^,+","g"),"").replace(new RegExp(",+$","g"),"");
    var projectInfoItemClone = $(projectInfoItem).clone();
    $(projectInfoItemClone).find(".cl-span-project-info-item-header-text").html("Building Type");
    $(projectInfoItemClone).find(".cl-span-project-info-item-value-text").html(building_type_string);
    $(projectInfoItemClone).find(".cl-span-project-info-item-value-text").val(building_type_string);
    $(projectLeftContainer).append(projectInfoItemClone);
}

var UpdateExpandedSection = function (projectTemplete,elem)
{
    var projectExpandedTopContainer = $(projectTemplete).find(".cl-div-project-info-expanded-top");
    var projectExpandedInfoItem = $(projectExpandedTopContainer).find(".cl-div-project-info-item");
    $(projectExpandedTopContainer).empty();
    //Start Date
    var projectExpandedInfoItemClone = $(projectExpandedInfoItem).clone();
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-header-text").html("Start Date");
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.project_a_start_date);
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.project_a_start_date);
    $(projectExpandedTopContainer).append(projectExpandedInfoItemClone);

    //End Date
    var projectExpandedInfoItemClone = $(projectExpandedInfoItem).clone();
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-header-text").html("End Date");
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.project_a_end_date);
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.project_a_end_date);
    $(projectExpandedTopContainer).append(projectExpandedInfoItemClone);

    //Project Cost
    var projectExpandedInfoItemClone = $(projectExpandedInfoItem).clone();
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-header-text").html("Cost");
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.project_cost);
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.project_cost);
    $(projectExpandedTopContainer).append(projectExpandedInfoItemClone);

    //Primary Contact
    var projectExpandedInfoItemClone = $(projectExpandedInfoItem).clone();
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-header-text").html("Primary Contact");
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.project_contact_person);
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.project_contact_person);
    $(projectExpandedTopContainer).append(projectExpandedInfoItemClone);

    //Contact Email
    var projectExpandedInfoItemClone = $(projectExpandedInfoItem).clone();
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-header-text").html("Contact Email");
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.project_contact_email);
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.project_contact_email);
    $(projectExpandedTopContainer).append(projectExpandedInfoItemClone);

    //Telephone
    var projectExpandedInfoItemClone = $(projectExpandedInfoItem).clone();
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-header-text").html("Telephone");
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.project_contact_telephone);
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.project_contact_telephone);
    $(projectExpandedTopContainer).append(projectExpandedInfoItemClone);

    //Address
    var projectExpandedInfoItemClone = $(projectExpandedInfoItem).clone();
    var projectExpandedInfoItemSpanTextClone = $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").clone();
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-header-text").html("Address");
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.project_address_line_1);
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.project_address_line_1);
    if(elem.project_address_line_2){
        var newSpanLine = $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").clone();
        $(newSpanLine).val(elem.project_address_line_2);
        $(newSpanLine).html(elem.project_address_line_2);
        $(projectExpandedInfoItemClone).find(".cl-div-project-info-item-value").append(newSpanLine);
    }
    $(projectExpandedTopContainer).append(projectExpandedInfoItemClone);

    //// City
    var projectExpandedInfoItemClone = $(projectExpandedInfoItem).clone();
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-header-text").html("City");
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.project_city);
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.project_city);
    $(projectExpandedTopContainer).append(projectExpandedInfoItemClone);

    //// State
    var projectExpandedInfoItemClone = $(projectExpandedInfoItem).clone();
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-header-text").html("State");
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.project_state);
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.project_state);
    $(projectExpandedTopContainer).append(projectExpandedInfoItemClone);

    //// Country
    var projectExpandedInfoItemClone = $(projectExpandedInfoItem).clone();
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-header-text").html("Country");
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.project_country);
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.project_country);
    $(projectExpandedTopContainer).append(projectExpandedInfoItemClone);

    //// Zipcode
    var projectExpandedInfoItemClone = $(projectExpandedInfoItem).clone();
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-header-text").html("ZIP Code");
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").html(elem.project_zipcode);
    $(projectExpandedInfoItemClone).find(".cl-span-project-info-item-value-text").val(elem.project_zipcode);
    $(projectExpandedTopContainer).append(projectExpandedInfoItemClone);
}

var UpdateProjectSummaryBlock = function (projectTemplete,elem)
{
    var projectSummaryContainer = $(projectTemplete).find(".cl-div-project-summary-block");
    var list_control = $(projectSummaryContainer).find("#id-ul-unchecked-project-info-item");
    list_control.empty();

    var project_owner = "Project Owner: "+ elem.project_owner;
    var project_architect = "Architect: "+elem.project_architect;
    var contact_person = "Contact Person : "+elem.project_contact_person;
    var contact_email = "Contact Email: "+elem.project_contact_email;
    var contact_telephone = "Contact Telephone: "+elem.project_contact_telephone;
    var address = "Address: "+elem.project_address_line_1; /* + " " + elem.project_address_line_2; */
    var start_date = "Anticipated Start Date: "+elem.project_a_start_date;
    var end_date = "Anticipated End Date: "+elem.project_a_end_date;
    var building_type_string = elem.project_scope ==="0" ? "Building" : "Building and Site";
    var project_scope = "<b>Project Scope: </b>"+building_type_string;
    var site_area = "Site Area: "+elem.site_area+ " sq.ft.";
    var project_cost = "Estimated Project Cost: $"+project_cost;
    var city = "City: "+elem.project_city;
    var state = "State: "+elem.project_state;
    var country = "Country: "+elem.project_country;
    var zip = "ZIP Code: "+elem.project_zipcode;

    area_string = get_area_string(elem.habitable_floor_area);
    var building_area = "Building Area: "+area_string+" sq.ft.";

    // project certification cost
    var cost = elem.project_certification_cost;
    if(elem.project_certification_cost == "0")
    {
        cost = "TBD";
    }
    var project_certification_cost = "Estimated Cost: $"+cost;


    append_to_list(list_control,project_owner,elem.project_owner);
    append_to_list(list_control,project_architect,elem.project_architect);
    append_to_list(list_control,contact_person,elem.contact_person);
    append_to_list(list_control,contact_email,elem.contact_email);
    append_to_list(list_control,contact_telephone,elem.contact_telephone);
    append_to_list(list_control,start_date,elem.start_date);
    append_to_list(list_control,end_date,elem.end_date);
    append_to_list(list_control,project_certification_cost,elem.project_certification_cost);
    append_to_list(list_control,city,elem.project_city);
    append_to_list(list_control,state,elem.project_state);
    append_to_list(list_control,country,elem.project_country);
    append_to_list(list_control,zip,elem.project_zipcode);
    append_to_list(list_control,site_area,elem.elem.site_area);
    append_to_list(list_control,building_area,elem.habitable_floor_area);

    var large_area_notice = $(projectSummaryContainer).find("#id-large-habitable-area-notice");
    $(projectSummaryContainer).append(large_area_notice);
    // hide the notice if the area is less thann habitable 100000 sq feet
    var habitable_floor_area = parseInt(elem.habitable_floor_area,10);
    if (/*habitable_floor_area < HABITABLE_FLOOR_AREA_THRESHOLD || */ habitable_floor_area == -2
        || habitable_floor_area == -1 )
    {
        $(large_area_notice).hide();
    }
}

var UpdateAvailableCreditCheck = function (project, isSatisfied, btn)
{
    var success_block = $(btn).parent().parent().parent().parent().find(".cl-div-project-requirement-available-credit-section") .find(".cl-project-requirement-success");
    var failure_block = $(btn).parent().parent().parent().parent().find(".cl-div-project-requirement-available-credit-section") .find(".cl-project-requirement-failure");

    var project_submission_type = parseInt(project.project_submission_type,10) == 0 ? STR_PROJECT_SUBMISSION_TYPE_SELF : STR_PROJECT_SUBMISSION_TYPE_ISUD;
    var available_credits = project.applicable_credits;

    if( isSatisfied )
    {
        // hide failure div block
        $(success_block).show();
        $(failure_block).hide();
        var message = STR_AVAILABLE_CREDITS_SUCCESS_MSG.replace(STR_PARAM_PROJECT_SUBMISSION_TYPE,project_submission_type);
        $(success_block).find(".cl-header-note").text(message);
    }
    else
    {
        // show failure div block
        $(success_block).hide();
        $(failure_block).show();
        var is_type_building = project.project_scope == 0? true : false;
        var with_or_without = project.project_scope == 0? "without" : "with";
        var minimum_applicable_credits = project.project_scope == 0? 55 : 60;
        var applicable_credits = project.applicable_credits;

        var message = STR_AVAILABLE_CREDITS_FAILURE_MSG;
        message=message.replace(STR_PARAM_APPLICABLE_SECTIONS,available_credits);
        message=message.replace(STR_PARAM_PROJECT_SUBMISSION_TYPE,project_submission_type);
        message=message.replace(STR_PARAM_WITHOUT_WITH,with_or_without);
        message=message.replace(STR_PARAM_MIN_AVAILABLE_CREDITS,minimum_applicable_credits);

        $(failure_block).find(".cl-header-note").text(message);

        show_disabled_sections(project, failure_block);

        // no footer message this time, commenting out
        // message = "To qualify for "+project_submission_type+", you must review the applicable sections and ensure all are marked “yes”."
        // $(failure_block).find(".cl-footer-note").text(message);

        var target = "solutions_l.php?edit=true&id=" + project.project_id;
        $(failure_block).find("a").attr("href",target);
    }
}

var show_disabled_sections = function(project_dict, failure_block)
{
    // console.log(project_dict);
    var enabled_sections = project_dict.enabled_sections;
    var counter = 0;
    var list_control = $(failure_block).find("#id-ul-zero-credit-sections");
    list_control.empty();

    $.each( enabled_sections, function(h1_key, h1_value)
    {
        if (typeof h1_value === 'object' )
        {
            $.each( h1_value, function(h2_key, h2_value)
            {
                // console.log("\n ",h1_key," ",h2_key," : ",h2_value["enabled"]);
                if(isNaN(h2_key))
                {

                }
                else if ( h2_value["enabled"] === "0")
                {
                    var section = h1_key +"."+ h2_key
                    list_control.append('<li>'+section+'</li>')
                }
                else if(typeof h2_value === 'object') // if upper control is dsiabled, dont't look at the third level
                {
                    $.each(h2_value, function(h3_key, h3_value)
                    {
                        if (h3_key !== "enabled")
                        {
                            // console.log("\n ",h1_key," ",h2_key," : ",h3_key," : ",h3_value["enabled"]);
                            if (h3_value["enabled"] === "0")
                            {
                                var section = h1_key + "." + h2_key + "." +h3_key;
                                list_control.append('<li>'+section+'</li>');
                            }
                        }
                    });
                }
            });
        }
    });

    return counter == 0 ?true:false;
}

var UpdateRequiredSolutionsCheck = function (project, isSatisfied, btn)
{
    var success_block = $(btn).parent().parent().parent().parent().find(".cl-div-project-requirement-required-solutions-section") .find(".cl-project-requirement-success");
    var failure_block = $(btn).parent().parent().parent().parent().find(".cl-div-project-requirement-required-solutions-section") .find(".cl-project-requirement-failure");
    if( isSatisfied )
    {
        // hide failure div block
        $(success_block).show();
        $(failure_block).hide();
    }
    else
    {
        // hide failure div block
        $(success_block).hide();
        $(failure_block).show();
        show_unchecked_required_solutions(project,failure_block);
        var target = "solutions_l.php?edit=true&id=" + project.project_id;
        $(failure_block).find("a").attr("href",target);
    }
}

var show_unchecked_required_solutions = function (project_dict,failure_block)
{
    var required_solutions = project_dict.required_solutions;
    var counter = 0;
    var list_control = $(failure_block).find("#id-ul-unchecked-required-solutions");
    list_control.empty();
    $.each( required_solutions, function(h1_key, h1_value)
    {
        if(h1_key != "all_required_solutions_checked" && h1_key != "all_enabled_required_solutions_checked")
        {
            $.each( h1_value, function(h2_key, h2_value)
            {
                if(!isIterable(h2_value))
                {
                    return true;
                }

                $.each( h2_value, function(h3_key, h3_value)
                {
                    if ( h3_value.is_checked === false && project_dict[h1_key][h2_key].enabled == true )
                    {
                        // console.log(h1_key, " ", h2_key, " ", h3_key, " : ",h3_value);
                        var section = h1_key + "."+ h2_key;
                        list_control.append('<li>'+section+'</li>');
                        counter++;
                        return false;
                    }

                    $.each( h3_value, function(h4_key, h4_value)
                    {
                        // after adding level 3 toggle button please change the second condition in if to below
                        // project_dict[h1_key][h2_key][h3_key].enabled == true)
                        if ( h4_value.is_checked === false && project_dict[h1_key][h2_key][h3_key].enabled == true
                            && project_dict[h1_key][h2_key].enabled == true )
                        {
                            // console.log(h1_key, " ", h2_key, " ", h3_key," ",h4_key, " : ",h4_value);
                            var section = h1_key + "."+ h2_key+"."+h3_key;
                            list_control.append('<li>'+section+'</li>');
                            counter++;
                            return false;
                        }
                    });
                });
            });
        }
    });

    // console.log("unchecked required solutions counter is : ",counter);
    return counter == 0 ?true:false;
}

var UpdateMinimumCreditCheck = function (project, isSatisfied, btn)
{
    var success_block = $(btn).parent().parent().parent().parent().find(".cl-div-project-requirement-minimum-credit-section") .find(".cl-project-requirement-success");
    var failure_block = $(btn).parent().parent().parent().parent().find(".cl-div-project-requirement-minimum-credit-section") .find(".cl-project-requirement-failure");
    if( isSatisfied )
    {
        // hide failure div block
        $(success_block).show();
        $(failure_block).hide();
    }
    else
    {
        // hide failure div block
        $(success_block).hide();
        $(failure_block).show();
        show_sections_with_zero_credits_earned(project, failure_block);
        var target = "solutions_l.php?edit=true&id=" + project.project_id;
        $(failure_block).find("a").attr("href",target);
    }
}

var show_sections_with_zero_credits_earned = function(project_dict, failure_block)
{
    // console.log(project_dict);
    var enabled_sections = project_dict.minimum_credit_check;
    var counter = 0;
    var list_control = $(failure_block).find("#id-ul-zero-credit-sections");
    list_control.empty();
    $.each( enabled_sections, function(h1_key, h1_value)
    {
        if (typeof h1_value === 'object' )
        {
            $.each( h1_value, function(h2_key, h2_value)
            {
                if (!isNaN(h2_key) && h2_value == false )
                {
                    // console.log("\n ",h1_key," ",h2_key," : ",h2_value);
                    var section = h1_key +"."+ h2_key
                    list_control.append('<li>'+section+'</li>');
                    counter++
                }
            });
        }
    });

    // console.log("Section enabled but zero credit count # : ",counter);
    return counter == 0 ?true:false;
}

var UpdateRequiredDocumentCheck = function (project, isSatisfied, btn)
{
    var success_block = $(btn).parent().parent().parent().parent().find(".cl-div-project-requirement-required-documents-section").find(".cl-project-requirement-success");
    var failure_block = $(btn).parent().parent().parent().parent().find(".cl-div-project-requirement-required-documents-section").find(".cl-project-requirement-failure");
    if(project.project_submission_type == "0")
    {
        $(success_block).parent().parent().hide();
        $(failure_block).parent().parent().hide();
        return;
    }
    if( isSatisfied )
    {
        // hide failure div block
        $(success_block).show();
        $(failure_block).hide();
    }
    else
    {
        // hide failure div block
        $(success_block).hide();
        $(failure_block).show();
        show_unchecked_documents_types(project, failure_block);
        var target = "submitProject.php?pid=" + project.project_id;
        $(failure_block).find("a").attr("href",target);
    }
}

var show_unchecked_documents_types = function(project, failure_block)
{
    var required_doc_types = project.required_doc_types
    var list_control = $(failure_block).find("#id-ul-unchecked-required-documents");
    list_control.empty();
    $.each(required_doc_types,function(doc_type,doc_type_value)
    {
        if (doc_type !== "success" && doc_type_value == false )
        {
            list_control.append('<li>'+doc_type+'</li>');
        }
    })
}

var UpdatePercentageCompletedCheck = function (project, status, btn)
{
    var success_block = $(btn).parent().parent().parent().parent().find(".cl-div-project-requirement-completed-percentage-section") .find(".cl-project-requirement-success");
    var failure_block = $(btn).parent().parent().parent().parent().find(".cl-div-project-requirement-completed-percentage-section") .find(".cl-project-requirement-failure");

    var success_block_with_warn = success_block.find(".cl-project-requirement-success-warn")
    success_block_with_warn.hide();
    //isSatisfied flag
    isSatisfied = status.credit_threshold_check;

    // get the type of the submission
    var project_submission_type = parseInt(project.project_submission_type,10) == 0 ? STR_PROJECT_SUBMISSION_TYPE_SELF : STR_PROJECT_SUBMISSION_TYPE_ISUD;
    var percentage_completion = Math.floor(parseFloat(project.award_percentage));
    var earned_credits = project.earned_credits;
    var bonus_credits = get_bonus_credits(project.bonus_credits);

    var required_percentage_completion=project.total_enabled_sections;
    if( isSatisfied )
    {
        // hide failure div block
        $(success_block).show();
        $(failure_block).hide();

        // success without warning
        if(status.minimum_credit_check)
        {
            var message = STR_EARNED_CREDITS_SUCCESS_MSG.replace(STR_PARAM_EARNED_CREDITS,earned_credits);
            message = message.replace(STR_PARAM_PERCENTAGE,percentage_completion);
            message = message.replace(STR_PARAM_PROJECT_SUBMISSION_TYPE,project_submission_type);
        }

        // success with warning
        if (!status.minimum_credit_check)
        {
            var message = STR_EARNED_CREDITS_SUCCESS_WARN_MSG.replace(STR_PARAM_EARNED_CREDITS,earned_credits);
            message = message.replace(STR_PARAM_PERCENTAGE,percentage_completion);
            message = message.replace(STR_PARAM_BONUS_CREDITS,bonus_credits);

            // show the warning block with the list
            success_block_with_warn.show();

            // augment the success message with the warning
            var warning = STR_EARNED_CREDITS_SUCCESS_WARN_WARNING.replace(STR_PARAM_PROJECT_SUBMISSION_TYPE,project_submission_type);

            // poulate the list
            show_sections_with_zero_credits_earned(project, success_block);

            // add link to the anchor tag for edit solution
            var target = "solutions_l.php?edit=true&id=" + project.project_id;
            $(success_block).find("a").attr("href",target);
            $(success_block).find("#id-advisory-msg").text(warning);
        }

        $(success_block).find(".cl-header-note").text(message);
    }
    else
    {
        // show failure div block
        $(success_block).hide();
        $(failure_block).show();

        var message = STR_EARNED_CREDITS_SUCCESS_WARN_MSG + STR_EARNED_CREDITS_FAILURE_MSG;
        message = message.replace(STR_PARAM_EARNED_CREDITS,earned_credits);
        message = message.replace(STR_PARAM_PERCENTAGE,percentage_completion);
        message = message.replace(STR_PARAM_BONUS_CREDITS,bonus_credits);
        message = message.replace(STR_PARAM_PROJECT_SUBMISSION_TYPE,project_submission_type);
        message = message.replace(STR_PARAM_APPLICABLE_SECTIONS,required_percentage_completion);

        $(failure_block).find(".cl-header-note").text(message);

        show_sections_with_zero_credits_earned(project, failure_block);

        var target = "solutions_l.php?edit=true&id=" + project.project_id;
        $(failure_block).find("a").attr("href",target);
    }
}


var updateReviewCheckMessage = function (project,  btn)
{
    var block = $(btn).parent().parent().parent().parent().find(".cl-div-ReviewCheckMessage-section").find("#id-review-check-message");
    var project_submission_type = parseInt(project.project_submission_type,10) == 0 ? STR_PROJECT_SUBMISSION_TYPE_SELF : STR_PROJECT_SUBMISSION_TYPE_ISUD;

    var message = STR_REVIEW_CHECK_MSG.replace(STR_PARAM_PROJECT_SUBMISSION_TYPE,project_submission_type);
    // below check if for the capital letter at the start of the sentence
    if(project_submission_type == STR_PROJECT_SUBMISSION_TYPE_SELF)
    {
        message= message.replace(STR_PARAM_PROJECT_SUBMISSION_TYPE_C,STR_PROJECT_SUBMISSION_TYPE_SELF_C);
    }
    else
    {
        message= message.replace(STR_PARAM_PROJECT_SUBMISSION_TYPE_C,project_submission_type);
    }
    $(block).text(message);
}

$("#id-btn-project-delete-yes").click(function(){
    var project_id = $(this).attr("project_id");
    var project_to_remove = $(this).attr("project_to_remove");
    $.post("API.php", {project: "DELETE", id: project_id}, function(data){
        location.reload();
    },"json");
})

function get_area_string(habitable_floor_area)
{
    if (habitable_floor_area == "-3" )
    {
        area_string = HABITABLE_FLOOR_AREA_3;
    }
    else if (habitable_floor_area == "-2")
    {
        area_string = HABITABLE_FLOOR_AREA_2;
    }
    else
    {
        area_string = HABITABLE_FLOOR_AREA_1;
    }
    return area_string;
}

function isIterable(obj)
{
    // checks for null and undefined
    if (obj == null || typeof obj !== 'object' || Object.keys(obj).length == 0) {
      return false;
    }
    return true;
}

function get_bonus_credits(bonus_solutions_count)
{
    var bonus = parseInt(bonus_solutions_count,10);
    var bonus_credits = bonus > 50 ? 10 : Math.floor(bonus/5);
    return bonus_credits;
}

function populate_filter_by_dropdown ()
{
    var $dropdown = $("#id-filter-by");
    $.each(FILTER_BY_JSON, function() {
        $dropdown.append($("<option />").val(this.value).text(this.text));
    });
}

function populate_sort_by_dropdown ()
{
    var $dropdown = $("#id-sort-by");
    $.each(SORT_BY_JSON, function() {
        $dropdown.append($("<option />").val(this.value).text(this.text));
    });
}

$('#id-filter-by').on('change', function() {
    apply_filter_and_search();
    /*
    if(this.value=="all")
    {
        show_project_list(PROJECT_LIST);
    }
    else
    {
        var PROJECT_LIST_FILTERED = filter_list_equql(PROJECT_LIST,'project_submission_type', this.value );
        show_project_list(PROJECT_LIST_FILTERED);
    }
    */


    /*
    optimization : don't recreate elements
    // just show and hide them as and when required

   // console.log(" this.value ",this.value);
   projects = $(OngoingContainer).find(".cl-div-project");
   var val = $(projects[0]).attr("project-submission-type");
   // console.log(" project val is  ",val);
    $(projects).each(function(item) {
        var val = $(item).attr("project-submission-type");
        // console.log(" attribute val ",val);
        // console.log(" this.value ",this.value);
        if($(item).attr("project-submission-type") !== this.value) {
          $(item).hide();
        }
        else
        {
            $(item).show();
        }
    });
    */
  })

  $('#id-sort-by').on('change', function() {
    apply_filter_and_search();
  })

  function apply_filter_and_search()
  {
    var filter_val = $("#id-filter-by").val();
    if(filter_val=="all")
    {
        PROJECT_LIST_FILTERED = PROJECT_LIST;
    }
    else
    {
        PROJECT_LIST_FILTERED = filter_list_equql(PROJECT_LIST,'project_submission_type', filter_val );
    }

    var sort_val = $("#id-sort-by").val();
    PROJECT_LIST_FILTERED = sortResults(PROJECT_LIST_FILTERED, sort_val, true);
    show_project_list(PROJECT_LIST_FILTERED);
  }


var show_upgrade_popup = function (msg, title=""){
    var modal = $("#id-modal-upgrade-membership-popup");
    if(title==""){
        title="Upgrade Membership";
        $(modal).find("#id-btn-notify-upgrade").show();
    }else if(title=="Project Permission"){
        $(modal).find("#id-btn-notify-upgrade").hide();
    } 
    $(modal).find("#id-team-pop-up-title").html(title);
    $(modal).find("#id-span-upgrade-message").html(msg);
    $(modal).modal('show');
    
}
