function navigateGoals(event){
    var action_id = $(event.originalTarget).attr("id");
    var current_last_date = $("#goals").children(":last").children(".date").text();
    current_last_date = Date.parse(current_last_date);
    var new_date = null;

    if(action_id == "go-previous"){
        new_date = current_last_date.add(-6).days();
    } else if(action_id == "go-next") {
        new_date = current_last_date.add(6).days();
    } else if(action_id == "go-last") { 
        new_date = Date.today();
    }

    $.get("/goal_grid", {'end_date': new_date.toString('yyyy-MM-dd')}, navigate_callback);
    //$("#goals").hide("slow");
}

function navigate_callback(data, status){
    if(status == "success"){
        $("#goals").replaceWith(data);
        //$("#goals").show("slow");
    } else {
        alert(status);
    }
}


function score(target){
    var goalName = $(target).children(".goal").text();
    var date = $(target.parentNode).children(".date").text();
    $.getJSON('/score', {"goalName": goalName, "date": date}, score_callback, 'JSON');
    target.innerHTML += "<img src=\"./images/token.png\"/ class=\"t\" onClick=\"remove(event);\">";
}

function score_callback(data, status){

}

function remove(event){
    event.stopPropagation();

    var action = $(event.originalTarget).parent();
    var goalName = action.children(".goal").text();
    var date = action.parent().children(".date").text();
    $.getJSON('/score', {"goalName": goalName, "date": date, "points": -1}, score_callback, 'JSON');
    $(event.originalTarget).hide();
}

$(document).ready(function() {
        $("#addgoal_dialog").jqm();
        $("#addgoal_dialog").jqmAddTrigger("#addgoal");
        $("#addgoal_dialog").jqmAddClose("#addgoal_cancel");
        
        
        $("div[@class=action]").click(function (){ score(this); });
        $("img[@class=t]").click(remove);

        $("#go-first").click(navigateGoals);
        $("#go-previous").click(navigateGoals);
        $("#go-next").click(navigateGoals);
        $("#go-last").click(navigateGoals);
    });