<commit_before>'use strict';
(function() {
    var t = klp.tabs = {};
    var templates = {};
    var dataCache = {};
    var schoolInfoURL;
    var tabs;
    var currentTab;
    var container_width = 960;
    var chart_gradient_param = [0, 0, 0, 300];

    t.init = function() {
        schoolInfoURL = 'schools/school/' + SCHOOL_ID;

        tabs = {
            'info': {
                getData: function() {
                    return klp.api.do(schoolInfoURL);
                },
                getContext: function(data) {
                    data.type_name = klp.utils.getSchoolType(SCHOOL_TYPE_ID);
                    return data;
                },
                onRender: function(data) {
                    $('a.gallery').colorbox({'rel': 'group1'});
                    console.log("post render info");
                }
            },
            'demographics': {
                getData: function() {
                    return klp.api.do(schoolInfoURL + '/demographics');
                },
                getContext: function(data) {
                    var d = klp.utils.addSchoolContext(data);
                    d.dise = klp.utils.getBoyGirlPercents(data.num_boys_dise, data.num_girls_dise);
                    d.type_name = klp.utils.getSchoolType(SCHOOL_TYPE_ID);
                    return d;
                },
                onRender: function(data) {
                    if (!data.num_boys && !data.num_girls) {
                        //console.log("no boy-girl data!");
                        $('.no-data.klp').show();
                        $('#boygirlChartWrapper').hide();
                    } else {
                        $('#num_students_piechart').boyGirlChart(data);
                    }

                    if (!data.num_boys_dise && !data.num_girls_dise) {
                        $('.no-data.dise').show();
                        $('#boygirlChartWrapperDISE').hide();
                    } else {
                        $('#num_students_piechart_dise').boyGirlChart(data.dise);
                    }
                }
            },
            'programmes': {
                getData: function() {
                    return klp.api.do(schoolInfoURL + '/programmes');
                }
            },
            'finances': {
                getData: function() {
                    return klp.api.do(schoolInfoURL + '/finance');
                },
                getContext: function(data) {
                    data.sg_amount = data.sg_amount ? data.sg_amount : 0;
                    data.smg_amount = data.smg_amount ? data.smg_amount : 0;
                    data.tlm_amount = data.tlm_amount ? data.tlm_amount : 0;
                    data.total_amount = data.sg_amount + data.smg_amount + data.tlm_amount;
                    data.type_name = klp.utils.getSchoolType(SCHOOL_TYPE_ID);
                    return data;
                },
                onRender: function(data) {
                    var container_width = $(document).find(".container:first").width();
                    var chartData = klp.utils.getFinancePercents(data);
                    var chartOptions = {
                        width: container_width,
                        height: 200,
                        innerSize: '60%'
                    };
                    $('#pie_chart_finance').financeChart(chartData, chartOptions);
                }
            },
            'infrastructure': {
                getData: function() {
                    return klp.api.do(schoolInfoURL + '/infrastructure');
                },
                getContext: function(data) {
                    data.type_name = klp.utils.getSchoolType(SCHOOL_TYPE_ID);
                    return data;
                }
            },
            'library': {
                getData: function() {
                    return klp.api.do(schoolInfoURL + '/library');
                },

                getContext: function(data) {
                    // Step 0: Check if library data exists.
                    data.years = [];
                    data.klasses = [];
                    data.lib_borrow_agg.forEach(function (element, index) {
                        data.years.push(element.trans_year);
                        data.klasses.push(element.class_name);
                    });
                    _.each(data.lib_lang_agg, function(element, index) {
                        element.forEach(function(element, index) {
                            data.years.push(element.year);
                            data.klasses.push(element.class_name);
                        });
                    });
                    _.each(data.lib_level_agg, function(element, index) {
                        element.forEach(function(element, index) {
                            data.years.push(element.year);
                            data.klasses.push(element.class_name);
                        });
                    });

                    // Step 1: Array of years.
                    data.years = _.uniq(data.years).sort();

                    // Step 2: Array of classes.
                    data.klasses = _.uniq(_.map(data.klasses, function (klass) {
                        return String(klass);
                    })).sort();

                    // Step 3: Array of levels.
                    data.levels = _.keys(data.lib_level_agg);

                    // Step 4: Array of languages.
                    data.languages = _.keys(data.lib_lang_agg);

                    console.log('years', data.years);
                    console.log('klasses', data.klasses);
                    console.log('levels', data.levels);
                    console.log('languages', data.languages);
                    data.type_name = klp.utils.getSchoolType(SCHOOL_TYPE_ID);
                    return data;
                },
                onRender: function(data) {
                    if (data.years.length === 0 || data.klasses.length === 0 || data.levels.length === 0) {
                        $(".options-wrapper").addClass('hide');
                        $("#graph_library").addClass('hide');
                        $('.no-data').removeClass('hide');
                        return;
                    }
                    $(".apply-selectboxit").selectBoxIt();
                    var $selectLibraryParam = $("#select_library_browse");
                    var $selectLibraryYear = $("#select_library_year");
                    var $selectLibraryClass = $("#select_library_class");

                    $selectLibraryParam.on('change', drawChart);
                    $selectLibraryYear.on('change', drawChart);
                    $selectLibraryClass.on('change', drawChart);

                    function drawChart() {
                        var libraryParam = $selectLibraryParam.val();
                        var libraryYear = $selectLibraryYear.val();
                        var libraryClass = $selectLibraryClass.val();
                        $('#graph_library').libraryChart(data, {'parameter': libraryParam, 'year': libraryYear, 'klass': libraryClass});
                    }

                    drawChart();
                }
            },
            'nutrition': {
                getData: function() {
                    return klp.api.do(schoolInfoURL + '/nutrition');
                },

                getContext: function(data) {
                    data.hasData = true;
                    if (_.isEmpty(data.mdm_agg)) {
                        data.hasData = false;
                        return data;
                    }
                    data.indent = [];
                    data.attendance = [];
                    data.categories = [];
                    data.diseEnrollment = [];
                    data.klpEnrollment = [];

                    data.mdm_agg.forEach(function(element, index) {
                        data.categories.push(element.mon+ ' week ' + element.wk);
                        data.indent.push(element.indent);
                        data.attendance.push(element.attend);
                        data.diseEnrollment.push(data.num_boys_dise + data.num_girls_dise);
                        data.klpEnrollment.push(data.num_boys + data.num_girls);
                    });
                    data.type_name = klp.utils.getSchoolType(SCHOOL_TYPE_ID);
                    return data;

                },

                onRender: function(data) {
                    if (data.hasData) {
                        $('.data').removeClass('hide');
                        $('#graph_nutrition').highcharts({
                            chart: {
                                type: 'area',
                                width: container_width,
                                height: klp.utils.getRelativeHeight(960,400, 230, container_width)
                            },
                            title:{
                                text: null
                            },
                            subtitle: {
                                text: "Food Indent vs Attendance Tracking"
                            },
                            xAxis: {
                                categories: data.categories,
                                tickInterval: 2
                                // allowDecimals: false,
                                // labels: {
                                //     formatter: function() {
                                //         return this.value; // clean, unformatted number for year
                                //     }
                                // }
                            },
                            yAxis: {
                                title: {
                                    text: 'Number of children'
                                },
                                labels: {
                                    formatter: function() {
                                        return this.value;
                                        // return this.value / 1000 +'k';
                                    }
                                }
                            },
                            credits:{
                                enabled: false
                            },
                            tooltip: {
                                // pointFormat: '{series.name} produced {point.y:,.0f}
warheads in {point.x}'
                            },
                            plotOptions: {
                                area: {
                                    fillOpacity: 0
                                }
                            },
                            series: [{
                                name: 'Indent',
                                data: data.indent,
                                color: '#56af31',
                                fillColor: {
                                    linearGradient: chart_gradient_param,
                                    stops: [
                                        [0, '#e5f3e0'],
                                        [1, 'rgba(255,255,255,0.3)']
                                    ]
                                }
                            }, {
                                name: 'Attendance',
                                data: data.attendance,
                                color: '#3892e3',
                                fillColor: {
                                    linearGradient: chart_gradient_param,
                                    stops: [
                                        [0, '#92c3ef'],
                                        [1, 'rgba(255,255,255,0.3)']
                                    ]
                                }
                            }, {
                                name: 'KLP Enrollment',
                                data: data.klpEnrollment,
                                color: '#646157'
                            }, {
                                name: 'DISE Enrollment',
                                data: data.diseEnrollment,
                                color: '#e4b324'
                            }
                            ]
                        });
                    } else {
                        $('.no-data').removeClass('hide');
                    }
                }
            },
            'share-story': {
                getData: function() {
                    //FIXME: replace with real SYS end-point
                    var url ="stories/";
                    var params = {
                        'school_id': SCHOOL_ID,
                        'answers': 'yes',
                        'verified': 'yes'
                    };
                    return klp.api.do(url, params);
                },
                getContext: function(data) {
                    var latestStory = getLatestStoryWithAnswers(data.features);
                    if (latestStory) {
                        data.latest_answers = getCleanedAnswers(latestStory.answers);
                    } else {
                        data.latest_answers = null;
                    }
                    console.log("sys data", data);
                    return data;

                    function getLatestStoryWithAnswers(stories) {
                        for (var i=0; i < stories.length; i++) {
                            var thisStory = stories[i];
                            if (thisStory.answers.length > 0) {
                                return thisStory;
                            }
                        }
                        return null;
                    }

                    function getCleanedAnswers(answers) {
                        var cleanedAnswers = [];
                        _(answers).each(function(a) {
                            if (a.text === 'Yes' || a.text === 'No') {
                                cleanedAnswers.push(a);
                            }
                        });
                        console.log("answers", answers, cleanedAnswers);
                        return cleanedAnswers;
                    }
                },
                onRender: function(data) {
                    var $container = $('.tab-content[data-tab=share-story]');
                    var containerHTML = $container.html();
                    klp.share_story.init(SCHOOL_ID, containerHTML);
                    var urlState = klp.router.getHash();
                    var queryParams = urlState.queryParams;
                    // if (queryParams.hasOwnProperty('state') && queryParams.state === 'form') {

                    // }
                    klp.router.events.on("hashchange:state", function(e, params) {
                        console.log("hashchange state fired", params);
                        if (params.changed['state'].newVal === null) {
                            //console.log("old html", oldHtml);
                            $container.html(containerHTML);
                        } else if (params.changed['state'].newVal === 'form') {
                            $("#trigger_share_story_form").click();
                        }
                    });
                }
            },
            'volunteer': {
                getData: function() {
                    var url = "volunteer_activities";
                    var params = {
                        school: SCHOOL_ID
                    };
                    return klp.api.do(url, params);
                },
                onRender: function(data) {
                    klp.volunteer_here.checkSelf(data.features);
                }
            }

        };

        //compile templates for tabs
        _(_(tabs).keys()).each(function(tabName) {
            console.log("tab name", tabName);
            var templateString = $('#tpl-tab-' + tabName).html();
            templates[tabName] = swig.compile(templateString);
        });

        $(document).on("click", ".js-tab-link", function(e){
            var $wrapper = $(".js-tabs-wrapper");
            var $trigger = $(this).closest(".js-tab-link");
            var tab_id = $trigger.attr('data-tab');

            //show tab
            t.showTab(tab_id, false);

        });

        var queryParams = klp.router.getHash().queryParams;
        if (queryParams.hasOwnProperty('tab') && queryParams['tab'] in tabs) {
            var firstTab = queryParams['tab'];
        } else {
            var firstTab = 'info';
        }

        var tabDeferred = t.showTab(firstTab, true);
        klp.router.events.on('hashchange:tab', function(e, params) {
            console.log("hashchange:tab", params);
            var queryParams = params.queryParams;
            if (queryParams['tab'] in tabs) {
                t.showTab(queryParams['tab']);
            }
        });

        //slightly ugly hack to lazy load all tabs only on mobile
        //FIXME: possibly, get "isMobile" somewhere else, not sure
        //checking for < 768 on page load is the best technique.
        if ($(window).width() < 768) {
            tabDeferred.done(function() {
                var allTabs = _(tabs).keys();
                var tabsToLoad = _(allTabs).without(firstTab);
                _(tabsToLoad).each(function(tabName) {
                    t.showTab(tabName, true);
                });
            });
        }
        console.log(templates);

    };

    /*
        Arguments:
            tabName <string>: name of tab to show
            replaceState <boolean>: whether to "replace state", if true,
                will not add a new history entry for this tab show. This exists
                so that when we load all tabs on mobile, we can avoid adding new history
                entries for each tab.

     */
    t.showTab = function(tabName, replaceState) {
        if (currentTab === tabName) {
            return;
        }
        if (typeof(replaceState) === 'undefined') {
            replaceState = false;
        }
        $('.tab-content.current').removeClass('current');
        var queryParams = klp.router.getHash().queryParams;
        if (!(queryParams.hasOwnProperty('tab') && queryParams['tab'] === tabName)) {
            klp.router.setHash(null, {'tab': tabName}, {trigger: false, replace: replaceState});
        }
        currentTab = tabName;
        var $tabButton = $('.js-tab-link[data-tab=' + tabName + ']');
        $tabButton.parent().find("li.current").removeClass('current');
        $tabButton.addClass("current");
        $('div[data-tab=' + tabName + ']').addClass('current');
        var $deferred = $.Deferred();
        getData(tabName, function(data) {
            if (tabs[tabName].hasOwnProperty('getContext')) {
                data = tabs[tabName].getContext(data);
            }
            var html = templates[tabName](data);
            //$('#loadingTab').removeClass('current');
            $('div[data-tab=' + tabName + ']').html(html);
            doPostRender(tabName, data);
            $deferred.resolve();
        });
        return $deferred;
    };

    function getData(tabName, callback) {
        if (dataCache.hasOwnProperty(tabName)) {
            callback(dataCache[tabName]);
            return;
        }
        var $xhr = tabs[tabName].getData();
        $xhr.done(function(data) {
            dataCache[tabName] = data;
            callback(data);
        });
    }

    function doPostRender(tabName, data) {
        if (tabs[tabName].hasOwnProperty('onRender')) {
            tabs[tabName].onRender(data);
        }
    }

})();<commit_msg>hide irrelevant tabs on preschool page, refs #251<commit_after>'use strict';
(function() {
    var t = klp.tabs = {};
    var templates = {};
    var dataCache = {};
    var schoolInfoURL;
    var tabs;
    var currentTab;
    var container_width = 960;
    var chart_gradient_param = [0, 0, 0, 300];
    var schoolType;

    t.init = function() {
        schoolInfoURL = 'schools/school/' + SCHOOL_ID;
        schoolType = SCHOOL_TYPE_ID === 2 ? 'preschool' : 'school';
        tabs = {
            'info': {
                getData: function() {
                    return klp.api.do(schoolInfoURL);
                },
                getContext: function(data) {
                    data.type_name = klp.utils.getSchoolType(SCHOOL_TYPE_ID);
                    return data;
                },
                onRender: function(data) {
                    $('a.gallery').colorbox({'rel': 'group1'});
                    console.log("post render info");
                }
            },
            'demographics': {
                getData: function() {
                    return klp.api.do(schoolInfoURL + '/demographics');
                },
                getContext: function(data) {
                    var d = klp.utils.addSchoolContext(data);
                    d.dise = klp.utils.getBoyGirlPercents(data.num_boys_dise, data.num_girls_dise);
                    d.type_name = klp.utils.getSchoolType(SCHOOL_TYPE_ID);
                    return d;
                },
                onRender: function(data) {
                    if (!data.num_boys && !data.num_girls) {
                        //console.log("no boy-girl data!");
                        $('.no-data.klp').show();
                        $('#boygirlChartWrapper').hide();
                    } else {
                        $('#num_students_piechart').boyGirlChart(data);
                    }

                    if (!data.num_boys_dise && !data.num_girls_dise) {
                        $('.no-data.dise').show();
                        $('#boygirlChartWrapperDISE').hide();
                    } else {
                        $('#num_students_piechart_dise').boyGirlChart(data.dise);
                    }
                }
            },
            'programmes': {
                getData: function() {
                    return klp.api.do(schoolInfoURL + '/programmes');
                }
            },
            'finances': {
                getData: function() {
                    return klp.api.do(schoolInfoURL + '/finance');
                },
                getContext: function(data) {
                    data.sg_amount = data.sg_amount ? data.sg_amount : 0;
                    data.smg_amount = data.smg_amount ? data.smg_amount : 0;
                    data.tlm_amount = data.tlm_amount ? data.tlm_amount : 0;
                    data.total_amount = data.sg_amount + data.smg_amount + data.tlm_amount;
                    data.type_name = klp.utils.getSchoolType(SCHOOL_TYPE_ID);
                    return data;
                },
                onRender: function(data) {
                    var container_width = $(document).find(".container:first").width();
                    var chartData = klp.utils.getFinancePercents(data);
                    var chartOptions = {
                        width: container_width,
                        height: 200,
                        innerSize: '60%'
                    };
                    $('#pie_chart_finance').financeChart(chartData, chartOptions);
                }
            },
            'infrastructure': {
                getData: function() {
                    return klp.api.do(schoolInfoURL + '/infrastructure');
                },
                getContext: function(data) {
                    data.type_name = klp.utils.getSchoolType(SCHOOL_TYPE_ID);
                    return data;
                }
            },
            'library': {
                getData: function() {
                    return klp.api.do(schoolInfoURL + '/library');
                },

                getContext: function(data) {
                    // Step 0: Check if library data exists.
                    data.years = [];
                    data.klasses = [];
                    data.lib_borrow_agg.forEach(function (element, index) {
                        data.years.push(element.trans_year);
                        data.klasses.push(element.class_name);
                    });
                    _.each(data.lib_lang_agg, function(element, index) {
                        element.forEach(function(element, index) {
                            data.years.push(element.year);
                            data.klasses.push(element.class_name);
                        });
                    });
                    _.each(data.lib_level_agg, function(element, index) {
                        element.forEach(function(element, index) {
                            data.years.push(element.year);
                            data.klasses.push(element.class_name);
                        });
                    });

                    // Step 1: Array of years.
                    data.years = _.uniq(data.years).sort();

                    // Step 2: Array of classes.
                    data.klasses = _.uniq(_.map(data.klasses, function (klass) {
                        return String(klass);
                    })).sort();

                    // Step 3: Array of levels.
                    data.levels = _.keys(data.lib_level_agg);

                    // Step 4: Array of languages.
                    data.languages = _.keys(data.lib_lang_agg);

                    console.log('years', data.years);
                    console.log('klasses', data.klasses);
                    console.log('levels', data.levels);
                    console.log('languages', data.languages);
                    data.type_name = klp.utils.getSchoolType(SCHOOL_TYPE_ID);
                    return data;
                },
                onRender: function(data) {
                    if (data.years.length === 0 || data.klasses.length === 0 || data.levels.length === 0) {
                        $(".options-wrapper").addClass('hide');
                        $("#graph_library").addClass('hide');
                        $('.no-data').removeClass('hide');
                        return;
                    }
                    $(".apply-selectboxit").selectBoxIt();
                    var $selectLibraryParam = $("#select_library_browse");
                    var $selectLibraryYear = $("#select_library_year");
                    var $selectLibraryClass = $("#select_library_class");

                    $selectLibraryParam.on('change', drawChart);
                    $selectLibraryYear.on('change', drawChart);
                    $selectLibraryClass.on('change', drawChart);

                    function drawChart() {
                        var libraryParam = $selectLibraryParam.val();
                        var libraryYear = $selectLibraryYear.val();
                        var libraryClass = $selectLibraryClass.val();
                        $('#graph_library').libraryChart(data, {'parameter': libraryParam, 'year': libraryYear, 'klass': libraryClass});
                    }

                    drawChart();
                }
            },
            'nutrition': {
                getData: function() {
                    return klp.api.do(schoolInfoURL + '/nutrition');
                },

                getContext: function(data) {
                    data.hasData = true;
                    if (_.isEmpty(data.mdm_agg)) {
                        data.hasData = false;
                        return data;
                    }
                    data.indent = [];
                    data.attendance = [];
                    data.categories = [];
                    data.diseEnrollment = [];
                    data.klpEnrollment = [];

                    data.mdm_agg.forEach(function(element, index) {
                        data.categories.push(element.mon+ ' week ' + element.wk);
                        data.indent.push(element.indent);
                        data.attendance.push(element.attend);
                        data.diseEnrollment.push(data.num_boys_dise + data.num_girls_dise);
                        data.klpEnrollment.push(data.num_boys + data.num_girls);
                    });
                    data.type_name = klp.utils.getSchoolType(SCHOOL_TYPE_ID);
                    return data;

                },

                onRender: function(data) {
                    if (data.hasData) {
                        $('.data').removeClass('hide');
                        $('#graph_nutrition').highcharts({
                            chart: {
                                type: 'area',
                                width: container_width,
                                height: klp.utils.getRelativeHeight(960,400, 230, container_width)
                            },
                            title:{
                                text: null
                            },
                            subtitle: {
                                text: "Food Indent vs Attendance Tracking"
                            },
                            xAxis: {
                                categories: data.categories,
                                tickInterval: 2
                                // allowDecimals: false,
                                // labels: {
                                //     formatter: function() {
                                //         return this.value; // clean, unformatted number for year
                                //     }
                                // }
                            },
                            yAxis: {
                                title: {
                                    text: 'Number of children'
                                },
                                labels: {
                                    formatter: function() {
                                        return this.value;
                                        // return this.value / 1000 +'k';
                                    }
                                }
                            },
                            credits:{
                                enabled: false
                            },
                            tooltip: {
                                // pointFormat: '{series.name} produced {point.y:,.0f}
warheads in {point.x}'
                            },
                            plotOptions: {
                                area: {
                                    fillOpacity: 0
                                }
                            },
                            series: [{
                                name: 'Indent',
                                data: data.indent,
                                color: '#56af31',
                                fillColor: {
                                    linearGradient: chart_gradient_param,
                                    stops: [
                                        [0, '#e5f3e0'],
                                        [1, 'rgba(255,255,255,0.3)']
                                    ]
                                }
                            }, {
                                name: 'Attendance',
                                data: data.attendance,
                                color: '#3892e3',
                                fillColor: {
                                    linearGradient: chart_gradient_param,
                                    stops: [
                                        [0, '#92c3ef'],
                                        [1, 'rgba(255,255,255,0.3)']
                                    ]
                                }
                            }, {
                                name: 'KLP Enrollment',
                                data: data.klpEnrollment,
                                color: '#646157'
                            }, {
                                name: 'DISE Enrollment',
                                data: data.diseEnrollment,
                                color: '#e4b324'
                            }
                            ]
                        });
                    } else {
                        $('.no-data').removeClass('hide');
                    }
                }
            },
            'share-story': {
                getData: function() {
                    //FIXME: replace with real SYS end-point
                    var url ="stories/";
                    var params = {
                        'school_id': SCHOOL_ID,
                        'answers': 'yes',
                        'verified': 'yes'
                    };
                    return klp.api.do(url, params);
                },
                getContext: function(data) {
                    var latestStory = getLatestStoryWithAnswers(data.features);
                    if (latestStory) {
                        data.latest_answers = getCleanedAnswers(latestStory.answers);
                    } else {
                        data.latest_answers = null;
                    }
                    console.log("sys data", data);
                    return data;

                    function getLatestStoryWithAnswers(stories) {
                        for (var i=0; i < stories.length; i++) {
                            var thisStory = stories[i];
                            if (thisStory.answers.length > 0) {
                                return thisStory;
                            }
                        }
                        return null;
                    }

                    function getCleanedAnswers(answers) {
                        var cleanedAnswers = [];
                        _(answers).each(function(a) {
                            if (a.text === 'Yes' || a.text === 'No') {
                                cleanedAnswers.push(a);
                            }
                        });
                        console.log("answers", answers, cleanedAnswers);
                        return cleanedAnswers;
                    }
                },
                onRender: function(data) {
                    var $container = $('.tab-content[data-tab=share-story]');
                    var containerHTML = $container.html();
                    klp.share_story.init(SCHOOL_ID, containerHTML);
                    var urlState = klp.router.getHash();
                    var queryParams = urlState.queryParams;
                    // if (queryParams.hasOwnProperty('state') && queryParams.state === 'form') {

                    // }
                    klp.router.events.on("hashchange:state", function(e, params) {
                        console.log("hashchange state fired", params);
                        if (params.changed['state'].newVal === null) {
                            //console.log("old html", oldHtml);
                            $container.html(containerHTML);
                        } else if (params.changed['state'].newVal === 'form') {
                            $("#trigger_share_story_form").click();
                        }
                    });
                }
            },
            'volunteer': {
                getData: function() {
                    var url = "volunteer_activities";
                    var params = {
                        school: SCHOOL_ID
                    };
                    return klp.api.do(url, params);
                },
                onRender: function(data) {
                    klp.volunteer_here.checkSelf(data.features);
                }
            }

        };

        //tabs to omit for preschools
        var preschoolOmit = ['finances', 'library', 'nutrition'];
        if (schoolType === 'preschool') {
            hidePreschoolTabs(preschoolOmit);
        }

        var keys = _(tabs).keys();
        if (schoolType === 'preschool') {
            keys = _(keys).without(preschoolOmit);
        }

        //compile templates for tabs
        _(keys).each(function(tabName) {
            console.log("tab name", tabName);
            var templateString = $('#tpl-tab-' + tabName).html();
            templates[tabName] = swig.compile(templateString);
        });

        $(document).on("click", ".js-tab-link", function(e){
            var $wrapper = $(".js-tabs-wrapper");
            var $trigger = $(this).closest(".js-tab-link");
            var tab_id = $trigger.attr('data-tab');

            //show tab
            t.showTab(tab_id, false);

        });

        var queryParams = klp.router.getHash().queryParams;
        if (queryParams.hasOwnProperty('tab') && queryParams['tab'] in tabs) {
            var firstTab = queryParams['tab'];
        } else {
            var firstTab = 'info';
        }

        var tabDeferred = t.showTab(firstTab, true);
        klp.router.events.on('hashchange:tab', function(e, params) {
            console.log("hashchange:tab", params);
            var queryParams = params.queryParams;
            if (queryParams['tab'] in tabs) {
                t.showTab(queryParams['tab']);
            }
        });

        //slightly ugly hack to lazy load all tabs only on mobile
        //FIXME: possibly, get "isMobile" somewhere else, not sure
        //checking for < 768 on page load is the best technique.
        if ($(window).width() < 768) {
            tabDeferred.done(function() {
                var tabsToLoad = _(keys).without(firstTab);
                _(tabsToLoad).each(function(tabName) {
                    t.showTab(tabName, true);
                });
            });
        }
        console.log(templates);

    };

    /*
        Arguments:
            tabName <string>: name of tab to show
            replaceState <boolean>: whether to "replace state", if true,
                will not add a new history entry for this tab show. This exists
                so that when we load all tabs on mobile, we can avoid adding new history
                entries for each tab.

     */
    t.showTab = function(tabName, replaceState) {
        if (currentTab === tabName) {
            return;
        }
        if (typeof(replaceState) === 'undefined') {
            replaceState = false;
        }
        $('.tab-content.current').removeClass('current');
        var queryParams = klp.router.getHash().queryParams;
        if (!(queryParams.hasOwnProperty('tab') && queryParams['tab'] === tabName)) {
            klp.router.setHash(null, {'tab': tabName}, {trigger: false, replace: replaceState});
        }
        currentTab = tabName;
        var $tabButton = $('.js-tab-link[data-tab=' + tabName + ']');
        $tabButton.parent().find("li.current").removeClass('current');
        $tabButton.addClass("current");
        $('div[data-tab=' + tabName + ']').addClass('current');
        var $deferred = $.Deferred();
        getData(tabName, function(data) {
            if (tabs[tabName].hasOwnProperty('getContext')) {
                data = tabs[tabName].getContext(data);
            }
            var html = templates[tabName](data);
            //$('#loadingTab').removeClass('current');
            $('div[data-tab=' + tabName + ']').html(html);
            doPostRender(tabName, data);
            $deferred.resolve();
        });
        return $deferred;
    };

    function getData(tabName, callback) {
        if (dataCache.hasOwnProperty(tabName)) {
            callback(dataCache[tabName]);
            return;
        }
        var $xhr = tabs[tabName].getData();
        $xhr.done(function(data) {
            dataCache[tabName] = data;
            callback(data);
        });
    }

    function doPostRender(tabName, data) {
        if (tabs[tabName].hasOwnProperty('onRender')) {
            tabs[tabName].onRender(data);
        }
    }

    function hidePreschoolTabs(tabNames) {
        _(tabNames).each(function(tabName) {
            $('.tabs').find('li[data-tab=' + tabName + ']').hide();
            $('.js-tabs-wrapper').find('[data-tab=' + tabName + ']').hide().prev().hide();
        });
    }

})();<|endoftext|>


<commit_before>describe('LiveStreamControllerTests', function(){
	var $scope, LiveStreamController;
    beforeEach(angular.mock.module('adminUI'));

    beforeEach(inject(function($injector, $rootScope, $controller) {
        $scope = $rootScope;
        createLiveStreamController = function() {
           return $controller('LiveStreamController', {
               '$scope': $scope,
           });
        }
    }));

    describe('loadVideo() tests', function() {
        beforeEach(function() {
            spyOn(toastr, "error");
        });

        it('should run the video when HLS is supported', function() {
            LiveStreamController = createLiveStreamController($scope);
            expect($scope.skipHlsCheck).toBeFalsy();
            $scope.loadVideo();
            expect(toastr.error).not.toHaveBeenCalled();
        });
        it('should show an error when HLS is not supported', function() {
            LiveStreamController = createLiveStreamController($scope);
            $scope.skipHlsCheck = true;
            expect($scope.skipHlsCheck).toBeTruthy();
            $scope.loadVideo();
            expect(toastr.error).toHaveBeenCalled();
        });
    });

});<commit_msg>Added test for the empty string case for the livestreamURL.<commit_after>describe('LiveStreamControllerTests', function(){
	var $scope, schedulerService, LiveStreamController;
    beforeEach(angular.mock.module('adminUI'));

    beforeEach(inject(function($injector, $rootScope, $controller, _schedulerService_) {
        $scope = $rootScope;
		createSchedulerService = function($rootScope) {
            return $injector.get('schedulerService');
        };
		schedulerService = createSchedulerService($scope);
        createLiveStreamController = function() {
           return $controller('LiveStreamController', {
               '$scope': $scope,
			   'schedulerService': schedulerService
           });
        }
    }));

    describe('loadVideo() tests', function() {
        beforeEach(function() {
            spyOn(toastr, "error");
        });
		it('should toast an error message when livestreamURL is an empty string', function() {
			LiveStreamController = createLiveStreamController($scope);
            schedulerService.livestreamURL = '';
            $scope.loadVideo();
            expect(toastr.error).toHaveBeenCalledWith("Please enter an output URL in config.", "Error");
        });
        it('should run the video when HLS is supported', function() {
            LiveStreamController = createLiveStreamController($scope);
            expect($scope.skipHlsCheck).toBeFalsy();
            $scope.loadVideo();
            expect(toastr.error).not.toHaveBeenCalled();
        });
        it('should show an error when HLS is not supported', function() {
            LiveStreamController = createLiveStreamController($scope);
            $scope.skipHlsCheck = true;
            expect($scope.skipHlsCheck).toBeTruthy();
            $scope.loadVideo();
            expect(toastr.error).toHaveBeenCalled();
        });
    });

});<|endoftext|>


<commit_before>import Matter from 'matter-js'
import R from 'ramda'
const { Engine, Render, World, Bodies, Body, Events, Vector, Bounds, Runner } = Matter

const FRICTION = 0.015
const RESTITUTION = 0.1

const STONE_RADIUS = 31
const HOUSE_RADIUS = 245
const SHEET_WIDTH = 820
const SHEET_HEIGHT = 2460
const BUTTON_Y = 498

// Stones out of bounds are removed from the sheet.
// The simulation is stopped when there are either no stones
// inside bounds or all the stones are slower than MIN_SPEED.
const BOUNDS = {
  min: { x: -SHEET_WIDTH / 2, y: -BUTTON_Y },
  max: { x: SHEET_WIDTH / 2, y: SHEET_HEIGHT - BUTTON_Y }
}
const MIN_SPEED = 0.01
const SIMULATION_STEP_MS = 1000 / 60

// FIXME rename angle to line, speed to weight
const getVelocity = (speed, angle) => {
  const vx = speed * Math.cos(angle * Math.PI / 180)
  const vy = -speed * Math.cos((90 - angle) * Math.PI / 180)
  return Vector.create(vx, vy)
}

const createStone = (x, y, angle, team, sprites) => {
  const options = {
    frictionAir: FRICTION,
    restitution: RESTITUTION,
    angle
  }
  if (sprites !== undefined) {
    options.render = {
      sprite: {
        texture: sprites[team]
      }
    }
  }
  const stone = Bodies.circle(x, y, STONE_RADIUS, options)
  stone.team = team
  return stone
}

const createStones = (delivery, stones, sprites) => {
  const stationary = stones.map(s => createStone(s.x,
                                                 s.y,
                                                 s.angle,
                                                 s.team,
                                                 sprites))

  const delivered = createStone(delivery.start_x,
                                BOUNDS.max.y,
                                0,
                                delivery.team,
                                sprites)

  Body.setAngularVelocity(delivered, delivery.curl)
  Body.setVelocity(delivered, getVelocity(delivery.speed, delivery.angle))

  return [delivered, ...stationary]
}

const createEngine = matterStones => {
  const engine = Engine.create()
  engine.world.gravity = Vector.create(0, 0)

  World.add(engine.world, matterStones)
  Events.on(engine, 'afterUpdate', () => {
    // Remove items that are out of bounds
    engine.world.bodies
      .filter(isOutOfBounds)
      .forEach(stone => World.remove(engine.world, stone))
  })

  return engine
}

const stoneToJson = stone => {
  const { x, y } = stone.position
  const team = stone.team
  const angle = stone.angle
  return { x, y, team, angle }
}

const isOutOfBounds = stone => !Bounds.overlaps(stone.bounds, BOUNDS)

const isMoving = stone => Vector.magnitude(stone.velocity) > MIN_SPEED

const isFinished = engine => (
  engine.world.bodies.length === 0 || !engine.world.bodies.some(isMoving)
)

const simulate = (delivery, stones) => {
  const matterStones = createStones(delivery, stones)
  const engine = createEngine(matterStones)

  const runStep = engine => {
    Events.trigger(engine, 'tick', { timestamp: engine.timing.timestamp })
    Engine.update(engine, SIMULATION_STEP_MS)
    Events.trigger(engine, 'afterTick', { timestamp: engine.timing.timestamp })
    return engine
  }
  R.until(isFinished, runStep)(engine)

  return engine.world.bodies.map(stoneToJson)
}

const createRunner = () => {
  const runnerOptions = {
    isFixed: true,
    delta: SIMULATION_STEP_MS
  }
  return Runner.create(runnerOptions)
}

const createRenderer = (engine, element, background) => {
  const renderer = Render.create({
    element,
    engine,
    bounds: BOUNDS,
    options: {
      hasBounds: true,
      background,
      height: SHEET_HEIGHT,
      width: SHEET_WIDTH,
      wireframes: false
    }
  })

  return renderer
}

const renderSimulation = (delivery, stones, sprites, background, element) => {
  return new Promise((resolve, reject) => {
    let t;

    const isEmpty = e => !e.hasChildNodes()
    const removeChild = element => {
      element.removeChild(element.firstChild)
      return element
    }
    R.unless(R.isEmpty, R.until(isEmpty, removeChild))(element)

    const matterStones = createStones(delivery, stones, sprites)
    const engine = createEngine(matterStones)
    const runner = createRunner()
    const renderer = createRenderer(engine, element, background)

    t = setTimeout(reject, 12000);

    Events.on(renderer, 'afterRender', () => {
      if (isFinished(engine)) {
        Render.stop(renderer);
        clearTimeout(t);
        resolve();
      }
    })

    Runner.run(runner, engine)
    Render.run(renderer)
  })
}

export { simulate, renderSimulation, STONE_RADIUS, HOUSE_RADIUS }
<commit_msg>Added support for swinging deliveries<commit_after>import Matter from 'matter-js'
import R from 'ramda'
const { Engine, Render, World, Bodies, Body, Events, Vector, Bounds, Runner } = Matter

const FRICTION = 0.015
const RESTITUTION = 0.1

const STONE_RADIUS = 31
const HOUSE_RADIUS = 245
const SHEET_WIDTH = 820
const SHEET_HEIGHT = 2460
const BUTTON_Y = 498

// Stones out of bounds are removed from the sheet.
// The simulation is stopped when there are either no stones
// inside bounds or all the stones are slower than MIN_SPEED.
const BOUNDS = {
  min: { x: -SHEET_WIDTH / 2, y: -BUTTON_Y },
  max: { x: SHEET_WIDTH / 2, y: SHEET_HEIGHT - BUTTON_Y }
}
const MIN_SPEED = 0.01
const SIMULATION_STEP_MS = 1000 / 60

// FIXME rename angle to line, speed to weight
const getVelocity = (speed, angle) => {
  const vx = speed * Math.cos(angle * Math.PI / 180)
  const vy = -speed * Math.cos((90 - angle) * Math.PI / 180)
  return Vector.create(vx, vy)
}

const createStone = (x, y, angle, team, sprites, isDelivery) => {
  const options = {
    frictionAir: FRICTION,
    restitution: RESTITUTION,
    angle
  }
  if (sprites !== undefined) {
    options.render = {
      sprite: {
        texture: sprites[team]
      }
    }
  }
  const stone = Bodies.circle(x, y, STONE_RADIUS, options)
  stone.team = team
  stone.isDelivery = isDelivery
  return stone
}

const createStones = (delivery, stones, sprites) => {
  const stationary = stones.map(s => createStone(s.x,
                                                 s.y,
                                                 s.angle,
                                                 s.team,
                                                 sprites,
                                                 false))

  const delivered = createStone(delivery.start_x,
                                BOUNDS.max.y,
                                0,
                                delivery.team,
                                sprites,
                                true)

  Body.setAngularVelocity(delivered, delivery.curl)
  Body.setVelocity(delivered, getVelocity(delivery.speed, delivery.angle))

  return [delivered, ...stationary]
}

const createEngine = matterStones => {
  const engine = Engine.create()
  engine.world.gravity = Vector.create(0, 0)

  World.add(engine.world, matterStones)
  Events.on(engine, 'afterUpdate', () => {
    applyCurl(engine)
    // Remove items that are out of bounds
    engine.world.bodies
      .filter(isOutOfBounds)
      .forEach(stone => World.remove(engine.world, stone))
  })

  return engine
}

const stoneToJson = stone => {
  const { x, y } = stone.position
  const team = stone.team
  const angle = stone.angle
  return { x, y, team, angle }
}

const isOutOfBounds = stone => !Bounds.overlaps(stone.bounds, BOUNDS)

const isMoving = stone => Vector.magnitude(stone.velocity) > MIN_SPEED

const isFinished = engine => (
  engine.world.bodies.length === 0 || !engine.world.bodies.some(isMoving)
)

const applyCurl  = engine => {
  const deliveryStone = engine.world.bodies.find(x => x.isDelivery === true)
  if (!deliveryStone)
  {
    return
  }

  const baseVector = deliveryStone.velocity;
  const scaledVector = Vector.mult(baseVector, Math.abs(deliveryStone.angularVelocity) / 4500)
  const angle = Math.sign(deliveryStone.angularVelocity) * 0.5 * Math.PI
  const directedVector = Vector.rotate(scaledVector, angle)

  Body.applyForce(deliveryStone, deliveryStone.position, directedVector)
}

const simulate = (delivery, stones) => {
  const matterStones = createStones(delivery, stones)
  const engine = createEngine(matterStones)

  const runStep = engine => {
    Events.trigger(engine, 'tick', { timestamp: engine.timing.timestamp })
    Engine.update(engine, SIMULATION_STEP_MS)
    Events.trigger(engine, 'afterTick', { timestamp: engine.timing.timestamp })
    return engine
  }
  R.until(isFinished, runStep)(engine)

  return engine.world.bodies.map(stoneToJson)
}

const createRunner = () => {
  const runnerOptions = {
    isFixed: true,
    delta: SIMULATION_STEP_MS
  }
  return Runner.create(runnerOptions)
}

const createRenderer = (engine, element, background) => {
  const renderer = Render.create({
    element,
    engine,
    bounds: BOUNDS,
    options: {
      hasBounds: true,
      background,
      height: SHEET_HEIGHT,
      width: SHEET_WIDTH,
      wireframes: false
    }
  })

  return renderer
}

const renderSimulation = (delivery, stones, sprites, background, element) => {
  return new Promise((resolve, reject) => {
    let failTimeout;

    const isEmpty = e => !e.hasChildNodes()
    const removeChild = element => {
      element.removeChild(element.firstChild)
      return element
    }
    R.unless(R.isEmpty, R.until(isEmpty, removeChild))(element)

    const matterStones = createStones(delivery, stones, sprites)
    const engine = createEngine(matterStones)
    const runner = createRunner()
    const renderer = createRenderer(engine, element, background)

    failTimeout = setTimeout(reject, 12000);

    Events.on(renderer, 'afterRender', () => {

      if (isFinished(engine)) {
        Render.stop(renderer);
        clearTimeout(failTimeout);
        resolve();
      }
    })

    Runner.run(runner, engine)
    Render.run(renderer)
  })
}

export { simulate, renderSimulation, STONE_RADIUS, HOUSE_RADIUS }<|endoftext|>


<commit_before>/*
Copyright 2015 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var dis = require("./dispatcher");

var MIN_DISPATCH_INTERVAL = 1 * 1000;

/**
 * This class watches for user activity (moving the mouse or pressing a key)
 * and dispatches the user_activity action at times when the user is interacting
 * with the app (but at a much lower frequency than mouse move events)
 */
class UserActivity {

    /**
     * Start listening to user activity
     */
    start() {
        document.onmousemove = this._onUserActivity.bind(this);
        document.onkeypress = this._onUserActivity.bind(this);
        this.lastActivityAtTs = new Date().getTime();
        this.lastDispatchAtTs = 0;
    }

    /**
     * Stop tracking user activity
     */
    stop() {
        document.onmousemove = undefined;
        document.onkeypress = undefined;
    }

    _onUserActivity() {
        this.lastActivityAtTs = (new Date).getTime();
        if (this.lastDispatchAtTs < this.lastActivityAtTs - MIN_DISPATCH_INTERVAL) {
            this.lastDispatchAtTs = this.lastActivityAtTs;
            dis.dispatch({
                action: 'user_activity'
            });
        }
    }
}

module.exports = new UserActivity();
<commit_msg>only dispatch user_activity event if the mouse actually moves (rather than the DOM moving under the mouse)<commit_after>/*
Copyright 2015 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var dis = require("./dispatcher");

var MIN_DISPATCH_INTERVAL = 1 * 1000;

/**
 * This class watches for user activity (moving the mouse or pressing a key)
 * and dispatches the user_activity action at times when the user is interacting
 * with the app (but at a much lower frequency than mouse move events)
 */
class UserActivity {

    /**
     * Start listening to user activity
     */
    start() {
        document.onmousemove = this._onUserActivity.bind(this);
        document.onkeypress = this._onUserActivity.bind(this);
        this.lastActivityAtTs = new Date().getTime();
        this.lastDispatchAtTs = 0;
    }

    /**
     * Stop tracking user activity
     */
    stop() {
        document.onmousemove = undefined;
        document.onkeypress = undefined;
    }

    _onUserActivity(event) {
        if (event.screenX) {
            if (event.screenX === this.lastScreenX &&
                event.screenY === this.lastScreenY)
            {
                // mouse hasn't actually moved
                return;
            }
            this.lastScreenX = event.screenX;
            this.lastScreenY = event.screenY;
        }

        this.lastActivityAtTs = (new Date).getTime();
        if (this.lastDispatchAtTs < this.lastActivityAtTs - MIN_DISPATCH_INTERVAL) {
            this.lastDispatchAtTs = this.lastActivityAtTs;
            dis.dispatch({
                action: 'user_activity'
            });
        }
    }
}

module.exports = new UserActivity();
<|endoftext|>


<commit_before>/* @flow strict-local */
import union from 'lodash.union';

import type { NarrowsState, Action } from '../types';
import {
  DEAD_QUEUE,
  LOGOUT,
  LOGIN_SUCCESS,
  ACCOUNT_SWITCH,
  MESSAGE_FETCH_COMPLETE,
  EVENT_NEW_MESSAGE,
  EVENT_MESSAGE_DELETE,
  EVENT_UPDATE_MESSAGE_FLAGS,
} from '../actionConstants';
import { LAST_MESSAGE_ANCHOR, FIRST_UNREAD_ANCHOR } from '../constants';
import { isMessageInNarrow, STARRED_NARROW_STR } from '../utils/narrow';
import { NULL_OBJECT } from '../nullObjects';

const initialState: NarrowsState = NULL_OBJECT;

const messageFetchComplete = (state, action) => {
  const key = JSON.stringify(action.narrow);
  const fetchedMessageIds = action.messages.map(message => message.id);
  const replaceExisting =
    action.anchor === FIRST_UNREAD_ANCHOR || action.anchor === LAST_MESSAGE_ANCHOR;
  return {
    ...state,
    [key]: replaceExisting
      ? fetchedMessageIds
      : union(state[key], fetchedMessageIds).sort((a, b) => a - b),
  };
};

const eventNewMessage = (state, action) => {
  let stateChange = false;
  const msg = {};
  Object.keys(state).forEach(key => {
    const isInNarrow = isMessageInNarrow(action.message, JSON.parse(key), action.ownEmail);
    const isCaughtUp = action.caughtUp[key] && action.caughtUp[key].newer;
    const messageDoesNotExist = state[key].find(id => action.message.id === id) === undefined;

    if (isInNarrow && isCaughtUp && messageDoesNotExist) {
      stateChange = true;
      msg[key] = [...state[key], action.message.id];
    } else {
      msg[key] = state[key];
    }
  });
  const newState = msg;
  return stateChange ? newState : state;
};

const eventMessageDelete = (state, action) => {
  let stateChange = false;
  const updatedState = {};
  Object.keys(state).forEach(key => {
    updatedState[key] = state[key].filter(id => id !== action.messageId);
    stateChange = stateChange || updatedState[key].length < state[key].length;
  });
  const newState = updatedState;
  return stateChange ? newState : state;
};

const eventUpdateMessageFlags = (state, action) => {
  const { messages, flag, operation } = action;
  const messagesSet = new Set(messages);
  const updates = [];

  if (flag === 'starred' && state[STARRED_NARROW_STR]) {
    if (operation === 'add') {
      updates.push({
        [STARRED_NARROW_STR]: [...state[STARRED_NARROW_STR], ...messages].sort(),
      });
    } else {
      // operation === 'remove'
      updates.push({
        [STARRED_NARROW_STR]: state[STARRED_NARROW_STR].filter(id => !messagesSet.has(id)),
      });
    }
  }

  if (!updates.length) {
    return state;
  }

  return Object.assign({}, state, ...updates);
};

export default (state: NarrowsState = initialState, action: Action): NarrowsState => {
  switch (action.type) {
    case DEAD_QUEUE:
    case LOGOUT:
    case LOGIN_SUCCESS:
    case ACCOUNT_SWITCH:
      return initialState;

    case MESSAGE_FETCH_COMPLETE:
      return messageFetchComplete(state, action);

    case EVENT_NEW_MESSAGE:
      return eventNewMessage(state, action);

    case EVENT_MESSAGE_DELETE:
      return eventMessageDelete(state, action);

    case EVENT_UPDATE_MESSAGE_FLAGS:
      return eventUpdateMessageFlags(state, action);

    default:
      return state;
  }
};
<commit_msg>narrowsReducer: Fix variable names in two loops.<commit_after>/* @flow strict-local */
import union from 'lodash.union';

import type { NarrowsState, Action } from '../types';
import {
  DEAD_QUEUE,
  LOGOUT,
  LOGIN_SUCCESS,
  ACCOUNT_SWITCH,
  MESSAGE_FETCH_COMPLETE,
  EVENT_NEW_MESSAGE,
  EVENT_MESSAGE_DELETE,
  EVENT_UPDATE_MESSAGE_FLAGS,
} from '../actionConstants';
import { LAST_MESSAGE_ANCHOR, FIRST_UNREAD_ANCHOR } from '../constants';
import { isMessageInNarrow, STARRED_NARROW_STR } from '../utils/narrow';
import { NULL_OBJECT } from '../nullObjects';

const initialState: NarrowsState = NULL_OBJECT;

const messageFetchComplete = (state, action) => {
  const key = JSON.stringify(action.narrow);
  const fetchedMessageIds = action.messages.map(message => message.id);
  const replaceExisting =
    action.anchor === FIRST_UNREAD_ANCHOR || action.anchor === LAST_MESSAGE_ANCHOR;
  return {
    ...state,
    [key]: replaceExisting
      ? fetchedMessageIds
      : union(state[key], fetchedMessageIds).sort((a, b) => a - b),
  };
};

const eventNewMessage = (state, action) => {
  let stateChange = false;
  const newState = {};
  Object.keys(state).forEach(key => {
    const isInNarrow = isMessageInNarrow(action.message, JSON.parse(key), action.ownEmail);
    const isCaughtUp = action.caughtUp[key] && action.caughtUp[key].newer;
    const messageDoesNotExist = state[key].find(id => action.message.id === id) === undefined;

    if (isInNarrow && isCaughtUp && messageDoesNotExist) {
      stateChange = true;
      newState[key] = [...state[key], action.message.id];
    } else {
      newState[key] = state[key];
    }
  });
  return stateChange ? newState : state;
};

const eventMessageDelete = (state, action) => {
  let stateChange = false;
  const newState = {};
  Object.keys(state).forEach(key => {
    newState[key] = state[key].filter(id => id !== action.messageId);
    stateChange = stateChange || newState[key].length < state[key].length;
  });
  return stateChange ? newState : state;
};

const eventUpdateMessageFlags = (state, action) => {
  const { messages, flag, operation } = action;
  const messagesSet = new Set(messages);
  const updates = [];

  if (flag === 'starred' && state[STARRED_NARROW_STR]) {
    if (operation === 'add') {
      updates.push({
        [STARRED_NARROW_STR]: [...state[STARRED_NARROW_STR], ...messages].sort(),
      });
    } else {
      // operation === 'remove'
      updates.push({
        [STARRED_NARROW_STR]: state[STARRED_NARROW_STR].filter(id => !messagesSet.has(id)),
      });
    }
  }

  if (!updates.length) {
    return state;
  }

  return Object.assign({}, state, ...updates);
};

export default (state: NarrowsState = initialState, action: Action): NarrowsState => {
  switch (action.type) {
    case DEAD_QUEUE:
    case LOGOUT:
    case LOGIN_SUCCESS:
    case ACCOUNT_SWITCH:
      return initialState;

    case MESSAGE_FETCH_COMPLETE:
      return messageFetchComplete(state, action);

    case EVENT_NEW_MESSAGE:
      return eventNewMessage(state, action);

    case EVENT_MESSAGE_DELETE:
      return eventMessageDelete(state, action);

    case EVENT_UPDATE_MESSAGE_FLAGS:
      return eventUpdateMessageFlags(state, action);

    default:
      return state;
  }
};
<|endoftext|>


<commit_before>/**********************************************************
 * General settings
 **********************************************************/

	var apik = '';
	var imageSelectedClass='selected';
	var imageNotSelectedClass='unselected';
	var imageContainerId='image-container';
	var searchFormId='search-form';
	var keywordFieldId='search-field';
	var pageFieldId='page-field';
	var submitFormId='submit-form';
	//*** Leave url blank to submit to self:
	var submitFormURL='';
	var searchRes;

/**********************************************************
 * Search flickr by keyword and show results
 **********************************************************/

function flickrSearch(apiKey,keyword,page)	{
	$.getJSON(
		'https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key='+ apiKey +'&text='+ keyword +'&extras=url_s&page='+page+'&per_page=15&format=json&jsoncallback=?',

		function(results){
    		$.each(results.photos.photo, function(i,item){
				var photoURL=item.url_s;
    			var photoID = item.id;
    			if (photoURL){
    				var imgElement='';
    				$('#'+imageContainerId).append(imgElement);
					$('#'+photoID).click(function(){
    					if ($(this).attr('class')==imageSelectedClass) {
    						$(this).attr('class', imageNotSelectedClass);
    					}
    					else {
    						$(this).attr('class', imageSelectedClass);
    					}
					});
    			}
 			});
		}
	);
}

/**********************************************************
 * Get info from photo by id and return json response
 **********************************************************/

function flickrPhotoInfo(apiKey, photoID)	{
	return $.getJSON('https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=' + apiKey + '&photo_id=' + photoID + '&format=json&jsoncallback=?',
    	function(data){
			//no use for this right now
    	}
	);
}

$(document).ready(function(){

	//jQuery('').attr('id', 'loader').attr('src', 'ajax-loader.gif').appendTo(imageContainerId);

	/* Define what happens when search form is submitted:
	 * 		1-Prevent form submission (default form behavior)
	 * 		2-Retrieve search keyword and page from form
	 * 		3-Do search on flickr, get photos
	 * 		4-Show photos										*/

	$('#'+searchFormId).submit(function(event){

		event.preventDefault();

		var searchKeyword=$('#'+keywordFieldId).val();
		var searchPage=$('#'+pageFieldId).val();

		flickrSearch(apik,searchKeyword,searchPage);
	});

	/* Attach onClick behaviour to submit button:
	* 		1-Prevent form submission (default form behavior)
	*		2-Get selected images
	*		3-Get flickr info from each image
	* 		4-Build JSON object and submit						*/

	$('#'+submitFormId).submit(function(event){

		event.preventDefault();

		var jsonImages;
		$('.'+imageSelectedClass).each(function(index) {
		  	id=$(this).attr('id');
		  	$.when(flickrPhotoInfo(apik,id)).done(function(pInfo){
		  		if (!jsonImages) {
		  			jsonImages=$.makeArray(pInfo);
		  		} else {
					jsonImages=jsonImages.concat($.makeArray(pInfo)); //=$.extend({}, jsonImages, pInfo);
					$('#'+imageContainerId).empty();
					$('#'+imageContainerId).append('
'+JSON.stringify(jsonImages[0])+'

');
					$('#'+imageContainerId).append('

'+JSON.stringify(jsonImages[1])+'
');
				}
			});
		});

		$.post( submitFormURL, jsonImages, function(data) {
         	// do something with response from server, or ignore it
         		$('#'+imageContainerId).empty();
				//$('#'+imageContainerId).append();
       	});
	});
});
<commit_msg>Small corrections<commit_after>/**********************************************************
 * General settings
 **********************************************************/

	//*** Your flickr api key goes here:
	var apik = '';
	var imageSelectedClass='selected';
	var imageNotSelectedClass='unselected';
	var imageContainerId='image-container';
	var searchFormId='search-form';
	var keywordFieldId='search-field';
	var pageFieldId='page-field';
	var submitFormId='submit-form';
	//*** Leave url blank to submit to self:
	var submitFormURL='';
	var searchRes;

/**********************************************************
 * Search flickr by keyword and show results
 **********************************************************/

function flickrSearch(apiKey,keyword,page)	{
	$.getJSON(
		'https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key='+ apiKey +'&text='+ keyword +'&extras=url_s&page='+page+'&per_page=15&format=json&jsoncallback=?',
		function(results){
    		$.each(results.photos.photo, function(i,item){
				var photoURL=item.url_s;
    			var photoID = item.id;
    			if (photoURL){
    				var imgElement='';
    				$('#'+imageContainerId).append(imgElement);
					$('#'+photoID).click(function(){
    					if ($(this).attr('class')==imageSelectedClass) {
    						$(this).attr('class', imageNotSelectedClass);
    					}
    					else {
    						$(this).attr('class', imageSelectedClass);
    					}
					});
    			}
 			});
		}
	);
}

/**********************************************************
 * Get info from photo by id and return json response
 **********************************************************/

function flickrPhotoInfo(apiKey, photoID)	{
	return $.getJSON('https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=' + apiKey + '&photo_id=' + photoID + '&format=json&jsoncallback=?',
    	function(data){
			//no use for this right now
    	}
	);
}

$(document).ready(function(){

	 /* Define what happens when search form is submitted:
	 * 		1-Prevent form submission (default form behavior)
	 * 		2-Retrieve search keyword and page from form
	 * 		3-Do search on flickr, show photos					*/

	$('#'+searchFormId).submit(function(event){

		event.preventDefault();

		var searchKeyword=$('#'+keywordFieldId).val();
		var searchPage=$('#'+pageFieldId).val();

		flickrSearch(apik,searchKeyword,searchPage);
	});

	/* Attach onClick behaviour to submit button:
	* 		1-Prevent form submission (default form behavior)
	*		2-Get selected images
	*		3-Get flickr info from each image
	* 		4-Build JSON object and submit						*/

	$('#'+submitFormId).submit(function(event){

		event.preventDefault();

		var jsonImages;
		$('.'+imageSelectedClass).each(function(index) {
		  	id=$(this).attr('id');
		  	$.when(flickrPhotoInfo(apik,id)).done(function(pInfo){
		  		if (!jsonImages) {
		  			jsonImages=$.makeArray(pInfo);
		  		} else {
					jsonImages=jsonImages.concat($.makeArray(pInfo));
				}
			});
		});

		$.post( submitFormURL, jsonImages, function(data) {
         	// do something with response from server, or ignore it
         		$('#'+imageContainerId).empty();
				//$('#'+imageContainerId).append();
       	});
	});
});
<|endoftext|>


<commit_before>"use strict";

const gulp = require('gulp');

/* ------------------------------------------ */
/*                 Landing                    */
/* ------------------------------------------ */

// Main stream
gulp.task('clear:landing', require('./gulp.tasks/landing/clean').all);
gulp.task('copy:dep:landing', require('./gulp.tasks/landing/copy/dependencies').landing);
gulp.task('copy:googleMaps:landing', require('./gulp.tasks/landing/copy/dependencies').googleMaps);
gulp.task('copy:img:landing', require('./gulp.tasks/landing/copy/images').landing);
gulp.task('copy:fonts:landing', require('./gulp.tasks/landing/copy/fonts').landing);
gulp.task('copy:tpl:landing', require('./gulp.tasks/landing/copy/templates').landing);
gulp.task('js:landing', require('./gulp.tasks/landing/scripts.js').landing);
gulp.task('sass:landing', require('./gulp.tasks/landing/sass').landing);

// Main task
gulp.task('build:landing', gulp.series(
    'clear:landing',
    gulp.parallel(
        'copy:dep:landing',
        'copy:googleMaps:landing',
        'copy:img:landing',
        'copy:fonts:landing',
        'copy:tpl:landing',
        'js:landing',
        'sass:landing'),
    function updateSrcLinks(cb) {
        return require('./gulp.tasks/landing/update.src.links').landing(cb)
    }
));

// Additional tasks
gulp.task('clear:js:landing', require('./gulp.tasks/landing/clean').js);
gulp.task('clear:css:landing', require('./gulp.tasks/landing/clean').styles);

// Watch tasks
gulp.task('sass:watch:landing', function () {
    const src = ['landing/static/sass/**/*.scss'];
    gulp.watch(src, gulp.series('clear:css:landing', 'sass:landing'));
});
gulp.task('js:watch:landing', function () {
    const src = ['landing/**/*.js', '!landing/static/**/*.*'];
    gulp.watch(src, gulp.series('clear:js:landing', 'js:landing'));
});

/* ------------------------------------------ */
/*                 Application                */
/* -------------------------------------------*/

// Main stream
gulp.task('clear:app', require('./gulp.tasks/application/clean').all);
gulp.task('copy:dep:app', require('./gulp.tasks/application/copy/dependencies').application);
gulp.task('copy:img:app', require('./gulp.tasks/application/copy/images').application);
gulp.task('copy:fonts:app', require('./gulp.tasks/application/copy/fonts').application);
gulp.task('copy:tpl:app', require('./gulp.tasks/application/copy/templates').application);
gulp.task('js:app', require('./gulp.tasks/application/scripts.js').application);
gulp.task('sass:app', require('./gulp.tasks/application/sass').application);

// Main task
gulp.task('build:app', gulp.series(
    'clear:app',
    gulp.parallel(
        'copy:dep:app',
        'copy:img:app',
        'copy:fonts:app',
        'copy:tpl:app',
        'js:app',
        'sass:app'),
    function updateSrcLinks(cb) {
        return require('./gulp.tasks/application/update.src.links').application(cb)
    }
));

// Additional tasks
gulp.task('clear:js:app', require('./gulp.tasks/application/clean').js);
gulp.task('clear:css:app', require('./gulp.tasks/application/clean').styles);

// Watch tasks
gulp.task('js:watch:app', function () {
    const src = ['app/**/*.js', '!app/static/**/*.*'];
    gulp.watch(src, gulp.series('clear:js:app', 'js:app'));
});
gulp.task('sass:watch:app', function () {
    const src = ['app/static/sass/**/*.scss'];
    gulp.watch(src, gulp.series('clear:css:app', 'sass:app'));
});

/* ------------------------------------------ */
/*                 Admin                      */
/* ------------------------------------------ */

// Main stream
gulp.task('clear:admin', require('./gulp.tasks/admin/clean').all);
gulp.task('copy:dep:admin', require('./gulp.tasks/admin/copy/dependencies').admin);
gulp.task('copy:img:admin', require('./gulp.tasks/admin/copy/images').admin);
gulp.task('copy:fonts:admin', require('./gulp.tasks/admin/copy/fonts').admin);
gulp.task('copy:tpl:admin', require('./gulp.tasks/admin/copy/templates').admin);
gulp.task('js:admin', require('./gulp.tasks/admin/scripts.js').admin);
gulp.task('sass:admin', require('./gulp.tasks/admin/sass').admin);

// Main task
gulp.task('build:admin', gulp.series(
    'clear:admin',
    gulp.parallel(
        'copy:dep:admin',
        'copy:img:admin',
        'copy:fonts:admin',
        'copy:tpl:admin',
        'js:admin',
        'sass:admin'),
    function updateSrcLinks(cb) {
        return require('./gulp.tasks/admin/update.src.links').admin(cb)
    }
));

// Additional tasks
gulp.task('clear:js:admin', require('./gulp.tasks/admin/clean').js);
gulp.task('clear:css:admin', require('./gulp.tasks/admin/clean').styles);

// Watch tasks
gulp.task('js:watch:admin', function () {
    const src = ['admin/**/*.js', '!admin/static/**/*.*'];
    gulp.watch(src, gulp.series('clear:js:admin', 'js:admin'));
});
gulp.task('sass:watch:admin', function () {
    const src = ['admin/static/sass/**/*.scss'];
    gulp.watch(src, gulp.series('clear:css:admin', 'sass:admin'));
});

/* ------------------------------------------ */
/*                 General                    */
/* ------------------------------------------ */

gulp.task('default', gulp.parallel(
    'build:landing',
    'build:app',
    'build:admin'
));
<commit_msg>Bug fix: gulp tasks<commit_after>"use strict";

const gulp = require('gulp');

/* ------------------------------------------ */
/*                 Landing                    */
/* ------------------------------------------ */

// Main stream
gulp.task('clear:landing', require('./gulp.tasks/landing/clean').all);
gulp.task('copy:dep:landing', require('./gulp.tasks/landing/copy/dependencies').landing);
gulp.task('copy:googleMaps:landing', require('./gulp.tasks/landing/copy/dependencies').googleMaps);
gulp.task('copy:img:landing', require('./gulp.tasks/landing/copy/images').landing);
gulp.task('copy:fonts:landing', require('./gulp.tasks/landing/copy/fonts').landing);
gulp.task('copy:tpl:landing', require('./gulp.tasks/landing/copy/templates').landing);
gulp.task('js:landing', require('./gulp.tasks/landing/scripts.js').landing);
gulp.task('sass:landing', require('./gulp.tasks/landing/sass').landing);

// Main task
gulp.task('build:landing', gulp.series(
    'clear:landing',
    gulp.parallel(
        'copy:dep:landing',
        'copy:googleMaps:landing',
        'copy:img:landing',
        'copy:fonts:landing',
        'copy:tpl:landing',
        'js:landing',
        'sass:landing'),
    function updateSrcLinks(cb) {
        return require('./gulp.tasks/landing/update.src.links').landing(cb)
    }
));

// Additional tasks
gulp.task('clear:js:landing', require('./gulp.tasks/landing/clean').js);
gulp.task('clear:css:landing', require('./gulp.tasks/landing/clean').styles);

// Watch tasks
gulp.task('sass:watch:landing', function () {
    const src = ['landing/static/sass/**/*.scss'];
    gulp.watch(src, gulp.series('clear:css:landing', 'sass:landing'));
});
gulp.task('js:watch:landing', function () {
    const src = ['landing/**/*.js', '!landing/static/**/*.*'];
    gulp.watch(src, gulp.series(
        'clear:js:landing',
        gulp.parallel('copy:dep:landing', 'js:landing')
    ));
});

/* ------------------------------------------ */
/*                 Application                */
/* -------------------------------------------*/

// Main stream
gulp.task('clear:app', require('./gulp.tasks/application/clean').all);
gulp.task('copy:dep:app', require('./gulp.tasks/application/copy/dependencies').application);
gulp.task('copy:img:app', require('./gulp.tasks/application/copy/images').application);
gulp.task('copy:fonts:app', require('./gulp.tasks/application/copy/fonts').application);
gulp.task('copy:tpl:app', require('./gulp.tasks/application/copy/templates').application);
gulp.task('js:app', require('./gulp.tasks/application/scripts.js').application);
gulp.task('sass:app', require('./gulp.tasks/application/sass').application);

// Main task
gulp.task('build:app', gulp.series(
    'clear:app',
    gulp.parallel(
        'copy:dep:app',
        'copy:img:app',
        'copy:fonts:app',
        'copy:tpl:app',
        'js:app',
        'sass:app'),
    function updateSrcLinks(cb) {
        return require('./gulp.tasks/application/update.src.links').application(cb)
    }
));

// Additional tasks
gulp.task('clear:js:app', require('./gulp.tasks/application/clean').js);
gulp.task('clear:css:app', require('./gulp.tasks/application/clean').styles);

// Watch tasks
gulp.task('js:watch:app', function () {
    const src = ['app/**/*.js', '!app/static/**/*.*'];
    gulp.watch(src, gulp.series(
        'clear:js:app',
        gulp.parallel('copy:dep:app', 'js:app')
    ));
});
gulp.task('sass:watch:app', function () {
    const src = ['app/static/sass/**/*.scss'];
    gulp.watch(src, gulp.series('clear:css:app', 'sass:app'));
});

/* ------------------------------------------ */
/*                 Admin                      */
/* ------------------------------------------ */

// Main stream
gulp.task('clear:admin', require('./gulp.tasks/admin/clean').all);
gulp.task('copy:dep:admin', require('./gulp.tasks/admin/copy/dependencies').admin);
gulp.task('copy:img:admin', require('./gulp.tasks/admin/copy/images').admin);
gulp.task('copy:fonts:admin', require('./gulp.tasks/admin/copy/fonts').admin);
gulp.task('copy:tpl:admin', require('./gulp.tasks/admin/copy/templates').admin);
gulp.task('js:admin', require('./gulp.tasks/admin/scripts.js').admin);
gulp.task('sass:admin', require('./gulp.tasks/admin/sass').admin);

// Main task
gulp.task('build:admin', gulp.series(
    'clear:admin',
    gulp.parallel(
        'copy:dep:admin',
        'copy:img:admin',
        'copy:fonts:admin',
        'copy:tpl:admin',
        'js:admin',
        'sass:admin'),
    function updateSrcLinks(cb) {
        return require('./gulp.tasks/admin/update.src.links').admin(cb)
    }
));

// Additional tasks
gulp.task('clear:js:admin', require('./gulp.tasks/admin/clean').js);
gulp.task('clear:css:admin', require('./gulp.tasks/admin/clean').styles);

// Watch tasks
gulp.task('js:watch:admin', function () {
    const src = ['admin/**/*.js', '!admin/static/**/*.*'];
    gulp.watch(src, gulp.series(
        'clear:js:admin',
        gulp.parallel('copy:dep:admin', 'js:admin')
    ));
});
gulp.task('sass:watch:admin', function () {
    const src = ['admin/static/sass/**/*.scss'];
    gulp.watch(src, gulp.series('clear:css:admin', 'sass:admin'));
});

/* ------------------------------------------ */
/*                 General                    */
/* ------------------------------------------ */

gulp.task('default', gulp.parallel(
    'build:landing',
    'build:app',
    'build:admin'
));
<|endoftext|>


<commit_before>window.extractToken = (hash) => {
  const match = hash.match(/access_token=(\w+)/);
  let token = !!match && match[1];
  if (!token) {
    token = localStorage.getItem('ello_access_token');
  }
  return token;
}

window.checkAuth = () => {
  const token = extractToken(document.location.hash);
  if (window.history && window.history.replaceState) {
    window.history.replaceState(window.history.state, document.title, window.location.pathname)
  } else {
    document.location.hash = '' // this is a fallback for IE < 10
  }
  if (token) {
    localStorage.setItem('ello_access_token', token)
  } else {
    // TODO: protocol, hostname, <port>, scope, client_id are all ENVs?
    const url = 'https://' + ENV.AUTH_DOMAIN + '/api/oauth/authorize.html' +
      '?response_type=token' +
      '&scope=web_app' +
      '&client_id='    + ENV.AUTH_CLIENT_ID +
      '&redirect_uri=' + ENV.AUTH_REDIRECT_URI;

    console.log(ENV.AUTH_REDIRECT_URI);

    window.location.href = url;
  }
}

window.resetAuth = () => {
  const token = localStorage.getItem('ello_access_token');
  if (token) {
    localStorage.removeItem('ello_access_token');
    window.checkAuth()
  }
}

window.checkAuth()
<commit_msg>Fixing the build<commit_after>window.extractToken = (hash) => {
  const match = hash.match(/access_token=(\w+)/);
  let token = !!match && match[1];
  if (!token) {
    token = localStorage.getItem('ello_access_token');
  }
  return token;
}

window.checkAuth = () => {
  const token = extractToken(document.location.hash);
  if (window.history && window.history.replaceState) {
    window.history.replaceState(window.history.state, document.title, window.location.pathname)
  } else {
    document.location.hash = '' // this is a fallback for IE < 10
  }
  if (token) {
    localStorage.setItem('ello_access_token', token)
  } else {
    // TODO: protocol, hostname, <port>, scope, client_id are all ENVs?
    const url = 'https://' + ENV.AUTH_DOMAIN + '/api/oauth/authorize.html' +
      '?response_type=token' +
      '&scope=web_app' +
      '&client_id='    + ENV.AUTH_CLIENT_ID +
      '&redirect_uri=' + ENV.AUTH_REDIRECT_URI;

    window.location.href = url;
  }
}

window.resetAuth = () => {
  const token = localStorage.getItem('ello_access_token');
  if (token) {
    localStorage.removeItem('ello_access_token');
    window.checkAuth()
  }
}

window.checkAuth()
<|endoftext|>


<commit_before>'use strict';

define(['app'], function (app) {
    var injectParams = ['$scope', '$injector','$location','$routeParams','dataService','upload'];

    // This is controller for this view
	var templatesController = function ($scope,$injector,$location,$routeParams,dataService,upload) {
		//for display form parts
		$scope.tempPart = $routeParams.tempPart;
		// all $scope object goes here
		$scope.alerts = [];
		$scope.maxSize = 5;
		$scope.totalRecords = "";
		$scope.tempListCurrentPage = 1;
		$scope.myTempCurrentPage = 1;
		$scope.customTempCurrentPage = 1;
		$scope.pageItems = 5;
		$scope.numPages = "";
		$scope.user_id = {user_id : 2}; // these are URL parameters
		// All $scope methods
		$scope.pageChanged = function(page,where) { // Pagination page changed
		angular.extend(where, $scope.user_id);
			dataService.get("/getmultiple/template/"+page+"/"+$scope.pageItems, where)
			.then(function(response) {  //function for templatelist response
				$scope.templates = response.data;
				//console.log($scope.properties);
			});
		};

		//function for close alert
			$scope.closeAlert = function(index) {
			$scope.alerts.splice(index, 1);
			};

		/*For display by default templatelist page {trupti}*/
		if(!$routeParams.tempPart) {
			$location.path('/dashboard/templates/listoftemplates');
		}

		//Upload Function for uploading files {Vilas}
		$scope.reqtemp={}; // this is form object
		$scope.userinfo = {userId:1, name:"vilas"}; // this is for uploading credentials
		$scope.path = "template/"; // path to store images on server
		$scope.reqtemp.scrible  = []; // uploaded images will store in this array
		$scope.upload = function(files,path,userinfo){ // this function for uploading files
			upload.upload(files,path,userinfo,function(data){
				if(data.status === 'success'){
					$scope.reqtemp.scrible.push(JSON.stringify(data.details));
					console.log(data.message);
				}else{
					alert(data.message);
				}

			});
		};
		$scope.generateThumb = function(files){  // this function will generate thumbnails of images
			upload.generateThumbs(files);
		};// End upload function

		// switch functions
		var mytemplates = function(){
			//function for mytemplate{trupti}
			dataService.get("/getmultiple/template/"+$scope.myTempCurrentPage+"/"+$scope.pageItems, $scope.user_id)
			.then(function(response) {  //function for my templates response
			if(response.status == 'success'){
					$scope.templates=response.data;
					$scope.alerts.push({type: response.status, msg:'data access successfully..'});
					$scope.totalRecords = response.totalRecords;
				}
				else
				{
					$scope.alerts.push({type: response.status, msg: response.message});
				};
				$scope.templates = response.data;
			});
		};

		var listoftemplates = function(){
			$scope.template_type = {template_type : 'public'};
			dataService.get("/getmultiple/template/"+$scope.tempListCurrentPage+"/"+$scope.pageItems, $scope.template_type)
				.then(function(response) {  //function for templatelist response
					if(response.status == 'success'){
					$scope.templates=response.data;
					$scope.alerts.push({type: response.status, msg:'data access successfully..'});
					$scope.totalRecords = response.totalRecords;

				}
				else
				{
					$scope.alerts.push({type: response.status, msg: response.message});
				};
			});//end of by default templist
		};

		var custometemplates = function(){
			$scope.template_type = {template_type : 'private',status:0 };
			//$scope.status = {status : 1};
			angular.extend($scope.template_type, $scope.user_id);
			dataService.get("/getmultiple/template/"+$scope.customTempCurrentPage+"/"+$scope.pageItems, $scope.template_type)
			.then(function(response) {  //function for template list response
				if(response.status == 'success'){
					$scope.templates=response.data;
					$scope.alerts.push({type: response.status, msg:'data access successfully..'});
					$scope.totalRecords = response.totalRecords;
				}
				else
				{
					$scope.alerts.push({type: response.status, msg: response.message});
				};

			});
		}
		var requestcustomtemplates = function(){
			//reset function{trupti}
			$scope.reset = function() {
				$scope.reqtemp = {};
			};
			//post method for insert data in request template form{trupti}
			$scope.postData = function(reqtemp) {
				dataService.post("/post/template",reqtemp)
				.then(function(response) {  //function for response of request temp
					$scope.reqtemp = response.data;
					console.log(response);
					$scope.reset();
				});
			}//end of post method{trupti}
		}

		switch($scope.tempPart) {
			case 'listoftemplates':
				listoftemplates();
				break;
			case 'mytemplates':
				mytemplates();
				break;
			case 'custometemplates':
				custometemplates();
				break;
			case 'requestcustomtemplates':
				requestcustomtemplates();
				break;
			default:
				listoftemplates();
		};

    };

	// Inject controller's dependencies
	templatesController.$inject = injectParams;
	// Register/apply controller dynamically
    app.register.controller('templatesController', templatesController);
});
<commit_msg>templatesController.js edited<commit_after>'use strict';

define(['app'], function (app) {
    var injectParams = ['$scope', '$injector','$location','$routeParams','dataService','upload'];

    // This is controller for this view
	var templatesController = function ($scope,$injector,$location,$routeParams,dataService,upload) {
		//for display form parts
		$scope.tempPart = $routeParams.tempPart;
		// all $scope object goes here
		$scope.alerts = [];
		$scope.maxSize = 5;
		$scope.totalRecords = "";
		$scope.tempListCurrentPage = 1;
		$scope.myTempCurrentPage = 1;
		$scope.customTempCurrentPage = 1;
		$scope.pageItems = 5;
		$scope.numPages = "";
		$scope.user_id = {user_id : 2}; // these are URL parameters
		// All $scope methods
		$scope.pageChanged = function(page,where) { // Pagination page changed
		angular.extend(where, $scope.user_id);
			dataService.get("/getmultiple/template/"+page+"/"+$scope.pageItems, where)
			.then(function(response) {  //function for templatelist response
				$scope.templates = response.data;
				//console.log($scope.properties);
			});
		};

		//function for close alert
			$scope.closeAlert = function(index) {
			$scope.alerts.splice(index, 1);
			};

		/*For display by default templatelist page {trupti}*/
		if(!$routeParams.tempPart) {
			$location.path('/dashboard/templates/listoftemplates');
		}

		//Upload Function for uploading files {Vilas}
		$scope.reqtemp={}; // this is form object
		$scope.userinfo = {userId:1, name:"vilas"}; // this is for uploading credentials
		$scope.path = "template/"; // path to store images on server
		$scope.reqtemp.scrible  = []; // uploaded images will store in this array
		$scope.upload = function(files,path,userinfo){ // this function for uploading files
			upload.upload(files,path,userinfo,function(data){
				if(data.status === 'success'){
					$scope.reqtemp.scrible.push(JSON.stringify(data.details));
					console.log(data.message);
				}else{
					alert(data.message);
				}

			});
		};
		$scope.generateThumb = function(files){  // this function will generate thumbnails of images
			upload.generateThumbs(files);
		};// End upload function

		// switch functions
		var mytemplates = function(){
			//function for mytemplate{trupti}
			dataService.get("/getmultiple/template/"+$scope.myTempCurrentPage+"/"+$scope.pageItems, $scope.user_id)
			.then(function(response) {  //function for my templates response
			if(response.status == 'success'){
					$scope.templates=response.data;
					//$scope.alerts.push({type: response.status, msg:'data access successfully..'});
					$scope.totalRecords = response.totalRecords;
				}
				else
				{
					$scope.alerts.push({type: response.status, msg: response.message});
				};
				$scope.templates = response.data;
			});
		};

		var listoftemplates = function(){
			$scope.template_type = {template_type : 'public'};
			dataService.get("/getmultiple/template/"+$scope.tempListCurrentPage+"/"+$scope.pageItems, $scope.template_type)
				.then(function(response) {  //function for templatelist response
					if(response.status == 'success'){
					$scope.templates=response.data;
					$scope.alerts.push({type: response.status, msg:'data access successfully..'});
					$scope.totalRecords = response.totalRecords;

				}
				else
				{
					$scope.alerts.push({type: response.status, msg: response.message});
				};
			});//end of by default templist
		};

		var custometemplates = function(){
			$scope.template_type = {template_type : 'private',status:0 };
			//$scope.status = {status : 1};
			angular.extend($scope.template_type, $scope.user_id);
			dataService.get("/getmultiple/template/"+$scope.customTempCurrentPage+"/"+$scope.pageItems, $scope.template_type)
			.then(function(response) {  //function for template list response
				if(response.status == 'success'){
					$scope.templates=response.data;
					$scope.alerts.push({type: response.status, msg:'data access successfully..'});
					$scope.totalRecords = response.totalRecords;
				}
				else
				{
					$scope.alerts.push({type: response.status, msg: response.message});
				};

			});
		}
		var requestcustomtemplates = function(){
			//reset function{trupti}
			$scope.reset = function() {
				$scope.reqtemp = {};
			};
			//post method for insert data in request template form{trupti}
			$scope.postData = function(reqtemp) {
				dataService.post("/post/template",reqtemp)
				.then(function(response) {  //function for response of request temp
					$scope.reqtemp = response.data;
					console.log(response);
					$scope.reset();
				});
			}//end of post method{trupti}
		}

		switch($scope.tempPart) {
			case 'listoftemplates':
				listoftemplates();
				break;
			case 'mytemplates':
				mytemplates();
				break;
			case 'custometemplates':
				custometemplates();
				break;
			case 'requestcustomtemplates':
				requestcustomtemplates();
				break;
			default:
				listoftemplates();
		};

    };

	// Inject controller's dependencies
	templatesController.$inject = injectParams;
	// Register/apply controller dynamically
    app.register.controller('templatesController', templatesController);
});
<|endoftext|>


<commit_before>
module.exports = {

    VERSION: "Jofogas's Zsozsobot v2",

    bet_request: function(g) {
        bet = g.current_buy_in - g.players[g.in_action]["bet"] + g.minimum_raise;
        return bet;
    },

    showdown: function(g) {

    }
};
<commit_msg>Try logging stuff...<commit_after>l = console.log();

module.exports = {

    VERSION: "Jofogas's Zsozsobot v2",

    bet_request: function(g) {
        bet = g.current_buy_in - g.players[g.in_action]["bet"] + g.minimum_raise;
        l("fearlessly raising: ", bet);
        return bet;
    },

    showdown: function(g) {

    }
};
<|endoftext|>