Object.keys = Object.keys || function(o) {
    var result = [];
    for (var name in o) {
        if (o.hasOwnProperty(name))
            result.push(name);
    }
    return result;
};

function parseTemplate(template, data)
{
    $.each(data, function (k, v) {
        template = template.replace(new RegExp(k, "g"), v);
    });
    return template;
}

function getUrlVars()
{
    var vars = {};
    if (document.location.search) {
        $.each(decodeURI(document.location.search).substring(1).split("&"), function (k, v) {
            var parts = v.split("=");
            vars[parts[0]] = parts[1];
        });
    }
    return vars;
}

function getUrlVar(name)
{
    var value;
    $.each(getUrlVars(), function (k, v) {
        if (k == name)
            value = v;
    });
    return value;
}

function addZero(s)
{
    return (s < 10 ? "0" : "") + s;
}

function getDate(d)
{
    d = d || new Date;

    var Y = d.getFullYear(),
        M = d.getMonth(),
        D = d.getDate(),
        h = d.getHours(),
        m = d.getMinutes();

    return Y + "-" + addZero(M) + "-" + addZero(D) + " " + addZero(h) + ":" + addZero(m);
}

var DATA, COMPETENCES, TABS, MAX_SCORE = 0, MAX_ANSWER = 0;

function loadData()
{
    $.getJSON(getUrlVar("test") ? "js/test.json" : "js/competence.json", function (data) {
        DATA = data;
        createCompetenceSelect();
    });
}

function getCompetencesVar()
{
    var c = getUrlVar("c");
    if (c)
        return c.match(/\d+/g);

    return null;
}

function getUniqueId()
{
    var tmp = ["competence"];
    for (var i = 0; i < arguments.length; i++)
        tmp.push(arguments[i]);

    return tmp.join("_");
}

function createCompetenceSelect()
{
    COMPETENCES = getCompetencesVar();
    MAX_ANSWER = Object.keys(DATA.answers).sort().pop();
    $("#select ul").remove();
    var html = "", max_score = 0;
    $.each(DATA.competence, function (i, competence) {
        html = html + parseTemplate('<li><input type="checkbox" id="s_:id" value=":value" /><label for="s_:id">:label</label></li>', {
            ":id" : getUniqueId(i),
            ":value" : i + 1,
            ":label" : competence.title
        });
        MAX_SCORE = Math.max(MAX_SCORE, MAX_ANSWER * competence.questions.length);
    });
    $("#start").before("<ul>" + html + "</ul>").unbind().click(function(e){
        var checkboxes = $("#select").find("input:checkbox").filter(":checked");
        if (checkboxes.size() == 0) {
            alert("Proszę wybrać kompetencje!");
            return false;
        }

        COMPETENCES = [];
        checkboxes.each(function(){
            COMPETENCES.push(this.value);
        });
        createCompetenceTest();
    });
    $("#competence, #score, #back, #random").hide();
    $("#select").show();

    if (COMPETENCES)
        createCompetenceTest();
}

function createRadioButtons(competence, section)
{
    var html = "", id, name;
    $.each(DATA.answers, function (value, label) {
        html = html + parseTemplate('<li><input type="radio" id=":id" name=":name" value=":value" /><label for=":id">:label</label></li>', {
            ":id" : getUniqueId(competence, section, value),
            ":name" : getUniqueId(competence, section),
            ":label" : label,
            ":value" : value
        });
    });
    return html;
}

function createCompetenceTest()
{
    if (DATA) {
        var content = "", tabs = "", lp = 1, tmp;
        $.each(DATA.competence, function (i, competence) {
            if (!COMPETENCES || $.inArray((i + 1) + "", COMPETENCES) > -1) {
                tabs = tabs + parseTemplate('<span id=":id" title=":title">:lp</span>', {
                    ":id" : "#" + getUniqueId(i),
                    ":lp" : lp++,
                    ":title" : competence.title
                });
                tmp = "";
                $.each(competence.questions, function (k, question) {
                    tmp = tmp + parseTemplate('<ul>:lp. :question :radios</ul>', {
                        ":lp" : k+ 1,
                        ":question" : question,
                        ":radios" : createRadioButtons(i, k)
                    });
                });
                content = content + parseTemplate('<div id=":id">:content</div>', {
                    ":id" : getUniqueId(i),
                    ":content" : tmp
                });
            }
        });
        $("#tabs > span, #test > div").remove();
        $("#test").prepend(content).filter("> div").hide();
        TABS = $("#tabs").html(tabs).find("> span").click(changeTab);
        TABS.filter(":first").addClass("active").trigger("click");
        $("#select").hide();
        $("#competence").show();
        $("#back").unbind().click(createCompetenceSelect).show();
        $("#next").unbind().click(nextTab);
        if (getUrlVar("random")) {
            if ($("#random").size() == 0) {
                $("<span></span>").addClass("button-green").attr("id", "random").text("Wypełnij").click(function(e){
                    fillRandom(prompt("Średni wynik (0 - wartości losowe)", 0));
                }).insertAfter("#back");
            }
            $("#random").show();
        }
    }
}

function getCompetenceScoreSummary(competence, avg)
{
    var keys = Object.keys(DATA.competence[competence].summary).reverse();
    var i;
    for (i = 0; i < keys.length; i++) {
        if (avg >= keys[i] * 1)
            return DATA.competence[competence].summary[keys[i]];
    }
    return DATA.competence[competence].summary[keys.reverse()[0]];
}

function createCompetenceScore(avgScore)
{
    var content = "", url = [], dataTable = new google.visualization.DataTable;
    dataTable.addColumn("string", "Kompetencja");
    dataTable.addColumn("number", "Wynik");
    $("#test > div").each(function(){
        var points = 0, avg;
        var competence = $(this).attr("id").split("_")[1];
        if (!avgScore || avgScore <= 0) {
            $(this).find(":radio").filter(":checked").each(function(){
                points = points + this.value * 1;
            });
            avg = points / $(this).find("ul").size();
        } else {
            avg = avgScore * 1;
        }
        content = content + parseTemplate('<p><strong>:name</strong>: :avg <p>:comment</p></p>', {
            ":name" : DATA.competence[competence].title,
            ":avg" : avg,
            ":comment" : getCompetenceScoreSummary(competence, avg)
        });
        url.push(DATA.competence[competence].title + "=" + avg);
        dataTable.addRow([DATA.competence[competence].title, avg]);
    });
    url = encodeURI(url.join("&"));
    $("#competence").hide();
    $("#overall-comment").html(content);
    /*google.visualization.drawChart({
        "containerId" : "bar-chart",
        "chartType" : "BarChart",
        "dataTable" : dataTable,
        "options" : {
            "chartArea" : {
                "width" : 300,
                "left" : 200
            },
            "legend" : {
                "position" : "none"
            },
            "hAxis" : {
                "format" : "#",
                "minValue" : 1,
                "maxValue" : MAX_ANSWER
            },
            "width" : 550
        }
    });*/
    $("#print").click(function(e){
        window.print();
    });
    $("#finish-date span").text(getDate());
    $("#score").show();
}

function checkCurrentTab()
{
    var currentTab = TABS.filter(".active");
    var currentDiv = $(currentTab.attr("id"));

    var status = currentDiv.find("ul").size() == currentDiv.find(":radio").filter(":checked").size();
    if (status) {
        currentTab.addClass("done");
    }

    return status;
}

function changeTab()
{
    checkCurrentTab();

    var newTabID = $(this).attr("id");
    var currentTab = getCurrentTab();
    var notDone = getNotDone();

    if (currentTab.attr("id") != newTabID && currentTab.hasClass("done") == false && !confirm("Nie odpowiedziałeś na wszystkie pytania. Na pewno chcesz kontynuować?")) {
        return;
    }

    $("#test > div").hide().filter(newTabID).show();
    currentTab = $(this).addClass("active");
    currentTab.siblings().removeClass("active");
    $("#circle").text(currentTab.text());
    $("#title").text(currentTab.attr("title"));
    scrollTo(0, 0);
    if (notDone == 1) {
        $("#next").text("Zobacz wyniki");
    }
}

function nextTab()
{
    var status = checkCurrentTab();
    var notDone = getNotDone();

    if (notDone == 0) {
        return createCompetenceScore();
    }

    if (notDone == 1 && status == false) {
        return alert("Nie odpowiedziałeś na wszystkie pytania.");
    }

    TABS.not(".active, .done").first().trigger("click");
}

function getCurrentTab()
{
    return TABS.filter(".active");
}

function getNotDone()
{
    return TABS.size() - TABS.filter(".done").size();
}

function fillRandom(avgScore)
{
    $("#test > div").each(function(){
        $(this).find("ul").each(function(){
            $(this).find(":radio")[parseInt(Math.random() * MAX_ANSWER)].checked = true;
        });
    });
    createCompetenceScore(avgScore);
}

jQuery(loadData);
google.load("visualization", "1.0", {"packages":["corechart"]});