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

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

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

var G_viewReviewerScore = false;
 

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_USER_AUTH_LEVEL = 0;
var G_IS_PROJECT_REVIEWER = false;
var G_PAGE_RELOAD = false;
// 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 d_visibility = "deleted";
var s_visibility = "self";
var a_visibility = "all";
var editMode = false;
var initialPopulationMode = true;
var params={};
var pbar;
var initialFetchChapterCount = 0;

var loadingMsgContainer = null;
var loadingMsgSpan = null;
var G_PROJECT_ID;
var G_checkbox_values={};
var G_solution_comment_status = [];

// isud project status
var UNDER_REVIEW = 2;
var UNDER_REVIEW_DISCUSSION = 3;
var INPROGRESS = 0;
var COMPLETED = 1;

String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}
if(!String.prototype.format) {
    String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number){
           return typeof args[number] != 'undefined'
            ? args[number]
            : match
         ;
        });
    };
}

$(document).ready(function () {
  load();
});
 
function load(){

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

    loadingMsgContainer = $(".cl-section-loading-msg");
    loadingMsgSpan = $(".cl-span-loading-msg");
    $(loadingMsgContainer).css("display","flex");
    hide_all_cl_divs();
    $("#available-sections-div").show();

    // 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;
        update_review_toggle_switch(params.id);

        $("#id-project-overview-bclink").attr("href", "projectOverview.php?edit=true&id="+G_PROJECT_ID);
        $("#id-project-overview-bclink").attr("pid", G_PROJECT_ID);

        $(".cl-div-chapter-sub-title").hide();
        $("#id-edit-solutions-utility-buttons").show();
        $(".cl-div-nav-image-holder-solution_l").css("display","flex");
        $(".cl-div-nav-project-award-details-holder").css("display","flex");
        $(".cl-div-nav-project-award-details-holder").css("max-width","100%");
        $(".cl-div-nav-project-award-details-holder").css("min-width","14.5%");
        $(".cl-div-nav-project-award-details-holder").css("height","80px");
        // $("#id-div-banner-site-banner").css("background", "-webkit-linear-gradient(left, #efefee 85%, #e8e8e8 19%)");
        //$(".cl-div-nav-image-holder").css("width","300px");
        $(".icon-holder").css("max-width","27%");

        // $("#id-div-site-navigation").css("background","-webkit-linear-gradient(left,#efefee,#efefee 65%,#e8e8e8 0,#e8e8e8)");
        $(".cl-form-solution-checkbox").show();
        $(".cl-div-hx-item-title-edit-status").show();
        $(".cl-div-chapter-credit-implemented-ratio-holder").show();
        $(".cl-div-hx-footer").show();
        fillGlobalDataFromDB(params.id);
        var container = $("#id-global-container");
        attachEventListeners(container);
        // Hide Browse button in edit mode
        // $("#id-img-navbar-p-browse").parent().css("display","none");
        $(".cl-div-site-breadcrumb").addClass("hide");
    } else {
        $("#id-project-overview-bclink").hide();
        $("#id-browse-solutions-txt").html(' > Browse Solutions');
        $("#id-edit-solutions-utility-buttons").hide();
        $(".cl-div-chapter-sub-title").show();
        $(".cl-div-nav-image-holder-solution_l").css("display","none");
        $(".cl-div-nav-project-award-details-holder").css("display","none");
        $(".cl-form-solution-checkbox").hide();
        $(".cl-div-hx-item-title-edit-status").hide();
        $(".cl-div-chapter-credit-implemented-ratio-holder").hide();
        $("#id-div-chapter-content-top-info").hide();
        $(".cl-div-hx-footer").hide();
        $(".cl-div-nav-image-holder-solution_l").addClass("hide");
        $(".cl-div-nav-project-award-details-holder").addClass("hide");
        // Removing reviewers elements
        $(".review-div").remove();
        $("#project-feedback-btn").remove();
        // Hide submit button in non-edit(browse solution) mode
        // $("#id-img-navbar-p-submit").parent().css("display","none");
        $("#cl-checklist-wrapper").remove();
        getChapters();
    }

    // $(".cl-div-selection-switch-holder").on("click",function(){
    //     return false;
    // });

    ///////////////////////////////////
    if(!G_PAGE_RELOAD){
        pbar = new ProgressBar.Circle('#id-div-project-award-progress-container', {
            color: '#F7941E',
            strokeWidth: 10,
            trailColor: '#e6e7e8',
            trailWidth: 10,
            text: {
                autoStyleContainer: false
            }
        });
        pbar.setText("0");
        pbar.set(0.0);
        pbar.text.style.fontSize = '1.2em';
        pbar.text.style.color = 'black';
        pbar.text.style.fontWeight = '600';
    }

    $(".cl-span-site-breadcrumb-title").html("Solutions");
    var solutionLandingPane = $("#id-pane-solution-landing");
    var solutionPane = $("#id-pane-solution");

    if (!global_columns_goals || global_columns_goals.length == 0) {
        $.post("API.php", { columns: "GOALS" }, function (data) {
            $.each(data, function (index, elem){
                global_columns_goals.push({name : elem, selected : true});
            });
        },"json");
    }

    if (!global_columns_phases || global_columns_phases.length == 0) {
        $.post("API.php", { columns: "PHASES" }, function (data) {
            $.each(data, function (index, elem){
                global_columns_phases.push({name : elem, selected : true});
            });
        },"json");
    }
}

function update_review_toggle_switch(project_id){
  $.post("API.php",{Review_checkbox_value:"GET_ALL",project_id:project_id},function(data){
    G_checkbox_values = data.review_checkbox_values;

    // console.log("data",data);
    // console.log("data 3:",data.review_checkbox_values);
    // process_review_cb_values(data);
  },"json");
}
function process_review_cb_values(data){

    var rb_values=data.review_checkbox_values;
    var sol_id;
    var value;
    for(var key in rb_values){
      sol_id=key;
      value=rb_values[key];

      set_rb_toggle_value(sol_id,value);
    }
}
function set_rb_toggle_value(sol_id,value,parentElement){
  // reference='id-div-h2-solution-item-1-1-1';
  if(sol_id.length>3){

    sol_id = sol_id.replace(/\./g, '-');
    var p_id = 'id-div-h2-solution-item-'+sol_id;
    // console.log("Parent Id :"+p_id);
    var p_elem = parentElement.find("#"+p_id);
    // console.log("p_elem : ",p_elem);
    var cs_parent = p_elem.find('.candlestick-bg');
    if(value==1)
      set_rb_negative(cs_parent);
  }
}
function set_rb_negative(parent){

  var toggle = parent.find(".candlestick-toggle");
  var on = parent.find(".candlestick-on");
  on.find(".fa").removeClass("fa-check");
  toggle.addClass("cs-toggle-off");
  parent.addClass("cs-off");
}
function set_rb_positive(parent){
  var toggle = parent.find(".candlestick-toggle");
  var off = parent.find(".candlestick-off");
  off.find(".fa").removeClass("fa-times");
  toggle.addClass("cs-toggle-on");
  parent.addClass("cs-on");
}
function hideSideBar(){
  $('.sidebarCSS').height('0');
  $("#empty-div").hide();
}
$('#rcl-button').click(function(){
  var bar_height = $('.sidebarCSS').height();
  if(bar_height!=0){ // To toggle
    hideSideBar();
    return;
  }
  $('.sidebarCSS').height('200px');
  $("#empty-div").show();
  $.post("API.php", {project: "DETAILS", id:params.id}, function(data)
  {
      var d =data[0];
      updateProjectRequirementUI(params.id,d.isud_status,d.project_submission_type);

  },"json");

  $('#sol-link').hide();
  $([document.documentElement, document.body]).animate({
    scrollTop: $(".sidebarCSS").offset().top
}, 2000);
})
$('#cl-checklist').click(function(){
  hideSideBar();
})

$('.checklist-btn').click(function(event){
  var id = event.target.id;
  hide_all_cl_divs();
  enable_all_cl_btns();
  var div_id = id.replace('btn','div');
  $('#'+div_id).show();
  $(this).prop('disabled', true);
})
function enable_all_cl_btns(){
  $("#available-sections-btn").prop('disabled', false);
  $("#earned-credit-btn").prop('disabled', false);
  $("#required-solutions-btn").prop('disabled', false);
  $("#required-documents-btn").prop('disabled', false);
  $("#in-review-checklist-btn").prop('disabled', false);
}
function hide_all_cl_divs(){
  $("#available-sections-div").hide();
  $("#earned-credit-div").hide();
  $("#required-solutions-div").hide();
  $("#required-documents-div").hide();
  $("#in-review-checklist-div").hide();
}


function updateProjectRequirementUI(project_id,isud_status,project_submission_type)
{
    // console.log('Updating project requirement ui ');
    // console.log("Project submission type :"+isud_status);
    if(project_submission_type == 1){
      // console.log('Inside If');
      $("#required-documents-btn").show();
    }
    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)
    {
        var btn =$("#checklist-div");
        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);

        UpdateInReviewChecklist(data.project_dict, btn);


    },"json");

}

var UpdateAvailableCreditCheck = function (project, isSatisfied, btn)
{
    var success_block = $(btn).find(".cl-div-project-requirement-available-credit-section") .find(".cl-project-requirement-success");
    var failure_block = $(btn).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 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).find(".cl-div-project-requirement-required-solutions-section") .find(".cl-project-requirement-success");
    var failure_block = $(btn).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 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).find(".cl-div-project-requirement-minimum-credit-section") .find(".cl-project-requirement-success");
    var failure_block = $(btn).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 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).find(".cl-div-project-requirement-required-documents-section").find(".cl-project-requirement-success");
    var failure_block = $(btn).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).find(".cl-div-project-requirement-completed-percentage-section") .find(".cl-project-requirement-success");
    var failure_block = $(btn).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 solutions
            $(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 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).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);
}
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 isIterable(obj)
{
    // checks for null and undefined
    if (obj == null || Object.keys(obj).length == 0) {
      return false;
    }
    return true;
}



function getChapters(){
    $(loadingMsgSpan).html("Loading chapter outlines");
    $.post("API.php", { chapter: -1 }, function (data) {
        var chapterListHolder = $("#id-div-solution-chapter-holder");
        var elem = $("#id-div-solution-chapter-list-item");
        //chapterListHolder.html('');
        $.each(data, function (index, e) {
            var newElem = elem.clone();
            e = e.header;
            id = newElem.attr("id") + "-" + e.h1.toString();
            newElem.attr("id", id);

            var chapterNo = newElem.find(".cl-div-chapter-number");
            chapterNo.html(e.h1.toString());

            var chapterTitle = newElem.find(".cl-div-chapter-title");
            chapterTitle.html(e.h1_title.toString());

            var chapterSubtitle = newElem.find(".cl-div-chapter-sub-title");
            chapterSubtitle.html(e.h1_points.toString()+" Credits");

            var chapterCreditRatioHolder = newElem.find(".cl-div-chapter-credit-implemented-ratio-holder");
            var chapterCreditRatioTotal = $(chapterCreditRatioHolder).find(".cl-div-ratio-rounded-elem-right span");
            var chapterCreditRatioEarned = $(chapterCreditRatioHolder).find(".cl-div-ratio-rounded-elem-left span");

            id = chapterCreditRatioHolder.attr("id") + e.h1.toString();
            chapterCreditRatioHolder.attr("id",id);

            newElem.on("click", getSolutionsForChapter);
            chapterListHolder.append(newElem);

            if(!editMode && typeof creditDict[index] === "undefined"){
                var creditH1Dict = {};
                creditH1Dict.earned_credits = 0;
                creditH1Dict.total_credits = parseInt(e.h1_points,10);
                creditH1Dict.applicable_credits = parseInt(e.h1_points,10);
                creditH1Dict.solutions_bonus = parseInt(0,10);
                creditDict[index] = creditH1Dict;
            } else if(editMode){
                creditDict[index].total_credits = parseInt(e.h1_points,10);
                creditDict[index].solutions_bonus = parseInt(0,10);
            }

            chapterCreditRatioTotal.html("of "+creditDict[index].applicable_credits);
            chapterCreditRatioEarned.html(creditDict[index].earned_credits);
        });
        if(!G_PAGE_RELOAD) chapterListHolder.children().first().remove();
        $("#id-pane-solution").show();
        $(".cl-solutions-section-right").css("min-height",($(".cl-solutions-section-left").height()));
        
        $.post("API.php", { query: "sr_version"}, function (data){
            if(data.response){
                srVersion = true;
                var ev = {currentTarget: {id: "-sr"}};
                $("#id-div-solution-chapter-holder").find(".cl-div-solution-chapter-list-item").first().click();
                //getSolutionsForChapter(ev);
            } else {
                initialFetchChapterCount = 0;
                // $.each($("#id-div-solution-chapter-holder").find(".cl-div-solution-chapter-list-item"), function(ind, elem){
                //     elem.click();
                // });
                $("#id-div-solution-chapter-holder").find(".cl-div-solution-chapter-list-item").first().click();
            }

        }, "json");

    }, "json");

}

function getSolutionsForChapter(event){
        $("#id-div-chapter-disabled-msg").hide();
        event.preventDefault();
        var chapter = event.currentTarget.id.substr(event.currentTarget.id.lastIndexOf("-")+1);
        initialPopulationMode = true;
        var chapterElem = this;

        //close all previously opened panes to save them
        $(".cl-div-chapter-content-h2-item-pane.collapse.in").collapse("hide");

        // if(!srVersion){
            $(".cl-div-solution-chapter-list-item").removeClass("active");
            $("#id-div-solution-chapter-list-item-"+chapter+" .cl-div-chapter-spin-i-holder").removeClass("hide");
            $("#id-div-solution-chapter-list-item-"+chapter+" .cl-div-chapter-chevron-holder").addClass("hide");
        // }

        $.post("API.php", { chapter: chapter }, function (data) {
            loadingMsgSpan.html("Loading content for chapter : "+chapter);
            initialFetchChapterCount++;

            var h2Holder = $("#id-div-chapter-content-h2-holder");
            var h2elem = $("#id-div-chapter-content-h2-holder-dummy .cl-div-chapter-content-h2-item")[0];
            h2Holder.empty();

            // $(".cl-div-chapter-content-h2-item-true").remove();
            $.each(data, function (i, e){
                d = e.header.h2_elems;

                $.each(d, function (index, e2) {
                    var newH2Elem = $(h2elem).clone();

                    newH2Elem.removeClass("hide");
                    newH2Elem.removeClass("cl-div-chapter-content-h2-item");
                    newH2Elem.addClass("cl-div-chapter-content-h2-item-true");
                    newH2Elem.addClass("unmarked");

                    var replacedHeaderTextH2 = e2.header_text.replace(/\./g,"-").toString();

                    id = newH2Elem.attr("id") + "-" + replacedHeaderTextH2;
                    newH2Elem.attr("id", id);

                    var h2Header = newH2Elem.find(".cl-div-chapter-content-h2-item-header");
                    var h2Pane = newH2Elem.find(".cl-div-chapter-content-h2-item-pane");
                    var h2Footer = newH2Elem.find(".cl-div-h2-footer");

                    var h2SaveBtn = h2Footer.find("#id-btn-hx-footer-save");
                    var h2ClearBtn = h2Footer.find("#id-btn-hx-footer-clear");
                    id = h2SaveBtn.attr("id") + "-" + replacedHeaderTextH2;
                    h2SaveBtn.attr("id",id);
                    id = h2ClearBtn.attr("id") + "-" + replacedHeaderTextH2;
                    h2ClearBtn.attr("id",id);
                    id = h2Pane.attr("id") + "-" + replacedHeaderTextH2;
                    h2Pane.attr("id",id);
                    h2Header.attr("data-target","#"+id);
                    h2Header.attr("data-parent","#"+$(h2Holder).attr("id"));

                    var h2FlipSwitch = h2Header.find(".cl-slider-flip-m");
                    id = h2FlipSwitch.attr("id") + "-" + replacedHeaderTextH2;
                    h2FlipSwitch.attr("id",id);
                    //h2FlipSwitch.flipswitch("refresh");

                    var h2Image = newH2Elem.find(".cl-div-h2-item-image");
                    h2Image.attr("src","images/PlusIcon.f542cb04.png");
                    h2Image.attr("data-src","images/PlusIcon.f542cb04.png");

                    var h2Text = newH2Elem.find(".cl-div-h2-item-number");
                    h2Text.html(e2.header_text.toString());

                    var h2Title = newH2Elem.find(".cl-div-h2-item-title");
                    h2Title.html(e2.h2_title.toString());

                    var instruction = newH2Elem.find(".cl-div-h2-item-subtitle");
                    instruction.html(e2.instruction.toString());

                    var h2Points = newH2Elem.find(".cl-div-h2-item-points");
                    h2Points.html(e2.h2_points.toString());

                    var numChildSolutions = Object.keys(e2.solutions).length;
                    $.each(e2.h3_elems, function(index, h3e){
                        numChildSolutions += Object.keys(h3e.solutions).length;
                    });

                    var h2SolutionsImplememtedRatioHolder = newH2Elem.find(".cl-div-implemented-ratio-holder");
                    var h2SolutionsImplememtedRatioTotal = $(h2SolutionsImplememtedRatioHolder).find(".cl-div-ratio-rounded-elem-right span");
                    var h2SolutionsImplememtedRatioImplemented = $(h2SolutionsImplememtedRatioHolder).find(".cl-div-ratio-rounded-elem-left span");

                    var h2CreditsRatioHolder = newH2Elem.find(".cl-div-earned-ratio-holder");
                    var h2CreditsRatioTotal = $(h2CreditsRatioHolder).find(".cl-div-ratio-rounded-elem-right span");
                    var h2CreditsRatioEarned = $(h2CreditsRatioHolder).find(".cl-div-ratio-rounded-elem-left span");

                    var h2NotificationHolder = newH2Elem.find(".cl-div-h2-item-title-notification-holder");
                    if(e2.design_resource !== null && e2.design_resource !== "NULL"&& e2.design_resource != null && e2.design_resource !== ""){
                        $(h2NotificationHolder).find("a").attr("href",e2.design_resource);
                    } else {
                        $(h2NotificationHolder).empty();
                    }

                    var h2SolutionsHolder = newH2Elem.find(".cl-div-h2-solutions-holder");
                    var h2SolutionsElem = newH2Elem.find(".cl-div-h2-solution-item");
                    h2SolutionsHolder.empty();

                    var h2s = e2.solutions;

                    if(!editMode && typeof creditDict[e2.h1][index] === "undefined"){
                        var creditH2Dict = {};
                        creditH2Dict.earned_credits = 0;
                        creditH2Dict.total_credits = parseInt(e2.h2_points,10);
                        creditH2Dict.applicable_credits = parseInt(e2.h2_points,10);
                        creditH2Dict.total_solutions = Object.keys(e2.solutions).length;
                        creditH2Dict.checked_solutions = 0;
                        creditH2Dict.solutions_bonus = 0;
                        creditH2Dict.thresholds = [];
                        creditH2Dict.thresholdLevels = [];

                        var th_s = e2.instruction;
                        while(th_s.indexOf(" of")>=0){
                            creditH2Dict.thresholds.unshift(parseInt(th_s.substring(th_s.substr(0,th_s.indexOf(" of")).lastIndexOf(" ")+1, th_s.indexOf(" of")),10));
                            th_s = th_s.substr(th_s.indexOf(" of")+3);
                        }

                        var th_s = e2.instruction;
                        while(th_s.indexOf(" Credit")>=0){
                            creditH2Dict.thresholdLevels.unshift(parseInt(th_s.substring(Math.max(0,th_s.substr(0,th_s.indexOf(" Credit")).lastIndexOf("|")+1), th_s.indexOf(" Credit")),10));
                            th_s = th_s.substr(th_s.indexOf(" Credit")+7);
                        }

                        creditDict[e2.h1][index] = creditH2Dict;
                    } else if(editMode){
                        creditDict[e2.h1][index].total_credits = parseInt(e2.h2_points,10);
                        creditDict[e2.h1][index].applicable_credits = creditDict[e2.h1][index].enabled == false ? 0 : parseInt(e2.h2_points,10);
                        creditDict[e2.h1][index].total_solutions = Object.keys(e2.solutions).length;
                        // console.log (e2.h1," ",index," : ",Object.keys(e2.solutions).length);
                        creditDict[e2.h1][index].solutions_bonus = 0;
                        var th_s = e2.instruction;
                        while(th_s.indexOf(" of")>=0){
                            creditDict[e2.h1][index].thresholds.unshift(parseInt(th_s.substring(th_s.substr(0,th_s.indexOf(" of")).lastIndexOf(" ")+1, th_s.indexOf(" of")),10));
                            th_s = th_s.substr(th_s.indexOf(" of")+3);
                        }

                        var th_s = e2.instruction;
                        while(th_s.indexOf(" Credit")>=0){
                            creditDict[e2.h1][index].thresholdLevels.unshift(parseInt(th_s.substring(Math.max(0,th_s.substr(0,th_s.indexOf(" Credit")).lastIndexOf("|")+1), th_s.indexOf(" Credit")),10));
                            th_s = th_s.substr(th_s.indexOf(" Credit")+7);
                        }
                    }

                    if(h2s.length > 0){

                    }

                    $.each(h2s, function (index, s){
                        var newSolutionElem = $(h2SolutionsElem).clone();
                        id = newSolutionElem.attr("id") + "-" + s.standard_no.replace(/\./g,"-").toString();
                        newSolutionElem.attr("id",id);

                        var solutionText = newSolutionElem.find(".cl-div-h2-solution-item-text");
                        solutionText.html(s.standard_text.toString());

                        var solutionPrequisite = newSolutionElem.find(".cl-div-h2-solution-item-prequisite");
                        if(s.prerequisite){
                            $(newSolutionElem).addClass("prequisite");
                        }

                        var solutionItemNumber = newSolutionElem.find(".cl-div-h2-solution-item-number-text");
                        solutionItemNumber.html("Solution "+s.standard_no);



                        set_rb_toggle_value(s.standard_no,rb_value,newSolutionElem);

                        var solutionItemHeader = newSolutionElem.find(".cl-div-h2-solution-item-header");
                        var solutionItemPane = newSolutionElem.find(".cl-div-h2-solution-item-pane");
                        id = solutionItemPane.attr("id") + "-" + s.standard_no.replace(/\./g,"-").toString();
                        solutionItemPane.attr("id",id);
                        solutionItemHeader.attr("data-target","#"+id);
                        //Start: Code which updates solution's review checkbox toggle switch
                        if(G_isud_status!=0){
                          var rb_value= G_checkbox_values[s.standard_no]; // Review checkbox value for the given solution no;

                          var rb_element=$(solutionItemHeader).find(".candlestick-bg");
                          var comment_icon = $(solutionItemHeader).find(".cl-comment-icon");
                          if (G_solution_comment_status.indexOf(s.standard_no) != -1 && rb_value!=-1)
                          {
                            comment_icon.css('visibility','visible');
                          }
                          
                          $.post("API.php",{comment:"GET",project_id:G_PROJECT_ID,solution_id:s.standard_no},function(data){
                             var comments = data.comments;
                             if(comments.length>0 && rb_value!=-1){
                                 comment_icon.css('visibility','visible');
                             }
                          },"json");
                          
                          if(rb_value==1){
                            if(G_IS_PROJECT_REVIEWER) {
                              set_rb_negative(rb_element);
                            }
                            else {
                              $(solutionItemHeader).find(".client-rb-checkboxCSS").addClass("flag-box");
                            }
                          }
                          else if(rb_value==-1) {
                            if(G_IS_PROJECT_REVIEWER){
                              set_rb_positive(rb_element);
                            }
                            else {
                              $(solutionItemHeader).find(".client-rb-checkboxCSS").addClass("approve-box");
                            }
                          }
                        }
                        //End: Code which updates solution's review checkbox toggle switch
                        var solutionItemImageNotificationHolder = newSolutionElem.find(".cl-div-h2-solution-item-image-notification-holder");

                        var solutionItemAttribGoalsHolder = newSolutionElem.find("#id-div-h2-solution-item-attrib-holder-goals");
                        var solutionItemAttribGoalsItem = solutionItemAttribGoalsHolder.find(".cl-div-h2-solution-item-attrib-item");
                        solutionItemAttribGoalsHolder.children().not(".cl-div-h2-solution-item-attrib-header").remove();

                        var solutionItemAttribPhasesHolder = newSolutionElem.find("#id-div-h2-solution-item-attrib-holder-phases");
                        var solutionItemAttribPhasesItem = solutionItemAttribPhasesHolder.find(".cl-div-h2-solution-item-attrib-item");
                        solutionItemAttribPhasesHolder.children().not(".cl-div-h2-solution-item-attrib-header").remove();

                        var solutionItemImageHolder = newSolutionElem.find(".cl-div-solution-item-pane-image-holder");
                        var solutionItemImageTextHolder = newSolutionElem.find(".cl-div-h2-solution-item-image-text-holder");
                        var solutionItemImageCarousel = solutionItemImageHolder.find("#id-solution-item-carousel");
                        var solutionItemImageCarouselIndicators = solutionItemImageCarousel.find(".cl-solution-item-carousel-indicators");
                        var solutionItemImageCarouselInner = solutionItemImageCarousel.find(".cl-solution-item-carousel-inner");
                        var solutionItemImageCarouselControlLeft = solutionItemImageCarousel.find(".left.carousel-control");
                        var solutionItemImageCarouselControlRight = solutionItemImageCarousel.find(".right.carousel-control");

                        var id = solutionItemImageCarousel.attr("id") + "-" + s.standard_no.replace(/\./g,"-").toString();
                        solutionItemImageCarousel.attr("id",id);
                        solutionItemImageCarouselControlLeft.attr("href","#"+id);
                        solutionItemImageCarouselControlRight.attr("href","#"+id);

                        if(s.fig_arr.length <= 0){
                            //solutionItemImageHolder.empty();
                            //solutionItemImageHolder.hide();
                            //solutionItemImageTextHolder.hide();
                            $(solutionItemImageHolder).find(".carousel-inner").hide();
                            solutionItemImageCarouselControlLeft.hide();
                            solutionItemImageCarouselControlRight.hide();
                            solutionItemImageCarouselIndicators.hide();
                        } else if(s.fig_arr.length == 1){
                            solutionItemImageCarouselControlLeft.hide();
                            solutionItemImageCarouselControlRight.hide();
                            solutionItemImageCarouselIndicators.hide();
                        }

                        if(s.fig_arr.length >= 1){
                            $(solutionItemImageHolder).css("min-height","360px");
                        }

                        $.each(s.fig_arr, function(index, fig){

                            var solutionItemImageCarouselIndicatorsLi = solutionItemImageCarouselIndicators.find("li").first().clone();
                            solutionItemImageCarouselIndicatorsLi.attr("data-slide-to",index);
                            solutionItemImageCarouselIndicatorsLi.attr("data-target","#"+id);

                            var solutionItemImageCarouselInnerItem = solutionItemImageCarouselInner.find(".cl-solution-item-carousel-item").first().clone();
                            var solutionItemImageCarouselInnerItemImage = solutionItemImageCarouselInnerItem.find("img");
                            var solutionItemImageCarouselInnerItemImageCaption = solutionItemImageCarouselInnerItem.find(".cl-solution-item-carousel-item-image-caption");
                            solutionItemImageCarouselInnerItemImage.attr("data-src",fig.fig_no);
                            solutionItemImageCarouselInnerItemImage.attr("alt",fig.fig_no);
                            solutionItemImageCarouselInnerItemImage.attr("data-caption",fig.fig_caption);
                            solutionItemImageCarouselInnerItemImage.attr("data-num",index);
                            solutionItemImageCarouselInnerItemImage.attr("src","");
                            solutionItemImageCarouselInnerItemImageCaption.html("<p>" + fig.fig_caption + "</p>");
                            solutionItemImageCarouselInnerItemImageCaption.attr("style", "padding-top:20px");

                            if(fig.fig_caption===''){
                                solutionItemImageCarouselInnerItemImageCaption.html(s.standard_no+" : "+fig.fig_no.replace("solution_images/",""));
                            }

                            if(index === 0){
                                solutionItemImageCarouselIndicators.empty();
                                solutionItemImageCarouselInner.empty();
                                solutionItemImageCarouselIndicatorsLi.removeClass("active");
                                solutionItemImageCarouselIndicatorsLi.addClass("active");
                                solutionItemImageCarouselInnerItem.removeClass("active");
                                solutionItemImageCarouselInnerItem.addClass("active");
                                solutionItemImageNotificationHolder.removeClass("hide");
                            } else {
                                solutionItemImageCarouselIndicatorsLi.removeClass("active");
                                solutionItemImageCarouselInnerItem.removeClass("active");
                            }

                            solutionItemImageCarouselIndicators.append(solutionItemImageCarouselIndicatorsLi);
                            solutionItemImageCarouselInner.append(solutionItemImageCarouselInnerItem);

                        });

                        $.each(global_columns_goals, function (index, goal){
                            var newAttribItem = $(solutionItemAttribGoalsItem).clone();
                            $(newAttribItem).find(".cl-div-h2-solution-item-attrib-item-text").html(goal.name);
                            if(s.goals.search(goal.name) != -1){ // goal active for this solution
                                $(newAttribItem).find(".cl-div-h2-solution-item-attrib-item-indicator .fa").addClass("fa-check");
                                $(newAttribItem).find(".cl-div-h2-solution-item-attrib-item-indicator .fa").removeClass("fa-square");
                                $(newAttribItem).find(".cl-div-h2-solution-item-attrib-item-text").addClass("active");
                            } else {
                                $(newAttribItem).find(".cl-div-h2-solution-item-attrib-item-text").attr("aria-hidden","true");
                            }

                            solutionItemAttribGoalsHolder.append(newAttribItem);
                        });

                        $.each(global_columns_phases, function (index, phase){
                            var newAttribItem = $(solutionItemAttribPhasesItem).clone();
                            $(newAttribItem).find(".cl-div-h2-solution-item-attrib-item-text").html(phase.name);
                            if(s.phases.search(phase.name) != -1){ // goal active for this solution
                                $(newAttribItem).find(".cl-div-h2-solution-item-attrib-item-indicator .fa").addClass("fa-check");
                                $(newAttribItem).find(".cl-div-h2-solution-item-attrib-item-indicator .fa").removeClass("fa-square");
                                $(newAttribItem).find(".cl-div-h2-solution-item-attrib-item-text").addClass("active");
                            } else {
                                $(newAttribItem).find(".cl-div-h2-solution-item-attrib-item-text").attr("aria-hidden","true");
                            }

                            solutionItemAttribPhasesHolder.append(newAttribItem);
                        });

                        h2SolutionsHolder.append(newSolutionElem);

                        if(typeof creditDict[s.h1][s.h2][index] === "undefined"){
                            creditDict[s.h1][s.h2][index] = {checked: 0};
                            creditDict[s.h1][s.h2][index] = {reviewed: 0};
                        } 
                        if(G_viewReviewerScore){
                            $(solutionItemHeader).find(".cl-div-hx-solution-item-checkbox").prop("checked", creditDict[s.h1][s.h2][index].checked === 1 ? true: false);
                            if(initialPopulationMode){
                              updateCreditCountandUI2(s.h1, s.h2, -1, index,creditDict[s.h1][s.h2][index].reviewed, creditDict, "reviewed");
                            }
                        }
                        else {
                            $(solutionItemHeader).find(".cl-div-hx-solution-item-checkbox").prop("checked",creditDict[s.h1][s.h2][index].checked === 1 ? true: false);
                            if(creditDict[s.h1][s.h2][index].checked === 0) $(solutionItemHeader).find(".client-rb-checkboxCSS").css("background-color","#DEDEDE");
                            if(initialPopulationMode){
                                updateCreditCountandUI2(s.h1, s.h2, -1, index,creditDict[s.h1][s.h2][index].checked, creditDict,"checked");
                            }
                        }

                    });

                    var h3Holder = newH2Elem.find(".cl-div-chapter-content-h3-holder");
                    var h3elem = newH2Elem.find(".cl-div-chapter-content-h3-item")[0];
                    h3Holder.empty();
                    id = $(h3Holder).attr("id") + "-" + replacedHeaderTextH2;
                    $(h3Holder).attr("id",id);
                    // $(".cl-div-chapter-content-h3-item-true").remove();
                    var d = e2.h3_elems;

                    if(Object.keys(d).length > 0){
                        $(instruction).addClass("hide");
                        $(h2Footer).addClass("hide");
                    }

                    h2Holder.append(newH2Elem);

                    h2CreditsRatioTotal.html("of "+creditDict[e2.h1][index].applicable_credits);
                    h2CreditsRatioEarned.html(creditDict[e2.h1][index].earned_credits);
                    h2SolutionsImplememtedRatioImplemented.html(creditDict[e2.h1][index].checked_solutions);
                    h2SolutionsImplememtedRatioTotal.html("of "+creditDict[e2.h1][index].total_solutions);

                    // restore level 2 toggle button value from creditDict i.e. from DB
                    restore_level_2_toggle_button (h2FlipSwitch, chapter, index, creditDict, newH2Elem);

                    $.each(d, function (index, e3) {
                        var newH3Elem = $(h3elem).clone();
                        var replacedHeaderTextH3 = e3.header_text.replace(/\./g,"-").toString();
                        id = newH3Elem.attr("id") + "-" + replacedHeaderTextH3;
                        newH3Elem.attr("id", id);
                        newH3Elem.removeClass("cl-div-chapter-content-h3-item");
                        newH3Elem.addClass("cl-div-chapter-content-h3-item-true");

                        var h3Header = newH3Elem.find(".cl-div-chapter-content-h3-item-header");
                        var h3Pane = newH3Elem.find(".cl-div-chapter-content-h3-item-pane");
                        var h3Footer = newH3Elem.find(".cl-div-h3-footer");

                        var h3SaveBtn = h3Footer.find("#id-btn-hx-footer-save");
                        var h3ClearBtn = h3Footer.find("#id-btn-hx-footer-clear");
                        id = h3SaveBtn.attr("id") + "-" + replacedHeaderTextH3;
                        h3SaveBtn.attr("id",id);
                        id = h3ClearBtn.attr("id") + "-" + replacedHeaderTextH3;
                        h3ClearBtn.attr("id",id);

                        id = h3Pane.attr("id") + "-" + replacedHeaderTextH3;
                        h3Pane.attr("id",id);
                        h3Header.attr("data-target","#"+id);
                        // h3Header.attr("data-parent","#"+$(h3Holder).attr("id"));

                        var h3Image = newH3Elem.find(".cl-div-h3-item-image");
                        h3Image.attr("src","images/PlusIcon.f542cb04.png");
                        h3Image.attr("data-src","images/PlusIcon.f542cb04.png");

                        var h3Text = newH3Elem.find(".cl-div-h3-item-number");
                        h3Text.html(e3.header_text.toString());

                        var h3Title = newH3Elem.find(".cl-div-h3-item-title");
                        h3Title.html(e3.h3_title.toString());

                        var instruction = newH3Elem.find(".cl-div-h3-item-subtitle");
                        instruction.html(e3.instruction.toString());

                        var h3Points = newH3Elem.find(".cl-div-h3-item-points");
                        h3Points.html(e3.h3_points.toString());

                        var h3NotificationHolder = newH3Elem.find(".cl-div-h3-item-title-notification-holder");
                        if(e3.design_resource !== null && e3.design_resource !== "NULL"&& e3.design_resource != null && e3.design_resource !== ""){
                            $(h3NotificationHolder).find("a").attr("href",e3.design_resource);
                        } else {
                            $(h3NotificationHolder).empty();
                        }

                        var h3SolutionsHolder = newH3Elem.find(".cl-div-h3-solutions-holder");
                        var h3SolutionsElem = newH3Elem.find(".cl-div-h3-solution-item");
                        h3SolutionsHolder.empty();

                        var h3s = e3.solutions;

                        // adding level 3 toggle button
                        h3s_length = Object.keys(h3s).length
                        if(h3s_length > 0)
                        {
                            var h3FlipSwitch = h3Header.find(".cl-slider-flip-m");
                            var replacedHeaderTextH3 = e3.header_text.replace(/\./g,"-").toString();
                            id = h3FlipSwitch.attr("id") + "-" + replacedHeaderTextH3;
                            h3FlipSwitch.attr("id",id);

                            // update_credits_for_level_3();
                            {
                                var h3SolutionsImplememtedRatioHolder = newH3Elem.find(".cl-div-implemented-ratio-holder");
                                var h3SolutionsImplememtedRatioTotal = $(h3SolutionsImplememtedRatioHolder).find(".cl-div-ratio-rounded-elem-right span");
                                var h3SolutionsImplememtedRatioImplemented = $(h3SolutionsImplememtedRatioHolder).find(".cl-div-ratio-rounded-elem-left span");

                                var h3CreditsRatioHolder = newH3Elem.find(".cl-div-earned-ratio-holder");
                                var h3CreditsRatioTotal = $(h3CreditsRatioHolder).find(".cl-div-ratio-rounded-elem-right span");
                                var h3CreditsRatioEarned = $(h3CreditsRatioHolder).find(".cl-div-ratio-rounded-elem-left span");
                            }
                        }


                        if(!editMode && typeof creditDict[e3.h1][e3.h2][index] === "undefined"){
                            var creditH3Dict = {};
                            creditH3Dict.earned_credits = 0;
                            creditH3Dict.total_credits = parseInt(e3.h3_points,10);
                            creditH3Dict.applicable_credits = parseInt(e3.h3_points,10);
                            creditH3Dict.solutions_bonus = parseInt(e3.h3_points,10);
                            creditH3Dict.total_solutions = Object.keys(e3.solutions).length;
                            creditH3Dict.checked_solutions = 0;
                            creditH3Dict.thresholds = [];
                            creditH3Dict.thresholdLevels = [];

                            var th_s = e3.instruction;
                            while(th_s.indexOf(" of")>=0){
                                creditH3Dict.thresholds.unshift(parseInt(th_s.substring(th_s.substr(0,th_s.indexOf(" of")).lastIndexOf(" ")+1, th_s.indexOf(" of")),10));
                                th_s = th_s.substr(th_s.indexOf(" of")+3);
                            }

                            var th_s = e3.instruction;
                            while(th_s.indexOf(" Credit")>=0){
                                creditH3Dict.thresholdLevels.unshift(parseInt(th_s.substring(Math.max(0,th_s.substr(0,th_s.indexOf(" Credit")).lastIndexOf("|")+1), th_s.indexOf(" Credit")),10));
                                th_s = th_s.substr(th_s.indexOf(" Credit")+7);
                            }

                            creditDict[e3.h1][e3.h2][index] = creditH3Dict;
                        } else if (editMode){
                            creditDict[e3.h1][e3.h2][index].total_credits = parseInt(e3.h3_points,10);
                            creditDict[e3.h1][e3.h2][index].applicable_credits = parseInt(e3.h3_points,10);
                            creditDict[e3.h1][e3.h2][index].solutions_bonus = parseInt(e3.h3_points,10);
                            creditDict[e3.h1][e3.h2][index].total_solutions = Object.keys(e3.solutions).length;
                            // update upper level solutions count
                            // update_solution_count_of_above_level()
                            {
                                creditDict[e3.h1][e3.h2].total_solutions = creditDict[e3.h1][e3.h2].total_solutions + creditDict[e3.h1][e3.h2][index].total_solutions;
                                h2SolutionsImplememtedRatioTotal.html("of "+creditDict[e3.h1][e3.h2].total_solutions);
                            }
                            // console.log (e3.h1," ",e3.h2," ",index," : ",Object.keys(e3.solutions).length);
                            var th_s = e3.instruction;
                            while(th_s.indexOf(" of")>=0){
                                creditDict[e3.h1][e3.h2][index].thresholds.unshift(parseInt(th_s.substring(th_s.substr(0,th_s.indexOf(" of")).lastIndexOf(" ")+1, th_s.indexOf(" of")),10));
                                th_s = th_s.substr(th_s.indexOf(" of")+3);
                            }

                            var th_s = e3.instruction;
                            while(th_s.indexOf(" Credit")>=0){
                                creditDict[e3.h1][e3.h2][index].thresholdLevels.unshift(parseInt(th_s.substring(Math.max(0,th_s.substr(0,th_s.indexOf(" Credit")).lastIndexOf("|")+1), th_s.indexOf(" Credit")),10));
                                th_s = th_s.substr(th_s.indexOf(" Credit")+7);
                            }
                        }

                        // for solutions similar to 4-1-1-1
                        $.each(h3s, function (index, s){
                            var newSolutionElem = $(h3SolutionsElem).clone();
                            id = newSolutionElem.attr("id") + "-" + s.standard_no.replace(/\./g,"-").toString();
                            newSolutionElem.attr("id",id);

                            var solutionText = newSolutionElem.find(".cl-div-h3-solution-item-text");
                            solutionText.html(s.standard_text.toString());

                            var solutionPrequisite = newSolutionElem.find(".cl-div-h3-solution-item-prequisite");
                            if(s.prerequisite){
                                $(newSolutionElem).addClass("prequisite");
                            }

                            var solutionItemNumber = newSolutionElem.find(".cl-div-h3-solution-item-number-text");
                            solutionItemNumber.html("Solution "+s.standard_no);

                            var solutionItemHeader = newSolutionElem.find(".cl-div-h3-solution-item-header");
                            var solutionItemPane = newSolutionElem.find(".cl-div-h3-solution-item-pane");
                            id = solutionItemPane.attr("id") + "-" + s.standard_no.replace(/\./g,"-").toString();
                            solutionItemPane.attr("id",id);
                            solutionItemHeader.attr("data-target","#"+id);
                            //Start: Code which updates solution's review checkbox toggle switch for third level
                            if(G_isud_status!=0 && G_isud_status != 4){
                              var rb_value= G_checkbox_values[s.standard_no]; // Review checkbox value for the given solution no;
                              var rb_element=$(solutionItemHeader).find(".candlestick-bg");
                              var comment_icon = $(solutionItemHeader).find(".cl-comment-icon");
                              if (G_solution_comment_status.indexOf(s.standard_no) != -1 && rb_value!=-1)
                              {
                                  comment_icon.css('visibility','visible');
                              }
                              
                              $.post("API.php",{comment:"GET",project_id:G_PROJECT_ID,solution_id:s.standard_no},function(data){
                                 var comments = data.comments;
                                 if(comments.length>0 && rb_value!=-1)
                                  comment_icon.css('visibility','visible');
                              },"json");
                              
                              if(rb_value==1){
                                if(G_IS_PROJECT_REVIEWER)
                                  set_rb_negative(rb_element);
                                else {
                                  $(solutionItemHeader).find(".client-rb-checkboxCSS").addClass("flag-box");
                                }
                              }
                              else if(rb_value==-1){
                                if(G_IS_PROJECT_REVIEWER) {
                                  set_rb_positive(rb_element);
                                }
                                else {
                                  $(solutionItemHeader).find(".client-rb-checkboxCSS").addClass("approve-box");
                                }
                              }
                          }
                            var solutionItemImageNotificationHolder = newSolutionElem.find(".cl-div-h3-solution-item-image-notification-holder");

                            var solutionItemAttribGoalsHolder = newSolutionElem.find("#id-div-h3-solution-item-attrib-holder-goals");
                            var solutionItemAttribGoalsItem = solutionItemAttribGoalsHolder.find(".cl-div-h3-solution-item-attrib-item");
                            solutionItemAttribGoalsHolder.children().not(".cl-div-h3-solution-item-attrib-header").remove();

                            var solutionItemAttribPhasesHolder = newSolutionElem.find("#id-div-h3-solution-item-attrib-holder-phases");
                            var solutionItemAttribPhasesItem = solutionItemAttribPhasesHolder.find(".cl-div-h3-solution-item-attrib-item");
                            solutionItemAttribPhasesHolder.children().not(".cl-div-h3-solution-item-attrib-header").remove();

                            var solutionItemImageHolder = newSolutionElem.find(".cl-div-solution-item-pane-image-holder");
                            var solutionItemImageTextHolder = newSolutionElem.find(".cl-div-h3-solution-item-image-text-holder");
                            var solutionItemImageCarousel = solutionItemImageHolder.find("#id-solution-item-carousel");
                            var solutionItemImageCarouselIndicators = solutionItemImageCarousel.find(".cl-solution-item-carousel-indicators");
                            var solutionItemImageCarouselInner = solutionItemImageCarousel.find(".cl-solution-item-carousel-inner");
                            var solutionItemImageCarouselControlLeft = solutionItemImageCarousel.find(".left.carousel-control");
                            var solutionItemImageCarouselControlRight = solutionItemImageCarousel.find(".right.carousel-control");

                            var id = solutionItemImageCarousel.attr("id") + "-" + s.standard_no.replace(/\./g,"-").toString();
                            solutionItemImageCarousel.attr("id",id);
                            solutionItemImageCarouselControlLeft.attr("href","#"+id);
                            solutionItemImageCarouselControlRight.attr("href","#"+id);

                            if(s.fig_arr.length <= 0){
                                //solutionItemImageHolder.empty();
                                //solutionItemImageHolder.hide();
                                //solutionItemImageTextHolder.hide();
                                $(solutionItemImageHolder).find(".carousel-inner").hide();
                                solutionItemImageCarouselControlLeft.hide();
                                solutionItemImageCarouselControlRight.hide();
                                solutionItemImageCarouselIndicators.hide();
                            } else if(s.fig_arr.length == 1){
                                solutionItemImageCarouselControlLeft.hide();
                                solutionItemImageCarouselControlRight.hide();
                                solutionItemImageCarouselIndicators.hide();
                            }

                            if(s.fig_arr.length >= 1){
                                $(solutionItemImageHolder).css("min-height","360px");
                            }

                            $.each(s.fig_arr, function(index, fig){

                                var solutionItemImageCarouselIndicatorsLi = solutionItemImageCarouselIndicators.find("li").first().clone();
                                solutionItemImageCarouselIndicatorsLi.attr("data-slide-to",index);
                                solutionItemImageCarouselIndicatorsLi.attr("data-target","#"+id);

                                var solutionItemImageCarouselInnerItem = solutionItemImageCarouselInner.find(".cl-solution-item-carousel-item").first().clone();
                                var solutionItemImageCarouselInnerItemImage = solutionItemImageCarouselInnerItem.find("img");
                                var solutionItemImageCarouselInnerItemImageCaption = solutionItemImageCarouselInnerItem.find(".cl-solution-item-carousel-item-image-caption");
                                solutionItemImageCarouselInnerItemImage.attr("data-src",fig.fig_no);
                                solutionItemImageCarouselInnerItemImage.attr("alt",fig.fig_no);
                                solutionItemImageCarouselInnerItemImage.attr("data-caption",fig.fig_caption);
                                solutionItemImageCarouselInnerItemImage.attr("data-num",index);
                                solutionItemImageCarouselInnerItemImage.attr("src","");
                                solutionItemImageCarouselInnerItemImageCaption.html("<p>" + fig.fig_caption + "</p>");
                                solutionItemImageCarouselInnerItemImageCaption.attr("style", "padding-top:20px");

                                if(fig.fig_caption===''){
                                    solutionItemImageCarouselInnerItemImageCaption.html(s.standard_no+" : "+fig.fig_no.replace("solution_images/",""));
                                }

                                if(index === 0){
                                    solutionItemImageCarouselIndicators.empty();
                                    solutionItemImageCarouselInner.empty();
                                    solutionItemImageCarouselIndicatorsLi.removeClass("active");
                                    solutionItemImageCarouselIndicatorsLi.addClass("active");
                                    solutionItemImageCarouselInnerItem.removeClass("active");
                                    solutionItemImageCarouselInnerItem.addClass("active");
                                    solutionItemImageNotificationHolder.removeClass("hide");
                                } else {
                                    solutionItemImageCarouselIndicatorsLi.removeClass("active");
                                    solutionItemImageCarouselInnerItem.removeClass("active");
                                }

                                solutionItemImageCarouselIndicators.append(solutionItemImageCarouselIndicatorsLi);
                                solutionItemImageCarouselInner.append(solutionItemImageCarouselInnerItem);

                            });

                            $.each(global_columns_goals, function (index, goal){
                                var newAttribItem = $(solutionItemAttribGoalsItem).clone();
                                $(newAttribItem).find(".cl-div-h3-solution-item-attrib-item-text").html(goal.name);
                                if(s.goals.search(goal.name) != -1){ // goal active for this solution
                                    $(newAttribItem).find(".cl-div-h3-solution-item-attrib-item-indicator .fa").addClass("fa-check");
                                    $(newAttribItem).find(".cl-div-h3-solution-item-attrib-item-indicator .fa").removeClass("fa-square");
                                    $(newAttribItem).find(".cl-div-h3-solution-item-attrib-item-text").addClass("active");
                                } else {
                                    $(newAttribItem).find(".cl-div-h3-solution-item-attrib-item-text").attr("aria-hidden","true");
                                }

                                solutionItemAttribGoalsHolder.append(newAttribItem);
                            });

                            $.each(global_columns_phases, function (index, phase){
                                var newAttribItem = $(solutionItemAttribPhasesItem).clone();
                                $(newAttribItem).find(".cl-div-h3-solution-item-attrib-item-text").html(phase.name);
                                if(s.phases.search(phase.name) != -1){ // goal active for this solution
                                    $(newAttribItem).find(".cl-div-h3-solution-item-attrib-item-indicator .fa").addClass("fa-check");
                                    $(newAttribItem).find(".cl-div-h3-solution-item-attrib-item-indicator .fa").removeClass("fa-square");
                                    $(newAttribItem).find(".cl-div-h3-solution-item-attrib-item-text").addClass("active");
                                } else {
                                    $(newAttribItem).find(".cl-div-h3-solution-item-attrib-item-text").attr("aria-hidden","true");
                                }

                                solutionItemAttribPhasesHolder.append(newAttribItem);
                            });

                            h3SolutionsHolder.append(newSolutionElem);

                            if(typeof creditDict[s.h1][s.h2][s.h3][index] === "undefined"){
                                creditDict[s.h1][s.h2][s.h3][index] = {checked: 0};
                                creditDict[s.h1][s.h2][s.h3][index] = {reviewed: 0};
                            }
                            if(G_viewReviewerScore){
                              $(solutionItemHeader).find(".cl-div-hx-solution-item-checkbox").prop("checked",creditDict[s.h1][s.h2][s.h3][index].checked === 1 ? true: false);
                                if(initialPopulationMode){
                                    updateCreditCountandUI2(s.h1, s.h2,s.h3, index,creditDict[s.h1][s.h2][s.h3][index].reviewed, creditDict, "reviewed");
                                }
                            }
                            else {
                                $(solutionItemHeader).find(".cl-div-hx-solution-item-checkbox").prop("checked",creditDict[s.h1][s.h2][s.h3][index].checked === 1 ? true: false);
                                if(creditDict[s.h1][s.h2][s.h3][index].checked === 0){
                                    $(solutionItemHeader).find(".client-rb-checkboxCSS").css("background-color","#DEDEDE");
                                }

                                if(initialPopulationMode){
                                   updateCreditCountandUI2(s.h1, s.h2,s.h3, index,creditDict[s.h1][s.h2][s.h3][index].checked, creditDict,"checked");
                                }
                            }

                        });

                        // update total solutions and total implemented solutiopns for level3 toggle buttons
                        h3CreditsRatioTotal.html("of "+creditDict[e3.h1][e3.h2][index].applicable_credits);
                        h3CreditsRatioEarned.html(creditDict[e3.h1][e3.h2][index].earned_credits);
                        h3SolutionsImplememtedRatioImplemented.html(creditDict[e3.h1][e3.h2][index].checked_solutions);
                        h3SolutionsImplememtedRatioTotal.html("of "+creditDict[e3.h1][e3.h2][index].total_solutions);

                        // restore level3 toggle button value from creditDict i.e. from DB
                        h3Holder.append(newH3Elem);
                        restore_level_3_toggle_button (h3FlipSwitch, e3, index, creditDict, newH3Elem);
                    });


                });

                initialPopulationMode = false;

            });

            if(srVersion){
                // $(".collapse").addClass("in");
                $(".collapse").addClass("active");
                // $(".collapse").collapse("show");
                $("img").unveil();
                $("img").trigger("unveil");
                $("img").trigger("lookup");
            }

            $("#id-div-solution-chapter-list-item-"+chapter).addClass("active");
            // $("#id-div-solution-chapter-list-item-"+chapter).find('img').attr('src','images/Chevron_orange.png');
            $("#id-div-solution-chapter-list-item-"+chapter+" .cl-div-chapter-spin-i-holder").addClass("hide");
            $("#id-div-solution-chapter-list-item-"+chapter+" .cl-div-chapter-chevron-holder").removeClass("hide");
            $("#id-div-solution-chapter-list-item-"+chapter+" .cl-div-chapter-chevron-holder").find(".cl-img-chapter-chevron").addClass("active");
            if ( $("#id-div-solution-chapter-list-item-"+chapter+" .cl-img-chapter-chevron").hasClass('active')){
                    $("#id-div-solution-chapter-list-item-"+chapter).children('img').attr('src', 'images/Chevron_orange.7ccbfb74.png');
            }

            $(".cl-div-chapter-content-h2-item-pane").on("hidden.bs.collapse", function(){
                $(this).parent().find(".cl-div-chapter-content-h2-item-header").find(".cl-div-h2-item-number").css("font-weight", "");
                $(this).parent().find(".cl-div-chapter-content-h2-item-header").find(".cl-div-h2-item-title-holder").css("font-weight", "");
                $(this).parent().find(".cl-div-chapter-content-h2-item-header .cl-div-h2-item-subtitle").addClass("hide");
                $(this).parent().find(".cl-div-chapter-content-h2-item-header .cl-img-h2-item-image").attr("src","images/Chevron_grey_small.de8d4377.png");
                
                return false;
            });

            $(".cl-div-chapter-content-h2-item-pane").on("hide.bs.collapse", function(){
                var target = $(this).attr("id");
                target = target.substr(target.indexOf("pane-")+5);
                var elems = target.split("-");

                if(editMode){
                    // alert(G_projectCreditCountEarned);
                    $.post("API.php", {project: "UPDATE", id :params.id, target: target, applicable_credits: G_projectCreditCountApplicable, earned_credits: G_projectCreditCountEarned, bonus_credits: G_projectSolutionsTowardsBonusCount, award_percentage: G_projectAwardPercentage, award_category: "Bronze", h1_credits_applicable: G_h1CreditsArrApplicableString, h1_credits_earned: G_h1CreditsArrEarnedString, data: creditDict[elems[0]][elems[1]]} , function (data) {
                    },"json");
                }

            });

            $(".cl-div-chapter-content-h3-item-pane").on("hidden.bs.collapse", function(){
                $(this).parent().find(".cl-div-chapter-content-h3-item-header").find(".cl-div-h3-item-number").css("font-weight", "");
                $(this).parent().find(".cl-div-chapter-content-h3-item-header").find(".cl-div-h3-item-title-holder").css("font-weight", "");
                $(this).parent().find(".cl-div-chapter-content-h3-item-header .cl-div-h3-item-subtitle").addClass("hide");
                $(this).parent().find(".cl-div-chapter-content-h3-item-header .cl-img-h3-item-image").attr("src","images/Chevron_grey_small.de8d4377.png");

                if(deferredOpenElem != null){
                    $(deferredOpenElem).collapse("show");
                    deferredOpenElem = null;
                }

                return false;
            });

            $(".cl-div-chapter-content-h3-item-pane").on("hide.bs.collapse", function(){

                var target = $(this).attr("id");
                target = target.substr(target.indexOf("pane-")+5);
                var elems = target.split("-");

                // always send the H2 item equalant of the creditDict.
                if(editMode){
                    $.post("API.php", {project: "UPDATE", id :params.id, target: target, applicable_credits: G_projectCreditCountApplicable, earned_credits: G_projectCreditCountEarned, bonus_credits: G_projectSolutionsTowardsBonusCount, award_percentage: G_projectAwardPercentage, award_category: "Bronze", h1_credits_applicable: G_h1CreditsArrApplicableString, h1_credits_earned: G_h1CreditsArrEarnedString, data: creditDict[elems[0]][elems[1]]} , function (data) {
                    },"json");
                }

            });

            $(".cl-div-chapter-content-h2-item-pane").on("shown.bs.collapse", function(){
                $(this).parent().find(".cl-div-chapter-content-h2-item-header .cl-div-h2-item-subtitle").removeClass("hide");
                $(this).parent().find(".cl-div-chapter-content-h2-item-header .cl-img-h2-item-image").attr("src","images/Chevron_orange_down.51415ee4.png");
                $(this).parent().find(".cl-div-chapter-content-h2-item-header").find(".cl-div-h2-item-number").css("font-weight", "bold");
                $(this).parent().find(".cl-div-chapter-content-h2-item-header").find(".cl-div-h2-item-title-holder").css("font-weight", "bold");
                // hide other panes logic goes here
                var pane = $(this).parent().find(".cl-div-chapter-content-h2-item-pane");
                var others = $(this).parent().parent().find(".cl-div-chapter-content-h2-item-pane").not(pane);
                $(others).collapse("hide");

                return false;
            });

            $(".cl-div-chapter-content-h3-item-pane").on("shown.bs.collapse", function(){
                // $(".cl-div-chapter-content-h3-item-pane").not(this).collapse("hide");
                $(this).parent().find(".cl-div-chapter-content-h3-item-header .cl-div-h3-item-subtitle").removeClass("hide");
                $(this).parent().find(".cl-div-chapter-content-h3-item-header .cl-img-h3-item-image").attr("src","images/Chevron_orange_down.51415ee4.png");
                $(this).parent().find(".cl-div-chapter-content-h3-item-header").find(".cl-div-h3-item-number").css("font-weight", "bold");
                $(this).parent().find(".cl-div-chapter-content-h3-item-header").find(".cl-div-h3-item-title-holder").css("font-weight", "bold");
                // $('html,body').animate({scrollTop: $(this).parent().offset().top}, 'fast');

                return false;
            });

            $(".cl-div-h2-solution-item-pane").on("shown.bs.collapse", function(){
                // $(".cl-div-h2-solution-item-pane").not(this).collapse("hide");
                $(this).parent().find(".cl-div-h2-solution-item-header .cl-img-h2-solution-item-chevron").attr("src","images/MinusIcon.f67ac4cc.png");
                $(this).parent().find(".cl-div-h2-solution-item-header").toggleClass("active");
                $(this).toggleClass("active");
                // alert('Minus');
                var carousel = $(this).find(".carousel");
                var img = $(carousel).find("img");
                $(carousel).carousel();
                $(carousel).carousel('pause');
                $(img).unveil(0, function(){
                    $(this).load(function(){
                        if(Number($(carousel).css('min-width').replace(/[^\d\.\-]/g, '')) < $(carousel).height()){
                            $(carousel).css("min-height",$(carousel).height());
                        }
                    });
                });
                $(img).trigger("unveil");
                $(img).trigger("lookup");

                //$('html,body').animate({scrollTop: $(this).parent().offset().top}, 'fast');
// 
                return false;
             });


             $(".cl-div-h2-solution-item-pane").on("hidden.bs.collapse", function(){
                $(this).parent().find(".cl-div-h2-solution-item-header .cl-img-h2-solution-item-chevron").attr("src","images/PlusIcon.f542cb04.png");
                $(this).parent().find(".cl-div-h2-solution-item-header").toggleClass("active");
                $(this).toggleClass("active");
                // alert('Plus');
                if(deferredOpenElem != null){
                    $(deferredOpenElem).collapse("show");
                    deferredOpenElem = null;
                }

                return false;
             });

            $(".cl-div-h3-solution-item-header").on("click", function(){
                var pane = $(this).parent().find(".cl-div-h3-solution-item-pane");
                var others = $(this).parent().parent().find(".cl-div-h3-solution-item-pane").not(pane);
                $(others).collapse("hide");
                deferredOpenElem = pane;
                $(deferredOpenElem).collapse("show");
                deferredOpenElem = null;
                if($(pane).hasClass("in")){
                    deferredOpenElem = null;
                }

                if(preFetchImages){
                    var img = $(this).parent().next().find("img");
                    $(img).unveil(0);
                    $(img).trigger("unveil");
                    $(img).trigger("lookup");
                }

                return !$(others).hasClass("in");
            });

            $(".cl-div-h2-solution-item-header").on("click", function(){
                var pane = $(this).parent().find(".cl-div-h2-solution-item-pane");
                var others = $(this).parent().parent().find(".cl-div-h2-solution-item-pane").not(pane);
                $(others).collapse("hide");
                deferredOpenElem = pane;
                $(deferredOpenElem).collapse("show");
                deferredOpenElem = null;
                if($(pane).hasClass("in")){
                    deferredOpenElem = null;
                }

                if(preFetchImages){
                    var img = $(this).parent().next().find("img");
                    $(img).unveil(0);
                    $(img).trigger("unveil");
                    $(img).trigger("lookup");
                }

                return !$(others).hasClass("in");
            });

            $(".cl-div-chapter-content-h3-item-header").on("click", function(){
                var pane = $(this).parent().find(".cl-div-chapter-content-h3-item-pane");
                var others = $(this).parent().parent().find(".cl-div-chapter-content-h3-item-pane").not(pane);
                $(others).collapse("hide");
                deferredOpenElem = pane;
                $(deferredOpenElem).collapse("show");
                deferredOpenElem = null;
                if($(pane).hasClass("in")){
                    deferredOpenElem = null;
                }
                return !$(others).hasClass("in");
            });

            $(".cl-div-h3-solution-item-pane").on("shown.bs.collapse", function(){
                // $(".cl-div-h3-solution-item-pane").not(this).collapse("hide");
                $(this).parent().find(".cl-div-h3-solution-item-header .cl-img-h3-solution-item-chevron").attr("src","images/MinusIcon.f67ac4cc.png");
                $(this).parent().find(".cl-div-h3-solution-item-header").toggleClass("active");
                $(this).toggleClass("active");

                var carousel = $(this).find(".carousel");
                var img = $(carousel).find("img");
                $(carousel).carousel("pause");
                $(img).unveil(0, function(){
                    $(this).load(function(){
                        if(Number($(carousel).css('min-width').replace(/[^\d\.\-]/g, '')) < $(carousel).height()){
                            $(carousel).css("min-height",$(carousel).height());
                        }
                    });
                });
                $(img).trigger("unveil");
                $(img).trigger("lookup");
                // $('html,body').animate({scrollTop: $(this).parent().offset().top}, 'fast');

                return false;
             });

             $(".cl-div-h3-solution-item-pane").on("hidden.bs.collapse", function(){
                $(this).parent().find(".cl-div-h3-solution-item-header .cl-img-h3-solution-item-chevron").attr("src","images/PlusIcon.f542cb04.png");
                $(this).parent().find(".cl-div-h3-solution-item-header").toggleClass("active");
                $(this).toggleClass("active");

                if(deferredOpenElem != null){
                    $(deferredOpenElem).collapse("show");
                    deferredOpenElem = null;
                }

                return false;
             });

             $(".cl-btn-h3-solution-item-close").on("click", function(){
                deferredOpenElem = null;
                $(this).parent().parent().collapse("hide");
             });

            $(".cl-btn-h2-solution-item-close").on("click", function(){
                deferredOpenElem = null;
                $(this).parent().parent().collapse("hide");
             });

             $(".cl-link-black-font").on("click",function(ev){
                 ev.stopPropagation();
             });

             $(".cl-div-hx-solution-item-checkbox").on("change", function(ev){
                 // console.log("checkbox changed: "+$(this).parent().parent().parent().parent().attr("data-target"));
                 var save_btn = $(this).parent().parent().parent().parent().parent().parent().parent().find(".cl-btn-hx-footer-save");
                 enable_div_save_button(save_btn);
                 var target = $(this).parent().parent().parent().parent().attr("data-target");
                 target = target.substr(target.indexOf("pane-")+5);
                 var elems = target.split("-");
                 var checkedVal = $(this).prop("checked") === true ? 1: 0 ;

                //Changed to maintain select and deselect history.
                // var parent = $(this).parent();
                // var head_parent = parent.parent().parent();
                // var sol_id=get_solution_id(head_parent);
                // alert(target);
                // var sol_id = target.replace(/\-/g, '.');;
                // // alert(sol_id);
                // if(checkedVal == 1){
                //     var selectionChangeText = "User has checked this solution";
                // }else{
                //     var selectionChangeText = "User has un-checked this solution";
                // }
                // $.post("API.php",{comment:"SET",project_id:G_PROJECT_ID,solution_id:sol_id,text: selectionChangeText, visibility: a_visibility},
                //          function (data) {
                //             if (data.success == true)
                //                 {
                                    
                //                 }
                //          },"json");

                //Code to maintain history of select and deselect Ends here
                console.log('Checked:  ');
                 if(elems.length === 4){
                    updateCreditCountandUI2(elems[0], elems[1], elems[2],elems[3],checkedVal, creditDict, "checked");
                 } else if(elems.length === 3){
                     updateCreditCountandUI2(elems[0], elems[1], -1, elems[2],checkedVal, creditDict, "checked");
                 }

                 ev.stopPropagation();
             });

            /* Review checkbox handler
            This function extracts the corresponding solution text and corresponding header text and populates it on the popup
            */
            $(".candlestick-off").on("click",function(ev){
              ev.stopPropagation();
              var parent = $(this).parent();
              var toggle = parent.find(".candlestick-toggle");
              var on = parent.find(".candlestick-on");
              reset_candlestick(parent);
              on.find(".fa").removeClass("fa-check");
              toggle.addClass("cs-toggle-off");
              parent.addClass("cs-off");
              var ms = Date.now();
              var head_parent = parent.parent().parent();
              $(this).parent().attr("id",ms);
              var sol_id=handle_review_slider(head_parent,ms);
              solIdArray = sol_id.split('.');
              solIdArray = sol_id.split('.');
              if(G_viewReviewerScore) {
                if(solIdArray.length === 4){
                   updateCreditCountandUI2(solIdArray[0], solIdArray[1], solIdArray[2], solIdArray[3], 0, creditDict,"reviewed");
                } else if(solIdArray.length === 3){
                    updateCreditCountandUI2(solIdArray[0], solIdArray[1], -1, solIdArray[2], 0 , creditDict,"reviewed");
                }
              }
            });
            function update_checkbox_value_in_db(value,sol_id){
                // console.log("Updating checkbox value in db..")
                $.post("API.php",{Review_checkbox_value:"SET",project_id:G_PROJECT_ID,solution_id:sol_id,value:value},function(data){
                    if(data.success){
                        G_solution_comment_status.push(sol_id);
                        G_checkbox_values[sol_id] = value;
                    }
              }, "json")
            }
            
            $(".candlestick-on").on("click",function(ev){
              ev.stopPropagation();
              var parent = $(this).parent();
              var toggle = parent.find(".candlestick-toggle");
              var off = parent.find(".candlestick-off");
              reset_candlestick(parent);
              off.find(".fa").removeClass("fa-times");
              toggle.addClass("cs-toggle-on");
              parent.addClass("cs-on");
              var head_parent = parent.parent().parent();
              var sol_id=get_solution_id(head_parent);
              // console.log("Hide the comment..")
              var comment_icon = head_parent.find(".cl-comment-icon");
              comment_icon.css('visibility','visible');
              solIdArray = sol_id.split('.');
              if(G_viewReviewerScore) {
                if(solIdArray.length === 4){
                   updateCreditCountandUI2(solIdArray[0], solIdArray[1], solIdArray[2], solIdArray[3], 1, creditDict,"reviewed");
                } else if(solIdArray.length === 3){
                    updateCreditCountandUI2(solIdArray[0], solIdArray[1], -1, solIdArray[2], 1 , creditDict,"reviewed");
                }
              }
              update_checkbox_value_in_db(-1,sol_id);
            });
            $(".candlestick-nc").on("click",function(ev){
              ev.stopPropagation();
              var parent = $(this).parent();
              reset_candlestick(parent);
              var head_parent = parent.parent().parent();
              var sol_id=get_solution_id(head_parent);
              solIdArray = sol_id.split('.');
              if(G_viewReviewerScore) {
                if(solIdArray.length === 4){
                   updateCreditCountandUI2(solIdArray[0], solIdArray[1], solIdArray[2], solIdArray[3], 0, creditDict,"reviewed");
                } else if(solIdArray.length === 3){
                    updateCreditCountandUI2(solIdArray[0], solIdArray[1], -1, solIdArray[2], 0 , creditDict,"reviewed");
                }
              }
              update_checkbox_value_in_db(0,sol_id);
            });
            function reset_candlestick(parent){
              var toggle = parent.find(".candlestick-toggle");
              var on = parent.find(".candlestick-on");
              var off = parent.find(".candlestick-off");
              parent.removeClass("cs-on");
              parent.removeClass("cs-off");
              toggle.removeClass("cs-toggle-off");
              toggle.removeClass("cs-toggle-on");
              on.find(".fa").addClass("fa-check");
              off.find(".fa").addClass("fa-times");

            }
            function get_solution_id(parent){
              var parent_div = parent;
              var attribute = parent_div.attr("data-target");

              var target = attribute.substr(attribute.indexOf("pane-")+5);
              var elems = target.split("-");
              var sol_id = target.replace(/-/gi,".");
              return sol_id;
            }
            function handle_review_slider(parent,sliderId){
                var parent_div = parent;
                var parent_class = parent_div.attr("class");
                parent_class = parent_class.replace(" active","");
                parent_class = parent_class.replace(" collapsed","");
                var text_class = parent_class.replace("header","text");
                var text = parent_div.find("."+text_class).text();  // Extracting solution text
                var chapter_div = parent_div.parent().parent().parent().parent().parent(); // Obtaining the div where the solution main header presents
                var item_number_class = parent_class.replace("-solution","");
                item_number_class = item_number_class.replace("header","number");
                item_number_class = item_number_class.replace(" collapsed","");
                var item_title_class = item_number_class.replace("number","title");
                item_title_class = item_title_class.replace(" collapsed","");
                var item_number = chapter_div.find("."+item_number_class).text();
                var item_title = chapter_div.find("."+item_title_class).text();
                var attribute = parent_div.attr("data-target");

                var target = attribute.substr(attribute.indexOf("pane-")+5);
                var elems = target.split("-");
                var sol_id = target.replace(/-/gi,".");
                // Displaying comments modal
                var cm_modal_id="#id-sol-comments-modal";
                $("#comments-thread-div").html("");
                $("#comments-thread-div").hide();
                $("#solution-comments-text").val("");
                $("#solution-comments-text").focus();
                $(cm_modal_id).modal("show"); //Displaying solution comments modal
                $(cm_modal_id).attr("data-target",sliderId);
                $(cm_modal_id).attr("sol_id",sol_id);
                $("#id-comment-header").html(""+item_number+" "+item_title); // Dynamically adding item number and title to the modal header
                $("#id-comment-solution").html(text); // Dynamically adding solution text to modal content
                return sol_id;
            }
             $(".cl-div-hx-solution-item-checkbox-review").on("change", function(ev){
                 var ms = Date.now();
                 $(this).attr('id',ms);
                 var checkedVal = $(this).prop("checked") === true ? 1: 0 ;
                 var parent_div = $(this).parent().parent().parent().parent();
                 var parent_class = parent_div.attr("class");
                 parent_class = parent_class.replace(" active","");
                 parent_class = parent_class.replace(" collapsed","");
                 var text_class = parent_class.replace("header","text");
                 var text = parent_div.find("."+text_class).text();  // Extracting solution text
                 var chapter_div = parent_div.parent().parent().parent().parent().parent(); // Obtaining the div where the solution main header presents
                 var item_number_class = parent_class.replace("-solution","");
                 item_number_class = item_number_class.replace("header","number");
                 item_number_class = item_number_class.replace(" collapsed","");
                 var item_title_class = item_number_class.replace("number","title");
                 item_title_class = item_title_class.replace(" collapsed","");
                 var item_number = chapter_div.find("."+item_number_class).text();
                 var item_title = chapter_div.find("."+item_title_class).text();
                 var save_btn = $(this).parent().parent().parent().parent().parent().parent().parent().find(".cl-btn-hx-footer-save");
                 enable_div_save_button(save_btn);
                 var attribute = $(this).parent().parent().parent().parent().attr("data-target");
                 var target = attribute.substr(attribute.indexOf("pane-")+5);
                 var elems = target.split("-");
                 var sol_id = target.replace(/-/gi,".");
                 // Get the comments related to this solution id
                 $.post("API.php",{comment:"GET",project_id:G_PROJECT_ID,solution_id:sol_id},function(data){
                   if(data.success){
                     var cm_modal_id="#id-sol-comments-modal";
                     $("#comments-thread-div").html("");
                     $("#comments-thread-div").hide();
                     $("#solution-comments-text").val("");
                     $("#solution-comments-text").focus();
                     $(cm_modal_id).modal("show"); //Displaying solution comments modal
                     $(cm_modal_id).attr("data-target",ms);
                     $("#id-comment-header").html(""+item_number+" "+item_title); // Dynamically adding item number and title to the modal header
                     $("#id-comment-solution").html(text); // Dynamically adding solution text to modal content

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

                 ev.stopPropagation();
             });
             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);
               navigate_to_projectfb_page();
             });
             $("#project-feedback-btn").unbind().on("click",function(){
               navigate_to_projectfb_page();
             });
             function navigate_to_projectfb_page(){
               var target = "project_feedback.php?edit=true&id=" + G_PROJECT_ID;
               var win = window.open(target,"_blank");
               win.focus();
             }
             $("#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);
               reset_candlestick(slider);
               // Exit out of solution comments box
             });
             function validate_modal_comments(){
                 var comment = $("#solution-comments-text").val();
                 if(comment.trim().length==0)
                  return false;
                 return true;
             }
             $("#id-save-cmnts").unbind().click(function(){
               var cm_modal_id="#id-sol-comments-modal";
               if(validate_modal_comments()){
                 var attr = preprocess_comments_modal_buttons(cm_modal_id);
                 // Save comments to the database and pop notification that the input has been saved
                 // Function to save comments to database

                 var comment = $("#solution-comments-text").val();
                 // 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);
               // Open a new popup showing send this comment or send all comments
               var popup_id="#popup-modal";
               $(popup_id).attr("data-target",attr);
               $(popup_id).attr("sol_id",sol_id);
               $("#id-popup-modal-title").html("Notification");
               $("#send-this-radio-btn").prop('checked', false);
               $("#send-all-radio-btn").prop('checked', false);
               $(popup_id).modal("show");
             });
             // 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){
               var attribute = $("#"+sliderId).parent().parent().attr("data-target");
               var target = attribute.substr(attribute.indexOf("pane-")+5);
               var sol_id = target.replace(/-/gi,".");
               update_checkbox_value_in_db(1,sol_id);
               $.post("API.php",{comment:"SET",project_id:G_PROJECT_ID,solution_id:sol_id,text:comment,visibility:s_visibility},
               function (data) {
                   if (data.success == true)
                   {
                     enable_comment_icon(sliderId);
                     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
               var attribute = $(this).parent().parent().attr("data-target");
               var target = attribute.substr(attribute.indexOf("pane-")+5);
               var sol_id = target.replace(/-/gi,".");
               var ms = Date.now();
               var parent_div = $(this).parent().parent();
               var parent_class = parent_div.attr("class");
               parent_class = parent_class.replace(" active","");
               parent_class = parent_class.replace(" collapsed","");
               var text_class = parent_class.replace("header","text");
               var text = parent_div.find("."+text_class).text();  // Extracting solution text
               var chapter_div = parent_div.parent().parent().parent().parent().parent(); // Obtaining the div where the solution main header presents
               var item_number_class = parent_class.replace("-solution","");
               item_number_class = item_number_class.replace("header","number");
               item_number_class = item_number_class.replace(" collapsed","");
               var item_title_class = item_number_class.replace("number","title");
               item_title_class = item_title_class.replace(" collapsed","");
               var item_number = chapter_div.find("."+item_number_class).text();
               var item_title = chapter_div.find("."+item_title_class).text();
               $(this).attr('id',ms);

               $.post("API.php",{comment:"GET",project_id:G_PROJECT_ID,solution_id:sol_id},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];
                       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);
                       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);
                   $("#id-comment-header").html(""+item_number+" "+item_title); // Dynamically adding item number and title to the modal header
                   $("#id-comment-solution").html(text); // Dynamically adding solution text to modal content

                 }
                 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 sol_id= $(popup_id).attr("sol_id");
               sol_id = typeof sol_id !== "undefined" ? sol_id : $("#id-sol-comments-modal").attr("sol_id");
               var comment = $("#solution-comments-text").val();
               // console.log("Send this radio button clicked for solution id: "+sol_id);
               $.post("API.php",{comment:"SET",project_id:G_PROJECT_ID,solution_id:sol_id,text:comment,visibility:a_visibility},
               function (data) {
                   if (data.success == true)
                   {
                     var cm_modal_id="#id-sol-comments-modal";
                     $(popup_id).modal("hide");
                     var attr = preprocess_comments_modal_buttons(cm_modal_id);
                     enable_comment_icon(attr);
                     update_checkbox_value_in_db(1,sol_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 sol_id= $(popup_id).attr("sol_id");
                var comment = $("#solution-comments-text").val();
                // console.log("Send this radio button clicked for solution id: "+sol_id);
                $(popup_id).modal("hide");
 
                $.post("API.php",{comment:"SET",project_id:G_PROJECT_ID,solution_id:sol_id,text:comment,visibility:s_visibility},
                function (data) {
                     if (data.success == true)
                     {
                         show_splash_popup("Redirecting to Full-Review page","",2); // Popup to display the message
                         var target = "projectfullreview.php?edit=true&id=" + G_PROJECT_ID;
                         var win = window.open(target,"_self");
                     }
                  },"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");
             });
             // Till here
             $(".cl-div-hx-solution-item-checkbox-review").on("click",function(){
               ev.stopPropagation();
             })
              $(".cl-div-h3-solution-item-checkbox-holder, .cl-div-h2-solution-item-checkbox-holder").on("click", function(ev){
                  ev.stopPropagation();
              });

             $(".cl-div-selection-switch-holder").click(function(ev){
                 return false;
             });

             $(".cl-btn-hx-footer-clear").on("click", function(ev){
                 var solutionCheckboxes = $(this).parent().parent().find(".cl-div-hx-solution-item-checkbox");
                 $.each(solutionCheckboxes, function(index, c){
                    if($(c).prop("checked") == true){
                        $(c).prop("checked",false);
                        var target = $(c).parent().parent().parent().parent().attr("data-target");
                        target = target.substr(target.indexOf("pane-")+5);
                        var elems = target.split("-");
                        var checkedVal = 0 ;
                        if(elems.length === 4){
                            updateCreditCountandUI2(elems[0], elems[1], elems[2], elems[3],checkedVal, creditDict,"checked");
                        } else if(elems.length === 3){
                            updateCreditCountandUI2(elems[0], elems[1], -1, elems[2],checkedVal, creditDict, "checked");
                        }
                    }
                 });
             });

             $(".cl-btn-hx-footer-save").on("click", function(ev){
                var target = $(this).attr("id");

                disable_div_save_button(this);

                target = target.substr(target.indexOf("save-")+5);
                var elems = target.split("-");
                var h1 = elems[0];
                var h2 = elems[1];
                if(editMode && (elems.length === 2 || elems.length === 3)){
                     // alert("b4 api ");
                    $.post("API.php", {project: "UPDATE", id :params.id, target: h1+"-"+h2, applicable_credits: G_projectCreditCountApplicable, earned_credits: G_projectCreditCountEarned, bonus_credits: G_projectSolutionsTowardsBonusCount, award_percentage: G_projectAwardPercentage, award_category: "Bronze", h1_credits_applicable: G_h1CreditsArrString, h1_credits_earned: G_h1CreditsArrEarnedString, data: creditDict[h1][h2]} , function (data) {
                        // alert("in api ");
                        if (data.response == true)
                        {
                            // show_splash_popup("Your input was saved","",2);
                            // var selectionChangeText = "";
                            // $.post("API.php",{comment:"SET",project_id:G_PROJECT_ID,solution_id:sol_id,text: selectionChangeText, visibility:s_visibility},
                            //          function (data) {
                            //             if (data.success == true)
                            //                 {
                            //                     enable_comment_icon(sliderId);
                            //                     show_splash_popup("Your input was saved","",2); // Popup to display the message
                            //                 }
                            //          },"json");
                        }
                        // else{
                        //     show_splash_popup("Your input was not saved","",2);
                        // }
                    },"json");
                }
             });

             //$(".cl-slider-flip-m").not("#id-div-chapter-content-h2-holder-dummy .ui-flipswitch").flipswitch();

             $(".cl-slider-flip-m").on("change",function(){
                 var selVal = $(this).find("option:selected").text();
                 // console.log("FlipSwitch ID: "+$(this).attr("id")+" val : "+selVal);
                var target = $(this).attr("id");
                 target = target.substr(target.indexOf("-m-")+3);
                 var elems = target.split("-");
                 // if length is 2 then it is SECOND level toggle switch
                 // if length is 3 then it is THIRD level toggle switch
                 if (elems.length == 2)
                 {
                    $(this).parents(".cl-div-chapter-content-h2-item-true").find(".cl-div-hx-solution-item-checkbox:checked").click();
                    if(selVal ==="Yes"){
                        $(this).parents(".cl-div-chapter-content-h2-item-true").find(".cl-form-solution-checkbox").removeClass("disabled");
                        $(this).parents(".cl-div-chapter-content-h2-item-true").removeClass("unmarked");
                        // $(this).parents(".cl-div-chapter-content-h2-item-true").find(".cl-slider-flip-m").show();
                        updateCreditApplicableCountAndUI(elems[0],elems[1],-1,true,true);
                    } else {
                        $(this).parents(".cl-div-chapter-content-h2-item-true").find(".cl-form-solution-checkbox").addClass("disabled");
                        $(this).parents(".cl-div-chapter-content-h2-item-true").addClass("unmarked");
                        // $(this).parents(".cl-div-chapter-content-h2-item-true").find(".cl-slider-flip-m").hide();
                        var level_3_buttons = $(this).parent().parent().parent().parent().parent().parent().parent().find('.cl-slider-flip-m');
                        disable_level_3_buttons(level_3_buttons);
                        updateCreditApplicableCountAndUI(elems[0],elems[1],-1,false,true);
                    }
                 }
                 else if (elems.length == 3)
                 {
                    $(this).parents(".cl-div-chapter-content-h3-item-true").find(".cl-div-hx-solution-item-checkbox:checked").click();
                    if(selVal ==="Yes"){
                        $(this).parents(".cl-div-chapter-content-h3-item-true").find(".cl-form-solution-checkbox").removeClass("disabled");
                        $(this).parents(".cl-div-chapter-content-h3-item-true").removeClass("unmarked");
                        var level_2_buttons = $(this).parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().find('.cl-slider-flip-m');
                        enable_level_2_button(level_2_buttons);
                        updateCreditApplicableCountAndUI(elems[0],elems[1],elems[2],true,true);
                    } else {
                        $(this).parents(".cl-div-chapter-content-h3-item-true").find(".cl-form-solution-checkbox").addClass("disabled");
                        $(this).parents(".cl-div-chapter-content-h3-item-true").addClass("unmarked");
                        updateCreditApplicableCountAndUI(elems[0],elems[1],elems[2],false,true);
                    }
                 }

             });

            if(initialFetchChapterCount < 9){
                $(chapterElem).next().click();
            }

            if(initialFetchChapterCount == 9){
                $("#id-div-solution-chapter-holder").find(".cl-div-solution-chapter-list-item").first().click();
            }

            if(initialFetchChapterCount > 9){
                $(loadingMsgContainer).css("display", "none");

                if(G_isud_status != 0 || G_USER_AUTH_LEVEL >= 3){ //!G_IS_PROJECT_OWNER ){
                    //lock and disable checkboxes and flipswitches
                    $(".checkbox").addClass("disabled"); // Disabling customer's checkboxes
                    $(".cl-div-selection-switch-holder").addClass("disabled");
                    $(".cl-div-lock-status-holder").css("display", "flex");
                    if((G_isud_status != 2 && G_USER_AUTH_LEVEL >= 3)){ //!G_IS_PROJECT_OWNER)){
                        $(".cl-div-hx-footer").css("display","none");
                        $(".cl-div-hx-footer").addClass("disabled");    
                    }
                    $(".cl-btn-hx-footer-clear").addClass("disabled");
                    if(G_isud_status != 2 || G_isud_status!=3 || G_USER_AUTH_LEVEL >= 3){//!G_IS_PROJECT_REVIEWER){
                      $(".cl-div-hx-solution-item-checkbox-review").addClass("disabled");
                    }
                } else {
                  $(".cl-div-lock-status-holder").css("display", "none");

                }

                initialFetchChapterCount = 100;
            }

            
            // $.post("API.php", { Review_checkbox_value: "GET_ALL", project_id : G_PROJECT_ID }, function (data) {
                
            //     if(data.success){

            //         datas = data.review_checkbox_values;

            //         $.each(datas, function(key, val) {
                        
            //              if(val == '1'){
            //                 // alert(val);
            //                 sol_id = key.replace(/\./g, '-');
            //                 id_num = sol_id.replace(/-/g,'').length -1;

            //                 var p_id = '#id-div-h'+id_num+'-solution-item-'+sol_id;

            //                 if(G_isud_status == 0 || (G_IS_PROJECT_OWNER && G_isud_status == 2 )){

            //                     $(p_id+" .checkbox").removeClass("disabled");
                              
            //                 }
            //              }
                        
            //         });
            //     }

            // },"json");

            //  $.each(data, function (i, e){
            //     d = e.header.h2_elems;

            //     $.each(d, function (index, e2) {
            //         var newH2Elem = $(h2elem).clone();

            //     }
            // }

        }, "json");
    



        // hide_chapter_details(chapter);
}

function updateCreditCountandUI2(h1, h2, h3, solution, checked, checkedDict, scoreVar) {

    var crDict = checkedDict[h1][h2];
    var h3EarnedCredits = 0;
    var h3SolutionCount = 0;

    if(h3<=0) {
        crDict[solution][scoreVar] = checked;
        crDict.checked_solutions = getScoreCount(crDict,scoreVar);
        creditsAndBonus = getEarnedCreditAndBonusCountUsingThreshold(crDict.thresholds, crDict.thresholdLevels, crDict.checked_solutions);
        crDict.earned_credits = creditsAndBonus[0]; crDict.solutions_bonus = creditsAndBonus[1];
    }

    else {
        crDict[h3][solution][scoreVar] = checked;
        crDict[h3].checked_solutions = getScoreCount(crDict[h3],scoreVar);
        crDict.checked_solutions = getScoreAndBonusCountForH2sHavingH3s(crDict,scoreVar);

        creditsAndBonus = getEarnedCreditAndBonusCountUsingThreshold(crDict[h3].thresholds,crDict[h3].thresholdLevels ,crDict[h3].checked_solutions)
        h3EarnedCredits = crDict[h3].earned_credits = creditsAndBonus[0];
        h3SolutionCount = crDict[h3].checked_solutions;
        crDict[h3].solutions_bonus = creditsAndBonus[1];

        creditsAndBonus = getCreditAndScoreForH2HavingH3(crDict);
        crDict.earned_credits = creditsAndBonus[0]; crDict.solutions_bonus = creditsAndBonus[1]
    }

    creditAndBonusListForH1 = getEarnedCreditAndBonusCount(checkedDict[h1])
    checkedDict[h1].earned_credits = creditAndBonusListForH1[0]
    checkedDict[h1].solutions_bonus = creditAndBonusListForH1[1]

    credits = getH1CreditsAndStoreInGlobalVars(checkedDict);
    var earnedCredits = credits[0]; var availCredits = credits[1]; var bonus = credits[2];

    var percentage = Math.round (earnedCredits * 100 / availCredits);
    percentage = percentage + bonus;
    var temp_percentage = percentage>100?100:percentage; // if percentage is above 100% it breaks the progress circle

    G_projectAwardPercentage = percentage;

    updateCreditCountandUI(h1, h2, h3, solution, checked);
    updateCreditsAndScoreUI(h3EarnedCredits, h3SolutionCount, crDict.earned_credits, crDict.checked_solutions, checkedDict[h1].earned_credits, earnedCredits, bonus, percentage, temp_percentage, h1, h2, h3);
}

function updateCreditsAndScoreUI(h3EarnedCredits, h3CheckedSolutions, h2EarnedCredits,
  h2CheckedSolutions, h1EarnedCredits, projectEarnedCredits, projectBonus, percentage, temp_percentage, h1, h2, h3){

  var solutionHolderDivID = "#id-div-chapter-content-h2-item-{0}-{1}".format(h1,h2);

  var creditsEarnedSpan = $(solutionHolderDivID).find(".cl-div-ratio-rounded-elem-left span").first();
  var solutionsSelectedCountSpan = $(solutionHolderDivID).find(".cl-div-ratio-rounded-elem-left span").first();
  var sidebarCreditRatioHolder = $("#id-div-chapter-credit-implemented-ratio-holder-{0}".format(h1)).find(".cl-div-ratio-rounded-elem-left span");

  var projectCreditRatioEarned = $("#id-div-project-award-credit-earned").find(".cl-span-project-award-credit-item-value");
  var projectCreditBonusEarned = $("#id-div-project-award-credit-bonus").find(".cl-span-project-award-credit-item-value");

  var solutionHolderDivID_level3 = "#id-div-chapter-content-h3-item-{0}-{1}-{2}".format(h1,h2,h3);
  var creditsEarnedSpan_level3 = $(solutionHolderDivID_level3).find(".cl-div-ratio-rounded-elem-left span").first();
  var solutionsSelectedCountSpan_level3 = $(solutionHolderDivID_level3).find(".cl-div-ratio-rounded-elem-left span").first();

  creditsEarnedSpan_level3.html(h3EarnedCredits);
  solutionsSelectedCountSpan_level3.html(h3CheckedSolutions);

  creditsEarnedSpan.html(h2EarnedCredits);
  solutionsSelectedCountSpan.html(h2CheckedSolutions);

  sidebarCreditRatioHolder.html(h1EarnedCredits);
  sidebarCreditRatioHolder.html(h1EarnedCredits)

  projectCreditRatioEarned.html(projectEarnedCredits);
  projectCreditBonusEarned.html(projectBonus);

  pbar.setText(Math.floor(percentage));
  pbar.set(Math.floor(temp_percentage)/100);

//   pbar.setText(Math.floor(percentage));
//   pbar.set(Math.floor(temp_percentage)/100);
}

function getScoreCount(creditDict,scoreVar) {
  solutionCheckedCount = 0;
  $.each(creditDict, function(index,h){
      if((typeof h === "object") && !$.isArray(h)) {
          solutionCheckedCount += h[scoreVar];
      }
  });
  return solutionCheckedCount;
}

function getScoreAndBonusCountForH2sHavingH3s(creditDict,scoreVar){
  solutionCheckedCount_lowerLevel = 0;
  solutionCheckedCount = 0;
  $.each(creditDict, function(index,h){
      if((typeof h === "object") && !$.isArray(h) && !(scoreVar in h)){  // has a h3 level
          solutionCheckedCount_lowerLevel = 0;
          $.each(h, function(i, s){
              if((typeof s === "object") && !$.isArray(s) && (scoreVar in s)){
                  // solutionCheckedCount += s.checked;
                  solutionCheckedCount_lowerLevel += s[scoreVar];
              }
          });
          solutionCheckedCount += solutionCheckedCount_lowerLevel;
      }
  });
  return solutionCheckedCount;
}

function getCreditAndScoreForH2HavingH3(creditDict){
  creditsEarnedCount = 0;
  excessSolutionsTowardsBonus = 0;

  $.each(creditDict, function(index, h){
      if((typeof h === "object") && !$.isArray(h) && ("earned_credits" in h)){
          creditsEarnedCount += h.earned_credits;
          excessSolutionsTowardsBonus += h.solutions_bonus;
      }
  });
  return [creditsEarnedCount, excessSolutionsTowardsBonus];
}

function getH1CreditsAndStoreInGlobalVars(creditDict){

    earnedCreditList = []
    availableCreditList = []
    earnedCreditCount = 0;
    availableCreditCount = 0;
    bonusSolMarked = 0;
    earnedCreditCsv = '';
    availableCreditCsv = '';

    $.each(creditDict, function(index,elem){
      if(typeof elem == 'object' && !$.isArray(elem) && ("earned_credits" in elem)){

        availableCredits = elem.applicable_credits;
        earnedCredits = elem.earned_credits;

        availableCreditCount += availableCredits;
        earnedCreditCount += earnedCredits;
        bonusSolMarked += elem.solutions_bonus;

        earnedCreditList.push(earnedCredits)
        availableCreditList.push(availableCredits)

        earnedCreditCsv += earnedCredits + ","
        availableCreditCsv += availableCredits + ","

      }
    });

    G_h1CreditsArrEarnedString = earnedCreditCsv.substr(0,earnedCreditCsv.length-1);
    G_h1CreditsArrEarned = earnedCreditList;

    G_h1CreditsArrApplicableString = availableCreditCsv.substr(0,availableCreditCsv.length-1);
    G_h1CreditsArr = availableCreditList;

    G_projectSolutionsTowardsBonusCount = bonusSolMarked;
    bonusSolMarked = (bonusSolMarked > 50) ? 10 : Math.floor(bonusSolMarked/5);


    return [earnedCreditCount, availableCreditCount, bonusSolMarked]
}

function getEarnedCreditAndBonusCountUsingThreshold(threshold, thresholdLevel, currentCount){
    var bonusCount = 0;
    var creditsEarned = 0;

    for(var index=0; index<threshold.length; index++){
        if(currentCount >= threshold[index]){
            bonusCount = threshold[index];
            creditsEarned = thresholdLevel[index];
        }
    }
    bonusCount = currentCount - bonusCount;
    return [creditsEarned,bonusCount];
}

function getEarnedCreditAndBonusCount(creditDict){
    var earnedCreditCount = 0;
    var earnedBonusCount = 0;
    $.each(creditDict, function(index,elem) {
        if((typeof elem == "object") && !$.isArray(elem) && ("earned_credits" in elem)){
            earnedCreditCount += elem.earned_credits;
            earnedBonusCount += elem.solutions_bonus;
        }
    });
    return [earnedCreditCount, earnedBonusCount];
}

// TODO: Remove this function and rename the updateCreditCountandUI2 function as updateCreditCountandUI.

// checked = 0 [unchecked]
// checked = 1 [checked]
function updateCreditCountandUI(h1, h2, h3, solution, checked){
    // alert('entered');
    var solutionRatioHolder = $("#id-div-chapter-content-h2-item-"+h1+"-"+h2).find(".cl-div-implemented-ratio-holder");
    var creditRatioHolder = $("#id-div-chapter-content-h2-item-"+h1+"-"+h2).find(".cl-div-earned-ratio-holder");

    // we need to take the 'first' element because in case of level 2 toggle buttons(which has level 3 toggle button e.g. 4-1-1 )
    // below jquery'find' returns array of controls
    // and then code that follows updates the earned credits wrongly for level 3 sub-headers e.g. 4-1-1
    var creditRatioEarned = $(creditRatioHolder).find(".cl-div-ratio-rounded-elem-left span").first();
    // same as above
    var solutionRatioEarned = $(solutionRatioHolder).find(".cl-div-ratio-rounded-elem-left span").first();

    if(h3>0)
    {
        var solutionRatioHolder_level3 = $("#id-div-chapter-content-h3-item-"+h1+"-"+h2+"-"+h3).find(".cl-div-implemented-ratio-holder");
        var creditRatioHolder_level3 = $("#id-div-chapter-content-h3-item-"+h1+"-"+h2+"-"+h3).find(".cl-div-earned-ratio-holder");
        var solutionRatioEarned_level3 = $(solutionRatioHolder_level3).find(".cl-div-ratio-rounded-elem-left span");
        var creditRatioEarned_level3 = $(creditRatioHolder_level3).find(".cl-div-ratio-rounded-elem-left span");
    }

    var solutionCheckedCount = 0;
    var solutionCheckedCount_lowerLevel = 0;
    var creditsEarnedCount = 0;

    var excessSolutionsTowardsBonus = 0;

    if(h3<=0){
        creditDict[h1][h2][solution].checked = checked;

        $.each(creditDict[h1][h2], function(index,h){
            if((typeof h === "object") && !$.isArray(h)) {
                solutionCheckedCount += h.checked;
            }
        });
        creditDict[h1][h2].checked_solutions = solutionCheckedCount;
        excessSolutionsTowardsBonus += creditDict[h1][h2].checked_solutions;
        var maxThreshold = 0;

        for (var index = 0; index < creditDict[h1][h2].thresholds.length; index++) {
            var element = creditDict[h1][h2].thresholds[index];
            if(creditDict[h1][h2].checked_solutions >= element){
                creditsEarnedCount = creditDict[h1][h2].thresholdLevels[index];
                maxThreshold = element;
            } else {
                break;
            }
        }
        excessSolutionsTowardsBonus -= maxThreshold;
        creditDict[h1][h2].earned_credits = creditsEarnedCount;
        creditDict[h1][h2].solutions_bonus = excessSolutionsTowardsBonus;


    } else {
        creditDict[h1][h2][h3][solution].checked = checked;
        var solutionCheckedCount_level3 = 0;
        $.each(creditDict[h1][h2][h3], function(index,h){
            if((typeof h === "object") && !$.isArray(h)) {
                solutionCheckedCount_level3 += h.checked;
            }
        });


        $.each(creditDict[h1][h2], function(index,h){
            if((typeof h === "object") && !$.isArray(h) && !("checked" in h)){  // has a h3 level
                solutionCheckedCount_lowerLevel = 0;
                $.each(h, function(i, s){
                    if((typeof s === "object") && !$.isArray(s) && ("checked" in s)){
                        // solutionCheckedCount += s.checked;
                        solutionCheckedCount_lowerLevel += s.checked;
                    }
                });
                solutionCheckedCount = solutionCheckedCount + solutionCheckedCount_lowerLevel;
            }
        });

        creditDict[h1][h2][h3].checked_solutions = solutionCheckedCount_level3;
        excessSolutionsTowardsBonus += creditDict[h1][h2][h3].checked_solutions;
        var maxThreshold = 0;

        for (var index = 0; index < creditDict[h1][h2][h3].thresholds.length; index++) {
            var element = creditDict[h1][h2][h3].thresholds[index];
            if(creditDict[h1][h2][h3].checked_solutions >= element){
                creditsEarnedCount = creditDict[h1][h2][h3].thresholdLevels[index];
                maxThreshold = element;
            } else {
                break;
            }
        }
        excessSolutionsTowardsBonus -= maxThreshold;
        creditDict[h1][h2][h3].earned_credits = creditsEarnedCount;
        creditDict[h1][h2][h3].solutions_bonus = excessSolutionsTowardsBonus;

        // update HTML i.e. UI
        creditRatioEarned_level3.html(creditsEarnedCount);
        solutionRatioEarned_level3.html(solutionCheckedCount_level3);
        console.log(solutionCheckedCount_level3);

        // For level 2 we need to show the 0 solutions if it has level-3 headers
        // solutionCheckedCount = 0;

        // calculate for level 2
        creditsEarnedCount = 0;
        excessSolutionsTowardsBonus = 0;
        $.each(creditDict[h1][h2], function(index, h){
            if((typeof h === "object") && !$.isArray(h) && ("earned_credits" in h)){
                creditsEarnedCount += h.earned_credits;
                excessSolutionsTowardsBonus += h.solutions_bonus;
            }
        });
        creditDict[h1][h2].earned_credits = creditsEarnedCount;
        creditDict[h1][h2].solutions_bonus = excessSolutionsTowardsBonus;


    }

    //Update chapter credits
    var chapterCreditRatioHolder = $("#id-div-chapter-credit-implemented-ratio-holder-"+h1);
    var chapterCreditRatioEarned = chapterCreditRatioHolder.find(".cl-div-ratio-rounded-elem-left span");
    var chapterCreditCount = 0;
    var chapterExcessSolutionsTowardsBonus = 0;

    $.each(creditDict[h1], function(index, elem){
        if((typeof elem === "object") && !$.isArray(elem) && ("earned_credits" in elem)){
            chapterCreditCount += elem.earned_credits;
            chapterExcessSolutionsTowardsBonus += elem.solutions_bonus;
        }
    });
    creditDict[h1].earned_credits = chapterCreditCount;
    creditDict[h1].solutions_bonus = chapterExcessSolutionsTowardsBonus;

    //Update project credits
    var projectCreditRatioEarned = $("#id-div-project-award-credit-earned").find(".cl-span-project-award-credit-item-value");
    var projectCreditBonusEarned = $("#id-div-project-award-credit-bonus").find(".cl-span-project-award-credit-item-value");
    var projectCreditCountApplicable = 0;
    var projectCreditCountEarned = 0;
    var projectExcessSolutionsTowardsBonus = 0;

    var h1_credits_applicable = '';
    var h1_credits_earned = '';

    $.each(creditDict, function(index, elem){
        if((typeof elem === "object") && !$.isArray(elem) && ("earned_credits" in elem)){
            projectCreditCountEarned += elem.earned_credits;
            projectCreditCountApplicable += elem.applicable_credits;
            projectExcessSolutionsTowardsBonus += elem.solutions_bonus;
            h1_credits_earned += elem.earned_credits+",";
            h1_credits_applicable += elem.applicable_credits+",";
        }
    });

    h1_credits_earned = h1_credits_earned.substr(0,h1_credits_earned.length-1);
    h1_credits_applicable = h1_credits_applicable.substr(0,h1_credits_applicable.length-1);
    G_h1CreditsArr = h1_credits_applicable.split(",");
    G_h1CreditsArrEarned = h1_credits_earned.split(",");
    G_h1CreditsArrEarnedString = h1_credits_earned;
    G_h1CreditsArrApplicableString = h1_credits_applicable;
    G_projectSolutionsTowardsBonusCount = projectExcessSolutionsTowardsBonus;
    var bonus = G_projectSolutionsTowardsBonusCount > 50 ? 10 : Math.floor(G_projectSolutionsTowardsBonusCount/5);

    chapterCreditRatioEarned.html(chapterCreditCount);
    solutionRatioEarned.html(solutionCheckedCount);
    creditRatioEarned.html(creditsEarnedCount);
    projectCreditRatioEarned.html(projectCreditCountEarned);
    projectCreditBonusEarned.html(bonus);

    var percentage = Math.round (projectCreditCountEarned * 100 / projectCreditCountApplicable);
    percentage = percentage + bonus;

    // earlier implementation
    // pbar.setText(Math.floor(percentage + bonus) + "%");
    // pbar.set(Math.floor(percentage + bonus)/100);

    // new implementation this renoves the bonus parts which causes percentage to rise above 100%
    // pbar.setText(Math.floor(percentage));
    var temp_percentage = percentage>100?100:percentage; // if percentage is above 100% it breaks the progress circle
    // pbar.set(Math.floor(temp_percentage)/100);
    // alert(projectCreditCountEarned);
    pbar.setText(Math.floor(percentage));
    pbar.set(Math.floor(temp_percentage)/100);
    G_projectCreditCountEarned = projectCreditCountEarned;
    G_projectAwardPercentage = percentage;
}

function updateCreditApplicableCountAndUI(h1,h2,h3,applicable, updateDB){
    if ( h3 === -1 )
    {
        // we need to take the 'first' element because in case of level 2 toggle buttons(which has level 3 toggle button e.g. 4-1-1 )
        // below jquery'find' returns array of controls
        // and then code that follows updates the earned credits wrongly for level 3 sub-headers e.g. 4-1-1
        var creditRatioHolder = $("#id-div-chapter-content-h2-item-"+h1+"-"+h2).find(".cl-div-earned-ratio-holder").first();
        var tempCreditDict = creditDict[h1][h2];
    }
    else
    {
        var creditRatioHolder = $("#id-div-chapter-content-h3-item-"+h1+"-"+h2+"-"+h3).find(".cl-div-earned-ratio-holder");
        // id-div-chapter-content-h3-item-4-1-1
        var tempCreditDict = creditDict[h1][h2][h3];
    }


    var creditRatioApplicable = $(creditRatioHolder).find(".cl-div-ratio-square-elem-right span");

    var chapterCreditRatioHolder = $("#id-div-chapter-credit-implemented-ratio-holder-"+h1);
    var chapterCreditRatioApplicable = chapterCreditRatioHolder.find(".cl-div-ratio-square-elem-right span");
    var chapterCreditCount = 0;

    var projectCreditRatioAvailable = $("#id-div-project-award-credit-available").find(".cl-span-project-award-credit-item-value");
    var projectProgressContainer = $("#id-div-project-award-progress-container");
    var projectCreditCountApplicable = 0;
    var projectCreditCountEarned = 0;
    var h1_credit_arr = '';

    tempCreditDict.applicable_credits = applicable ? tempCreditDict.total_credits : 0;
    tempCreditDict.enabled = applicable;
    $.each(tempCreditDict, function(index, elem){
        if((typeof elem === "object") && !$.isArray(elem) && ("applicable_credits" in elem)){
            elem.applicable_credits = ( applicable && elem.enabled ) ? elem.total_credits : 0;
            elem.solutions_bonus = ( applicable && elem.enabled )? elem.solutions_bonus : 0;
            G_projectSolutionsTowardsBonusCount -= applicable ? 0 : elem.checked_solutions;
        }
    });

    // calculate the applicable credits for given chapter
    $.each(creditDict[h1], function(index, elem){
        if((typeof elem === "object") && !$.isArray(elem) && ("applicable_credits" in elem)){
            if( (typeof elem[1] !== 'undefined') && "applicable_credits" in elem[1])
            {
                $.each(elem, function(index, elem_level2)
                {
                  if((typeof elem_level2 === "object") && !$.isArray(elem_level2) && ("applicable_credits" in elem_level2)){
                      chapterCreditCount += elem_level2.applicable_credits;
                  }
                })
            }
            else
            {
                chapterCreditCount += elem.applicable_credits;
            }
        }
    });
    // update the dictionary with the calculated applcable credits above
    creditDict[h1].applicable_credits = chapterCreditCount;

    $.each(creditDict, function(index, elem){
        if((typeof elem === "object") && !$.isArray(elem) && ("applicable_credits" in elem)){
            projectCreditCountApplicable += elem.applicable_credits;
            projectCreditCountEarned += elem.earned_credits;
            h1_credit_arr += elem.applicable_credits+",";
        }
    });

    h1_credit_arr = h1_credit_arr.substr(0,h1_credit_arr.length-1);
    // moving below line at the end of the function
    // creditDict[h1][h2].enabled = applicable ? true : false;


    $(creditRatioApplicable).html("of "+tempCreditDict.applicable_credits);
    $(chapterCreditRatioApplicable).html("of "+chapterCreditCount);
    $(projectCreditRatioAvailable).html(projectCreditCountApplicable);
    var bonus = G_projectSolutionsTowardsBonusCount > 50 ? 10 : Math.floor(G_projectSolutionsTowardsBonusCount/5);

    var percentage = Math.round( projectCreditCountEarned * 100 / projectCreditCountApplicable );
    percentage = percentage + bonus;

    // pbar.setText(Math.floor(percentage));
    var temp_percentage = percentage>100?100:percentage;
    // pbar.set(Math.floor(temp_percentage)/100);

    G_projectCreditCountApplicable = projectCreditCountApplicable;
    G_projectAwardPercentage = percentage;
    G_h1CreditsArrString = h1_credit_arr;
    G_h1CreditsArr = G_h1CreditsArrString.split(",");

    if ( h3 === -1 )
    {
        target = h1+"-"+h2;
        creditDict[h1][h2].enabled = applicable ? true : false;
        data = creditDict[h1][h2];
    }
    else
    {
        target = h1+"-"+h2+"-"+h3;
        creditDict[h1][h2][h3].enabled = applicable ? true : false;
        data = creditDict[h1][h2][h3];
    }

    if(editMode && updateDB){
        $.post("API.php", {project: "UPDATE", id :params.id, target: target, applicable_credits: G_projectCreditCountApplicable, earned_credits: G_projectCreditCountEarned, bonus_credits: G_projectSolutionsTowardsBonusCount, award_percentage: G_projectAwardPercentage, award_category: "Bronze", h1_credits_applicable: G_h1CreditsArrString, h1_credits_earned: G_h1CreditsArrEarnedString, data: data /*creditDict[h1][h2]*/} , function (data) {
        },"json");
    }
}

function fillGlobalDataFromDB(id){
    $.post("API.php", {project: "DETAILS", id :id}, function (data) {
        var d = data[0];
        set_title(d.project_title);

        G_projectAwardPercentage = parseFloat(d.award_percentage);
        G_projectSolutionsTowardsBonusCount = parseInt(d.bonus_credits, 10);
        G_projectCreditCountApplicable = parseInt(d.applicable_credits, 10);
        G_projectCreditCountEarned = parseInt(d.earned_credits, 10);
        G_h1CreditsArrString = d.h1_credits_applicable;
        G_h1CreditsArr = G_h1CreditsArrString.split(",");
        G_h1CreditsArrEarnedString = d.h1_credits_earned;
        G_h1CreditsArrEarned = G_h1CreditsArrEarnedString.split(",");
        G_isud_status = parseInt(d.isud_status, 10);
        G_project_scope = parseInt(d.project_scope,10);
        G_IS_PROJECT_OWNER = d.is_requesting_user_owner;
        G_IS_PROJECT_REVIEWER = d.is_requesting_user_reviewer;
        G_USER_AUTH_LEVEL = d.project_permission_id;
        show_hide_client_reviewer_divs();
        
        delete d.h1_credits;
        delete d.award_percentage;
        delete d.award_category;
        delete d.bonus_credits;
        delete d.earned_credits;
        delete d.applicable_credits;
        delete d.innovative_credits;
        delete d.innovative_credits_submitted_count;
        delete d.project_id;
        delete d.h1_credits_applicable;
        delete d.h1_credits_earned;

        var header_mask = d.header_mask;
        delete d.header_mask;

        var header_mask_dict = {};
        header_mask_dict = build_header_mask_dict(header_mask);
        activateClientOrReviewerScore()
        /*
        var header_mask_h1 = header_mask.split(";");
         $.each(header_mask_h1, function(index,val){
            var header_mask_h2 = val.split(",");
            header_mask_arr[index+1] = {};
            $.each(header_mask_h2, function(index2,val2){
                header_mask_arr[index+1][index2+1] = parseInt(val2,10);
            });
        });
        */
       $.post("API.php",{comment:"GET_SOLUTIONS_STATUS",project_id:G_PROJECT_ID},function(data){
            G_solution_comment_status = data.solutions;
        },"json");

        creditDict = build_credit_dict(d,header_mask_dict);
        if(G_IS_PROJECT_REVIEWER) {
          if(G_viewReviewerScore) creditDict = addReviewerScoreToCreditDict(creditDict);
          $(".cl-switch-reviewer-score").flipswitch();
          $(".cl-div-switch-reviewer-score").css('display','block');
        }
        getChapters();

    },"json");
}

function activateClientOrReviewerScore(){
    $(".score-switch-holder-items").removeClass("solutions-active-link");
    if(G_IS_PROJECT_REVIEWER){
        G_viewReviewerScore = true;
        $("#title-bar-reviewer-score").addClass("solutions-active-link");
    }else{
        G_viewReviewerScore = false;
        {$("#title-bar-client-score").addClass("solutions-active-link");}
    }
}

function addReviewerScoreToCreditDict(creditDict) {
    $.each(G_checkbox_values, function(index, solution){
        s = index.split('.');
        if(s.length == 3) {
            solution == -1 ? creditDict[s[0]][s[1]][s[2]].reviewed = 1 :
             creditDict[s[0]][s[1]][s[2]].reviewed = 0;
        } else if(s.length == 4) {
            solution == -1 ? creditDict[s[0]][s[1]][s[2]][s[3]].reviewed = 1
              : creditDict[s[0]][s[1]][s[2]][s[3]].reviewed = 0;
        }
    });
    return creditDict;
}

var build_credit_dict = function(project_details,header_mask_dict)
{
    var sol;
    var splits = [];
    var credit_dict = {};
    for (var key in project_details)
    {
        if (project_details.hasOwnProperty(key) )
        {
            sol = project_details[key];
            splits = key.split("_").splice(1);

            if ( ($.isNumeric(splits[0]) == true) && (splits.length === 3 || splits.length === 4) )
            {
                if(typeof credit_dict[splits[0]] === "undefined")
                {
                    var creditH1Dict = {};
                    creditH1Dict.earned_credits = parseInt(typeof G_h1CreditsArrEarned[parseInt(splits[0],10)-1] === "undefined" ? 0 : G_h1CreditsArrEarned[parseInt(splits[0],10)-1], 10);
                    creditH1Dict.total_credits = 0;
                    creditH1Dict.solutions_bonus = 0;
                    creditH1Dict.applicable_credits = parseInt(typeof G_h1CreditsArr[parseInt(splits[0],10)-1] === "undefined" ? 0 : G_h1CreditsArr[parseInt(splits[0],10)-1], 10);
                    creditH1Dict.enabled = header_mask_dict[splits[0]].enabled;
                    credit_dict[splits[0]] = creditH1Dict;
                }

                if(typeof credit_dict[splits[0]][splits[1]] === "undefined")
                {
                    temp_dict = build_empty_h2_h3_dict();
                    temp_dict.enabled = header_mask_dict[splits[0]][splits[1]].enabled;
                    credit_dict[splits[0]][splits[1]] = temp_dict;
                }

                if(splits.length === 3) //h2 Solution
                {
                    if(typeof credit_dict[splits[0]][splits[1]][splits[2]] === "undefined")
                    {
                        var solutionDict = {};
                        solutionDict.checked = parseInt(project_details[key]);
                        // TODO: Remove after the server returns correct values, right now we are getting 0 values for solution that don't exist.
                        solutionDict.reviewed = 0;
                        credit_dict[splits[0]][splits[1]][splits[2]] = solutionDict;
                    }
                }
                else if (splits.length === 4) //h3 Solution
                {
                    if(typeof credit_dict[splits[0]][splits[1]][splits[2]] === "undefined")
                    {
                        temp_dict = build_empty_h2_h3_dict();
                        temp_dict.enabled = header_mask_dict[splits[0]][splits[1]][splits[2]].enabled;
                        credit_dict[splits[0]][splits[1]][splits[2]] = temp_dict;
                    }

                    if(typeof credit_dict[splits[0]][splits[1]][splits[2]][splits[3]] === "undefined")
                    {
                        var solutionDict = {};
                        solutionDict.checked = parseInt(project_details[key]);
                        // TODO: Remove after the server returns correct values, right now we are getting 0 values for solution that don't exist.
                        solutionDict.reviewed = 0;
                        credit_dict[splits[0]][splits[1]][splits[2]][splits[3]] = solutionDict;
                    }
                }
            }
        }
    }
    return credit_dict;
}

var build_empty_h2_h3_dict = function()
{
    var h2_h3_dict = {};
    h2_h3_dict.earned_credits = 0;
    h2_h3_dict.total_credits = 0;
    h2_h3_dict.applicable_credits = 0;
    h2_h3_dict.total_solutions = 0;
    h2_h3_dict.checked_solutions = 0;
    h2_h3_dict.solutions_bonus = 0;
    h2_h3_dict.thresholds = [];
    h2_h3_dict.thresholdLevels = [];
    return h2_h3_dict;
}

var build_header_mask_dict = function(header_mask)
{
	var header_mask_dict = {};

    var header_mask_h1 = header_mask.split(";");
    $.each(header_mask_h1, function(index_h1,val_1)
    {
        var header_mask_h2 = val_1.split(",");
        header_mask_dict[index_h1+1] = {};
        header_mask_dict[index_h1+1].enabled = true;

        $.each(header_mask_h2, function(index_h2,val_2)
        {
        	var temp_mask_h2_dict = {};
        	temp_mask_h2_dict.enabled = parseInt(val_2,10)? true:false;

            if(typeof header_mask_dict[index_h1 + 1][index_h2 + 1] === "undefined")
            	header_mask_dict[index_h1 + 1][index_h2 + 1] = temp_mask_h2_dict;

            var header_mask_h3 = val_2.split(":");
            $.each(header_mask_h3, function(index_h3,val_3)
            {
            	if (index_h3 != 0)
            	{
            		var temp_mask_h3_dict = {};
            		temp_mask_h3_dict.enabled = parseInt(val_3,10)?true:false;
            		header_mask_dict[index_h1 + 1] [index_h2 + 1] [index_h3] = temp_mask_h3_dict;
            	}
            });
        });
    });

    return header_mask_dict;
}


var restore_level_2_toggle_button = function (h2FlipSwitch, chapter, index, creditDict, newH2Elem)
{
    $(h2FlipSwitch.children()[0]).prop("selected",false);
    $(h2FlipSwitch.children()[1]).prop("selected",false);

    if(typeof creditDict[chapter] === "undefined" || typeof creditDict[chapter][index] === "undefined"){
        $(h2FlipSwitch.children()[1]).prop("selected",true);
        $(newH2Elem).removeClass("unmarked");
    } else {
        $(h2FlipSwitch.children()[(creditDict[chapter][index].enabled ? 1: 0)]).prop("selected",true);
        updateCreditApplicableCountAndUI(chapter,index, -1, creditDict[chapter][index].enabled, false);

        if(creditDict[chapter][index].enabled)
            $(newH2Elem).removeClass("unmarked");

    }
    h2FlipSwitch.flipswitch();
}

var restore_level_3_toggle_button = function (h3FlipSwitch, e3, index, creditDict, newH3Elem)
{
    $(h3FlipSwitch.children()[0]).prop("selected",false);
    $(h3FlipSwitch.children()[1]).prop("selected",false);

    if(typeof creditDict[e3.h1] === "undefined" || typeof creditDict[e3.h1][e3.h2] === "undefined")
    {
        $(h3FlipSwitch.children()[1]).prop("selected",true);
        $(newH3Elem).removeClass("unmarked");
    }
    else
    {
        $(h3FlipSwitch.children()[(creditDict[e3.h1][e3.h2][index].enabled ? 1: 0)]).prop("selected",true);
        updateCreditApplicableCountAndUI(e3.h1, e3.h2, index, creditDict[e3.h1][e3.h2][index].enabled, false);

        // this is for hiding or showing checkboxes depending upon the status of the toggle button
        if(creditDict[e3.h1][e3.h2][index].enabled)
        {
            $(newH3Elem).removeClass("unmarked");
        }
        else
        {
            $(newH3Elem).addClass("unmarked");
        }
    }
    h3FlipSwitch.flipswitch();
}

var disable_level_3_buttons = function(flip_switches){
    $.each(flip_switches, function(index,toggle_switch)
    {
        // index 0 is the level 2 filpswitch
        // all other are level3 toggle
        if(index != 0)
        {
            // console.log(toggle_switch.id);
            $(toggle_switch).val('off').flipswitch('refresh');
        }
    })
}

var enable_level_2_button = function(flip_switches){
    $.each(flip_switches, function(index,toggle_switch)
    {
        // index 0 is the level 2 filpswitch
        // all other are level3 toggle
        if(index == 0)
        {
            // console.log(toggle_switch.id);
            $(toggle_switch).val('on').flipswitch('refresh');
        }
    })
}

$(".cl-return-to-dashboard-btn").click(function()
{
    if(!G_IS_PROJECT_OWNER){
    show_splash_popup(STR_DASHBOARD_MOVE_STR,"myProjects.php",3);
    }
    else{
        show_splash_popup(STR_DASHBOARD_MOVE_STR,"myProjects.php",3);
    }
});

var set_title = function(title){
    $("#id-project-title-text span").text(title+" Solutions");
    $("#id-pane-solution").show();
}

var disable_div_save_button=function(elem)
{
    $(elem).css("background-color","#c6c6c6");
    $(elem).css("border","none");
    $(elem).css("cursor","no-drop");
    $(elem).find("span").text("Saved");
}

var enable_div_save_button = function(elem)
{
    $(elem).css("background-color","#0d71ba");
    $(elem).css("border","1px solid #0d71ba");
    $(elem).css("cursor","default");
    $(elem).find("span").text("Save");
}

var hide_chapter_details = function(chapter)
{
    if(chapter==5 && G_project_scope == 0 && params.id != undefined)
    {
        $("#id-div-chapter-content").hide();
        $("#id-div-chapter-disabled-msg").show();
        //$("#id-div-chapter-disabled-msg span").append("");
        $("#id-div-chapter-disabled-msg span").html(STR_CHAPTER_5_SITE_DISABLED);

        var target = "createProject.php?edit=true&p=" + params.id;
        $("#id-div-chapter-disabled-msg span a").attr("href",target);

    }
    else
    {
        $("#id-div-chapter-disabled-msg").hide();
        $("#id-div-chapter-content").show();
    }
}

$(".score-switch-holder-items").on("click", function() {
  var text = $(this).text();
  G_PAGE_RELOAD = true;
  $(".score-switch-holder-items").removeClass("solutions-active-link");
  $(this).addClass("solutions-active-link");

  if(text.indexOf("Reviewer Score") >= 0) {
    G_viewReviewerScore = true;
    load();
  }
  if(text.indexOf("Client Score") >= 0) {
    G_viewReviewerScore = false;
    load();
  }
});

$('#print-pdf-button').click(function()
{
    if( typeof params.id !== "undefined")
    {
        var target = "print_solutions.php?id=" + params.id;
    }
    else
    {
        target = "print_solutions.php";
    }
    window.location.href = target;
});

function show_hide_client_reviewer_divs()
{
    if(!G_IS_PROJECT_REVIEWER)
    {
        // Delete all review divs if the project reviewer is not the current user
        $(".review-div").remove();
    }
    else
    {
        $(".client-review-div").remove();
        if( G_isud_status==1)
        {
            $(".candlestick-wrapper").remove();
            //$(".candlestick-wrapper").prop("disabled", true);
        }
    }

    // if project is under review and not open for discussion
    // reviewer is reviewing project in his own time
    if( G_isud_status==2 && G_IS_PROJECT_OWNER )
    {
        $(".client-review-div").remove();
        // $(".cl-comment-icon").remove();
    }

    if( G_isud_status== 0  || (G_isud_status == 2 && G_IS_PROJECT_OWNER))
    {
        $("#in-review-checklist-btn").remove();
        $("#in-review-checklist-div").remove();
    }

    if(G_isud_status==0 )
    {
        $(".cl-review-div").remove();
        $(".review-div").remove();
        $("#project-feedback-btn").remove();
        $(".client-review-div").remove();
    }
    else
    {
        $(".cl-nonreview-div").remove();
    }
}

var UpdateInReviewChecklist = function (project, btn)
{
    var success_block = $(".cl-div-project-in-review-checklist-section").find(".cl-project-requirement-success");
    var failure_block = $(".cl-div-project-in-review-checklist-section").find(".cl-project-requirement-failure");
    var isSatisfied = true;

    if( project.isud_status == UNDER_REVIEW )
    {
        isSatisfied = project.review_status.yellow == 0;
    }
    if( project.isud_status == UNDER_REVIEW_DISCUSSION )
    {
        isSatisfied = project.review_status.yellow == 0 && project.review_status.red == 0;
    }

    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);
        show_solutions(failure_block, project.review_status, project.isud_status)
    }
}

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

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

//Event Listeners

function attachEventListeners(projectElem){
    attachEditEventListener(projectElem, true);
}

function attachEditEventListener(projectElem, attach){
    var btn = $(projectElem).find(".cl-project-edit-btn");
    var iconBtn = $(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 = "projectOverview.php?edit=true&id=" + G_PROJECT_ID;
            window.location.href = target;
        });
        $(iconBtn).click(function(ev){
            var target = "createProject.php?edit=true&p=" + G_PROJECT_ID;
            window.location.href = target;
        });
    }
}
;