// global DOM template holders
var printable_doc ;
var chapter_holder;
var chapter_separator_hr;

var CHAPTER_COUNT=0;
var TOTAL_CHAPTERS = 9;
var CHAPTERS = {};
var pbar;
var PROJECT_ID;
var G_PAGE_RELOAD = false;

var statuses = ['Ongoing', 'Completed','In Pre-Certification Review','Pending', 'Inactive'];
var months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];

$(document).ready(function () 
{
    printable_doc = $(".cl-printable-doc")
    cover_container = $(".score_card_cover");
    chapter_holder = $(".cl-chapter-holder");
    chapter_separator_hr = $("#id-chapter-separator");    
    chapter_holder.hide();
    chapter_separator_hr.hide();
    PROJECT_ID = get_project_id_from_url();

    $.post("API.php", { chapter: -1 }, function (data) 
    {
        CHAPTER_COUNT = 0
        $.each(data, function (index, chapter) 
        {
            chapter = chapter.header;
            var chapter_number = chapter.h1.toString()
            getChapters(chapter_number);
        });
    },"json");

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


var getChapters =  function(chapter_number){
   
    $.post("API.php", { chapter: chapter_number }, function (data) {
        // response from API
        var chapter_info = data[chapter_number].header;
        CHAPTERS[chapter_number] = chapter_info;
        CHAPTER_COUNT = CHAPTER_COUNT+1;

        if(CHAPTER_COUNT == TOTAL_CHAPTERS )
        {
            // Get the project specific dictionary
            if (typeof PROJECT_ID == "undefined")
            {
                display_chapters(data);  
            }
            else
            {
                $.post("API.php", { project: "GET_DICT", project_id: PROJECT_ID }, function(data)
                {
                    // display everything :)
                    console.log("JSON DATA is ************  ",data);
                    display_chapters(data);           
                },"json");
            }            
        }        
    }, "json");
}

function display_chapters(curr_project_dict)
{
    $.each(CHAPTERS, function (index, chapter_info) 
    {
        // get dom elements
        var dom_chapter_holder = chapter_holder.clone();
        dom_chapter_holder.show();
        var dom_chapter_separator_hr = chapter_separator_hr.clone();
        dom_chapter_separator_hr.show();

        var dom_chapter_title = $(dom_chapter_holder).find(".cl-chapter-title");   
        var dom_chapter_number = $(dom_chapter_holder).find(".cl-chapter-number");
        var dom_chapter_credits = $(dom_chapter_holder).find(".cl-chapter-credits");
        
        dom_chapter_number.html(chapter_info.h1.toString());
        dom_chapter_title.html(chapter_info.h1_title.toString());
        dom_chapter_credits.html(chapter_info.h1_points.toString()+ " Credits");

        if( typeof curr_project_dict =="undefined")
        {
            show_h2_headers(dom_chapter_holder, chapter_info.h2_elems, curr_project_dict );
        }
        else
        {
            show_h2_headers(dom_chapter_holder, chapter_info.h2_elems, curr_project_dict[ index ] );
        }

        printable_doc.append(dom_chapter_holder);
        printable_doc.append(dom_chapter_separator_hr);
    });    
}


function show_h2_headers(dom_chapter_holder, H2, chapter_settings )
{
    //console.log("H2 is ",H2);
    var dom_header_holder = $(dom_chapter_holder).find(".cl-header-holder").clone();

    $.each(H2, function (index, header){
        var dom_header = $(dom_header_holder).clone();
        $(dom_header).find(".cl-header-number").html(header.header_text);
        $(dom_header).find(".cl-header").html(header.h2_title);        
        $(dom_header).find(".cl-instruction").html(header.instruction);
        if(header.h3_elems.length == 0)
        {
            $(dom_header).find(".cl-header-hr").show();
        }
        else
        {
            $(dom_header).find(".cl-solutions-holder").css("margin-bottom","5px");
        }
        
        if( typeof chapter_settings == "undefined")
        {
            show_h3_headers(dom_header, header.h3_elems, chapter_settings );
            show_h2_solutions(dom_header, header.solutions, chapter_settings);
        }
        else
        {
            show_h3_headers(dom_header, header.h3_elems, chapter_settings[ index ] );
            show_h2_solutions(dom_header, header.solutions, chapter_settings[ index ] );
        }
        $(dom_chapter_holder).append(dom_header);
    });
}

function show_h3_headers(dom_chapter_holder, H3 , header_settings )
{
    // console.log("H3 is ",H3);
    var dom_sub_header_holder = $(dom_chapter_holder).find(".cl-sub-header-holder").clone();
    $.each(H3, function (index, header){
        var dom_header = $(dom_sub_header_holder).clone();
        $(dom_header).find(".cl-sub-header").html(header.h3_title);        
        $(dom_header).find(".cl-sub-instruction").html(header.instruction);
        $(dom_header).find(".cl-sub-header-number").html(header.header_text);
        $(dom_header).find("hr").show();
        if( typeof header_settings == "undefined")
        {
            show_h3_solutions(dom_header, header.solutions, header_settings);
        }
        else
        {
            show_h3_solutions(dom_header, header.solutions, header_settings[ index ]);
        }
        $(dom_chapter_holder).append(dom_header);
    });
}

function show_h2_solutions(dom_header, solutions, solution_settings )
{
    var dom_solutions_holder = $(dom_header).find(".cl-solutions-holder");
    var dom_solution_holder_temp = $(dom_solutions_holder).find(".cl-solution-holder").clone();
    
    $.each(solutions, function (index, solution){
        var dom_solution_holder = dom_solution_holder_temp.clone();        
        $(dom_solution_holder).find(".cl-solution-number-text").html(solution.standard_no);
        $(dom_solution_holder).find(".cl-solution").html(solution.standard_text);
        $(dom_solution_holder).find(".cl-solution-check-box").show();

        var checkbox_val = false;
        if( typeof solution_settings !== "undefined")
        {
            checkbox_val = solution_settings[index]["checked"]=== "1";
        }
        
        $(dom_solution_holder).find(".cl-solution-check-box input[type=checkbox]").prop('checked', checkbox_val );
        if(solution.prerequisite)
        {
            $(dom_solution_holder).find(".cl-solution-number-text").css('background','orange');
            $(dom_solution_holder).find(".cl-solution-required").show();
            $(dom_solution_holder).find(".cl-solution-required").css('background','orange');
        }
        $(dom_solutions_holder).append(dom_solution_holder);
    });
}

function show_h3_solutions(dom_header, solutions, solution_settings)
{
    var dom_solutions_holder = $(dom_header).find(".cl-sub-solutions-holder");
    var dom_solution_holder_temp = $(dom_solutions_holder).find(".cl-sub-solution-holder").clone();
    
    $.each(solutions, function (index, solution){
        var dom_solution_holder = dom_solution_holder_temp.clone();
        $(dom_solution_holder).find(".cl-sub-solution-number-text").html(solution.standard_no);
        $(dom_solution_holder).find(".cl-sub-solution").html(solution.standard_text);
        $(dom_solution_holder).find(".cl-sub-solution-check-box").show();

        var checkbox_val = false;
        if( typeof solution_settings !== "undefined")
        {
            checkbox_val = solution_settings[index]["checked"]=== "1";
        }
        $(dom_solution_holder).find(".cl-sub-solution-check-box input[type=checkbox]").prop('checked', checkbox_val );
        if(solution.prerequisite)
        {
            $(dom_solution_holder).find(".cl-sub-solution-number-text").css('background','orange');
            $(dom_solution_holder).find(".cl-sub-solution-required").show();
            $(dom_solution_holder).find(".cl-sub-solution-required").css('background','orange');
        }
        $(dom_solutions_holder).append(dom_solution_holder);
    });
}

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

function fillGlobalDataFromDB(id, cover_container){
    $.post("API.php", {project: "DETAILS", id :id}, function (data) {
        var d = data[0];
        console.log(JSON.stringify(d));
        $(cover_container).find("#id-project-name").html(d.project_title);
        $(cover_container).find("#id-progress").html(statuses[d['isud_status']]);

        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1;
        mm = months[mm - 1];
        var yyyy = today.getFullYear();

        $(cover_container).find("#id-subtitle").html("Project Scorecard as of " + mm+ " " + dd + ", " + yyyy);
        
        var projectAwardPercentage = parseFloat(d.award_percentage);
        var projectSolutionsTowardsBonusCount = parseInt(d.bonus_credits, 10);
        var projectCreditCountApplicable = parseInt(d.applicable_credits, 10);
        var projectCreditCountEarned = parseInt(d.earned_credits, 10);
        updateCreditsAndScoreUI(projectCreditCountEarned, projectSolutionsTowardsBonusCount, projectCreditCountApplicable, projectAwardPercentage);
    },"json");
}


function updateCreditsAndScoreUI(projectEarnedCredits, projectBonus, projectAvailble, projectAwardPercentage){


  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 projectCreditAvailble = $("#id-div-project-award-credit-available").find(".cl-span-project-award-credit-item-value");

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

    // var percentage = Math.round (projectEarnedCredits * 100 / projectAvailble);
    // percentage = percentage + projectBonus;
    var temp_percentage = projectAwardPercentage>100?100:projectAwardPercentage; // if percentage is above 100% it breaks the progress circle


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