// please don't judge me on this code; I feel like I just vomitted jQuery all over my vim buffer

$(function()
{
    // script
    $('.scriptMenu li a').click(function(event)
    {
        event.preventDefault();
        $('.scriptMenu li').removeClass('active');
        $(this).closest('li').addClass('active');
        $('.scriptContainer>div')
            .removeClass('active')
            .filter('.' + $(this).attr('rel'))
                .addClass('active');
    });

    // fake data
    var dailyData = [
        { day: 0, idx: 0, mood: 6.2123756385181, health: 5.33085475003188, bedtime: 7.52977642213009, waketime: 2.78028341501406, other: 'football day' },
        { day: 1, idx: 0, mood: 1.04805366240627, health: 2.56416630242072, bedtime: 0.537064902346622, waketime: 2.5450119286828, other: 'starting to get sick I think' },
        { day: 2, idx: 0, mood: 7.31867827591857, health: 5.6444447770333, bedtime: 9.27879473313628, waketime: 8.15841630738353, other: 'late night' },
        { day: 3, idx: 0, mood: 1.1938142103569, health: 1.78243899144042, bedtime: 0, waketime: 6.43989452704171, other: 'argument with rob yesterday' },
        { day: 4, idx: 0, mood: 7.02626571057477, health: 5.18565707824558, bedtime: 5.79002807941105, waketime: 2.3695362743637, other: 'first day at work' },
        { day: 5, idx: 0, mood: 9.20718057356141, health: 7.30517056102996, bedtime: 10, waketime: 8.07911441491039, other: 'board meeting' },
        { day: 6, idx: 0, mood: 1.35751136184477, health: 4, bedtime: 2, waketime: 8.25304900974936, other: 'nothing special today' },
        { day: 7, idx: 0, mood: 3.9470999376867, health: 2.77754271743905, bedtime: 2.6931177795382, waketime: 0.533407824572433, other: 'trouble sleeping' },
        { day: 8, idx: 0, mood: 7.62228551074345, health: 6.57795048114182, bedtime: 8.8685023265843, waketime: 3.78317609834699, other: 'more trouble sleeping' },
        { day: 9, idx: 0, mood: 2.82176994259506, health: 2.99093673768622, bedtime: 0.886247861730366, waketime: 8.51378713450794, other: 'still trouble sleeping' },
        { day: 10, idx: 0, mood: 7.11971372399741, health: 5.13954686327007, bedtime: 6.94790509015273, waketime: 1.63202743977142, other: 'stayed late at work' },
        { day: 11, idx: 0, mood: 3.1970728293215, health: 4.75662610356063, bedtime: 1.21611195122175, waketime: 3.35948736633193, other: 'board meeting' },
        { day: 12, idx: 0, mood: 8.702330171020611, health: 6, bedtime: 5, waketime: 4.65646216367805, other: 'good nights rest' },
        { day: 13, idx: 0, mood: 7.02581000844586, health: 5.09703221012579, bedtime: 6.51301684749931, waketime: 2.77126605737111, other: 'feel great' },
        { day: 14, idx: 0, mood: 1.7151650339041, health: 0.194524150423692, bedtime: 0.682586071442426, waketime: 2.55439593155178, other: 'starting to get sick again' }
    ];
    var eventData = [
        { day: 3, idx: 3, whatHappened: 'Just failed my midterm exam.' },
        { day: 7, idx: 4, whatHappened: 'There was a creepy guy on the bus.' },
        { day: 9, idx: 3, whatHappened: 'My team leader is a jerk!' },
        { day: 12, idx: 3, whatHappened: 'I bombed my job interview.' },
        { day: 13, idx: 4, whatHappened: 'I had a huge argument with my boss.' }
    ];
    var worksheetData = [
        { day: 8, idx: 3, shouldStatement: 'I should find a higher-paying job.' },
        { day: 10, idx: 3, shouldStatement: 'I should probably keep my opinions to myself.' },
        { day: 12, idx: 2, shouldStatement: 'I should really eat less.' }
    ];

    // main menu icons
    var isVizActive = false;
    $('.vizIcon').click(function(event)
    {
        event.preventDefault();

        if (!isVizActive)
        {
            $('.homeCombo').animate({
                bottom: '4px'
            });
            $('.vertHomeCombo').animate({
                left: '4px'
            });
            $('.homeScreen').animate({
                left: '29px',
                top: '-42px'
            });
            $('.iconVizActive').fadeIn('normal');
            $('.grid').fadeIn('normal');
        }
        else
        {
            $('.homeCombo').animate({
                bottom: '-35px'
            });
            $('.vertHomeCombo').animate({
                left: '-35px'
            });
            $('.homeScreen').animate({
                left: '-13px',
                top: 0
            });
            $('.iconVizActive').fadeOut('normal');
            $('.grid').fadeOut('normal');
        }
        isVizActive = !isVizActive;
    });

    // home screen
    $('.days').frictionScroll({
        paddingRight: 500
    });

    // init timeline
    var $nodeInfoBubble = $('.timeline .nodeInfoBubble');
    var newTimelineNode = function(data, type)
    {
        var $elem = $('<div class="node ' + type + '"></div>');
        $elem.appendTo($('.timeline'));

        var left = 20 * (data.idx + 1) + 125 * data.day;
        $elem.data('dotcalm-left', left);
        $elem.css('left', left + 'px');

        $elem.click(function()
        {
            if (isVizActive)
                return;

            $('.days').draggable('disable');

            $elem.addClass('active');
            $('.days').animate({
                    left: (-1 * left) + 40
                }, 'normal', 'swing',
                function()
                {
                    if (type == 'daily')
                        $('.timeline .nodeInfoBox.dailyLogBox')
                            .find('p').text(data.other).end()
                            .find('.mood').empty().append($('<div class="moodIndicator"><div class="indic" style="left:' + (data.mood * 20) + 'px"></div></div>')).end()
                            .find('.health').empty().append($('<div class="moodIndicator"><div class="indic" style="left:' + (data.health * 20) + 'px"></div></div>')).end()
                            .find('.bedTime').text($.floatToBedTime(data.bedtime)).end()
                            .find('.wakeTime').text($.floatToWakeTime(data.waketime)).end()
                            .css('left', (left - 8) + 'px')
                            .fadeIn('normal');
                    else if (type == 'event')
                        $('.timeline .nodeInfoBox.eventLogBox')
                            .find('p').text(data.whatHappened).end()
                            .css('left', (left - 8) + 'px')
                            .fadeIn('normal');
                    else if (type == 'worksheet')
                        $('.timeline .nodeInfoBox.worksheetLogBox')
                            .find('p').text(data.shouldStatement).end()
                            .css('left', (left - 8) + 'px')
                            .fadeIn('normal');
                }
            );
        });
    };
    $.each(dailyData, function()
    {
        newTimelineNode(this, 'daily');
    });
    $.each(eventData, function()
    {
        newTimelineNode(this, 'event');
    });
    $.each(worksheetData, function()
    {
        newTimelineNode(this, 'worksheet');
    });
    $('.timeline .nodeInfoBox .xButton').click(function()
    {
        $('.timeline .nodeInfoBox').fadeOut('normal',
            function()
            {
                $('.node.active').removeClass('active');
                $('.days').draggable('enable');
            });
    });
    var timelineTimer = null;
    var $timeline = $('.timeline');
    var timelinePos = 0;
    timelineTimer = setInterval(function()
    {
        $timeline.css('background-position', timelinePos + 'px center');
        timelinePos = (timelinePos - 1) % 533;

        $timeline.find('.node').each(function()
        {
            var $node = $(this);
            var top = (Math.sin(($node.data('dotcalm-left') - timelinePos) / 85 - 1.2) * 43 + 147);
            $node.css('top', top + 'px');
            if ($node.is('.active'))
                $nodeInfoBubble.css('top', (top - 8) + 'px');
        });
    }, 50);

    // 2d viz
    var newGraphNode = function(data)
    {
        var $elem = $('<div class="node daily"></div>');
        $elem.appendTo($('.graph'));
        $elem.css('top', '-26px');
        $elem.css('left', (Math.random() * 480) + 'px');
        $elem.data('dotcalm-data', data);
        $elem.data('dotcalm-pos', { x: 0, y: 0 });

        $elem.click(function()
        {
            if (isVizActive)
                return;

            var pos = $elem.data('dotcalm-pos');

            $elem.addClass('active');
            $('.graph').animate({
                    left: -1 * (pos.x - 54),
                    top: 160 - pos.y
                }, 'normal', 'swing',
                function()
                {
                    $('.graph .nodeInfoBox')
                        .find('p').text(data.other).end()
                        .find('.mood').empty().append($('<div class="moodIndicator"><div class="indic" style="left:' + (data.mood * 20) + 'px"></div></div>')).end()
                        .find('.health').empty().append($('<div class="moodIndicator"><div class="indic" style="left:' + (data.health * 20) + 'px"></div></div>')).end()
                        .find('.bedTime').text($.floatToBedTime(data.bedtime)).end()
                        .find('.wakeTime').text($.floatToWakeTime(data.waketime)).end()
                        .css('left', (pos.x - 22) + 'px')
                        .css('top', (pos.y - 155) + 'px')
                        .fadeIn('normal');
                }   
            );
        });
    };
    $.each(dailyData, function()
    {
        newGraphNode(this);
    });
    $('.graph .nodeInfoBox .xButton').click(function()
    {
        $('.graph').animate({
            left: 0,
            top: 0
        });
        $('.graph .nodeInfoBox').fadeOut('normal',
            function()
            {
                $('.node.active').removeClass('active');
            });
    });
    var is2Dviz = false;
    var axes = { x: 'day', y: 'wave' };
    var updateGraph = function()
    {
        if (axes.y == 'wave')
        {
            $('.invalidGraph')
                .html('please choose a variable besides <em>wave</em>')
                .fadeIn();
            return;
        }
        if (axes.x == 'day')
        {
            $('.invalidGraph')
                .html('please choose a variable besides <em>days</em>')
                .fadeIn();
            return;
        }
        $('.invalidGraph').fadeOut();

        $('.graph .node').each(function() {
            var $node = $(this);
            var data = $node.data('dotcalm-data');
            var pos = { x: data[axes.x] * 48, y: (10 - data[axes.y]) * 32 };

            $node.data('dotcalm-pos', pos);
            $node.animate({
                top: (pos.y - 13) + 'px',
                left: (pos.x - 13) + 'px'
            });
        });
    };

    $('.homeComboControl').dropDown({
        clickedCallback: function($elem)
        {
            if ($elem.is('.option'))
            {
                var axis = $elem.parents().is('.vertHomeComboPop') ? 'y' : 'x';
                var sel = $elem.attr('rel');
                if (sel == 'wave')
                {
                    // abort viz, go back to wave
                    axes.x = 'day';
                    $('.homeCombo')
                        .removeClass('day wave mood health bedtime waketime')
                        .addClass('day');
                    axes.y = 'wave';
                    $('.vertHomeCombo')
                        .removeClass('day wave mood health bedtime waketime')
                        .addClass('wave');
                    $('.graph .node').each(function()
                    {
                        $(this).css('top', '-26px')
                               .css('left', (Math.random() * 480) + 'px');
                    });
                    if (is2Dviz)
                    {
                        $('.graph').fadeOut();
                        $('.days').fadeIn();
                        is2Dviz = false;
                    }
                    return true;
                }
                else if ((sel == 'day') && (axes.y != 'wave'))
                {
                    alert('day view is not supported in this prototype except when ' +
                          'viewing the wave on the y axis; please select another option.');
                    return false;
                }

                axes[axis] = sel;
                $elem
                    .closest('.homeComboControl')
                    .find('.trigger')
                    .removeClass('day wave mood health bedtime waketime')
                    .addClass(sel);
                updateGraph();
                if (!is2Dviz)
                {
                    $('.graph').fadeIn();
                    $('.days').fadeOut();
                    is2Dviz = true;
                }
                return true;
            }
        },
        hideTrigger: false
    });

    // new form
    $('.newMenuArea').dropDown({
        clickedCallback: function($elem)
        {
            if ($elem.is('.optionNew'))
            {
                $('.formBackground').fadeIn();
                var type = $elem.attr('rel');
                if (type == 'daily')
                    $('.dailyWrapper').show().css('margin-left', 0);
                else if (type == 'event')
                    $('.eventWrapper').show().css('margin-left', 0);
                else if (type == 'worksheet')
                    $('.worksheetWrapper').show().css('margin-left', 0);
                $('.dailyHead').text($elem.text());

                $('.progress').empty();
                for (var i = 0; i < $('.questionWrapper>div:visible .question').length; i++)
                    $('.progress').append($('<li></li>'));
                $('.progress li:first').addClass('active');

                return true;
            }
            else
            {
                return $elem.is('.xButton');
            }
        }
    });
    $('.formBackground .xButton').click(function()
    {
        $('.formBackground')
            .fadeOut()
            .find('.questionWrapper').children().hide();
    });
    $('.formBackground .backButton').click(function()
    {
        var $form = $('.questionWrapper>div:visible');
        if (parseInt($form.css('margin-left')) == 0)
            return;
        $form.animate({
            marginLeft: (parseInt($form.css('margin-left')) + 440) + 'px'
        });
        $('.progress li.active')
            .removeClass('active')
            .prev().addClass('active');
        if (parseInt($form.css('margin-left')) > -450)
            $('.formBackground .backButton').addClass('disabled');
    });
    var slidersinit = false;
    $('.formBackground .forwardButton').click(function()
    {
        var $form = $('.questionWrapper>div:visible');
        if (($form.find('.question').length - 1) * 440 <= -1 * parseInt($form.css('margin-left')))
        {
            var data = {};
            var type = '';
            if ($form.is('.dailyWrapper'))
            {
                data = {
                    idx: 0,
                    mood: 5,
                    health: 5,
                    bedtime: 5,
                    waketime: 5,
                    other: ''
                };
                type = 'daily';
            }
            if ($form.is('.eventWrapper'))
            {
                data = {
                    idx: 2,
                    whatHappened: ''
                };
                type = 'event';
            }
            if ($form.is('.worksheetWrapper'))
            {
                data = {
                    idx: 4,
                    shouldStatement: ''
                };
                type = 'worksheet';
            }
            $form.find('.question').each(function()
            {
                var value = $(this).data('dotcalm-value');
                if (value !== null && value !== undefined)
                    data[$(this).attr('rel')] = value;
            });
            data.day = 15;
            if (type == 'daily')
                newGraphNode(data);
            newTimelineNode(data, type);
            $('input').val('');
            $('.formBackground').fadeOut('normal', function()
            {
                $form.hide(); 
            });
            return;
        }
        $('.formBackground .backButton').removeClass('disabled');
        $form.animate({
            marginLeft: (parseInt($form.css('margin-left')) - 440) + 'px'
        });
        $('.progress li.active')
            .removeClass('active')
            .next().addClass('active');
        if (!slidersinit)
        {
            slidersinit = true;
            $('.timeSlider .timeSliderInner').frictionScroll({
                moveInit: false,
                noContainment: true
            });
        }
    });

    // controls
    $('.slider .nub').draggable({
        axis: 'x',
        containment: 'parent',
        drag: function(event, ui)
        {
            var $this = $(this);
            $this.closest('.question').data('dotcalm-value', parseInt($this.css('left')) / 43.4);
        }
    });
    $('.questionInput').keyup(function(event)
    {
        $(this).closest('.question').data('dotcalm-value', $(this).val());
    });
    $('.distortionsEditButton').click(function(event)
    {
        $('.distortionsPopup').animate({
            bottom: 0
        });
    });
    $('.distortionsPopupDone').click(function(event)
    {
        $('.distortionsEditor').text('mind reading, predicting the future');
        $('.distortionsPopup').animate({
            bottom: '-279px'
        });
    });

    $('.unsupportedButtons').click(function(event) { alert('sorry, those features are not supported in this demo.'); });
});
