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

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

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

var creditDict = {};
var G_projectCreditCountApplicable = 100;
var G_projectCreditCountEarned = 0;
var G_projectSolutionsTowardsBonusCount = 0;
var G_projectAwardPercentage = 0.0;
var G_h1CreditsArrString = '';
var G_h1CreditsArrEarnedString = '';
var G_h1CreditsArrApplicableString = '';
var G_h1CreditsArr = [];
var G_h1CreditsArrEarned = [];
var G_isud_status = 0;
var G_IS_PROJECT_OWNER = true;
// Project scope : Building and Site =1 and Building only =0
// used to hide and show Chapter 5 based on scope.
var G_project_scope = 0;

var editMode = false;
var initialPopulationMode = true;
var params={};
var pbar;
var initialFetchChapterCount = 0;

var loadingMsgContainer = null;
var loadingMsgSpan = null;
String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

$(document).ready(function () {

    var user_email = "";

    window.location.search.replace(/[?&;#]+([^=&]+)=([^&]*)/gi,function(str,key,value){params[key] = value;});

    $("img").unveil();
    $("img").trigger("unveil");
    /*replace the browse icon in the navigation bar to active browse icon.*/
    $("#id-img-navbar-p-browse").attr("src","images/browsesolutions_icon_active.png");

    loadingMsgContainer = $(".cl-section-loading-msg");
    loadingMsgSpan = $(".cl-span-loading-msg");
    $(loadingMsgContainer).css("display","flex");

    // TODO : Fix this temp //////////
    if(typeof params.edit !== "undefined" && params.edit ==="true" && (typeof params.id !== "undefined")){
        editMode = true;
        //$(".icon-holder").css("margin-right","5%");
        $(".cl-div-chapter-sub-title").hide();
        $(".cl-div-nav-image-holder-solution_l").css("display","flex");
        $(".cl-div-nav-project-award-details-holder").css("display","flex");
        $(".cl-div-nav-project-award-details-holder").css("max-width","100%");
        $(".cl-div-nav-project-award-details-holder").css("min-width","14.5%");
        $(".cl-div-nav-project-award-details-holder").css("height","80px");
        $(".cl-div-nav-project-award-details-holder").css("background-color","#e8e8e8");
        // $("#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);
        // Hide Browse button in edit mode
        // $("#id-img-navbar-p-browse").parent().css("display","none");
        $(".cl-div-site-breadcrumb").addClass("hide");
    } else {
        $(".cl-div-chapter-sub-title").show();
        $(".cl-div-nav-image-holder-solution_l").css("display","none");
        $(".cl-div-nav-project-award-details-holder").css("display","none");
        $(".cl-form-solution-checkbox").hide();
        $(".cl-div-hx-item-title-edit-status").hide();
        $(".cl-div-chapter-credit-implemented-ratio-holder").hide();
        $("#id-div-chapter-content-top-info").hide();
        $(".cl-div-hx-footer").hide();
        $(".cl-div-nav-image-holder-solution_l").addClass("hide");
        $(".cl-div-nav-project-award-details-holder").addClass("hide");
        // Hide submit button in non-edit(browse solution) mode
        // $("#id-img-navbar-p-submit").parent().css("display","none");
        getChapters();
    }

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

    ///////////////////////////////////

    pbar = new ProgressBar.Circle('#id-div-project-award-progress-container', {
        color: '#F7941E',
        strokeWidth: 10,
        trailColor: '#ffffff',
        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 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();

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

/*
$(window).unload(function(){
    $(loadingMsgContainer).css("display","flex");
    $(loadingMsgSpan).html("Saving Data. Please wait !");
    if(initialFetchChapterCount >= 100 && editMode){
        $.each(creditDict, function(indexh1, h1Elem){

            if(parseInt(h1Elem) === NaN)
                continue;

            $.each(h1Elem, function(indexh2, h2Elem){

                if(parseInt(h2Elem) === NaN)
                    continue;

                $.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: h2Elem } , function (data) {
                },"json");
            });
        });
    }

    // console.log("Page Unloaded");
    return;
});
*/

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);
        });
        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/unitarrow_closed.png");
                    h2Image.attr("data-src","images/unitarrow_closed.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);

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

                        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};
                        } else {
                            $(solutionItemHeader).find(".cl-div-hx-solution-item-checkbox").prop("checked",creditDict[s.h1][s.h2][index].checked === 1 ? true: false);
                            if(initialPopulationMode){
                                updateCreditCountandUI(s.h1,s.h2,-1,index,creditDict[s.h1][s.h2][index].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/unitarrow_closed.png");
                        h3Image.attr("data-src","images/unitarrow_closed.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);

                            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};
                            } else {
                                $(solutionItemHeader).find(".cl-div-hx-solution-item-checkbox").prop("checked",creditDict[s.h1][s.h2][s.h3][index].checked === 1 ? true: false);
                                if(initialPopulationMode){
                                    updateCreditCountandUI(s.h1,s.h2,s.h3,index,creditDict[s.h1][s.h2][s.h3][index].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);
                    });

                    /*
                    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);
                    */
                    /*
                    {
                        $(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, creditDict[chapter][index].enabled, false);

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

                        }
                        h2FlipSwitch.flipswitch();
                    }*/

                });

                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+" .cl-div-chapter-spin-i-holder").addClass("hide");
            $("#id-div-solution-chapter-list-item-"+chapter+" .cl-div-chapter-chevron-holder").removeClass("hide");

            $(".cl-div-chapter-content-h2-item-pane").on("hidden.bs.collapse", function(){
                $(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/unitarrow_closed.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){
                    $.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 .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/unitarrow_closed.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/unitarrow_open.png");

                // 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/unitarrow_open.png");

                // $('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/unitarrow_open.png");
                $(this).parent().find(".cl-div-h2-solution-item-header").toggleClass("active");
                $(this).toggleClass("active");

                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/unitarrow_closed.png");
                $(this).parent().find(".cl-div-h2-solution-item-header").toggleClass("active");
                $(this).toggleClass("active");

                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/unitarrow_open.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/unitarrow_closed.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 ;
                 if(elems.length === 4){
                    updateCreditCountandUI(elems[0], elems[1], elems[2], elems[3],checkedVal);
                 } else if(elems.length === 3){
                     updateCreditCountandUI(elems[0], elems[1], -1, elems[2],checkedVal);
                 }

                 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){
                    $(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){
                        updateCreditCountandUI(elems[0], elems[1], elems[2], elems[3],checkedVal);
                    } else if(elems.length === 3){
                        updateCreditCountandUI(elems[0], elems[1], -1, elems[2],checkedVal);
                    }
                 });
             });

             $(".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)){
                    $.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) {
                        if (data.response == true)
                        {

                        }
                    },"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_IS_PROJECT_OWNER ){
                    //lock and disable checkboxes and flipswitches
                    $(".checkbox").addClass("disabled");
                    $(".cl-div-selection-switch-holder").addClass("disabled");
                    $(".cl-div-lock-status-holder").css("display", "flex");
                    $(".cl-div-hx-footer").css("display","none");
                    $(".cl-div-hx-footer").addClass("disabled");
                } else {
                    $(".cl-div-lock-status-holder").css("display", "none");
                }

                initialFetchChapterCount = 100;
            }

        }, "json");
        hide_chapter_details(chapter);
}

// checked = 0 [unchecked]
// checked = 1 [checked]
function updateCreditCountandUI(h1, h2, h3, solution, checked){

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

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

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

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

        creditDict = build_credit_dict(d,header_mask_dict);
        getChapters();
    },"json");
}

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]);
                        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]);
                        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)
{
    // console.log("Toggle button is : ",e3.h1," ",e3.h2," ",index);
    $(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()
{
    show_splash_popup(STR_DASHBOARD_MOVE_STR,"projectDashboard-copy.php",3);
});

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

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

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