$(function(){
    $.get( '/data.csv', function(data) {
        Papa.parse(data, {
            header: true,
            dynamicTyping: true,
            complete: function(results) {
                processCoachingData(results.data);
            }
        });
    });
});



window.week_introductions = {
    gain_muscle: {
        week_1: 'A good protein intake at every meal helps to renew the cells that build muscle: meat, fish, eggs, dairy products.',
        week_2: 'Vary your breakfasts and add proteins that will help to boost your muscle potential:  dairy products, ham or eggs.',
        week_3: 'Question of timing: before doing any physical activity, avoid eating foods that cause bloating (raw vegetables, starchy carbs).',
        week_4: 'To prevent the risk of sore, aching muscles, remember to drink sparkling water rich in bicarbonate after exercise.'
    },
    tone_up: {
        week_1: 'If you set yourself small achievable goals that can be measured every day, it will be easier to achieve your main goal.',
        week_2: 'When you do your shopping, think about filling the fridge with fresh products, rather than filling the cupboards with dry, savoury and sweet foods.',
        week_3: 'Don’t let any sweet treats in the house that you won’t be able to resist and that will stop you from achieving your goal.',
        week_4: 'Identify the emotions and situations that make you eat when you’re not hungry so that you can stay one step ahead and keep getting slimmer.'
    },
    stabilize: {
        week_1: 'Make sure you know the difference between hunger and cravings, as well as when to stop when you’ve had enough.',
        week_2: 'Remember to drink water regularly throughout the day – still or sparkling, cold or at room temperature – and restrict sugary drinks.',
        week_3: 'Don’t panic if you’ve made a meal that is too rich or copious: wait until you’re hungry again and compensate for it by making the next meal lighter.',
        week_4: 'Learn to cook according to your own tastes and needs: good, small home-made dishes contain less fat, salt and sugar than processed meals.'
    },
    lose_weight: {
        week_1: 'Take your time and lose weight gradually, without rushing and without depriving yourself: this will make it more enjoyable and easier to keep up.',
        week_2: 'If you feel like you’re hungry all the time, increase the proportion of high-fibre foods, which will fill you up more.',
        week_3: 'Carefully note down everything you eat in a little notebook: this will help you notice those little extras, where you’re having too much and how you’re progressing.',
        week_4: 'Organise your cupboards and fridge so that you can eat healthily if you need a snack and don’t risk the temptation of less healthy treats.'
    },
    gain_weight: {
        week_1: 'Whet your appetite by setting the table nicely, varying your dishes, allowing yourself treats in small amounts and adding your favourite foods to the menu.',
        week_2: 'Eat starchy carbohydrates at every meal: take advantage to get to know the wide range of organic and wholemeal cereals and pulses that are on offer.',
        week_3: 'Add flavour to your dishes with the help of herbs and spices from around the world and a well-chosen selection of fats.',
        week_4: 'Remember to go out in the fresh air and take a few deep breaths before sitting down at the table: it’s the best and healthiest way to increase your appetite.'
    }
};

function processCoachingData(data) {

    var activeCategory = getUrlParameter('category');
    var activeWeek = getUrlParameter('week');
    var tree = {};

    var categoryType, weekType, dayType, periodType, objective;

    data.map(function(row) {
        weekType = 'week_' + row.week;
        categoryType = row.type;
        objective = row.objectif
        dayType = 'day_' + row.day;
        periodType = row.period;

        if (objective !== '' && objective !== undefined && objective !== null)
            objective = objective.trim();

        // check line is complete and is not another header line :
        if (categoryType === '' || categoryType === undefined || categoryType === null ||
          dayType === '' || dayType === undefined || dayType === null ||
          weekType === '' || weekType === undefined  || weekType === null ||
          periodType === '' || periodType === undefined || periodType === null ||
          objective !== 'nutrition'
        )
            return;


        periodType = periodType.trim();
        categoryType = categoryType.trim();
        dayType = dayType.trim();
        weekType = weekType.trim();


        if (activeCategory === 'ideal_weight' && ('gain_weight' === categoryType || 'lose_weight' === categoryType))
            categoryType = 'ideal_weight';

        if (activeCategory !== '' && activeCategory !== categoryType)
            return;

        if (!(categoryType in tree))
            tree[categoryType] = {};

        if (activeWeek !== '' && activeWeek !== weekType)
            return;

        if (!(weekType in tree[categoryType]))
            tree[categoryType][weekType] = {};

        if (!(dayType in tree[categoryType][weekType]))
            tree[categoryType][weekType][dayType] = {};

        if (!(periodType in tree[categoryType][weekType][dayType]))
            tree[categoryType][weekType][dayType][periodType] = [];

        tree[categoryType][weekType][dayType][periodType].push({
            title: row.title,
            link: row.link,
            image: row.image,
        });
    });

    $(window).trigger('coachingDataReady', [tree, activeCategory, activeWeek]);
    return tree;
}

function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
