﻿var UserWorkouts = {
    workouts: [],
    workoutsFilter: null,
    currentWorkoutIndex: -1,
    currentWorkout: {},
    workoutsCount: 0,
    startId: null,
    anchorId: null,
    workoutsLoaded: function(workouts) {
        UserWorkouts.workouts = workouts;
        UserWorkouts.workoutsCount = UserWorkouts.workouts.length;
        var findID = $("#workout_id").val();
        for (var i = 0; i < UserWorkouts.workouts.length; i++) {
            if (UserWorkouts.workouts[i] == findID) {
                UserWorkouts.currentWorkoutIndex = i;
                break;
            }
        }
        if (UserWorkouts.anchorId) {
            UserWorkouts.startId = UserWorkouts.currentWorkoutIndex;
            if (UserWorkouts.setCurrentWorkoutId(UserWorkouts.anchorId)) {
                loadWorkout();
            }
            else { UserWorkouts.setCurrentWorkoutId(UserWorkouts.startId); }
        }
    },

    load: function() {
        $.getJSON('/Json/WorkoutsByViewlevel', { user_id: $("#user_id").val() }, UserWorkouts.workoutsLoaded);

    },

    getCurrentWorkoutId: function() {

        if (UserWorkouts.currentWorkoutIndex != -1) {
            return UserWorkouts.workouts[UserWorkouts.currentWorkoutIndex];
        }
        else {
            return $("#workout_id").val()
        }
    },
    setCurrentWorkoutId: function(newId) {
        var isListed = false;
        for (var i = 0; i < UserWorkouts.workouts.length; i++) {
            if (UserWorkouts.workouts[i] == newId) {
                UserWorkouts.currentWorkoutIndex = i;
                isListed = true;
                break;
            }
        }
        $("#workout_id").val(newId);
        return isListed;
    }


};
var hashCallback = function(obj) {
    if (obj && obj.id) {
        UserWorkouts.setCurrentWorkoutId(obj.id);
    }
    else {
        UserWorkouts.setCurrentWorkoutId(UserWorkouts.startId);
    }
    loadWorkout();
}

$(document).ready(function() {
    WorkoutMap.init();
    UserWorkouts.startId = $("#workout_id").val();
    var anchorId = ajaxHistory.attrFromAnchor("id");
    if (anchorId) {
        if (!UserWorkouts.setCurrentWorkoutId(anchorId)) {
            UserWorkouts.setCurrentWorkoutId(UserWorkouts.startId);
            UserWorkouts.anchorId = anchorId;
        }
    }
    WorkoutMap.onCheckpointsChanged = CheckpointsView.renderHTML;
    workoutGraph.hoverCallBack = WorkoutMap.subPathHighlight.draw;
    ajaxHistory.hashCallback = hashCallback;
    CheckpointsView.unitSystem = $('#ms').val();
    WorkoutMap.unitSystem = $('#ms').val();
    WorkoutMapInit(false);
    UserWorkouts.load();
    $('#tabs').show();
    $('#tabs').tabs({
        select: function(event, ui) {
            if (ui.index == 1) {
                WorkoutMap.removeStatsMarkers();
                if (CheckpointsView.autoMode) {
                    WorkoutMap.loadAutocheckpoints();
                } else {
                    WorkoutMap.loadManualcheckpoints();
                }
            }
            if (ui.index == 0) {
                WorkoutMap.removeAllMarkers();
                WorkoutMap.addStatsMarkers();
            }
        }
    });


    $("#dialog").dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        buttons: {
            Ok: function() {
                $(this).dialog('close');
            }
        }
    });



    $("#tags_dialog").dialog({
        autoOpen: false,
        bgiframe: true,
        modal: true,
        buttons: {
            'Save': function() {
                $('#getLocation').val($("#location").val());
                $('#getTags').val($("#tags").val());
                $.post("/Workouts/UpdateTags",
                            {
                                workouts: UserWorkouts.getCurrentWorkoutId(),
                                location: $('#location').val(), tags: $('#tags').val()
                            },
                            function() {
                            }
                        );
                $(this).dialog('close');
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        }
    });
    $("#go_fullscreen").click(function() {
        var params = getURLParams();
        if (params.key) {
            document.location = "/Workouts/Embed/" + UserWorkouts.getCurrentWorkoutId() + '?key=' + params.key;
        }
        else {
            document.location = "/Workouts/Embed/" + UserWorkouts.getCurrentWorkoutId();
        }
    });

    $("#cpIntervalDialog").dialog({
        title: "Set checkpoints distance interval",
        autoOpen: false,
        bgiframe: true,
        modal: true,
        buttons: {
            'Update': function() {
                var meters = Convertor.fromDistance($("#cpInterval").val(), $("#ms").val());
                if (meters < 100) { meters = 100; }
                WorkoutMap.changeAutocheckpoints(meters);
                $(this).dialog('close');
            }
        }
    });

    if (!anchorId) {
        loadWorkout(true);
    }
    workoutGraph.showHide(0);

});


function resetTabs() {
    $('#tabs').tabs('select', 0);
}
var successNext = function() {
    $('#workoutStats').fadeIn();
}
var successNextDet = function() {
    $('#workoutDetails').fadeIn();
}
function loadDetails() {
    $('#workoutDetails').fadeOut();
    $('#workoutStats').fadeOut();
    $('#workoutDetails').load("/Workouts/GetDetails", { id: UserWorkouts.getCurrentWorkoutId() }, successNextDet);
    $('#workoutStats').load("/Workouts/GetStats", { id: UserWorkouts.getCurrentWorkoutId() }, successNext);
}

function previousWorkout() {
    if (UserWorkouts.currentWorkoutIndex > 0) {
        UserWorkouts.currentWorkoutIndex--;
        ajaxHistory.attrToAnchor("id", UserWorkouts.getCurrentWorkoutId());
        loadWorkout();

    }
}
function nextWorkout() {
    if (UserWorkouts.currentWorkoutIndex < UserWorkouts.workoutsCount - 1) {
        UserWorkouts.currentWorkoutIndex++;
        ajaxHistory.attrToAnchor("id", UserWorkouts.getCurrentWorkoutId());
        loadWorkout();

    }
}

var hrm_click = function() {
    $("#hrm_breakdown_button").toggleClass("marble_button_active");
    $("#hrm_breakdown_dialog").toggle();
}

function calcMaxHRM(age) {
    return 205.8 - (0.685 * age);
}

function loadWorkout(skipDetails) {
    WorkoutMap.startLoading();
    var url = "/Json/GetWorkoutMapBS/";
    if ($("#simplify").val() == "True") {
        url = "/Json/GetWorkoutSimplify/";
    }
    $.getJSON(url + UserWorkouts.getCurrentWorkoutId(), { r: Number(new Date()) }, function(data) {
        WorkoutMap.loadedWorkout(data.map, data.best);
        workoutGraph.drawJSON(data);
        if (workoutHRM) { workoutHRM.load(data, 1.0 * $("#userMaxHr").val()); }
        WorkoutMap.endLoading();
    })
    workoutComments.load(UserWorkouts.getCurrentWorkoutId());
    if (!skipDetails) {
        loadDetails();
        resetTabs();
    }
}


function toggleComments() {
    workoutComments.show(UserWorkouts.getCurrentWorkoutId());
    return false;
}
var workoutComments = {
    areShown: false,
    widLoaded: 0,
    load: function(wid) {
        if (this.areShown) {
            $("#bottomCommentsHolder").load("/WorkoutComments/Create/" + wid);
            this.widLoaded = wid;
        }
    },
    show: function(wid) {
        if (!this.areShown) {
            this.areShown = true;
            if (wid != this.widLoaded) { this.load(wid); }
            $("#bottomCommentsHolder").show();

        }
        else {
            this.areShown = false;
            $("#bottomCommentsHolder").hide();
        }
        return false;
    }
}
function tagWorkout() {
    $('#location').val($('#getLocation').val())
    $('#tags').val($('#getTags').val())
    $('#tags_dialog').dialog('open');
}
