﻿var results = [],
    qShortLabels = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16'],
    qLabels = ['Differentiation', 'Communal specification', 'Individual specification', 'Internalization', 'Initiation', 'Legitimation', 'Enrolment', 'Activation', 'Interactional Workability', 'Relational Integration', 'Skill set Workability', 'Contextual Integration|Systematization', 'Communal appraisal', 'Individual appraisal', 'Reconfiguration'],
    overviewImg = 'http://chart.apis.google.com/chart?chf=bg,s,E7E7E800&cht=r&chs={WIDTH}x{HEIGHT}&chd=t:{DATA}&chco=008FD590&chm=B,008FD590,0,1,5&chxt=x,y,x&chxs=0,E7E7E8,9,-1,tl,CCCCCC20|1,000000,9,0.9,tl,CCCCCC20|2,E7E7E8,9,-1,tl,000000&chxl=|0:|_||||_||||_||||_|||1:|0|25|50|75|100|2:|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_&chls=2,0,0';
    imgUrl = 'http://chart.apis.google.com/chart?chf=bg,s,E7E7E800&cht=r&chs={WIDTH}x{HEIGHT}&chd=t:{DATA}&chco=008FD590&chm=B,008FD590,0,1,5&chxt=x,y&chxs=0,333333,9,1,lt,CCCCCC20|1,999999,9,0.9,tl,E5E5E520&chxl=0:|{LABELS}|1:|0|25|50|75|100&chls=2,0,0';

    $(function () {

        // *********** Intro links on menus ***************

        $('#nav li:has(ul)').each(function () {
            var introLabel = $('> a', this).text() == 'NPT Toolkit' ? 'NPT Toolkit' : 'Introduction';
            $('> ul', this).prepend('<li class="intro"><a href="' + $('> a', this).attr('href') + '">' + introLabel + '</a></li>');
        });

        // *********** Highlight navbar ***************

        var currUrl = location.href.split('/')[location.href.split('/').length - 1].replace('/', '');
        if (currUrl) $('#nav li a[href$=/' + currUrl + ']').parents().addClass('current');

        // *********** Create Level-3 navigation ***************

        if ($('#subNavigation').length && $('#nav li.current  li.current li').length) {
            $('#content').addClass('narrow');
            $('#subNavigation').html('<ul>' + $('#nav ul > li.current ul').html() + '</ul>');
            /*if ($('#subNavigation li.current').length == 0) {
            $('#subNavigation > a').addClass('current');
            }*/
        }
        else {
            $('#subNavigation').remove();
        }

        // *********** Citation date ***************

        var monthNames = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
        var now = new Date();
        var dateSuffix = 'th';

        if (now.getDate() == 1) { dateSuffix = 'st' }
        else if (now.getDate() == 2) { dateSuffix = 'nd' }
        else if (now.getDate() == 3) { dateSuffix = 'rd' }

        $('#date').text(now.getDate() + dateSuffix + " " + monthNames[now.getMonth()] + " " + now.getFullYear())

        // *********** Toolkit navigation ***************

        var currQ = 0;
        var totalQ = $('#toolkit .q').length;
        var qH = $('#toolkit .q:first').outerHeight();
        var qPadding = 10;
        var inView = 4;
        var sliderSteps = 10;

        // Round them corners
        if ($('#toolkit').length) {
            $('.buttons a, #results > div').corner();
            $('#toolkit .q').corner('15px');
        }
        $('#aux a, #subNavigation, #citation').corner();
        $('button').corner('5px');

        // Button behaviours
        $('a.prev').click(function () {
            if (!$(this).is('.disabled')) {
                currQ = currQ - inView;
                changeQ();
            }
            return false;
        });
        $('a.next').click(function () {
            if (!$(this).is('.disabled')) {
                currQ = currQ + inView;
                changeQ();
            }
            return false;
        });
        $('a.results').click(function () {

            // Reset results 
            results.length = 0;

            // Draw overview chart
            $('.q input').each(function () {
                results.push(parseFloat($(this).val()) * 10);
            });

            // Add the first number at the end to complete circle
            results.push(results[0]);
            $('#overview .resultsGraph').attr('src', overviewImg.replace('{WIDTH}', 280).replace('{HEIGHT}', 280).replace('{DATA}', results.join(',')));

            // Analysis charts
            for (group = 0; group < 4; group++) {
                var groupResults = results.slice(group * 4, (group * 4 + 4));
                groupResults.push(groupResults[0]);
                var groupLabels = qShortLabels.slice(group * 4, (group * 4 + 4));
                //$('#results .analysis:nth-child(' + (group + 2) + ') .resultsGraph').attr('src', 'http://chart.apis.google.com/chart?chf=bg,s,E7E7E8&cht=r&chs=180x180&chd=t:' + groupResults.join(',') + '&chco=008FD5&chm=B,008FD533,0,1.0,5.0&chxt=x&chxl=0:|' + groupLabels.join('|') + '&chls=2,0,0');
                $('#results .analysis:nth-child(' + (group + 2) + ') .resultsGraph')
                .attr('src', imgUrl.replace('{WIDTH}', 180).replace('{HEIGHT}', 180).replace('{DATA}', groupResults.join(',')).replace('{LABELS}', groupLabels.join('|')));
            }

            $('#toolkit').hide();
            $('#results').show();
            $('#questionsnav, #qnumbers, #resultsnav').toggle();
            return false;
        });

        $('a.back').click(function () {
            $('#results').hide();
            $('#toolkit').show();
            $('#questionsnav, #qnumbers, #resultsnav').toggle();
            return false;
        });

        $('a.download').click(function () {
            window.open('http://tools.normalizationprocess.org/GeneratePDF.aspx?A=' + results.join('|'));
            return false;
        });

        function changeQ() {

            // Animate Q into position
            var newH = -currQ * (qH + qPadding);
            //alert(newH);
            $('#questions').animate({ marginTop: newH + 'px' }, 1000);

            // Arrange buttons
            if (currQ == 0) {
                $('a.prev').addClass('disabled');
            }
            else {
                $('a.prev').removeClass('disabled');
            }

            // Highlight question number
            $('li.on', $('#qnumbers')).removeClass('on');
            $('#qnumbers li').filter(function (index) {
                return index >= currQ && index < currQ + inView;
            }).addClass('on');

            if (currQ >= totalQ - inView) {
                $('a.next').hide();
                $('a.results').show();
            }
            else {
                $('a.next').show();
                $('a.results').hide();
            }
        }

        // Add and navigate with titles
        $('.q').append('<div class="title min">Not at all</div><div class="title max">Completely</div>');

        /*$('.title').click(function () {
        var $s = $('div.slider', $(this).parent());
        var posL = $(this).is('.min') ? $('.handler', $s).width() / 2 : $s.width() - $('.handler', $s).width();
        positionHandler($s, $s.offset().left + posL, true);
        });*/


        // *********** Sliders ***************

        // Add sliders DOM
        $('input.slider').each(function () {
            $(this).val(5).after('<div class="slider"><div class="sliderbg"></div><div class="handler"></div></div>').hide();
        });

        // Add question numbers
        $('.q').each(function (i) {
            $('#qnumbers ul').append('<li ' + (i == 0 || i < inView ? 'class="on"' : '') + '><a href="#Question' + (i + 1) + '">' + (i + 1) + '</a></li>');
        });

        // Navigate with numbers
        $('#qnumbers a').click(function () {
            currQ = parseFloat($(this).text()) - 1;
            changeQ();
            return false;
        });


        // Trigger on moving the handler
        $('div.handler').mousedown(function (e) {
            var $s = $(this).parent();
            $(document)
            .mousemove(function (e) {
                positionHandler($s, e.pageX);
                return false;
            })
            .mouseup(function () {
                $(this).unbind('mousemove').unbind('mouseup');
            });
        });

        // Trigger on clicking on the slider
        $('div.slider').click(function (e) {
            positionHandler($(this), e.pageX, true);
        });

        // Reposition handler and set value
        function positionHandler($s, x, animate) {
            var $h = $('div.handler', $s);
            var $bg = $('div.sliderbg', $s);
            // Calc x position
            var posX = x - $s.offset().left;
            var stepW = Math.floor($s.width() / sliderSteps);
            var step = Math.floor(posX / stepW);
            posX = (step * stepW);

            if (step < sliderSteps && step >= 0) {
                var speed = animate ? 200 : 0;
                $h.animate({ left: posX + 'px' }, speed);
                $bg.animate({ width: (posX + stepW / 2) + 'px' }, speed);

                $('input', $s.parent()).val(step);
            }

        }

        // Duplicate statements for results 
        $('#results li').each(function (i) {
            $(this).text($('#questions h3').eq(i).text().split('. ')[1]);
        });

        // *********** Form validation ***************

        $('#btnSubmit').click(function () {
            $('#contactForm .mandatory').each(function () {
                if (this.value == '') {
                    $(this).addClass('error');
                }
            });
            if ($('#contactForm .error').length > 0) {
                alert('Please complete all fields marked with an asterisk.');
                return false;
            }
        });

        $('#contactForm .mandatory').blur(function () {
            if (this.value != '') {
                $(this).removeClass('error');
            }
        });

        // Send contact form to last page
        var redirectPage = $('input[name=hRedirect]').val() + '?page=' + location.href;
        $('input[name=hRedirect]').val(redirectPage);

        if (location.href.indexOf('your-feedback-has-been-sent.aspx?page=') != -1) {
            redirectPage = location.href.split('?page=')[1];
            $('#content p').html('<a href="' + redirectPage + '">Click here to return to the previous page</a>.');
        }

        //$('a.results').trigger('click');

    });
