Demo entry 1487327

gmba javascript

   

Submitted by anonymous on Apr 22, 2015 at 17:02
Language: JavaScript. Code size: 75.8 kB.

(function ($) {

    var gmba = gmba || {},
    s,
    $this,
    staff = ['kellis1', 'kle103', 'ac6414', 'js308', 'mwells', 'omerlo', 'aeisinge', 'rl812', 'hsiddiq', 'aktownse', 'abogdan', 'djl201', 'cskinsle', 'jbourgui', 'jdosreis', 'ncollis', 'ghedges', 'szhang4'],
    access = false,
    decider = false,

    // Helper functions

    loader5 = '<div id="loader5"><p></p></div>',
    loader = '<img id="loader" src="../../../resources/img/ajax-loader.gif"/>';

    loadersnake = '<img id="loadersnake" src="../../../resources/img/ajax-loader-snake.gif"/>',
    user = $('.bp-login-widget-user-link a', window.parent.document),
    name = user.attr('title'),
    username = user.attr('href'),
    username1 = user.attr('href'),
    userimg = $('.bp-login-widget-user-avatar a img', window.parent.document),
    post = '<div class="post"></div>',
    furtherInfoFrame = $('#further-info-frame', window.parent.document),
    boo = false,
    completed = false,
    timing = 7500,
    answer = '',
    gmba.ajax = {

        init: function (opts) {
            var params = {
                    dataType    : opts.dataType || "",
                    url         : opts.url  || "",
                    data        : opts.data || "",
                    beforeSend  : opts.beforeSend || function () {},
                    success     : opts.onSuccess || function () {},
                    error       : opts.onError || function () {},
                    timeout     : opts.timeout  || 10000,
                    done        : false
                };
            $.ajax(params);
        }
    },

    //chars count

    gmba.chars = {
        init: function (chars) {
            $('.chars').text(chars);
            var counting = '';
            if($('.image-tile').length){
                counting = $('.chars').prev('textarea');
            }else{
                counting = $('.chars').prev('input');
            }
            counting.keyup(function() {
                var val = $(this),
                len = val.val().length;
                if (len >= chars +1) {
                  val.value = val.val().substring(0, chars);
                  val.keypress(function (e) {e.preventDefault()});
                } else {
                    $('.chars').text(chars - len);
                }
            });
        }
    }

    //print
    gmba.print = {
        init: function () {
            var doc = new jsPDF('landscape'),
            name = $('#print').data('activity');

            doc.fromHTML($('#print').get(0), 15, 15, {
                'width': 750
            });
            var windowName = 'userConsole'; 
            var popUp = doc.output('dataurlnewwindow', {});
            if (popUp == null || typeof(popUp)=='undefined') {  
                $('.print').after('<p>Your browser may have a block on pop ups.</p> <p>Please press \'SAVE TO PDF\' again.</p>')
            }
        }
    },

    //scrolltop
    gmba.scrollTop = {
        init: function () {
            var frame = parent.document.getElementById("activity-frame");
            if(frame !== null){
                var scroll = frame.offsetTop + 160;
                top.scrollTo(0,scroll)
            }
        }
    },

    gmba.scrollBottom = {
        init: function () {
            var frame = parent.document.getElementById("activity-frame");
            if(frame !== null){
               $('html, body', window.parent.document).animate({scrollTop: $('#activity-frame', window.parent.document).height() + 300}, 1500);
            }
        }
    },

    // Activities

    gmba.chart = {

        beforeSend: function () {
            $('#loader').remove();
            $('#loader5').remove();
            $('.chart-area-wrapper').append(loader);
        },

        onSuccess: function (data) {
            $('#loader').remove();
            $('body').css('background', 'white');
            var i = 0,
                k = 0,
                colors = ['#b81a0e', '#c56b17', '#f9c94e', '#4d9d2d', '#15175e', '#751280', '#560826', '#463827', '#cd6f93', '#baa590'],
                rgbcol = ['rgba(184,26,14,0.2)', 'rgba(197,107,23,0.2)', 'rgba(249,201,78,0.2)', 'rgba(77,157,45,0.2)', 'rgba(21,23,94,0.2)']
                answers = [],
                labels = [],
                sizes = [],
                piedata = [],
                arr = [],
                prev = '',
                graph = data.graph,
                options = $('.graph form options').length;

                // setting graph colours

                if($('.bluered').length){
                    colors = ['#15175e', '#b81a0e']
                }

                // extracts question to show with answer

                var question = $('.ss-form-question:first-of-type .ss-q-title').text();
                $('.chart').prepend(("<p class='question'><em>"+question+"</em></p>"));
                if($('.feedback').length){
                    $('.youranswer').after('<p>'+answer+'</p>');
                }

                // works out aggregate score of results

                if($('.aggregate').length){
                    var count = data.graph.length,
                    groupAgg = 0,
                    personalAgg = 0;

                    // Group Aggregate

                    for (var i = 0; i < data.graph.length; i++) {
                        var object = data.graph[i],
                            object2 = data.graph[count-1],
                            value = '';
                        for (property in object) {
                            if(object[property] <= 5){
                                value = object[property];
                            }else{
                                value = 3;
                            }
                            if(property !== 'Timestamp'){
                                if(value != ''){
                                    groupAgg += value;
                                }else{
                                    groupAgg += 3;
                                }
                            }
                        }
                    }

                    groupAgg = groupAgg / count;
                    if(!$('.noround').length){
                        groupAgg = Math.round(groupAgg);
                    }

                    // Personal Aggregate

                    var object2 = data.graph[count-1],
                    value2 = '';
                    for (property2 in object2) {
                         if(object[property2] <= 5){
                                value2 = object2[property2];
                            }else{
                                value2 = 3;
                            }
                        if(property2 !== 'Timestamp'){
                            if(value != ''){
                                personalAgg += value2;
                            }else{
                                personalAgg += 3;
                            }
                        }
                    }

                    if($('.addition').length){
                        var p = parseFloat(personalAgg),
                        g = parseFloat(groupAgg),
                        result = p + g;
                        $('.chart-area').after('<div class="key"><p>The deal comes to $'+ result +'m but you only had $2.8m!</p></div>')
                    }

                    labels = ['Group Result', 'Your Result'],
                    sizes = [groupAgg, personalAgg];
                }

                // matrix bar

                else if($('.matrix-bar').length){
                     $('.chart-area').after('<div class="key"><table></table></div>');
                    $(".chart form .ss-gridrow-leftlabel").each(function(){
                        if($(this).text() !== ''){
                            labels.push($(this).text());
                        }
                    });
                    $(".chart thead td").each(function(){
                        if($(this).find('label').text() !== ''){
                            if($(this).find('label').text() === 'True' || $(this).find('label').text() === 'False'){
                                answers.push($(this).find('label').text().toLowerCase());
                            } else{
                                answers.push($(this).find('label').text());
                            }

                        }
                    });
                    var r = $('thead tr td').length - 1;
                    var c = labels.length;

                    // adds answers to array

                    for(var i=0; i<r; i++ ) {
                      arr[answers[i]] = [];
                    }

                    // adds questions to array udner each answer
                    for (var i = 0; i < r; i++)
                    {
                        for (var j =  arr[answers[i]].length; j < c; j++)
                        {
                            arr[answers[i]][labels[j]] = 0;

                        }
                    }

                   if($('.shortlabels').length){
                        for(var i=0; i<c; i++ ) {
                            labels[i] = labels[i].substring(0, labels[i].indexOf('.'));
                        }
                    }

                    // loops through data to add each time each answer appears for each question

                    for (var key in graph) {
                        var obj = graph[key];
                        for (var prop in obj) {
                           if(obj.hasOwnProperty(prop)){
                                if(prop != 'Timestamp'){
                                    if(prop != 'username'){
                                        prop2 = prop.replace(/_/g, ' '),
                                        prop2 = $.trim(prop2);
                                        arr[obj[prop]][prop2] ++;
                                    }
                                }
                            }
                        }
                    }

                    // extracts this information into simple array

                    var arr2 = [],
                    counter = 0;
                    for(key in arr) {
                        arr2.push([]);
                        var obj = arr[key];
                        for (var prop in obj) {
                           if(obj.hasOwnProperty(prop)){
                                arr2[counter].push(obj[prop]);
                            }
                        }
                        counter ++;
                    }

                    var sets = [];

                     for(var k = 0; k < r; k++){
                        sets.push(
                            {
                                label: "GMBA",
                                fillColor: rgbcol[k],
                                strokeColor: rgbcol[k],
                                pointColor: rgbcol[k],
                                pointStrokeColor: "#fff",
                                pointHighlightFill: "#fff",
                                pointHighlightStroke: rgbcol[k],
                                data: arr2[k]
                            }
                        )

                        $('.key table').append('<tr><td><svg height="20" width="20"><circle cx="10" cy="10" r="20" fill='+rgbcol[k]+' /></svg></td><td>'+answers[k]+'</td></tr>')
                    }

                    var chartData = {
                                    labels: labels,
                                    datasets: sets
                    }

                }

                // pie charts

                else if($('.pie').length)


                {
                    $('.chart-area-wrapper').css('overflow', 'auto');
                    $('.chart-area').after('<div class="key"><table></table></div>');
                    for(; k < data.graph.length; k++){
                        if(graph[k].answers.length != 0)
                        arr.push(graph[k].answers);
                    };
                    arr.sort();
                    if($('.pie.truefalse').length){
                        arr.reverse();
                    }
                    for ( var i = 0; i < arr.length; i++ ) {
                        var percent = arr.length / 100;
                        if ( arr[i] !== prev ) {
                            labels.push(arr[i]);
                            sizes.push(1);
                        } else {
                            sizes[sizes.length-1] ++;
                        }
                        prev = arr[i];
                    }
                    var total = arr.length;
                    for(var j = 0; j < labels.length; j++){
                        piedata.push({value: Math.round((sizes[j] / total) * 100), color: colors[j], highlight: '#000', label: labels[j]});
                        if($('.key').length){
                            $('.key table').append('<tr><td><svg height="20" width="20"><circle cx="10" cy="10" r="20" fill='+colors[j]+' /></svg></td><td>'+labels[j]+'</td></tr>')
                        }
                    }
                }

                // line graphs

                else if($('.line').length)

                {
                    $(".chart form option").each(function(){
                        if($(this).val() !== ''){
                            labels.push($(this).val());
                        }
                    });
                    if($('.cummulative').length){
                        for ( var i = 0; i < labels.length; i++ ) {
                            sizes.push(0);
                            for( var k = 0; k< graph.length; k++){
                                if(labels[i] === graph[k].answers){
                                    for(var j = 0; j<=i; j++){
                                        sizes[j]++;
                                    }
                                }
                            }
                        }
                    }else{
                        for ( var i = 0; i < labels.length; i++ ) {
                            sizes.push(0);
                            for( var k = 0; k< graph.length; k++){
                                if(typeof graph[k].answers === "number"){
                                    graph[k].answers = graph[k].answers.toString();
                                }
                                if(labels[i] === graph[k].answers){
                                       sizes[i]++;
                                }
                            }
                        }
                    }
                }else if($('.individual').length){
                    $(".chart form .ss-choice-label").each(function(){
                        if($(this).text() !== ''){
                            labels.push($(this).text());
                        }
                    });
                    for ( var i = 0; i < labels.length; i++ ) {
                        sizes.push(0);
                        for( var k = 0; k < graph.length; k++){
                            if(labels[i] === graph[k].answers){
                                sizes[i]++;
                            }
                        }
                        if($('.shortlabels').length){
                            labels[i] = labels[i].substring(0, labels[i].indexOf('.'));
                        }
                    }
                }else if($('.multi').length){
                     $(".chart input[type='checkbox']").each(function(){
                        if($(this).val() !== ''){
                            labels.push($(this).val());
                        }
                    });
                    for ( var i = 0; i < labels.length; i++ ) {
                        sizes.push(0);
                        for( var k = 0; k< graph.length; k++){
                            result = graph[k].answers.split(',');
                            for(var j = 0; j < result.length; j++){
                                if(labels[i] === result[j].trim()){
                                    sizes[i]++;
                                }
                            }
                        }
                        if($('.shortlabels').length){
                            labels[i] = labels[i].substring(0, labels[i].indexOf('.'));
                        }
                    }
                }

                // chartdata 

                if(!$('.matrix-bar').length){

                var chartData = {
                                    labels: labels,
                                    datasets: [
                                        {
                                            label: "GMBA",
                                            fillColor: "rgba(102,102,102,0.2)",
                                            strokeColor: "rgba(102,102,102,1)",
                                            pointColor: "rgba(102,102,102,1)",
                                            pointStrokeColor: "#fff",
                                            pointHighlightFill: "#fff",
                                            pointHighlightStroke: "rgba(82,82,82,1)",
                                            data: sizes
                                        },
                                    ]
                                }
                }

                // inject chart

                if($('.chart-area').length){
                     $('.chart-area').empty().append('<canvas id="myChart" width="400" height="200" style="background: white"></canvas>');
                     if($('form').data("name")){
                        $('.chart-area-wrapper').before("<h3>"+$('form').data("name")+" Result</h3>")
                     }else if($('.result').length){
                        $('.chart-area-wrapper').before("<h3>Previous Result</h3>")
                     }else{
                        $('.chart-area-wrapper').before("<h3>Your Cohort Answered</h3>")
                     }
                    var ctx = document.getElementById("myChart").getContext("2d");
                    //var isiPad = navigator.userAgent.match(/iPad/i) != null;
                    if($('.line').length){
                        var myLineChart = new Chart(ctx).Line(chartData, {tooltipTemplate: "<%if (label){%><%}%><%= value %> People", responsive: true, showTooltips: false,  tooltipFontSize: 10, onAnimationComplete : function(){this.showTooltip(this.datasets[0].points)}});
                     }else if($('.bar').length){
                        if(!$('.matrix-bar').length){
                            var myBarChart = new Chart(ctx).Bar(chartData, {tooltipTemplate: "<%if (label){%><%}%><%= value %>", responsive: true, showTooltips: false,  tooltipFontSize: 12, onAnimationComplete : function(){this.showTooltip(this.datasets[0].bars)}});
                        }else{
                            var myBarChart = new Chart(ctx).Bar(chartData, {tooltipTemplate: "<%if (label){%><%}%><%= value %>", responsive: true, showTooltips: true,  tooltipFontSize: 12, });
                        }
                     }else if($('.pie').length){
                         var myPieChart = new Chart(ctx).Pie(piedata, {tooltipTemplate: "<%if (label){%><%}%><%= value %>%", responsive: true, showTooltips: true, tooltipFontSize: 12});
                     }

                     if(boo === true){
                            if($('.key').length){
                                $('.key').after('<button class="return">Return to Form</button>');
                            }else{
                                $('.chart-area-wrapper').css('overflow', 'auto').append('<button class="return">Return to Form</button>');
                            }
                     }

                     if($('.feedback').length && completed === true || boo === false){
                        $('.feedback').appendTo('.chart-area-wrapper').fadeIn();
                     }
                     if($('.further-info').length && boo === false){
                        $('.further-info').fadeIn();
                        if($('.vid-pres').length){
                            gmba.popcorn.init();
                        }
                     }
                     if($('.key').length){
                        $('.key').fadeIn();
                     }
                     if($('.longlabels').length){
                        $('.longlabels').fadeIn();
                     }
                }
                window.parent.postMessage('iframe-update', '*');

                // responsiveness during window resize

                setTimeout(function(){
                    $( window ).resize(function(){
                    if($('.line').length){
                        var myLineChart = new Chart(ctx).Line(chartData, {tooltipTemplate: "<%if (label){%><%}%><%= value %> People", responsive: true, showTooltips: true,  tooltipFontSize: 10, tooltipTemplate: "<%if (label){%><%}%><%= value %> People",});
                    }else if($('.bar').length){
                        var myBarChart = new Chart(ctx).Bar(chartData, {responsive: true, showTooltips: true});
                    }else if($('.pie').length){
                        var myPieChart = new Chart(ctx).Pie(piedata, {tooltipTemplate: "<%if (label){%><%}%><%= value %>%", responsive: true, showTooltips: true});
                    }
                })}, 10000);
                if(furtherInfoFrame.length){
                    furtherInfoFrame.show();
                }
                 window.parent.postMessage('iframe-update', '*');
        },

        onError: function () {
            $('#loader').remove();
            $('.chart-area').html('<p>There has been an error please try again later</p>');
        },

        ajax: function () {
            var json = $('.chart form').data('url'),
                j = 'https://script.google.com/macros/s/AKfycbx1e7fju-b7tD4LYuzBZUdrjm5HrdH0EINhZkvebroWHQQq4Q/exec?id='+json+'&sheet=graph',
                opts = {
                    dataType  : 'jsonp',
                    url       : j,
                    beforeSend : gmba.chart.beforeSend,
                    onSuccess : gmba.chart.onSuccess,
                    onError   : gmba.chart.onError
                };
                gmba.ajax.init(opts);
        },

        bind: function () {
                $('.chart .ss-form').fadeOut().promise().done(function() {
                    //loader = loader5;
                    if($('.key').length){
                        $('.key').before('<div class="chart-area-wrapper">'+loader+'<div class="chart-area"></div></div>')
                    }
                    else if($('.longlabels').length){
                       $('.longlabels').before('<div class="chart-area-wrapper">'+loader+'<div class="chart-area"></div></div>')
                    }
                    else if($('.further-info').length){
                        $('.further-info').before('<div class="chart-area-wrapper">'+loader+'<div class="chart-area"></div></div>')
                    }
                    else{
                        $('.chart').append('<div class="chart-area-wrapper">'+loader+'<div class="chart-area"></div></div>')
                    }
                    if(boo !== true && !$('.result').length){
                        $('.chart-area-wrapper').prepend(loader5);
                        gmba.timer.init();
                    }
                });

                $('body').on('click', '.chart .return', function() {
                    $('.chart').empty().append(loader);
                    setTimeout(function(){ location.reload();}, 400);
                });
        },

        init: function () {

            // adds username to secret box in form

            if($('form input[title="username"]').length){
                username = username.split("/")[7];
                $('form input[title="username"]').val(username);
            }


            window.parent.postMessage('iframe-update', '*');
            $('.chart form').submit(function () {
                if($('input[type="radio"]').length){
                    answer += document.querySelector('input[type="radio"]:checked').value;
                }else if($('input[type="checkbox"]').length){
                    $('input[type="checkbox"]').each(function () {
                            if($(this).is(':checked') === true){
                                answer += $(this).val()+'</br>';
                            }
                    });
                }else if($('.chart form option').length){
                    $('.chart form option').each(function () {
                            if($(this).is(':selected') === true){
                                answer += $(this).val()+'</br>';
                            }
                    });
                }
                gmba.chart.bind();
                setTimeout(function(){gmba.chart.ajax()}, timing);
            });
            $('.view').on('click', function(e) {
                e.preventDefault();
                gmba.chart.bind();
                gmba.chart.ajax();
                boo = true;
            });

            if($('.result').length){
                gmba.chart.bind();
                gmba.chart.ajax();
            }

            if(furtherInfoFrame.length){
                furtherInfoFrame.hide();
            }
        }
    },

    gmba.compareMatrixResult = {
        init: function () {
            $('.decider').fadeOut();
            var res = [];
           $('.own-result-matrix .yours').each(function () {
                res.push($(this).index());
           })
            var row = $('.summary-matrix tbody tr').length;
            for(i=0;i<=row;i++){
                $('.summary-matrix tbody tr:nth-child('+ (i+1) +')').find($('td:nth-child(2)')).text(res[i]);
            }
            var compare = decider ? this.selfCompare(res) : this.prevCompare(res);
        },

        selfCompare: function (res) {
            var row = $('.summary-matrix tbody tr').length;
            for(i=0;i<=row;i++){
                $('.summary-matrix tbody tr:nth-child('+ (i+1) +')').find($('td:nth-child(3)')).text(res[i]);
            }
            $('.summary-matrix').delay(1000).fadeIn(function () {
                 window.parent.postMessage('iframe-update', '*');
            });
        },

        prevCompare: function (res) {
                $('.compare-matrix').delay(1000).fadeIn(function () {
                    window.parent.postMessage('iframe-update', '*');
                });
                $('.compare-matrix form').on('submit', function() {
                    $('.compare-matrix #navigation-table').hide();
                    $('.compare-matrix input[type="radio"]:checked').each(function() {
                    $(this).parents('td').addClass('yours');
                });
                $('.compare-matrix form td input').fadeOut();
                setTimeout(gmba.compareMatrixResult.css, 1000);
            });
        },
        css: function (){
            $('.compare-matrix .yours').css({'background' : '#eee'}).append('<span>Your Choice</span>');
            window.parent.postMessage('iframe-update', '*');
            gmba.compareMatrixResult.result();
        },
        result : function() {
            var res2 = [];
            $('.compare-matrix .yours').each(function () {
                res2.push($(this).index());
           });
            var row = $('.summary-matrix tbody tr').length;
            for(j=0;j<=row;j++){
                $('.summary-matrix tbody tr:nth-child('+ (j+1) +')').find($('td:nth-child(3)')).text(res2[j]);
            }
            $('.summary-matrix').fadeIn(function () {
                window.parent.postMessage('iframe-update', '*');
            });
        }

    },

    gmba.decider = {
        init: function (){
            $('.compare-matrix').hide();
            $('.summary-matrix').hide();
            $('#compare-matrix', window.parent.document).hide();
            $('#compare-matrix-result', window.parent.document).hide();
            $('.decider form').on('submit', function(){
                if($('.decider form input[type="radio"]:checked').val() === 'Yes'){
                    decider = true;
                    gmba.compareMatrixResult.init();
                }else{
                    gmba.compareMatrixResult.init();
                }
            });
        }
    },

    gmba.formThankyou = {
        init: function () {
            $('.thankyou').hide();
            this.bind();
        },
        bind : function () {
            $('.simple-form').on('submit', function () {
                $('.ss-form').fadeOut(function () {
                    $('.thankyou').fadeIn();
                    window.parent.postMessage('iframe-update', '*');
                })
            });
        }
    },

    gmba.geolocate = {


        setMarkers: function (data, map) {
                var infowindow = null,
                    html = '<div class="iw"><div class="imgwrap"><a target="_blank" class="iw-img" href=""><img/></a></div><div class="iw-content"><h4></h4><p></p></div><div class="feedback"><h3>Tutor Feedback</h3></div></div>';
                infowindow = new google.maps.InfoWindow({
                    content: "holding..."
                });
                var pinColor = '';
                $.each( data.geolocate, function(gmarker, index) {
                    switch (data.geolocate[gmarker].Category) {
                        case 'Professional services':
                            pinColor = '78da65'
                            break;
                        case 'Manufacturing':
                            pinColor = '6594da'
                            break;
                        case 'Healthcare':
                            pinColor = 'da65c3'
                            break;
                        case 'Technology':
                            pinColor = 'da656a'
                            break;
                        case 'Finance':
                            pinColor = 'daa765'
                            break;
                        case 'Entertainment':
                            pinColor = '7365da'
                            break;
                        case 'Other':
                            pinColor = '65dac5'
                            break;
                        default:
                            pinColor = '78da65'
                        }
                        pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor),
                        ll = data.geolocate[gmarker].Location.split(","),
                        myLatlng = new google.maps.LatLng(ll[0], ll[1]);
                    var marker = new google.maps.Marker({
                        position: myLatlng,
                        map: map,
                        icon: pinImage
                    });
                    google.maps.event.addListener(marker, 'click', function () {
                        infowindow.setContent(html);
                        infowindow.open(map, this);
                        if($('form').data('title') !== undefined){
                            $('.iw-content').prepend('<h3>'+$('form').data('title')+'</h3>')
                        }
                        if(data.geolocate[gmarker].Image_URL != undefined){
                            $('.iw-img').attr('href', data.geolocate[gmarker].Image_URL);
                            $('.iw-img img').attr('src', data.geolocate[gmarker].Image_URL);
                        }else{
                            $('.imgwrap').remove();
                            $('.iw-content').addClass('noimage');
                        }
                        if(data.geolocate[gmarker].Image_URL2 != undefined){
                            $('.imgwrap').append('<a class="iw-img2" href="'+ data.geolocate[gmarker].Image_URL2 +'"><img/></a>');
                            $('.iw-img2 img').attr('src', data.geolocate[gmarker].Image_URL2);
                        }
                        if(data.geolocate[gmarker].Category != undefined && data.geolocate[gmarker].Category.length){
                            $('.iw-content h4').text(data.geolocate[gmarker].Category);
                        }
                        $('.iw-content p').text(data.geolocate[gmarker].Comment);
                        if(data.geolocate[gmarker].Feedback != undefined && data.geolocate[gmarker].Feedback.length){
                            $('.iw .feedback').append('<p>'+data.geolocate[gmarker].Feedback+'</p>')
                            $('.feedback').show();
                        }
                        if(data.geolocate[gmarker].Endorse != undefined && data.geolocate[gmarker].Endorse.length){
                            $('.iw ').addClass('starred').prepend('<p class="flagged">Tutor endorsed</p>');
                        }
                        if(data.geolocate[gmarker].username != undefined && data.geolocate[gmarker].username.length){
                            $('.iw-content h3').after('<div class="user"><a target="_parent" href="https://www.imperial.ac.uk/business-school/elearning/hub/members/' + username + '/messages/compose/?r=' + data.geolocate[gmarker].username + '"><img src="' + data.geolocate[gmarker].userimage + '"/><p>'+data.geolocate[gmarker].username+'</p></a></div>')
                        }
                    });

                });

                google.maps.event.addDomListener(window, "resize", function() {
                   var center = map.getCenter();
                   google.maps.event.trigger(map, "resize");
                   map.setCenter(center);
                });
        },

        map: function (data) {
            $('#map').empty();
            var mapCanvas = document.getElementById('map');
            var mapOptions = {
              center: new google.maps.LatLng(51.499461499999995, -0.17530959999999998),
              zoom: 2,
              backgroundColor: '#fff'
            }
            var map = new google.maps.Map(mapCanvas, mapOptions);
            this.setMarkers(data, map);
            window.parent.postMessage('iframe-update', '*');
        },

        locate: function (position) {
            if(position !== undefined){
                var la = position.coords.latitude,
                lo = position.coords.longitude;
                $('.geo').next('input').val(la+', '+lo);
                $('#loadersnake').remove();
            } else {
               $('.geo').after('<p>We cannot find your location. Please enter your postcode / location below.</p>') 
            }
        },

        beforeSend: function () {
            $('#map').empty().append(loader);
        },

        onSuccess: function (data) {
            gmba.geolocate.map(data);
        },

        onError: function () {
            $('#map').empty().hide();
        },

        ajax: function () {
             var
                opts = {
                    dataType  : 'jsonp',
                    url       : 'https://script.google.com/macros/s/AKfycbx1e7fju-b7tD4LYuzBZUdrjm5HrdH0EINhZkvebroWHQQq4Q/exec?id='+$('.geolocate form').data('url')+'&sheet=geolocate',
                    beforeSend : gmba.geolocate.beforeSend,
                    onSuccess : gmba.geolocate.onSuccess,
                    onError   : gmba.geolocate.onError
                };
                gmba.ajax.init(opts);
        },

        bind: function () {
            $('.geo').on('click', function (e) {
                e.preventDefault();
                $('.geo').next('input').after(loadersnake);
               if (navigator.geolocation) {
                  navigator.geolocation.getCurrentPosition(gmba.geolocate.locate);
                }else{
                    $('.geo').after('<p>Your browser doesn\'t support geolocation. Please enter your postcode / location below.</p>')
                }
            });

            $('.geolocate form').submit(function() {
                $('.ss-form').fadeOut();
                window.parent.postMessage('iframe-update', '*');
                if(boo === true){
                    $('#map').empty().append(loader);
                }else{
                    $('#map').empty().append(loader5).append(loader);
                    gmba.timer.init();
                }
                setTimeout(function(){gmba.geolocate.ajax()}, 10000);
            });

        },

        init: function () {
            if(username != undefined && $('form input[title="username"]').length){
                username = username.split("/")[7];
                $('form input[title="username"]').val(username);
                $('form input[title="userimg"]').val(userimg.attr('src'));

            }
            var w = $('#map').width();
            $('#map').height((w / 100) * 50);
            this.bind();
            this.ajax();
            gmba.chars.init(250);
        }
    },

    gmba.imageTile = {

        beforeSend: function () {
            $('#freewall').empty().append(loader);
        },

        onSuccess: function (data) {
            if(boo === true){
                $('.ss-form input[type="text"]').val('');
                $('.ss-form textarea').val('');
            }
            var temp = "<div class='brick {cls}' style='width:{width}px;'><a target='_blank' href='{ref}'><img src='{index}' width='96%'><div class='comment'>{category}<p>{comment}</p>{feedback}{endorsed}</div></a></div>";
            var w = 1, h = 1, html = '', limitItem = data.imagetile.length;
            for (var i = 0; i < limitItem; ++i) {
                w = 1 + 3 * Math.random() << 0;
                var src = data.imagetile[i].Image_URL,
                com = data.imagetile[i].Comment,
                cat = '',
                starred = '', 
                endorsed = '',
                feedback = '';
                if(data.imagetile[i].Endorsed !== ''){
                    starred = 'starred',
                    endorsed = '<p class="flagged">Tutor Endorsed</p>'
                }
                if(data.imagetile[i].Feedback !== ''){
                    feedback = '<div class="feedback"><h3>Tutor Feedback</h3><p>'+data.imagetile[i].Feedback+'</p></div>'
                }
                if(src !== ''){
                    html += temp.replace("{cls}", starred).replace(/\{width\}/g, w*150).replace("{index}", src).replace("{ref}", src).replace("{comment}", com).replace("{category}", cat).replace("{endorsed}", endorsed).replace("{feedback}", feedback);
                }
                if(data.imagetile[i].Category !== ''){
                    cat = data.imagetile[i].Category;
                }

                window.parent.postMessage('iframe-update', '*');
            }
            $("#freewall").html(html);

             var wall = new freewall("#freewall");
             wall.reset({
                selector: '.brick',
                animate: true,
                cellW: 150,
                cellH: 'auto',
                onResize: function() {
                    wall.fitWidth();
                }
            });

            var images = wall.container.find('.brick');
            images.find('img').load(function() {
                wall.fitWidth();
                window.parent.postMessage('iframe-update', '*');
            });
        },

        onError: function () {
            $('#freewall').empty().append('<p>There has been an error please refresh the page</p>')
        },

        ajax: function () {
             var
                opts = {
                    dataType  : 'jsonp',
                    url       : 'https://script.google.com/macros/s/AKfycbwn83FISTq-0m2nfyYG3Ilohksa7Ia6gcd4swSQN1nSTX0WMK0/exec?id='+$('.image-tile form').data('url')+'&sheet=imagetile',
                    beforeSend : gmba.imageTile.beforeSend,
                    onSuccess : gmba.imageTile.onSuccess,
                    onError   : gmba.imageTile.onError
                };
                gmba.ajax.init(opts);
        },

        bind: function () {
            $('.image-tile form').submit(function () {
                $('.ss-form').fadeOut();
                $('#freewall').html(loader5).append(loader);
                gmba.timer.init();
                setTimeout(function(){gmba.imageTile.ajax()}, timing);
            });
            var boo = true;
        },

        init: function () {
            gmba.chars.init(250);
            var boo = false;

            if($('form input[title="username"]').length){
                $('form input[title="username"]').val(username);
            }

            this.ajax();
            this.bind();
        }
    },

    gmba.leapfrog = {
        init: function () {
           var lf = $('.leapedfrog', window.parent.document);
           if(lf.length){
                lf.hide();
                this.bind(lf);
            }
        },

        bind : function (lf) {
            $('.leapfrog form').on('submit', function () {
                var order = $(this).data('order');
                $(order, window.parent.document).fadeIn();
            });
        }
    },

    gmba.longAnswer = {
        init: function () {
            this.bind();
            this.ajax();
        },

        bind: function (){
            $('.ss-form').on('submit', function () {
                $('form').fadeOut();
                $('.answers').empty().append(loader5).append(loader);
                gmba.timer.init();
                setTimeout(function(){gmba.longAnswer.ajax()}, 5000);
            })
        },

        ajax: function () {
            var $this = this,
            json = $('form').data('url'),
            j = 'https://script.google.com/macros/s/AKfycbx1e7fju-b7tD4LYuzBZUdrjm5HrdH0EINhZkvebroWHQQq4Q/exec?id='+json+'&sheet=longanswer',
            opts = {
                dataType  : 'jsonp',
                url       : j,
                beforeSend : $this.beforeSend,
                onSuccess : $this.onSuccess,
                onError   : $this.onError
            };

            gmba.ajax.init(opts);
        },

        beforeSend : function () {
            $('.answers').remove();
            $('form').after('<div class="answers"></div>');
            $('.answers').append(loader);
        },

        onError : function () {
            $('.answers').empty().append('<p>No answers to display</p>')
        },

        onSuccess : function (data) {
            $('.answers').empty();
            for (key in data.longanswer){
                $('.answers').prepend('<div></div>');
                var obj = data.longanswer[key];
                for(prop in obj){
                    if(prop !== 'Timestamp'){
                        prop2 = prop.replace(/_/g, ' ');
                        if (prop2.indexOf("Syndicate") >= 0){
                            $('.answers > div:first-of-type').append('<div class="group"><h3>'+prop2+'</h3><p>'+obj[prop]+'</p></div>');
                        }else{
                            $('.answers > div:first-of-type').append('<h3>'+prop2+'</h3><p>'+obj[prop]+'</p>');
                        }
                    }
                }
            }
            $('.answers').prepend('<h2>' + $('form').data('title') + '</h2>')
            window.parent.postMessage('iframe-update', '*');
        },
    },

    //matrix

    gmba.printMatrix = {
        bind: function () {
            $('.print').on('click', function() {
                var l = $('textarea').length,
                    c = 1;
                    if(l > 0){
                        $('.matrix textarea').each(function(){
                            var ans = $(this).val(),
                            h = $(this).parent('td').height();
                            $(this).parent('td').height(h);
                            $(this).fadeOut(function(){
                                $(this).replaceWith(ans);
                                if(c === l){
                                    gmba.print.init();
                                    $('.matrix td').hover(function() {
                                        var hi = $(this).outerHeight();
                                        $(this).find('div').height(hi).fadeToggle();
                                    })
                                    return;
                                }
                                c ++;
                            })
                        });
                    }else{
                        gmba.print.init();
                    }
            });
        },

        init: function () {
            this.bind();
        }
    },


    //popcorn video

    gmba.popcorn = {

        onSuccess: function (data) {
            $('.timeline').width(0);
            $('.timeline div').append('<h3>Chapters</h3>').hide();
            var url = 'http://player.vimeo.com/video/' + $('#popcorn').data('vimeo'),
                wrapper = Popcorn.HTMLVimeoVideoElement( "#popcorn" );
                wrapper.src = url;
            var video = Popcorn(wrapper, {
                defaults: {
                    image: {
                        target: 'presentation'
                    }
                }
                });
            var i = 0,
                count = 1,
                times = [];
                for(; i < data.settings.length; i++){
                    var obj = (data.settings[i]);
                    video.image({
                        start: obj.start,
                        end: obj.end,
                        src: obj.src
                    });
                    var dur = obj.end - obj.start,
                        mins = Math.floor(dur / 60),
                        secs = dur - mins * 60,
                        secs = (secs < 10 ? '0' : '') + secs;
                    $('.timeline > div').append('<div><a href="'+obj.start+'"><p>'+obj.name+'</p><p class="duration"> ('+mins+':'+secs+')</p></a></div>')
                    count ++;
                    times.push(obj.start);
                }
                video.on( "timeupdate", function() {
                    var active = $.inArray(Math.floor(this.currentTime()), times);
                    if(active > -1){
                        $('.timeline div').removeClass('active');
                        $('.timeline div').eq(active + 1).addClass('active');
                    }
                });
                video.play();
                $('.timeline').append('<div class="cover"><p>Press play to activate playlist</p></div>');
                $('.cover').css('min-height', '120px');
                video.on( "playing", function() {
                    $('.cover').fadeOut(function () {
                        $(this).remove();
                    })
                });
                var ww = $(window).width();
                $( window ).resize(function() {
                    if($(window).width() < ww){
                        $('.timeline').css({'-webkit-transition':'none','-moz-transition': 'none','-o-transition': 'none','transition': 'none'})
                    }else{
                        $('.timeline').css({'-webkit-transition':'width 0.8s ease-in-out','-moz-transition': 'width 0.8s ease-in-out','-o-transition': 'width 0.8s ease-in-out','transition': 'width 0.8s ease-in-out'})
                    }
                    if($('.vid-pres').hasClass('active')){
                        if($(window).width() < 900){
                            var w = '100%';
                        }else{
                            var w = $('body').width() - $('.presentation-wrapper').width();
                        }
                        $('.timeline').width(w);
                        setTimeout(function(){$('.cover').css('height', $('.timeline').height())}, 801);
                    };
                });
                $('#show-sidebar', window.parent.document).on('click', function () {
                    $('.timeline').css({'-webkit-transition':'none','-moz-transition': 'none','-o-transition': 'none','transition': 'none'}).width($('.timeline').width() - 300);
                });
                $('body').on('click', '.timeline a', function (e) {
                    e.preventDefault();
                    var time = $(this).attr('href'),
                        cTime = video.currentTime();
                    video.cue(cTime, function(){
                        this.currentTime(time);
                    })
                    var eventId = video.getLastTrackEventId();
                    video.removeTrackEvent(eventId);
                    video.play();
                });
                $('body').on('click', '.pres-player', function (e) {
                    e.preventDefault();
                    if($('.vid-pres').hasClass('active')){
                        $('#presentation').fadeOut();
                        $('.timeline').width(0);
                        $('.timeline div').fadeOut(function(){
                            window.parent.postMessage('iframe-update', '*');
                        });
                    }else{
                        if($(window).width() < 900){
                            var w = '100%';
                        }else{
                            var w = $('body').width() - $('.presentation-wrapper').width();
                        }

                        $('.timeline').width(w).fadeIn();
                        $('.timeline div').fadeIn();
                        $('#presentation').stop().fadeIn();
                    }
                    $(this).prevAll('.vid-pres').toggleClass('active');
                    if($('.vid-pres').hasClass('active')){
                        $('.pres-player').text('Hide presentation');
                    }else{
                        $('.pres-player').text('View presentation');
                    }
                    window.parent.postMessage('iframe-update', '*');
                });
                $('body').on('live', 'video', function () {
                    $('video').addClass('hi');
                });
        },

        onError: function () {

        },

        init: function () {
        var slides = $('.vid-pres').data('slides');
        if(slides !== undefined){
            $('.pres-player').after('<a class="button" href="../slides/'+slides+'.pdf" target="_blank">Download Slides</a>');
        }
        $('.reveal').on('click', function () {
            var txt = $(this).text();
            if(txt === 'View transcript'){
                $(this).text('Hide transcript');
            }else{
                $(this).text('View transcript');
            }
        });
        var h = ($('#popcorn').width() / 16) * 9;
                $('#popcorn').height(h);
                $(window).resize(function () { var h = ($('#popcorn').width() / 16) * 9; $('#popcorn').height(h);});
        var     json = $('#popcorn').data('json')
                j = 'https://script.google.com/macros/s/AKfycbx1e7fju-b7tD4LYuzBZUdrjm5HrdH0EINhZkvebroWHQQq4Q/exec?id=' + json + '&sheet=settings',
                opts = {
                    dataType  : 'jsonp',
                    url       : j,
                    onSuccess : gmba.popcorn.onSuccess,
                    onError   : gmba.popcorn.onError
                };
                gmba.ajax.init(opts);
      }

    },

    gmba.previousload = {
        init: function () {
           var pl = $('.previous', window.parent.document);
           if(pl.length){
                pl.hide();
                this.bind(pl);
            }
        },

        bind : function (pl) {
            $('.previous-load form').on('submit', function () {
                var previous = $(this).data('previous');
                $(previous, window.parent.document).delay(timing).fadeIn();
            });
        }
    },

    gmba.newResultMatrix = {

        settings: {
            resultCluster : $('.result-cluster'),
            resultTable : $('.matrix-grid'),
            cons : 100,
            answer : '',
            ans : 0,
            labels : [],
            sizes : [],
            matrix : [],
            formAns : '',
            n : ''
        },

        init : function () {
            s = this.settings,
            $this = this;
            s.resultTable.hide();
            this.bind();
            this.calcPercent();
        },

        calcPercent : function () {
            s.resultCluster.find('input').keyup(function () {percent();});
            var percent = function() {$('.percent p span').text(s.cons - calcDif());},
            calcDif = function() {
                var dif = 0;
                s.resultCluster.find('input').each(function() {dif += Number($(this).val());});
                return dif;
            };
        },

        bind : function () {
            $('.new-result-matrix form').submit(function () {
                gmba.loadDelay.init($this, $('.new-result-matrix'));
                $this.yourAns();
            })
        },

        yourAns : function () {
            var m2 = '';
            $('input[type="radio"]:checked').each(function() {
                    s.answer += $(this).data('matrix');
            });

            s.resultCluster.find('input[type="text"]').each(function() {
                if(s.ans < Number($(this).val())){
                    s.ans = Number($(this).val());
                    m2 = $(this).data('matrix');
                }
            });

            s.answer += m2;

            $('.matrix-grid td[data-matrix ="'+s.answer+'"]').addClass('yours').prepend('<span>You</span>');
        },

        ajax : function() {
            var json = $('.new-result-matrix form').data('url'),
            j = 'https://script.google.com/macros/s/AKfycbx1e7fju-b7tD4LYuzBZUdrjm5HrdH0EINhZkvebroWHQQq4Q/exec?id='+json+'&sheet=matrix',
            opts = {
                dataType  : 'jsonp',
                url       : j,
                beforeSend : $this.beforeSend,
                onSuccess : $this.onSuccess,
                onError   : $this.onError
            };

            gmba.ajax.init(opts);
        },

        beforeSend : function() {
            $('#loader5').remove();
        },

        onSuccess : function(data) {
            $('#loader').remove();
            $this.matrixResult(data);
            $('.matrix-grid').fadeIn();
            window.parent.postMessage('iframe-update', '*');
        },

        onError : function () {
            $('#loader').remove();
            $('body').append('<p>There has been an error, please try again later</p>');
        },

        matrixResult : function (data) {

            var array = {

                labels : function() {
                            s.resultTable.find('td').each(function() {
                                s.labels.push($(this).data('matrix'));
                            });
                            return s.labels;
                        },

                matrix : function() {

                    var firstMatrix = function (i) {
                        $('input[type="radio"]').each(function() {
                            if (data.matrix[i].answer === $(this).val()) s.formAns = $(this).data('matrix');
                        });
                        return s.formAns;
                    };

                    var secondMatrix = function (i) {
                        for(name in data.matrix[i]){
                            if(name !== 'answer' && name !== ''){
                                if(s.ans < data.matrix[i][name]){
                                    s.ans = data.matrix[i][name];
                                    s.n = name;
                                }
                            }
                        }
                        return s.n;
                    };

                    for(var i = 0; i < data.matrix.length; i++){
                        delete data.matrix[i].Timestamp;
                        s.matrix.push(firstMatrix(i) + secondMatrix(i));
                        s.ans = 0;
                        s.formAns = '';
                    }

                    s.matrix.sort();

                    return s.matrix;
                },

                sizes : function() {

                    var labels = this.labels(),
                    matrix = this.matrix();

                    for(var j = 0; j < labels.length; j++){
                        s.sizes.push(0);
                        for(var k = 0; k < matrix.length; k++){
                            if(labels[j] === matrix[k]){
                                s.sizes[j]++;
                            }
                        }
                    }

                    return s.sizes;
                }
            };

            var count = 0,
            sizes = array.sizes();
            $('.matrix-grid td').each(function() {
                $(this).append(' ('+sizes[count]+')');
                count++;
            });
        }

    },

    gmba.outsideFeedback = {

        settings : {
            of : $('#outside-feedback', window.parent.document),
            json : $('.outside-feedback form').data('url'),
            sheet : $('.outside-feedback form').data('sheet'),
            username : username
        },

        init : function () {

            $this = this;
            s = $this.settings,
            j = 'https://script.google.com/macros/s/AKfycbx1e7fju-b7tD4LYuzBZUdrjm5HrdH0EINhZkvebroWHQQq4Q/exec?id='+s.json+'&sheet='+s.sheet,
            opts = {
                dataType  : 'jsonp',
                url       : j,
                onError   : $this.onError,
                onSuccess : $this.onSuccess,
            };
            if(s.username.substring(0, 6) === "https:"){
                var longuser = true;
            }
            if(s.username != undefined && longuser === true){
                s.username = s.username.split("/")[7];
            }

            if($('form input[title="username"]').length){
                $('form input[title="username"]').val(s.username);
            }

            gmba.ajax.init(opts);

        },

        onError : function () {
            s = $this.settings;
            if(s.of.length){
                s.of.hide();
                $this.bind();
           }
        },

        onSuccess : function (data) {
            s = $this.settings;
            if(s.username === undefined){
                user.attr('href').split("/")[7];
            }
            var usernames = [];
            for(name in data){
                for(newname in data[name]){
                    staff.push(data[name][newname].username);
                }
            }
            if($.inArray(s.username, staff) > -1){
                    access = true;
            }
            if(access === false){
                 s.of.hide();
                $this.bind();
            }
        },

        bind : function () {
            $('.outside-feedback form').on('submit', function () {
                s.of.delay(timing).fadeIn();
            });
        }
    },

    gmba.timer = {
        init: function () {
            var times = ['Thank you for your response', 'Please wait whilst we process your submission...', 'We will show you your results as quickly as possible, please do not refresh the page']
            var i = 0, l = times.length;
            (function count() {
                $('#loader5').text(times[i]);
                if(++i<l) {
                    setTimeout(count, 2500);
                }
            })();
        }
    },

    gmba.loadDelay = {
        init: function($this, loadDest) {
            loadDest.prepend(loader5, loader).find('.ss-form').hide();
             window.parent.postMessage('iframe-update', '*');
            gmba.timer.init();
            setTimeout(function(){$this.ajax()}, timing);
        }
    },

    gmba.ownResultMatrix = {
        settings : {
            form : $('.own-result-matrix')
        },

        init : function(){
            s = this.settings,
            $this = this;
            $('.result-matrix').hide();
            $('.decider').hide();
            this.bind();
        },

        bind : function(){
            s.form.find('form').submit(function () {
                s.form.find('#navigation-table').hide();
                $('input[type="radio"]:checked').each(function() {
                    $(this).parents('td').addClass('yours');
                });
                s.form.find('form td input').fadeOut();
                setTimeout($this.css, 1000);
            });
        },
        css: function (){
            $('.yours').css({'background' : '#eee'}).append('<span>Your Choice</span>');
            $('.decider').fadeIn();
            window.parent.postMessage('iframe-update', '*');
        }
    },


    // gmba.reference = {

    //     init : function () {
    //         if($('#reference', window.parent.document).length > 0){
    //             $('.view').click();
    //         }
    //     }
    // },

    gmba.resultMatrix = {

        settings : {
            form : $('.result-matrix'),
            labels : [],
            result : [],
            questions : [],
            sizes : []
        },

        init : function(){
            s = this.settings,
            $this = this;
            this.bind();
        },

        bind : function () {
            s.form.find('form').submit(function () {
                $('.ss-form').append(loader5).append(loader).css('padding-bottom', '40px');
                s.form.find('tr:nth-child(1) input[type="radio"]').each(function() {
                s.labels.push($(this).val());
                })
            s.form.find('form td input').fadeOut();
                window.parent.postMessage('iframe-update', '*');
                gmba.timer.init();
                setTimeout(function(){$this.ajax()}, 5000)
                $('input[type="radio"]:checked').each(function() {
                    $(this).parents('td').addClass('yours');
                });
            });
        },

        ajax : function() {
            var json = s.form.find('form').data('url'),
            j = 'https://script.google.com/macros/s/AKfycbx1e7fju-b7tD4LYuzBZUdrjm5HrdH0EINhZkvebroWHQQq4Q/exec?id='+json+'&sheet=matrix',
            opts = {
                dataType  : 'jsonp',
                url       : j,
                beforeSend :$this.beforeSend,
                onSuccess : $this.onSuccess,
                onError   : $this.onError
            };
           gmba.ajax.init(opts);
        },

        beforeSend : function() {

        },

        onError : function () {
            s.form.find('form').after('There has been an error, please refresh and resubmit your answers');
        },

        onSuccess : function (data) {
            $('#loader5').remove();
            $('#loader').remove();
            $('.yours').css({'background' : '#eee'}).append('<span>Your Choice</span>');
            $this.cummulativeResult(data);
            if($('.further-info').length){
                $('.further-info').fadeIn();
                window.parent.postMessage('iframe-update', '*');
            }
        },

        cummulativeResult : function (data) {

            delete data.matrix[0].Timestamp;
            for (name in data.matrix[0]){
                s.questions.push(name);
            }

            for(j=0; j<s.questions.length; j++){
                var arr = new Array();
                for(i=0; i<data.matrix.length; i++){
                    if(data.matrix[i].Timestamp){
                        delete data.matrix[i].Timestamp;
                    }
                    var questions = s.questions[j];
                    arr.push(data.matrix[i][questions]);
                }
                arr.sort();
                s.result.push(arr);
            }

            $this.sizes();
        },

        sizes : function () {
            for (var i = 0; i<s.result.length; i++){
                var arr = new Array();
                for(var j = 0; j < s.labels.length; j++){
                    arr.push(0);
                    for(var k = 0; k < s.result[i].length; k++){
                        if(s.labels[j] === s.result[i][k]){
                            arr[j]++;
                        }
                    }
                }
                s.sizes.push(arr);
            }

            $this.inject();

        },

        inject : function () {
            $('.ss-form-entry tbody td').each(function () {
                if(!$(this).hasClass('ss-gridrow-leftlabel')){
                    var row = $(this).parent('tr').index(),
                        col = $(this).index() - 1;
                    $(this).append('<p>Total Votes: '+s.sizes[row][col]+'</p>');
                }
            });
        }
    },

    gmba.scrollToTop = {
        init : function () {
            $('.scrollTop')
        }
    },

    gmba.userAccess = {
        init: function () {
            var $this = this,
            username = username1.split("/")[7];
            $('.user-access-reveal').hide();


            if($('form input[title="username"]').length ){
                $('form input[title="username"]').val(username);
            }

            this.ajax();
        },

        ajax: function () {
               var  json = $('form').data('url'),
               sheet = $('form').data('sheet'),
                j = 'https://script.google.com/macros/s/AKfycbx1e7fju-b7tD4LYuzBZUdrjm5HrdH0EINhZkvebroWHQQq4Q/exec?id=' + json + '&sheet=' + sheet,
                opts = {
                    dataType  : 'jsonp',
                    url       : j,
                    beforeSend : gmba.userAccess.beforeSend,
                    onSuccess : gmba.userAccess.onSuccess,
                    onError   : gmba.userAccess.onError
                };

                gmba.ajax.init(opts);
        },

        beforeSend : function () {
        },

        onError : function () {
        },

        onSuccess : function (data) {
            var username = username1.split("/")[7];
            for(name in data){
                for(newname in data[name]){
                    if($('.chart').length){
                        var usernameArr = [];
                        usernameArr.push(data[name][newname].username);
                    }else{
                        if($.inArray(data[name][newname].username, staff) == -1){
                                staff.push(data[name][newname].username);
                        }

                    }

                }
            }

            if($('.chart').length){
                if($.inArray(username, usernameArr) > -1){
                    completed = true;
                    $('body').addClass('hide-return');
                    $('.view').trigger('click');
                }
            }else{
                if($.inArray(username, staff) > -1){
                      $('.user-access-reveal').show();
                }
            }
        }


    },

    gmba.wordCloud = {

        settings : {
            username : username
        },

        init: function (data) {
                var $this = this,
                s = $this.settings;
                if(s.username.substring(0, 6) === "https:"){
                    var longuser = true;
                }
                if(s.username != undefined && longuser === true){
                    s.username = s.username.split("/")[7];
                }

                if($('form input[title="username"]').length ){
                    $('form input[title="username"]').val(s.username);
                }

                if($.inArray(s.username, staff) > -1){
                    access = true;
                }

                $('.ss-form .ss-secondary-text').text('Separate multiple entries with a comma');
                gmba.chars.init(25);
                if($('.prereveal').length){
                    gmba.wordCloud.ajax();
                    if(!$('.cloud-wrapper').length){
                        $('.ss-form').after('<div class="cloud-wrapper"></div>');
                    }
                }
                this.bind();
                this.ajax();
        },

        beforeSend: function () {
            $('#loader').remove();
            $('#loader5').remove();
            $('.chart-area-wrapper').append(loader);
        },

        ajax: function () {
               var  json = $('.cloud form').data('url'),
                j = 'https://script.google.com/macros/s/AKfycbx1e7fju-b7tD4LYuzBZUdrjm5HrdH0EINhZkvebroWHQQq4Q/exec?id=' + json + '&sheet=wordcloud',
                opts = {
                    dataType  : 'jsonp',
                    url       : j,
                    beforeSend : gmba.wordCloud.beforeSend,
                    onSuccess : gmba.wordCloud.onSuccess,
                    onError   : gmba.wordCloud.onError
                };
                gmba.ajax.init(opts);
        },

        bind: function () {
            $('form').submit(function() {
                access = true;
                if(!$('.cloud-wrapper').length){
                    $('.ss-form').after('<div class="cloud-wrapper"></div>');
                }

                var q = $('.ss-form-question:first-of-type .ss-q-title').text();
                $('.ss-form').fadeOut(function () {
                    $('.cloud-wrapper').css('display', 'block').empty().prepend(loader5).append(loader).before('<p class="question"><em>'+q+'</em></p>');
                    window.parent.postMessage('iframe-update', '*');
                    setTimeout(function(){gmba.wordCloud.ajax()}, timing);
                    gmba.timer.init();
                });
            });
        },

        onSuccess: function (data) {
            s = gmba.wordCloud.settings;
            if(!$('.cloud-wrapper').length){
                $('.ss-form').after('<div class="cloud-wrapper"></div>');
            }
            var usernames = [];
            for(name in data){
                for(newname in data[name]){
                    usernames.push(data[name][newname].username);
                }
            }
            if($.inArray(s.username, usernames) > -1){
                    access = true;
            }
            if(access === false){
                $('.cloud-wrapper').hide();
            }else{
                $('.cloud-wrapper').show();
            }
            $('.cloud-wrapper').empty();
            var fill = d3.scale.category20(),
            arr = [],
            words = [],
            sizes = [],
            prev = '',
            k = 0,
            i = 0,
            v = 0,
            anchor = '',
            w = $(window).width() - 40,
            size = '';
            for(; k < data.wordcloud.length; k++){
                var obj = (data.wordcloud[k]);
                var objArr = obj.words.split(',');
                for (var t = 0; t < objArr.length; t++) {
                    arr.push(objArr[t].trim().toLowerCase());
                }
            };
            arr.sort();
            for ( var i = 0; i < arr.length; i++ ) {
                if ( arr[i] !== prev ) {
                    words.push(arr[i]);
                    sizes.push(25);
                } else {
                    sizes[sizes.length-1] += 5;
                }
                prev = arr[i];
            }
            d3.layout.cloud().size([w, 300])
              .words(words.map(function(d) {
                if($('.cloud.sizes').length){
                    if(size > 100){
                        size = 100;
                    }else{
                        size = sizes[v];
                    }
                }else{
                    size = 40;
                }
                v++;
                return {text: d, size: size};
              }))
              .padding(10)
              .rotate(function() { return ~~(Math.random() * 2) * 90; })
              .overflow(true)
              .fontSize(function(d) { return d.size; })
              .on("end", draw)
              .start();

          function draw(words) {
            var dwords = [];
            d3.select(".cloud-wrapper").append("svg")
                .attr("width", w)
                .attr("height", 600)
              .append("g")
                .attr("transform", "translate(0,0)")
              .selectAll("text")
                .data(words)
              .enter().append("text")
                .style("font-size", function(d) { return d.size + "px"; })
                .style("font-family", "MetaWebPro-Book, sans-serif")
                .style("fill", function(d, i) { dwords.push(d); return fill(i); })
                .attr("text-anchor", 'middle')
                .text(function(d) { return d.text; });
                retransform(dwords);
          }
          window.parent.postMessage('iframe-update', '*');

          function retransform(dwords){
                var u = 0;
                $('text').each(function (){
                    var wid = $(this).width(),
                    hie = $(this).height();
                    if(dwords[u].rotate === 90){
                        if(dwords[u].y < wid){
                            dwords[u].y = wid;
                        }
                    }else{
                        if(dwords[u].y < hie){
                            dwords[u].y = hie;
                        }
                    }
                    $(this).attr('transform', "translate(" + [dwords[u].x, dwords[u].y] + ")rotate(" + dwords[u].rotate + ")")
                    u++;
                });
          }

        },

        onError: function () {

        },

        beforeSend: function () {
            $('.cloud-wrapper').empty();
            $('.cloud-wrapper').prepend(loader);
            window.parent.postMessage('iframe-update', '*');
        }

    },

    gmba.hq = {
        init: function () {
            if($('.chart').length){
                gmba.chart.init();
            }
            if($('.decider').length){
                gmba.decider.init();
            }
            if($('.simple-form').length){
                gmba.formThankyou.init();
            }
            if($('.geolocate').length){
                gmba.geolocate.init();
            }
            if($('.image-tile').length){
                gmba.imageTile.init();
            }
            if($('.leapfrog').length){
                gmba.leapfrog.init();
            }
            if($('.long-answer').length){
                gmba.longAnswer.init();
            }
            if($('.new-result-matrix').length){
                gmba.newResultMatrix.init();
            }
            if($('.own-result-matrix').length){
                gmba.ownResultMatrix.init();
            }
            if($('.outside-feedback').length){
                gmba.outsideFeedback.init();
            }
            if($('.matrix').length){
                gmba.printMatrix.init();
            }
            if($('#popcorn').length){
                gmba.popcorn.init();
            }
            if($('.previous-load').length){
                gmba.previousload.init();
            }
            // if($('.reference').length){
            //     gmba.reference.init();
            // }
            if($('.result-matrix').length){
                gmba.resultMatrix.init();
            }
            if($('.scroll-to-top').length){
                gmba.scrollToTop.init();
            }
            if($('.user-access').length || $('.chart form input[title="username"]')){
                gmba.userAccess.init();
            }
            if($('.cloud').length){
                gmba.wordCloud.init();
            }
        }

    },


    $(document).ready(function () {
        gmba.hq.init();

    });

}(jQuery));

This snippet took 0.13 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).