
/// <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 upgradeMsg = "";
 
var HABITABLE_FLOOR_AREA_THRESHOLD = 100000;

// 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": "Ongoing"
}, {
	"value": "1",
	"text": "Completed"
},{
    "value": "2",
    "text": "In-Review"
},{
    "value": "3",
    "text": "Pending"
},
{
    "value": "4",
    "text": "Inactive"
}

];
// Cached List of the project used for sorting n all
var PROJECT_LIST = "";

var subscription_type = '';


///This is for etesting/

$(document).ready(function () {

    // if(userRole == 1 || userRole == 2){
    //     window.location.replace("projectAdminDashboard.php");
    // }
 
    // $("#id-nav-holder-right").css("border-bottom", "2px solid #555");
    $("img").unveil();
    $("img").trigger('unveil');
    /*replace the manage icon in the navigation bar to active manage icon.*/
    $("#id-img-navbar-p-manage").attr("src", "images/manageproject_icon_active.968ed1f7.png");

    loadingMsgContainer = $(".cl-section-loading-msg");
    loadingMsgSpan = $(".cl-span-loading-msg");
    OngoingContainer = $(".cl-div-ongoing-p-holder").find(".cl-div-p-item-holder");
    CompletedContainer = $(".cl-div-completed-p-holder").find(".cl-div-p-item-holder");
    PendingContainer = $(".cl-div-pending-p-holder").find(".cl-div-p-item-holder");
    PROJECT_DOM = $(OngoingContainer).find(".cl-div-project").clone();

    populate_filter_by_dropdown();
    populate_sort_by_dropdown();
    $.post("API.php",{project: "LIST"}, function(data){
        // default sorting mechanism
        PROJECT_LIST = data;
        // PROJECT_LIST = sortResults(PROJECT_LIST, 'project_title', true);
        //var pro_list = filter_list_equql(PROJECT_LIST,'project_submission_type','0');

        show_project_list(PROJECT_LIST);
    },"json");

    $('.cl-btn-notify-upgrade').click(function(ev){
            // if(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 account_user_id = '<?php echo $_SESSION["user"]->_id; ?>';
    // console.log(account_user_id);

    $("#id-btn-select-project").click(function(){
       
            var selectedProjectID = []; //$("input[name=select-project-name-radio]:checked").val();

            // var selected = [];
            
            $.each($("input[name='select-project-name-radio']:checked"), function(){
                selectedProjectID.push($(this).val());
            });
            // alert(selectedProjectID);
            // alert(JSON.stringify(selectedProjectID));

            $.post("API.php", { project: "SELECT_PROJECT", project_id: selectedProjectID, creating_user_id: account_user_id }, function (data) {
                
                if(data['response'] == true){
                   alert('Success');
                   location.reload();
                }
                else{
                    alert('Error. Please reload the page.');
                }
            
            }, 'json');

    });


    
    $.post("API.php", { dashboard: "SUBSCRIPTION_TYPE"}, function (data) {
        if(data.response){
            localStorage.setItem("subscription_type", data.subscription_type);
            console.log(data.subscription_type);
        }
    },"json");

});


var show_project_list = function(project_list)
{
    //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();

    $(OngoingContainer).empty();
    $(CompletedContainer).empty();
    $(PendingContainer).empty();
    // console.log('Printing project list');
    console.log(project_list);
    // console.log(project_list['0']['subscription_type']);
if(userRole == 3){

    $.post("API.php", { register: "GETUSER", username: account_user_email }, function (data) {
                // alert(JSON.stringify(data));
                if(data.length > 0){
                    userID = data[0]['_id'];
                    subscription_type = data[0]['subscription_type'];

                    // if(subscription_type == 'Supporter'){
                    //     var isExpired = new Date(data[0]['supporter_expiry_date']) < new Date();
                    //     var projectsLimit = 1;
                    //     upgradeMsg = 'Thank you for using isUD. You are limited to 1 project under the Supporter membership. If you would like to add another project, please upgrade your Membership. If you have any questions, please contact us at info@thisisud.com';
                    // }
                    // else if(subscription_type == 'free'){
                    //     var isExpired = new Date(data[0]['free_trial_expiry_date']) < new Date();
                    //     var projectsLimit = 1;
                    //     upgradeMsg = 'Thank you for using isUD. You are limited to 1 project under the Free Trial membership. If you would like to add another project, please upgrade your Membership. If you have any questions, please contact us at info@thisisud.com';
                    // }else if(subscription_type == 'Innovator'){
                        var isExpired = new Date(data[0]['innovator_expiry_date']) < new Date();
                        var projectsLimit = 5;
                        upgradeMsg = 'Thank you for using isUD. You are limited to 5 projects under the Innovator membership. If you would like to add another project or have questions, please contact us at info@thisisud.com';
                    // }
                    // else if(subscription_type == 'Collaborator'){
                    //     var isExpired = false;
                    //     var projectsLimit = 999;
                        // upgradeMsg = 'Thank you for using isUD. You are limited to 2 projects under the Innovator membership. If you would like to add another project or have questions, please contact us at info@thisisud.com';
                    // }

                    // if(isExpired){
                        // upgradeMsg = "Your "+data[0]['subscription_type']+" plan subscription expired. Please Renew / Upgrade.";
                    //     upgradeMsg = "Your 30 Day- "+data[0]['subscription_type']+" trial expired. Please contact us.";
                    //     show_upgrade_popup(upgradeMsg);
                    //     attachNewProjectEventListener($("#id-global-container"), false);
                    // }

                    var projectsCount = $(project_list).filter(function (i,n){return (n.isud_status==='0' && n.creating_user_id == account_user_id)});
                    // alert(projectsCount.length);
                    // alert(projectsLimit);

                    if(projectsCount.length > projectsLimit){

                        // upgradeMsg = "You have reached / exceeded your limit of "+ projectsLimit +" Projects. Please upgrade to Innovator Membership to add up to 2 projects, and receive additional projects.";
                        var modal = $("#select-modal");
                        var projectsContainer = $(modal).find("#id-project-titles-container");
                        $(modal).find('.cl-div-section-msg').append('<p>You have '+projectsCount.length+' active projects, but are limited to only '+projectsLimit+' on '+subscription_type+' Plan. Please select from below which you wish to retain or upgrade to higher plan.</p>');
                        var projectsList = $(projectsContainer).clone();
                        $(projectsContainer).empty();

                        $.each(project_list, function(index, elem){
                           
                            // alert(elem.isud_status);
                            // alert(elem.isud_status != 4 );
                            if(elem.isud_status != 4 && elem.isud_status != 1 ){
                                // alert('in if');
                                var clonedinput = $(projectsList).find("#id-select-project-form-inputs").clone();
                                var input = $(clonedinput).find("#id-select-project-input"); 
                                var label = $(clonedinput).find("#id-select-project-label"); 

                                $(input).attr("value", elem._id);
                                $(input).attr("id","id-select-project-input-"+elem._id);
                                $(label).attr("for","id-select-project-input-"+elem._id);
                                $(label).html(elem.project_title);

                                $(projectsContainer).append(clonedinput);
                            }else{

                            }

                        });

                        $(modal).modal('show');

                        $('input[type=checkbox]').on('change', function (e) {
                            if ($('input[type=checkbox]:checked').length > projectsLimit) {
                                $(this).prop('checked', false);
                                alert("Allowed only "+projectsLimit+".");
                            }
                        });

                        attachNewProjectEventListener($("#id-global-container"), false);
                    }else if(projectsCount.length == projectsLimit){
                        // upgradeMsg = "You have reached your limit of "+ projectsLimit +" Projects.";
                        attachNewProjectEventListener($("#id-global-container"), false);
                    }
                    else{
                        attachNewProjectEventListener($("#id-global-container"), true);
                    }
                }
            }, 'json');

}    
else{
    attachNewProjectEventListener($("#id-global-container"), true);
}

    $.each(project_list, function(index, elem){
        var projectTemplete = $(PROJECT_DOM).clone();

        var projectSlNo = $(projectTemplete).find(".cl-span-project-sl-no");
        var projectTitle = $(projectTemplete).find(".cl-span-project-title-text");
        var projectOwner = $(projectTemplete).find(".cl-span-project-owner");
        var projectStatus = $(projectTemplete).find(".cl-span-project-status");
        var projectAddress1 = $(projectTemplete).find(".cl-span-project-address1");
        var projectAddress2 = $(projectTemplete).find(".cl-span-project-address2");
        

        $(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);

        var statuses = ['Ongoing', 'Completed','In Pre-Certification Review','Pending', 'Inactive'];

        $(projectSlNo).html(elem.sl_pr_no);
        var po_href = "projectOverview.php?edit=true&id="+elem._id;
        var link = "<a href='"+po_href+"' style='color: #0b5592;'>"+elem.project_title+"</a>";
        $(projectTitle).html(link);        
        $(projectOwner).html(elem.project_owner);
        $(projectAddress1).html(elem.project_address_line_1);
        $(projectAddress2).html(elem.project_city+" "+elem.project_state+" "+elem.project_zipcode);
        $(projectStatus).html(statuses[elem.isud_status]);

        $(OngoingContainer).append(projectTemplete);

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

       
        UpdateRightContainer(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();
    
    if(!project_list || project_list.length <= 0){
        $("#id-buttons-span").hide();
    }
}


function attachNewProjectEventListener(projectElem, attach){
    var btn = $(projectElem).find(".cl-project-create-btn");
    
    if(!attach){
        console.log('in if');
        $(btn).css("cursor", "no-drop");
        // $(btn).prop("disabled",true);
        // alert('upgrade b4 click');
        $(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);
            }
            return false;
        });
    } else {
        console.log('in else');
        $(btn).css("cursor", "pointer");
        $(btn).click(function(ev){
            var target = "createProject.php";
            window.location.href = target;
        });
    }
}


// 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 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(){
    // $("#id-buttons-span").hide();
    // $("#id-header-new-project-btn").hide();
    // $("#id-buttons-span").css("display", "none");
    $(".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");
    // $(".cl-div-ongoing-p-holder").find(".cl-div-p-empty-holder").removeClass("hide");
}

function attachEventListeners(projectElem){
    attachEditEventListener(projectElem, true);
    attachProjectDocumentUploadEventListener(projectElem, true);
    attachDeleteEventListener(projectElem, true);
    attachSubmitEventListener(projectElem, false);
    attachUpdateEventListener(projectElem, true);
    attachOverviewBtnEventListener(projectElem, true);
    attachDetailsExpandEventListener(projectElem, true);
    attachRequirementExpandEventListener(projectElem, true);
}

function attachEditEventListener(projectElem, attach){
    var btn = $(projectElem).find(".cl-i-project-edit");
    if(!attach){
        $(btn).css("cursor", "no-drop");
        $(btn).click(function(ev){
            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;
        });
    }
}

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)
{
    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
    {
        $(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){
    var btn = $(projectElem).find(".cl-project-update-btn");
    if(!attach){
        $(btn).css("cursor", "no-drop");
        $(btn).click(function(ev){
            return false;
        });
    } else {
        $(btn).css("cursor", "pointer");
        $(btn).click(function(ev){
            //var target = "solutions_l.php?edit=true&id=" + $(this).attr("data-project-id");
            var target = "solutions_l.php?edit=true&id=" + $(this).attr("data-project-id");
            window.location.href = target;
        });
    }
}

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



function attachDetailsExpandEventListener(projectElem, attach){
    var btn = $(projectElem).find(".cl-img-project-details-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");

            if($(btn).hasClass("expanding")){
                $(btn).attr("src","images/minus.bf306561.png");
                $(btn).parent().parent().find(".cl-div-project-info-expanded-holder").find(".cl-div-project-info-item").css("max-height","100%");
                $(btn).parent().parent().find(".cl-div-project-info-expanded-holder").slideDown();
                $(btn).parent().parent().find(".cl-span-project-info-item-value-text").css("max-width","100%");
                $(btn).parent().parent().find(".cl-div-project-info-item").css("max-width","100%");
            } else {
                $(btn).attr("src","images/plus.221a06c8.png");
                $(btn).parent().parent().find(".cl-div-project-info-expanded-holder").slideUp();
                $(btn).parent().parent().find(".cl-div-project-info-expanded-holder").find(".cl-div-project-info-item").css("max-height","4em");
                $(btn).parent().parent().find(".cl-span-project-info-item-value-text").css("max-width","250px");
                $(btn).parent().parent().find(".cl-div-project-info-item").css("max-width","250px");
            }
        });
    }
}



function attachProjectDocumentUploadEventListener(projectElem, attach)
{
    var btn = $(projectElem).find(".cl-i-project-upload-doc");
    if(!attach)
    {
        $(btn).css("cursor", "no-drop");
        $(btn).click(function(ev){
            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 attachRequirementExpandEventListener( projectElem, attach){
    var btn = $(projectElem).find(".cl-img-project-requirement-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).filter("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().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.221a06c8.png");
                $(btn).parent().parent().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 updateProjectRequirementUI(projectElem, btn)
{
    var project_id = $(projectElem).attr("data-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)
            {
                attachSubmitEventListener(projectElem, true);
            }
        }
        else
        {
            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 UpdateLeftContainer =  function(projectTemplete,elem)
{
    var projectLeftContainer = $(projectTemplete).find(".cl-div-myproject-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 UpdateRightContainer = function (projectTemplete,elem)
{
    var projectRightContainer = $(projectTemplete).find(".cl-div-project-info-right");

    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 = $(projectAwardDetailsHolder).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 = '1.8em';
    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 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 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 append_to_list = function(list_control,display_str,check_str)
{
    if (check_str == "")
    {
        list_control.append('<li style="color:red">'+display_str+'</li>');
    }
    else
    {
        list_control.append('<li>'+display_str+'</li>');
    }
}

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");
    if(userRole == 1){
        FILTER_BY_JSON.unshift({
            "value": "4",
            "text": "Admin Projects"
        },{
            "value": "5",
            "text": "Other Projects"
        });
    }
    $.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 if(filter_val > 3)
    {
        PROJECT_LIST_FILTERED = filter_list_equql(PROJECT_LIST,'is_admin_project', filter_val );
    }
    else
    {
        PROJECT_LIST_FILTERED = filter_list_equql(PROJECT_LIST,'isud_status', 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){
    
    var modal = $("#id-modal-upgrade-membership-popup");
    $(modal).find("#id-team-pop-up-title").html("Add New Project");
    $(modal).find("#id-span-upgrade-message").html(msg);
    $(modal).modal('show');
}
