<commit_before>(function(){
	'use strict';

	angular.module('app')
        .config( function initRoutes( $stateProvider ) {
            $stateProvider
            .state( 'details.summary', {
                url: '',
                views: {
                    "" : {
                        controller: 'DetailsSummaryController',
                        templateUrl: 'views/details/tabs/summary/summary.tpl.html'
                    }
                },
                data:{ pageTitle: 'Octo | 18F' },
                resolve: {
                    eventReactionChartData: function(Restangular, $stateParams) {
                        return Restangular.one('events').customGET('reactions',{'q':$stateParams.name,'typ':$stateParams.typ});
                    },
                    eventOutcomesChartData: function(Restangular, $stateParams) {
                        return Restangular.one('events').customGET('reactionOutComes',{'q':$stateParams.name,'typ':$stateParams.typ});
                    },
                    recallCountData: function(Restangular, $stateParams) {
                        return Restangular.one('recalls').customGET('countByDate',{'q':$stateParams.name,'typ':$stateParams.typ});
                    },
                    eventCountData: function(Restangular, $stateParams) {
                        return Restangular.one('events').customGET('countByDate',{'q':$stateParams.name,'typ':$stateParams.typ});
                    },
                    ageCountData: function(Restangular, $stateParams) {
                        return Restangular.one('events').customGET('countByAge',{'q':$stateParams.name,'typ':$stateParams.typ});
                    },
                    genderCountData: function(Restangular, $stateParams) {
                        return Restangular.one('events').customGET('countByGender',{'q':$stateParams.name,'typ':$stateParams.typ});
                    }
                }
            })
            ;
        })
        .controller( 'DetailsSummaryController', DetailsSummaryController);

        function DetailsSummaryController($log, $scope, Restangular, $state, detailsData, $stateParams, eventsData, recallsData, referenceData, eventReactionChartData, eventOutcomesChartData, recallCountData, eventCountData, ageCountData, genderCountData) {
            $scope.references = referenceData.response;
            $scope.details = detailsData;
            $scope.indicator = $stateParams.typ;
            $scope.name = $stateParams.name;
            $scope.events = eventsData;
            $scope.events.filters = {};
            $scope.charts = {};
            $scope.charts.events = {};
            $scope.charts.events.colors1 = ['#1E6982','#4D7E96','#5397AD','#89C6D4','#B2C6D4','#214a58'];
            $scope.charts.events.colors2 = ['#4c6f28','#5c872f','#6ca037','#7cb83e','#8cc551','#9cce69'];
            $scope.maxPerPage = 5;

            $scope.charts.events.reactions = eventReactionChartData.result;
            $scope.charts.events.reactions.totalCount = eventReactionChartData.meta.totalCount;
            $scope.charts.events.outcomes = eventOutcomesChartData.results;
            $scope.charts.events.eventCount = eventCountData.results;
            $scope.charts.events.recallCount = recallCountData.results;
            $scope.charts.events.ageCount = ageCountData.results;
            $scope.charts.events.genderCount = genderCountData.results;

            $scope.events.currentPage = 1;
            $scope.events.maxPages = 5;
            $scope.events.totalPages = Math.ceil($scope.events.response.count / $scope.maxPerPage);

            if($scope.events.totalPages > 1000) {
                $scope.events.totalPages = 1000;
            }

            /* Settings for highcharts */

            Highcharts.setOptions({
                lang: {
                    thousandsSep: ','
                }
            });

            $scope.updateEvents = function () {

                var query = {'q':$stateParams.name.toUpperCase(),'typ':$stateParams.typ,'limit':$scope.maxPerPage,'skip':($scope.events.currentPage-1)*$scope.maxPerPage};

                if($scope.events.filters.gender) {
                    query.gender = $scope.events.filters.gender.code;
                }

                if($scope.events.filters.age) {
                    if($scope.events.filters.age.minAge) {
                        query.minAge = $scope.events.filters.age.minAge;
                    }

                    if($scope.events.filters.age.maxAge) {
                        query.maxAge = $scope.events.filters.age.maxAge;
                    }
                }

                if($scope.events.filters.time) {
                    if($scope.events.filters.time.minDt) {
                        query.toDate = moment().subtract($scope.events.filters.time.minDt, 'years').format("YYYY-MM-DD");
                    }

                    if($scope.events.filters.time.maxDt) {
                        query.fromDate = moment().subtract($scope.events.filters.time.maxDt, 'years').format("YYYY-MM-DD");
                    }
                }

                if($scope.events.filters.severity) {
                    query.seriousness = $scope.events.filters.severity.code;
                }

                Restangular.one('events').customGET('reactions',query)
                .then(function(data) {
                    $scope.charts.events.reactions = data.result;
                    $scope.charts.events.reactions.totalCount = data.meta.totalCount;
                }, function() {
                });

                Restangular.one('events').customGET('reactionOutComes',query)
                .then(function(data) {
                    $scope.charts.events.outcomes = data.results;
                }, function() {
                });

                Restangular.one('recalls').customGET('countByDate',query)
                .then(function(data) {
                    $scope.charts.events.recallCount = data.results;
                }, function() {
                });

                Restangular.one('events').customGET('countByDate',query)
                .then(function(data) {
                    $scope.charts.events.eventCount = data.results;
                }, function() {
                });

                Restangular.one('events').customGET('countByAge',query)
                .then(function(data) {
                    $scope.charts.events.ageCount = data.results;
                }, function() {
                });

                Restangular.one('events').customGET('countByGender',query)
                .then(function(data) {
                    $scope.charts.events.genderCount = data.results;
                }, function() {
                });

                return Restangular.one('events').customGET('',query)
                .then(function(data) {
                    $scope.events.response = data.response;
                    $scope.events.pageChangeAction = 0;
                }, function() {
                    $scope.events.pageChangeAction = 0;
                });
            };

            $scope.updateGender = function (gender) {
                if(gender) {
                    $scope.events.filters.gender = gender;
                    $scope.events.currentPage = 1;
                }
                else {
                    delete($scope.events.filters.gender);
                }
                $scope.updateEvents();
            };

            $scope.updateAge = function (age) {
                if(age) {
                    $scope.events.filters.age = age;
                    $scope.events.currentPage = 1;
                }
                else {
                    delete($scope.events.filters.age);
                }
                $scope.updateEvents();
            };

            $scope.updateTimeframe = function (time) {
                if(time) {
                    $scope.events.filters.time = time;
                    $scope.events.currentPage = 1;
                }
                else {
                    delete($scope.events.filters.time);
                }
                $scope.updateEvents();
            };

            $scope.updateSeverity = function (severity) {
                if(severity) {
                    $scope.events.filters.severity = severity;
                    $scope.events.currentPage = 1;
                }
                else {
                    delete($scope.events.filters.severity);
                }
                $scope.updateEvents();
            };

            if($scope.charts.events.reactions) {
                $scope.reactionsChart = {
                    options: {
                        chart: {
                            type: 'pie'
                        },
                        plotOptions: {
                            pie: {
                                allowPointSelect: true,
                                cursor: 'pointer',
                                showInLegend: true,
                                colors: $scope.charts.events.colors1,
                                dataLabels: {
                                    enabled: false,
                                    format: '{point.name}: {point.percentage:.1f} %',
                                    style: {
                                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                                    }
                                }
                            }
                        },
                        tooltip: {
                            pointFormatter: function () {
                                return '\u25CF '+this.series.name+': '+Highcharts.numberFormat(this.y)+'<)/b> ('+Math.round(this.y/$scope.charts.events.reactions.totalCount*100,2) + '%'+')
.';
                            }
                        }
                    },
                    series: [{
                        name: 'Reactions',
                        data: $scope.charts.events.reactions.map(function(item){
                            return {'name':item.label, 'y':item.value};
                        })
                    }],
                    title: {
                        text: 'Top 5 Adverse Reactions'
                    },
                    loading: false
                };
            }

            if($scope.charts.events.outcomes) {
                $scope.outcomesChart = {
                    options: {
                        chart: {
                            type: 'pie'
                        },
                        plotOptions: {
                            pie: {
                                allowPointSelect: true,
                                cursor: 'pointer',
                                showInLegend: true,
                                colors: $scope.charts.events.colors2,
                                dataLabels: {
                                    enabled: false,
                                    format: '{point.name}: {point.percentage:.1f} %',
                                    style: {
                                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                                    }
                                }
                            }
                        },
                        tooltip: {
                            pointFormatter: function () {
                                return '\u25CF '+this.series.name+': '+Highcharts.numberFormat(this.y)+' ('+Math.round(this.y/$scope.events.response.count*100,2) + '%'+')
.';
                            }
                        }
                    },
                    series: [{
                        name: 'Outcomes',
                        data: $scope.charts.events.outcomes.map(function(item){
                            return {'name':item.label, 'y':item.value};
                        })
                    }],
                    title: {
                        text: 'Event Outcomes'
                    },
                    loading: false
                };
            }

            if($scope.charts.events.genderCount) {
                $scope.genderChart = {
                    options: {
                        chart: {
                            type: 'column'
                        },
                        plotOptions: {
                            column: {
                                showInLegend: false,
                                colorByPoint:true
                            }
                        },
                        colors: ['#293655','#89C5D3','#B1C5D3']
                    },
                    yAxis: {
                        title: {
                            text: "Events"
                        }
                    },
                    xAxis: {
                        categories: $scope.charts.events.genderCount.map(function(item){
                            return item.label;
                        }),
                        title: {
                            text: "Patient Gender"
                        }
                    },
                    series: [{
                        name: 'Adverse Events',
                        data: $scope.charts.events.genderCount.map(function(item){
                            return item.value;
                        })
                    }],
                    title: {
                        text: 'Adverse Events By Gender'
                    },

                    loading: false
                };
            }

            if($scope.charts.events.ageCount) {
                $scope.ageChart = {
                    options: {
                        chart: {
                            type: 'bar'
                        },
                        plotOptions: {
                            bar: {
                                showInLegend: false,
                                colorByPoint:true
                            }
                        },
                        colors: ['#5397AC']
                    },
                    yAxis: {
                        title: {
                            text: "Events"
                        }
                    },
                    xAxis: {
                        categories: $scope.charts.events.ageCount.map(function(item){
                            return item.label;
                        }),
                        title: {
                            text: "Patient Age"
                        }
                    },
                    series: [{
                        name: 'Adverse Events',
                        data: $scope.charts.events.ageCount.map(function(item){
                            return item.value;
                        })
                    }],
                    title: {
                        text: 'Adverse Events By Age'
                    },

                    loading: false
                };
            }
            if($scope.charts.events.eventCount || $scope.charts.events.recallCount) {
                $scope.timeChart = {
                    options: {
                        chart: {
                            zoomType: 'x'
                        },
                        rangeSelector: {
                            enabled: true
                        },
                        navigator: {
                            enabled: true
                        }
                    },
                    xAxis: {
                        type: 'datetime'
                    },
                    yAxis: [{ // Primary yAxis
                        labels: {
                            format: '{value}',
                            style: {
                                color: '#293655'
                            }
                        },
                        title: {
                            text: 'Recalls',
                            style: {
                                color: '#293655'
                            }
                        },
                        min:0
                    }, { // Secondary yAxis
                        title: {
                            text: 'Adverse Events',
                            style: {
                                color: '#5397AC'
                            }
                        },
                        labels: {
                            format: '{value}',
                            style: {
                                color: '#5397AC'
                            }
                        },
                        opposite: true,
                        min: 0
                    }],
                    series: [{
                        name: 'Adverse Events',
                        type: 'line',
                        color: '#5397AC',
                        data: $scope.charts.events.eventCount,
                        tooltip: {
                            valueSuffix: ''
                        },
                        dataGrouping: {
                            approximation: "sum",
                            enabled: true,
                            forced: true,
                            units: [['month',[3]]]
                        }
                    }, {
                        name: 'Recalls',
                        type: 'column',
                        color: '#293655',
                        yAxis: 1,
                        data: $scope.charts.events.recallCount
                    }],
                    title: {
                        text: 'Adverse Events vs Recalls'
                    },
                    loading: false,
                    useHighStocks: true
                };
            }
        }
})();

<commit_msg>Updated chart verbiage<commit_after>(function(){
	'use strict';

	angular.module('app')
        .config( function initRoutes( $stateProvider ) {
            $stateProvider
            .state( 'details.summary', {
                url: '',
                views: {
                    "" : {
                        controller: 'DetailsSummaryController',
                        templateUrl: 'views/details/tabs/summary/summary.tpl.html'
                    }
                },
                data:{ pageTitle: 'Octo | 18F' },
                resolve: {
                    eventReactionChartData: function(Restangular, $stateParams) {
                        return Restangular.one('events').customGET('reactions',{'q':$stateParams.name,'typ':$stateParams.typ});
                    },
                    eventOutcomesChartData: function(Restangular, $stateParams) {
                        return Restangular.one('events').customGET('reactionOutComes',{'q':$stateParams.name,'typ':$stateParams.typ});
                    },
                    recallCountData: function(Restangular, $stateParams) {
                        return Restangular.one('recalls').customGET('countByDate',{'q':$stateParams.name,'typ':$stateParams.typ});
                    },
                    eventCountData: function(Restangular, $stateParams) {
                        return Restangular.one('events').customGET('countByDate',{'q':$stateParams.name,'typ':$stateParams.typ});
                    },
                    ageCountData: function(Restangular, $stateParams) {
                        return Restangular.one('events').customGET('countByAge',{'q':$stateParams.name,'typ':$stateParams.typ});
                    },
                    genderCountData: function(Restangular, $stateParams) {
                        return Restangular.one('events').customGET('countByGender',{'q':$stateParams.name,'typ':$stateParams.typ});
                    }
                }
            })
            ;
        })
        .controller( 'DetailsSummaryController', DetailsSummaryController);

        function DetailsSummaryController($log, $scope, Restangular, $state, detailsData, $stateParams, eventsData, recallsData, referenceData, eventReactionChartData, eventOutcomesChartData, recallCountData, eventCountData, ageCountData, genderCountData) {
            $scope.references = referenceData.response;
            $scope.details = detailsData;
            $scope.indicator = $stateParams.typ;
            $scope.name = $stateParams.name;
            $scope.events = eventsData;
            $scope.events.filters = {};
            $scope.charts = {};
            $scope.charts.events = {};
            $scope.charts.events.colors1 = ['#1E6982','#4D7E96','#5397AD','#89C6D4','#B2C6D4','#214a58'];
            $scope.charts.events.colors2 = ['#4c6f28','#5c872f','#6ca037','#7cb83e','#8cc551','#9cce69'];
            $scope.maxPerPage = 5;

            $scope.charts.events.reactions = eventReactionChartData.result;
            $scope.charts.events.reactions.totalCount = eventReactionChartData.meta.totalCount;
            $scope.charts.events.outcomes = eventOutcomesChartData.results;
            $scope.charts.events.eventCount = eventCountData.results;
            $scope.charts.events.recallCount = recallCountData.results;
            $scope.charts.events.ageCount = ageCountData.results;
            $scope.charts.events.genderCount = genderCountData.results;

            $scope.events.currentPage = 1;
            $scope.events.maxPages = 5;
            $scope.events.totalPages = Math.ceil($scope.events.response.count / $scope.maxPerPage);

            if($scope.events.totalPages > 1000) {
                $scope.events.totalPages = 1000;
            }

            /* Settings for highcharts */

            Highcharts.setOptions({
                lang: {
                    thousandsSep: ','
                }
            });

            $scope.updateEvents = function () {

                var query = {'q':$stateParams.name.toUpperCase(),'typ':$stateParams.typ,'limit':$scope.maxPerPage,'skip':($scope.events.currentPage-1)*$scope.maxPerPage};

                if($scope.events.filters.gender) {
                    query.gender = $scope.events.filters.gender.code;
                }

                if($scope.events.filters.age) {
                    if($scope.events.filters.age.minAge) {
                        query.minAge = $scope.events.filters.age.minAge;
                    }

                    if($scope.events.filters.age.maxAge) {
                        query.maxAge = $scope.events.filters.age.maxAge;
                    }
                }

                if($scope.events.filters.time) {
                    if($scope.events.filters.time.minDt) {
                        query.toDate = moment().subtract($scope.events.filters.time.minDt, 'years').format("YYYY-MM-DD");
                    }

                    if($scope.events.filters.time.maxDt) {
                        query.fromDate = moment().subtract($scope.events.filters.time.maxDt, 'years').format("YYYY-MM-DD");
                    }
                }

                if($scope.events.filters.severity) {
                    query.seriousness = $scope.events.filters.severity.code;
                }

                Restangular.one('events').customGET('reactions',query)
                .then(function(data) {
                    $scope.charts.events.reactions = data.result;
                    $scope.charts.events.reactions.totalCount = data.meta.totalCount;
                }, function() {
                });

                Restangular.one('events').customGET('reactionOutComes',query)
                .then(function(data) {
                    $scope.charts.events.outcomes = data.results;
                }, function() {
                });

                Restangular.one('recalls').customGET('countByDate',query)
                .then(function(data) {
                    $scope.charts.events.recallCount = data.results;
                }, function() {
                });

                Restangular.one('events').customGET('countByDate',query)
                .then(function(data) {
                    $scope.charts.events.eventCount = data.results;
                }, function() {
                });

                Restangular.one('events').customGET('countByAge',query)
                .then(function(data) {
                    $scope.charts.events.ageCount = data.results;
                }, function() {
                });

                Restangular.one('events').customGET('countByGender',query)
                .then(function(data) {
                    $scope.charts.events.genderCount = data.results;
                }, function() {
                });

                return Restangular.one('events').customGET('',query)
                .then(function(data) {
                    $scope.events.response = data.response;
                    $scope.events.pageChangeAction = 0;
                }, function() {
                    $scope.events.pageChangeAction = 0;
                });
            };

            $scope.updateGender = function (gender) {
                if(gender) {
                    $scope.events.filters.gender = gender;
                    $scope.events.currentPage = 1;
                }
                else {
                    delete($scope.events.filters.gender);
                }
                $scope.updateEvents();
            };

            $scope.updateAge = function (age) {
                if(age) {
                    $scope.events.filters.age = age;
                    $scope.events.currentPage = 1;
                }
                else {
                    delete($scope.events.filters.age);
                }
                $scope.updateEvents();
            };

            $scope.updateTimeframe = function (time) {
                if(time) {
                    $scope.events.filters.time = time;
                    $scope.events.currentPage = 1;
                }
                else {
                    delete($scope.events.filters.time);
                }
                $scope.updateEvents();
            };

            $scope.updateSeverity = function (severity) {
                if(severity) {
                    $scope.events.filters.severity = severity;
                    $scope.events.currentPage = 1;
                }
                else {
                    delete($scope.events.filters.severity);
                }
                $scope.updateEvents();
            };

            if($scope.charts.events.reactions) {
                $scope.reactionsChart = {
                    options: {
                        chart: {
                            type: 'pie'
                        },
                        plotOptions: {
                            pie: {
                                allowPointSelect: true,
                                cursor: 'pointer',
                                showInLegend: true,
                                colors: $scope.charts.events.colors1,
                                dataLabels: {
                                    enabled: false,
                                    format: '{point.name}: {point.percentage:.1f} %',
                                    style: {
                                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                                    }
                                }
                            }
                        },
                        tooltip: {
                            pointFormatter: function () {
                                return '\u25CF '+this.series.name+': '+Highcharts.numberFormat(this.y)+'<)/b> ('+Math.round(this.y/$scope.charts.events.reactions.totalCount*100,2) + '%'+')
.';
                            }
                        }
                    },
                    series: [{
                        name: 'Reactions',
                        data: $scope.charts.events.reactions.map(function(item){
                            return {'name':item.label, 'y':item.value};
                        })
                    }],
                    title: {
                        text: 'Top 5 Reactions'
                    },
                    loading: false
                };
            }

            if($scope.charts.events.outcomes) {
                $scope.outcomesChart = {
                    options: {
                        chart: {
                            type: 'pie'
                        },
                        plotOptions: {
                            pie: {
                                allowPointSelect: true,
                                cursor: 'pointer',
                                showInLegend: true,
                                colors: $scope.charts.events.colors2,
                                dataLabels: {
                                    enabled: false,
                                    format: '{point.name}: {point.percentage:.1f} %',
                                    style: {
                                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                                    }
                                }
                            }
                        },
                        tooltip: {
                            pointFormatter: function () {
                                return '\u25CF '+this.series.name+': '+Highcharts.numberFormat(this.y)+' ('+Math.round(this.y/$scope.events.response.count*100,2) + '%'+')
.';
                            }
                        }
                    },
                    series: [{
                        name: 'Outcomes',
                        data: $scope.charts.events.outcomes.map(function(item){
                            return {'name':item.label, 'y':item.value};
                        })
                    }],
                    title: {
                        text: 'Event Outcomes'
                    },
                    loading: false
                };
            }

            if($scope.charts.events.genderCount) {
                $scope.genderChart = {
                    options: {
                        chart: {
                            type: 'column'
                        },
                        plotOptions: {
                            column: {
                                showInLegend: false,
                                colorByPoint:true
                            }
                        },
                        colors: ['#293655','#89C5D3','#B1C5D3']
                    },
                    yAxis: {
                        title: {
                            text: "Events"
                        }
                    },
                    xAxis: {
                        categories: $scope.charts.events.genderCount.map(function(item){
                            return item.label;
                        }),
                        title: {
                            text: "Patient Gender"
                        }
                    },
                    series: [{
                        name: 'Adverse Events',
                        data: $scope.charts.events.genderCount.map(function(item){
                            return item.value;
                        })
                    }],
                    title: {
                        text: 'Adverse Events By Gender'
                    },

                    loading: false
                };
            }

            if($scope.charts.events.ageCount) {
                $scope.ageChart = {
                    options: {
                        chart: {
                            type: 'bar'
                        },
                        plotOptions: {
                            bar: {
                                showInLegend: false,
                                colorByPoint:true
                            }
                        },
                        colors: ['#5397AC']
                    },
                    yAxis: {
                        title: {
                            text: "Events"
                        }
                    },
                    xAxis: {
                        categories: $scope.charts.events.ageCount.map(function(item){
                            return item.label;
                        }),
                        title: {
                            text: "Patient Age"
                        }
                    },
                    series: [{
                        name: 'Adverse Events',
                        data: $scope.charts.events.ageCount.map(function(item){
                            return item.value;
                        })
                    }],
                    title: {
                        text: 'Adverse Events By Age'
                    },

                    loading: false
                };
            }
            if($scope.charts.events.eventCount || $scope.charts.events.recallCount) {
                $scope.timeChart = {
                    options: {
                        chart: {
                            zoomType: 'x'
                        },
                        rangeSelector: {
                            enabled: true
                        },
                        navigator: {
                            enabled: true
                        }
                    },
                    xAxis: {
                        type: 'datetime'
                    },
                    yAxis: [{ // Primary yAxis
                        labels: {
                            format: '{value}',
                            style: {
                                color: '#293655'
                            }
                        },
                        title: {
                            text: 'Recalls',
                            style: {
                                color: '#293655'
                            }
                        },
                        min:0
                    }, { // Secondary yAxis
                        title: {
                            text: 'Adverse Events',
                            style: {
                                color: '#5397AC'
                            }
                        },
                        labels: {
                            format: '{value}',
                            style: {
                                color: '#5397AC'
                            }
                        },
                        opposite: true,
                        min: 0
                    }],
                    series: [{
                        name: 'Adverse Events',
                        type: 'line',
                        color: '#5397AC',
                        data: $scope.charts.events.eventCount,
                        tooltip: {
                            valueSuffix: ''
                        },
                        dataGrouping: {
                            approximation: "sum",
                            enabled: true,
                            forced: true,
                            units: [['month',[3]]]
                        }
                    }, {
                        name: 'Recalls',
                        type: 'column',
                        color: '#293655',
                        yAxis: 1,
                        data: $scope.charts.events.recallCount
                    }],
                    title: {
                        text: 'Adverse Events vs Recalls'
                    },
                    loading: false,
                    useHighStocks: true
                };
            }
        }
})();

<|endoftext|>


<commit_before>// -------------------------------------------------------------------------- \\
// File: SwitchView.js                                                        \\
// Module: CollectionViews                                                    \\
// Requires: Core, Foundation, View                                           \\
// Author: Neil Jenkins                                                       \\
// License: © 2010–2013 FastMail Pty Ltd. All rights reserved.                \\
// -------------------------------------------------------------------------- \\

/*global document */

"use strict";

( function ( NS ) {

var View = NS.View;
var Element = NS.Element;

var forEachView = function ( views, method, args ) {
    var l = views ? views.length : 0,
        view;
    while ( l-- ) {
        view = views[l];
        if ( view instanceof View && !view.isDestroyed ) {
            if ( args ) {
                view[ method ].apply( view, args );
            } else {
                view[ method ]();
            }
        }
    }
};

var flattenAndPrune = function ( array, node ) {
    if ( node instanceof Array ) {
        node.reduce( flattenAndPrune, array );
    } else if ( node ) {
        array.push( node );
    }
    return array;
};

var SwitchView = NS.Class({

    Extends: View,

    init: function ( mixin ) {
        this.views = [];
        this.subViews = [];

        SwitchView.parent.init.call( this, mixin );

        this.isRendered = true;

        var views = this.get( 'views' ),
            l = views.length,
            view;
        while ( l-- ) {
            view = views[l];
            if ( view && !( view instanceof Array ) ) {
                views[l] = [ view ];
            }
        }
    },

    destroy: function () {
        var views = this.get( 'views' ),
            l = views.length;
        while ( l-- ) {
            forEachView( views[l], 'destroy' );
        }
        views = this.get( 'subViews' );
        l = views.length;
        while ( l-- ) {
            forEachView( views[l], 'destroy' );
        }
        SwitchView.parent.destroy.call( this );
    },

    // ---

    layer: function () {
        return document.createComment( 'SwitchView ' + this.get( 'id' ) );
    }.property(),

    willEnterDocument: function () {
        this.resumeBindings();
        this.redraw( true );
        return this;
    },

    didEnterDocument: function () {
        if ( this.get( 'index' ) !== this._index ) {
            this.switchNeedsRedraw();
        }
        return this.set( 'isInDocument', true );
    },

    willLeaveDocument: function () {
        return this.set( 'isInDocument', false );
    },

    didLeaveDocument: function () {
        return this.suspendBindings();
    },

    // ---

    // -1 => Not yet added to parent
    // Otherwise, index of view(s) currently in parent
    _index: -1,

    // Index of view that should be in parent.
    index: 0,

    redraw: function ( willEnterDocument ) {
        var oldIndex = this._index,
            newIndex = this.get( 'index' ),
            parentView, view, subViews;
        // If not yet added to parent, nothing to redraw; _add will be called
        // automatically soon.
        if ( !this.isDestroyed && oldIndex > -1 && oldIndex !== newIndex ) {
            parentView = this.get( 'parentView' );
            if ( parentView ) {
                view = this._remove( parentView );
                subViews = this.get( 'subViews' );
                if ( willEnterDocument ) {
                    forEachView( view, 'didLeaveDocument' );
                    forEachView( subViews[ oldIndex ], 'didLeaveDocument' );
                }
                view = this._add();
                if ( willEnterDocument ) {
                    forEachView( view, 'willEnterDocument' );
                    forEachView( subViews[ newIndex ], 'willEnterDocument' );
                }
            }
        }
    },

    switchNeedsRedraw: function () {
        if ( this.get( 'isInDocument' ) ) {
            NS.RunLoop.queueFn( 'render', this.redraw, this );
        }
    }.observes( 'index' ),

    parentViewDidChange: function ( _, __, oldParent, newParent ) {
        if ( oldParent ) {
            // May be a NOP, but just in case.
            oldParent.removeObserverForKey( 'childViews', this, '_add' );
            this._remove( oldParent );
        }
        if ( newParent ) {
            if ( newParent.get( 'isRendered' ) ) {
                // We need to wait until we've been inserted to know where our
                // DOM marker has been place, and so where to insert the real
                // view(s).
                newParent.addObserverForKey( 'childViews', this, '_add' );
            } else {
                // If not rendered, just add our views in the right place in the
                // parent's childView list. They'll be rendered in the right
                // spot.
                this._add();
            }
        }
    }.observes( 'parentView' ),

    _add: function ( object, key ) {
        if ( object ) {
            object.removeObserverForKey( key, this, '_add' );
        }
        var index = this.get( 'index' ),
            view = this.get( 'views' )[ index ],
            subView = this.get( 'subViews' )[ index ],
            parent = this.get( 'parentView' ),
            isInDocument = this.get( 'isInDocument' ),
            position = this.get( 'layer' ),
            layer = position.parentNode,
            l = view ? view.length : 0,
            node, before;

        if ( subView ) {
            forEachView( subView, 'set', [ 'parentView', parent ] );
            if ( isInDocument ) {
                forEachView( subView, 'willEnterDocument' );
            }
        }
        while ( l-- ) {
            node = view[l];
            if ( node instanceof View ) {
                parent.insertView( node, this, 'after' );
            } else {
                if ( typeof node !== 'object' ) {
                    node = view[l] = document.createTextNode( node );
                }
                before = position.nextSibling;
                if ( before ) {
                    layer.insertBefore( node, before );
                } else {
                    layer.appendChild( node );
                }
            }
        }
        if ( subView ) {
            if ( isInDocument ) {
                forEachView( subView, 'didEnterDocument' );
            }
            parent.set( 'childViews',
                parent.get( 'childViews' ).concat( subView ) );
        }
        this._index = index;
        return view;
    },

    _remove: function ( parent ) {
        var oldIndex = this._index,
            view = this.get( 'views' )[ oldIndex ],
            subView = this.get( 'subViews' )[ oldIndex ],
            isInDocument = this.get( 'isInDocument' ),
            l = view ? view.length : 0,
            node;

        if ( isInDocument && subView ) {
            forEachView( subView, 'willLeaveDocument' );
        }
        while ( l-- ) {
            node = view[l];
            if ( node instanceof View ) {
                parent.removeView( node );
            } else {
                node.parentNode.removeChild( node );
            }
        }
        if ( subView ) {
            if ( isInDocument ) {
                forEachView( subView, 'didLeaveDocument' );
            }
            forEachView( subView, 'set', [ 'parentView', null ] );
            parent.set( 'childViews',
                parent.get( 'childViews' ).filter( function ( view ) {
                    return subView.indexOf( view ) === -1;
                })
            );
        }
        this._index = -1;
        return view;
    },

    // ---

    /*
        If views are inside el() methods, they will call this method. Collect
        them up, then pass them as subViews when show() or otherwise() is
        called.
    */
    insertView: function ( view, parentNode ) {
        this.childViews.push( view );
        var oldParent = view.get( 'parentView' );
        if ( oldParent ) {
            oldParent.removeView( view );
        }
        parentNode.appendChild( view.render().get( 'layer' ) );
        return this;
    },

    _addCondition: function ( view, index ) {
        view = view ?
            view instanceof Array ?
                view :
                [ view ] :
            null;
        this.views[ index ] = view.reduce( flattenAndPrune, [] );
        var subView = this.childViews;
        if ( subView.length ) {
            this.subViews[ index ] = subView;
            this.childViews = [];
        }
        return this;
    },

    show: function ( view ) {
        return this._addCondition( view, 0 );
    },

    otherwise: function ( view ) {
        return this._addCondition( view, 1 );
    },

    end: function () {
        Element.forView( this._oldView );
        this._oldView = null;
        return this;
    }
});

NS.SwitchView = SwitchView;

var pickViewWhen = function ( bool ) {
    return bool ? 0 : 1;
};
var pickViewUnless = function ( bool ) {
    return bool ? 1 : 0;
};

var createView = function ( object, property, transform ) {
    var switchView = new SwitchView({
        index: NS.bind( property, object, transform )
    });
    switchView._oldView = Element.forView( switchView );
    return switchView;
};

Element.when = function ( object, property ) {
    return createView( object, property, pickViewWhen );
};
Element.unless = function ( object, property ) {
    return createView( object, property, pickViewUnless );
};

}( this.O ) );
<commit_msg>Add ability to set transform in Element.(when|unless)<commit_after>// -------------------------------------------------------------------------- \\
// File: SwitchView.js                                                        \\
// Module: CollectionViews                                                    \\
// Requires: Core, Foundation, View                                           \\
// Author: Neil Jenkins                                                       \\
// License: © 2010–2013 FastMail Pty Ltd. All rights reserved.                \\
// -------------------------------------------------------------------------- \\

/*global document */

"use strict";

( function ( NS ) {

var View = NS.View;
var Element = NS.Element;

var forEachView = function ( views, method, args ) {
    var l = views ? views.length : 0,
        view;
    while ( l-- ) {
        view = views[l];
        if ( view instanceof View && !view.isDestroyed ) {
            if ( args ) {
                view[ method ].apply( view, args );
            } else {
                view[ method ]();
            }
        }
    }
};

var flattenAndPrune = function ( array, node ) {
    if ( node instanceof Array ) {
        node.reduce( flattenAndPrune, array );
    } else if ( node ) {
        array.push( node );
    }
    return array;
};

var SwitchView = NS.Class({

    Extends: View,

    init: function ( mixin ) {
        this.views = [];
        this.subViews = [];

        SwitchView.parent.init.call( this, mixin );

        this.isRendered = true;

        var views = this.get( 'views' ),
            l = views.length,
            view;
        while ( l-- ) {
            view = views[l];
            if ( view && !( view instanceof Array ) ) {
                views[l] = [ view ];
            }
        }
    },

    destroy: function () {
        var views = this.get( 'views' ),
            l = views.length;
        while ( l-- ) {
            forEachView( views[l], 'destroy' );
        }
        views = this.get( 'subViews' );
        l = views.length;
        while ( l-- ) {
            forEachView( views[l], 'destroy' );
        }
        SwitchView.parent.destroy.call( this );
    },

    // ---

    layer: function () {
        return document.createComment( 'SwitchView ' + this.get( 'id' ) );
    }.property(),

    willEnterDocument: function () {
        this.resumeBindings();
        this.redraw( true );
        return this;
    },

    didEnterDocument: function () {
        if ( this.get( 'index' ) !== this._index ) {
            this.switchNeedsRedraw();
        }
        return this.set( 'isInDocument', true );
    },

    willLeaveDocument: function () {
        return this.set( 'isInDocument', false );
    },

    didLeaveDocument: function () {
        return this.suspendBindings();
    },

    // ---

    // -1 => Not yet added to parent
    // Otherwise, index of view(s) currently in parent
    _index: -1,

    // Index of view that should be in parent.
    index: 0,

    redraw: function ( willEnterDocument ) {
        var oldIndex = this._index,
            newIndex = this.get( 'index' ),
            parentView, view, subViews;
        // If not yet added to parent, nothing to redraw; _add will be called
        // automatically soon.
        if ( !this.isDestroyed && oldIndex > -1 && oldIndex !== newIndex ) {
            parentView = this.get( 'parentView' );
            if ( parentView ) {
                view = this._remove( parentView );
                subViews = this.get( 'subViews' );
                if ( willEnterDocument ) {
                    forEachView( view, 'didLeaveDocument' );
                    forEachView( subViews[ oldIndex ], 'didLeaveDocument' );
                }
                view = this._add();
                if ( willEnterDocument ) {
                    forEachView( view, 'willEnterDocument' );
                    forEachView( subViews[ newIndex ], 'willEnterDocument' );
                }
            }
        }
    },

    switchNeedsRedraw: function () {
        if ( this.get( 'isInDocument' ) ) {
            NS.RunLoop.queueFn( 'render', this.redraw, this );
        }
    }.observes( 'index' ),

    parentViewDidChange: function ( _, __, oldParent, newParent ) {
        if ( oldParent ) {
            // May be a NOP, but just in case.
            oldParent.removeObserverForKey( 'childViews', this, '_add' );
            this._remove( oldParent );
        }
        if ( newParent ) {
            if ( newParent.get( 'isRendered' ) ) {
                // We need to wait until we've been inserted to know where our
                // DOM marker has been place, and so where to insert the real
                // view(s).
                newParent.addObserverForKey( 'childViews', this, '_add' );
            } else {
                // If not rendered, just add our views in the right place in the
                // parent's childView list. They'll be rendered in the right
                // spot.
                this._add();
            }
        }
    }.observes( 'parentView' ),

    _add: function ( object, key ) {
        if ( object ) {
            object.removeObserverForKey( key, this, '_add' );
        }
        var index = this.get( 'index' ),
            view = this.get( 'views' )[ index ],
            subView = this.get( 'subViews' )[ index ],
            parent = this.get( 'parentView' ),
            isInDocument = this.get( 'isInDocument' ),
            position = this.get( 'layer' ),
            layer = position.parentNode,
            l = view ? view.length : 0,
            node, before;

        if ( subView ) {
            forEachView( subView, 'set', [ 'parentView', parent ] );
            if ( isInDocument ) {
                forEachView( subView, 'willEnterDocument' );
            }
        }
        while ( l-- ) {
            node = view[l];
            if ( node instanceof View ) {
                parent.insertView( node, this, 'after' );
            } else {
                if ( typeof node !== 'object' ) {
                    node = view[l] = document.createTextNode( node );
                }
                before = position.nextSibling;
                if ( before ) {
                    layer.insertBefore( node, before );
                } else {
                    layer.appendChild( node );
                }
            }
        }
        if ( subView ) {
            if ( isInDocument ) {
                forEachView( subView, 'didEnterDocument' );
            }
            parent.set( 'childViews',
                parent.get( 'childViews' ).concat( subView ) );
        }
        this._index = index;
        return view;
    },

    _remove: function ( parent ) {
        var oldIndex = this._index,
            view = this.get( 'views' )[ oldIndex ],
            subView = this.get( 'subViews' )[ oldIndex ],
            isInDocument = this.get( 'isInDocument' ),
            l = view ? view.length : 0,
            node;

        if ( isInDocument && subView ) {
            forEachView( subView, 'willLeaveDocument' );
        }
        while ( l-- ) {
            node = view[l];
            if ( node instanceof View ) {
                parent.removeView( node );
            } else {
                node.parentNode.removeChild( node );
            }
        }
        if ( subView ) {
            if ( isInDocument ) {
                forEachView( subView, 'didLeaveDocument' );
            }
            forEachView( subView, 'set', [ 'parentView', null ] );
            parent.set( 'childViews',
                parent.get( 'childViews' ).filter( function ( view ) {
                    return subView.indexOf( view ) === -1;
                })
            );
        }
        this._index = -1;
        return view;
    },

    // ---

    /*
        If views are inside el() methods, they will call this method. Collect
        them up, then pass them as subViews when show() or otherwise() is
        called.
    */
    insertView: function ( view, parentNode ) {
        this.childViews.push( view );
        var oldParent = view.get( 'parentView' );
        if ( oldParent ) {
            oldParent.removeView( view );
        }
        parentNode.appendChild( view.render().get( 'layer' ) );
        return this;
    },

    _addCondition: function ( view, index ) {
        view = view ?
            view instanceof Array ?
                view :
                [ view ] :
            null;
        this.views[ index ] = view.reduce( flattenAndPrune, [] );
        var subView = this.childViews;
        if ( subView.length ) {
            this.subViews[ index ] = subView;
            this.childViews = [];
        }
        return this;
    },

    show: function ( view ) {
        return this._addCondition( view, 0 );
    },

    otherwise: function ( view ) {
        return this._addCondition( view, 1 );
    },

    end: function () {
        Element.forView( this._oldView );
        this._oldView = null;
        return this;
    }
});

NS.SwitchView = SwitchView;

var pickViewWhen = function ( bool ) {
    return bool ? 0 : 1;
};
var pickViewUnless = function ( bool ) {
    return bool ? 1 : 0;
};

var createView = function ( object, property, transform ) {
    var switchView = new SwitchView({
        index: NS.bind( property, object, transform )
    });
    switchView._oldView = Element.forView( switchView );
    return switchView;
};

Element.when = function ( object, property, transform ) {
    var pickView = transform ? function ( value, syncForward ) {
        return pickViewWhen( transform( value, syncForward ) );
    } : pickViewWhen;
    return createView( object, property, pickView );
};
Element.unless = function ( object, property, transform ) {
    var pickView = transform ? function ( value, syncForward ) {
        return pickViewUnless( transform( value, syncForward ) );
    } : pickViewUnless;
    return createView( object, property, pickView );
};

}( this.O ) );
<|endoftext|>


<commit_before>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.2 - Developed by d4rkd0s  ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.AUTO, '', { preload: preload, create: create, update: update });
    function preload() {
        //setting up starting vars
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        horseHealth = 10;
        console.log("%c   horseHealth: 10   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        speed = 250;
        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('apple', 'assets/images/apple_red.png');
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.audio('applesound', 'assets/sounds/apple.wav');
        game.load.audio('bobsound', 'assets/sounds/bob.wav')
        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        apple = game.add.sprite(100, 200, 'apple');

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        applesound = game.add.audio('applesound');
        applesound.allowMultiple = true;

        bobsound = game.add.audio('bobsound');
        bobsound.allowMultiple = true;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        game.physics.arcade.enable(apple);
        game.physics.arcade.enableBody(apple);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        apple.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        horse.anchor.x = 0.5;
        horse.anchor.y = 0.5;
    }//create()

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);
        game.physics.arcade.collide(ocean, apple);
        game.physics.arcade.collide(horse, ocean);
        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        //bob faster as he scores
        speed = 200+(10*score);

        //move mr.horse
        horse.velocity = game.physics.arcade.accelerateToObject(horse, apple, 50+(score*5), 50+(score*5), 50+(score*5));

        if ( apple.alive == true){
            if ( game.physics.arcade.overlap(apple, player) == true ){
                score = score + 1;
                bobsound.play();
                $( "#score" ).text("Score: " + score);
                apple.kill();
                console.log("Score: " + score);
            }
            if ( game.physics.arcade.collide(apple, horse) == true ){
                horseHealth = horseHealth - 1;
                if ( horseHealth == 1 ){
                    $( "#horseHealth" ).text(horseHealth + " apple until your horse dies!");
                }
                else{
                    $( "#horseHealth" ).text(horseHealth + " apples until your horse dies!");
                }
                applesound.play();
                apple.kill();
                if ( horseHealth == 0 ){
                    $( "#score" ).text("Final Score: " + score);
                    $( "#horseHealth" ).text("Your horse has died!");
                    game.physics.destroy();
                }
                console.log("horseHealth: " + horseHealth);
            }
        }//apple alive
        else{
            randX = Math.floor(Math.random()*(800-50+1)+50);
            randY = Math.floor(Math.random()*(550-180+1)+180);
            if ( game.physics.arcade.overlap(apple, horse) == true ){
                console.log("Apple spawned on horse, regenerating randX and randY");
                randX = Math.floor(Math.random()*(800-50+1)+50);
                randY = Math.floor(Math.random()*(550-180+1)+180);
                apple.kill();
            }
            else{
                console.log("Apple is clear of horse, spawned apple.");
                apple = game.add.sprite(randX, randY, 'apple');
                game.physics.arcade.enable(apple);
                game.physics.arcade.enableBody(apple);
                apple.body.collideWorldBounds = true;
                game.physics.arcade.collide(player, apple);
                game.physics.arcade.collide(ocean, apple);
            }

        }//dead apple

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -speed;
                player.body.velocity.y = -speed;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -speed;
                player.body.velocity.y = speed;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -speed*2;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = speed;
                player.body.velocity.y = -speed;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = speed;
                player.body.velocity.y = speed;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = speed*2;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -speed;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = speed;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

};
});<commit_msg>Layer<commit_after>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.2 - Developed by d4rkd0s  ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.AUTO, '', { preload: preload, create: create, update: update });
    function preload() {
        //setting up starting vars
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        horseHealth = 10;
        console.log("%c   horseHealth: 10   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        speed = 250;
        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('apple', 'assets/images/apple_red.png');
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.audio('applesound', 'assets/sounds/apple.wav');
        game.load.audio('bobsound', 'assets/sounds/bob.wav')
        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects

        apple = game.add.sprite(100, 200, 'apple');

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        applesound = game.add.audio('applesound');
        applesound.allowMultiple = true;

        bobsound = game.add.audio('bobsound');
        bobsound.allowMultiple = true;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //add player
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        game.physics.arcade.enable(apple);
        game.physics.arcade.enableBody(apple);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        apple.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        horse.anchor.x = 0.5;
        horse.anchor.y = 0.5;
    }//create()

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);
        game.physics.arcade.collide(ocean, apple);
        game.physics.arcade.collide(horse, ocean);
        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        //bob faster as he scores
        speed = 200+(10*score);

        //move mr.horse
        horse.velocity = game.physics.arcade.accelerateToObject(horse, apple, 50+(score*5), 50+(score*5), 50+(score*5));

        if ( apple.alive == true){
            if ( game.physics.arcade.overlap(apple, player) == true ){
                score = score + 1;
                bobsound.play();
                $( "#score" ).text("Score: " + score);
                apple.kill();
                console.log("Score: " + score);
            }
            if ( game.physics.arcade.collide(apple, horse) == true ){
                horseHealth = horseHealth - 1;
                if ( horseHealth == 1 ){
                    $( "#horseHealth" ).text(horseHealth + " apple until your horse dies!");
                }
                else{
                    $( "#horseHealth" ).text(horseHealth + " apples until your horse dies!");
                }
                applesound.play();
                apple.kill();
                if ( horseHealth == 0 ){
                    $( "#score" ).text("Final Score: " + score);
                    $( "#horseHealth" ).text("Your horse has died!");
                    game.physics.destroy();
                }
                console.log("horseHealth: " + horseHealth);
            }
        }//apple alive
        else{
            randX = Math.floor(Math.random()*(800-50+1)+50);
            randY = Math.floor(Math.random()*(550-180+1)+180);
            if ( game.physics.arcade.overlap(apple, horse) == true ){
                console.log("Apple spawned on horse, regenerating randX and randY");
                randX = Math.floor(Math.random()*(800-50+1)+50);
                randY = Math.floor(Math.random()*(550-180+1)+180);
                apple.kill();
            }
            else{
                console.log("Apple is clear of horse, spawned apple.");
                apple = game.add.sprite(randX, randY, 'apple');
                game.physics.arcade.enable(apple);
                game.physics.arcade.enableBody(apple);
                apple.body.collideWorldBounds = true;
                game.physics.arcade.collide(player, apple);
                game.physics.arcade.collide(ocean, apple);
            }

        }//dead apple

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -speed;
                player.body.velocity.y = -speed;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -speed;
                player.body.velocity.y = speed;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -speed*2;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = speed;
                player.body.velocity.y = -speed;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = speed;
                player.body.velocity.y = speed;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = speed*2;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -speed;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = speed;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

};
});<|endoftext|>


<commit_before>import { Table, Modal, Header, Image } from 'semantic-ui-react';
import React from 'react';

const MessagesTable = ({ allMessages, convertTime }) => {
  return (

Subject

Sender

Notes

        {
        allMessages.map(message =>
          <Modal
            key={message.id}
            trigger={

                  {message.title}
                  {`Received about ${convertTime(message.createdAt)}`}

{`${message.sender.firstName} ${message.sender.lastName}`}

None

            }
          >
            <Modal.Header>{message.title}</Modal.Header>
            <Modal.Content image>
              <Image wrapped size="small" src="./client/src/assets/half-raptor.png" />
              <Modal.Description>
                {message.title}

{message.body}

              </Modal.Description>
            </Modal.Content>
          </Modal>,
          )
        }

  );
};

MessagesTable.propTypes = {
  allMessages: React.PropTypes.array.isRequired,
  convertTime: React.PropTypes.func.isRequired,
};

export default MessagesTable;
<commit_msg>Add the ReplyFormModal component to MessagesTable<commit_after>import { Table, Modal, Header, Image, Container, Button } from 'semantic-ui-react';
import React from 'react';
import ReplyFormModal from './ReplyFormModal';

const MessagesTable = ({ allMessages, convertTime }) => {
  return (

Subject

Sender

Notes

        {
        allMessages.map(message =>
          <Modal
            key={message.id}
            size="small"
            trigger={

                  {message.title}
                  {`Received about ${convertTime(message.createdAt)}`}

{`${message.sender.firstName} ${message.sender.lastName}`}

None

            }
          >
            <Modal.Header>{message.title}</Modal.Header>
            <Modal.Content image>
              <Image wrapped size="small" src="./client/src/assets/half-raptor.png" />
              <Modal.Description>
                {message.title}

{`From: ${message.user.firstName} ${message.user.lastName}`}

{message.body}

              </Modal.Description>
            </Modal.Content>
            <Modal.Actions>
              <Button>
                <ReplyFormModal />
              </Button>
            </Modal.Actions>
          </Modal>,
          )
        }

  );
};

MessagesTable.propTypes = {
  allMessages: React.PropTypes.array.isRequired,
  convertTime: React.PropTypes.func.isRequired,
};

export default MessagesTable;
<|endoftext|>


<commit_before>'use strict';

var joblint = require('joblint');

module.exports = defineController;

function defineController (app) {
    app.all('/ws', function (req, res, next) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Headers', 'X-Requested-With');
        next();
    });
    app.post('/ws', requireUrlEncodedPostBody, requireUnemptyJobSpec, function (req, res) {
        res.jsonp(joblint(req.body.spec));
    });
    app.all('/ws', function (req, res) {
        return res.jsonp(405, {
            error: 'Method not allowed, POST request expected'
        });
    });
}

function requireUrlEncodedPostBody (req, res, next) {
    if (req.headers['content-type'] !== 'application/x-www-form-urlencoded') {
        return res.jsonp(400, {
            error: 'Request must have a content-type of "application/x-www-form-urlencoded"'
        });
    }
    next();
}

function requireUnemptyJobSpec (req, res, next) {
    if (!req.body.spec || !req.body.spec.trim()) {
        return res.jsonp(400, {
            error: 'Spec must be a non-empty string'
        });
    }
    next();
}
<commit_msg>Fix the content-type check in the webservice<commit_after>'use strict';

var joblint = require('joblint');

module.exports = defineController;

function defineController (app) {
    app.all('/ws', function (req, res, next) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Headers', 'X-Requested-With');
        next();
    });
    app.post('/ws', requireUrlEncodedPostBody, requireUnemptyJobSpec, function (req, res) {
        res.jsonp(joblint(req.body.spec));
    });
    app.all('/ws', function (req, res) {
        return res.jsonp(405, {
            error: 'Method not allowed, POST request expected'
        });
    });
}

function requireUrlEncodedPostBody (req, res, next) {
    if (!req.is('application/x-www-form-urlencoded')) {
        return res.jsonp(400, {
            error: 'Request must have a content-type of "application/x-www-form-urlencoded"'
        });
    }
    next();
}

function requireUnemptyJobSpec (req, res, next) {
    if (!req.body.spec || !req.body.spec.trim()) {
        return res.jsonp(400, {
            error: 'Spec must be a non-empty string'
        });
    }
    next();
}
<|endoftext|>


<commit_before>// 美容服务
angular.module('fiona').controller('BeautyController', function($scope, $controller, commons) {

    $scope.dropdowns = { };

    commons.findDict($scope.dropdowns, {assistantIdSet: "服务助理", hairdresserIdSet: "服务师", packageUnitSet: "物品单位"});

    $controller('BaseController', {$scope: $scope}); //继承

    /**
     * 美容服务
     * ---------------------------
     * */
    $scope.beautyportal = {

        id: "beauty",

        name: "美容服务",

        server: "/api/v2/services",

        defilters: {serviceCode: "服务单号", gestCode: "会员编号", gestName: "会员姓名", petName: "宠物昵称", assistantName: "服务助理", hairdresserName: "服务师" },

        callback: {
            update: function(){
                $scope.petportal.unique($scope.beauty.petId);

                $scope.beautydetailportal.search();
            },

            insert: function() {
                 $scope.beauty.totalNum = 0;
                 $scope.beauty.totalCost = 0;

                 $scope.serialNumber({id: "beauty", fieldName : "serviceCode", numberName : "服务编号"});

                 $scope.setSelectDefault("beauty", ["itemCode", "hairdresserId", "assistantId"]);
            },
            submitbefore: function(){

                if($scope.beauty.assistantId)
                {
                    $scope.beauty.assistantName = $scope.dropdowns.assistantIdSet.getObjectWithId({id: $scope.beauty.assistantId}).personName;
                }

                if($scope.beauty.hairdresserId)
                {
                    $scope.beauty.hairdresserName = $scope.dropdowns.hairdresserIdSet.getObjectWithId({id: $scope.beauty.hairdresserId}).personName;
                }
            },
             submit : function () {
                 // 遍历保存所有子项
                 angular.forEach($scope.beautydetails, function (_beautydetail) {
                     // 寄养ID
                     _beautydetail.serviceId = $scope.beauty.id;

                     $scope.beautydetailportal.saveWithEntity(_beautydetail);
                 });
             }
        }
    };

    $controller('BaseCRUDController', {$scope: $scope, component: $scope.beautyportal}); //继承

    /**
     * 服务项目
     * ---------------------------
     * */
    $scope.beautydetailportal = {

        foreign: "beauty",

        foreignkey: "serviceId", // 外键

        id: "beautydetail",

        name: "服务项目",

        server: "/api/v2/servicedetails",

        defilters: { },

        callback: {
            delete: function(){

              // 重新计算
              $scope.rearith();
            }
        }
    };

    $controller('BaseCRUDController', {$scope: $scope, component: $scope.beautydetailportal}); //继承

    /**
     * 自动补全选择商品
     * ---------------------------
     * */
    $controller('ProductAutoCompleteController', {$scope: $scope}); //继承

    $scope.productportal.checked = function (_product) {

        if (!$scope.beautydetails) {
            $scope.beautydetails = [];
        }

        if($scope.beautydetails.existprop('itemCode', _product.itemCode)) {   // 是否已选择

            var beautydetail = $scope.beautydetails.unique('itemCode', _product.itemCode);

//            commons.modaldanger("beauty", "[ 商品" +_product.itemName+ " ]已存在");
        }
        else {
            // 未选择新添加

            var beautydetail= {};

            angular.forEach(["itemCode", "itemName", "packageUnit", "sellPrice",  "itemStandard", "barCode"], function (name) {
                beautydetail[name] = _product[name];
            });

            // 个数
            beautydetail.inputCount = 1;

            beautydetail.totalCost = beautydetail.inputCount * beautydetail.sellPrice;

            $scope.beautydetails.push(beautydetail);

//            commons.modalsuccess("beauty", "成功添加[ " +beautydetail.itemName+ " ]商品");
        }

        // 重新计算
        $scope.rearith();
    };

    $scope.productportal.autocompletedata();

    /**
     * 宠物管理
     * ---------------------------
     * */
    $controller('PetPopupCheckedPanelController', {$scope: $scope}); //继承

    $scope.petportal.checked = function (_pet) {

        $scope.pet = _pet;

        // 会员ID
        $scope.beauty.gestId = _pet.gestId;

        // 会员编号
        $scope.beauty.gestCode = _pet.gestCode;

        // 会员姓名
        $scope.beauty.gestName = _pet.gestName;

        // 会员手机
        $scope.beauty.mobilePhone = "";

        // 宠物ID
        $scope.beauty.petId = _pet.id;

        // 宠物名称
        $scope.beauty.petName = _pet.petName;

        $("#petselect").modal('hide');
    };

    // 实始化
    $scope.beautyportal.filter();

    // 计算器
    $scope.rearith = function () {

      $scope.beauty.totalNum = 0;
      $scope.beauty.totalCost = 0;

      angular.forEach($scope.beautydetails, function (_beauty) {
        // 小计
        _beauty.totalCost = _beauty.sellPrice * _beauty.inputCount;

        // 总数量
        $scope.beauty.totalNum += _beauty.inputCount;

        // 总金额
        $scope.beauty.totalCost += _beauty.totalCost;
      });
    }
});
<commit_msg>单价获取修改<commit_after>// 美容服务
angular.module('fiona').controller('BeautyController', function($scope, $controller, commons) {

    $scope.dropdowns = { };

    commons.findDict($scope.dropdowns, {assistantIdSet: "服务助理", hairdresserIdSet: "服务师", packageUnitSet: "物品单位"});

    $controller('BaseController', {$scope: $scope}); //继承

    /**
     * 美容服务
     * ---------------------------
     * */
    $scope.beautyportal = {

        id: "beauty",

        name: "美容服务",

        server: "/api/v2/services",

        defilters: {serviceCode: "服务单号", gestCode: "会员编号", gestName: "会员姓名", petName: "宠物昵称", assistantName: "服务助理", hairdresserName: "服务师" },

        callback: {
            update: function(){
                $scope.petportal.unique($scope.beauty.petId);

                $scope.beautydetailportal.search();
            },

            insert: function() {
                 $scope.beauty.totalNum = 0;
                 $scope.beauty.totalCost = 0;

                 $scope.serialNumber({id: "beauty", fieldName : "serviceCode", numberName : "服务编号"});

                 $scope.setSelectDefault("beauty", ["itemCode", "hairdresserId", "assistantId"]);
            },
            submitbefore: function(){

                if($scope.beauty.assistantId)
                {
                    $scope.beauty.assistantName = $scope.dropdowns.assistantIdSet.getObjectWithId({id: $scope.beauty.assistantId}).personName;
                }

                if($scope.beauty.hairdresserId)
                {
                    $scope.beauty.hairdresserName = $scope.dropdowns.hairdresserIdSet.getObjectWithId({id: $scope.beauty.hairdresserId}).personName;
                }
            },
             submit : function () {
                 // 遍历保存所有子项
                 angular.forEach($scope.beautydetails, function (_beautydetail) {
                     // 寄养ID
                     _beautydetail.serviceId = $scope.beauty.id;

                     $scope.beautydetailportal.saveWithEntity(_beautydetail);
                 });
             }
        }
    };

    $controller('BaseCRUDController', {$scope: $scope, component: $scope.beautyportal}); //继承

    /**
     * 服务项目
     * ---------------------------
     * */
    $scope.beautydetailportal = {

        foreign: "beauty",

        foreignkey: "serviceId", // 外键

        id: "beautydetail",

        name: "服务项目",

        server: "/api/v2/servicedetails",

        defilters: { },

        callback: {
            delete: function(){

              // 重新计算
              $scope.rearith();
            }
        }
    };

    $controller('BaseCRUDController', {$scope: $scope, component: $scope.beautydetailportal}); //继承

    /**
     * 自动补全选择商品
     * ---------------------------
     * */
    $controller('ProductAutoCompleteController', {$scope: $scope}); //继承

    $scope.productportal.checked = function (_product) {

        if (!$scope.beautydetails) {
            $scope.beautydetails = [];
        }

        if($scope.beautydetails.existprop('itemCode', _product.itemCode)) {   // 是否已选择

            var beautydetail = $scope.beautydetails.unique('itemCode', _product.itemCode);

//            commons.modaldanger("beauty", "[ 商品" +_product.itemName+ " ]已存在");
        }
        else {
            // 未选择新添加

            var beautydetail= {};

            angular.forEach(["itemCode", "itemName", "packageUnit", "sellPrice",  "itemStandard", "barCode"], function (name) {
                beautydetail[name] = _product[name];
            });
            beautydetail["sellPrice"] = _product["recipePrice"];
            beautydetail["packageUnit"] = _product["recipeUnit"];

            // 个数
            beautydetail.inputCount = 1;

            beautydetail.totalCost = beautydetail.inputCount * beautydetail.sellPrice;

            $scope.beautydetails.push(beautydetail);

//            commons.modalsuccess("beauty", "成功添加[ " +beautydetail.itemName+ " ]商品");
        }

        // 重新计算
        $scope.rearith();
    };

    $scope.productportal.autocompletedata();

    /**
     * 宠物管理
     * ---------------------------
     * */
    $controller('PetPopupCheckedPanelController', {$scope: $scope}); //继承

    $scope.petportal.checked = function (_pet) {

        $scope.pet = _pet;

        // 会员ID
        $scope.beauty.gestId = _pet.gestId;

        // 会员编号
        $scope.beauty.gestCode = _pet.gestCode;

        // 会员姓名
        $scope.beauty.gestName = _pet.gestName;

        // 会员手机
        $scope.beauty.mobilePhone = "";

        // 宠物ID
        $scope.beauty.petId = _pet.id;

        // 宠物名称
        $scope.beauty.petName = _pet.petName;

        $("#petselect").modal('hide');
    };

    // 实始化
    $scope.beautyportal.filter();

    // 计算器
    $scope.rearith = function () {

      $scope.beauty.totalNum = 0;
      $scope.beauty.totalCost = 0;

      angular.forEach($scope.beautydetails, function (_beauty) {
        // 小计
        _beauty.totalCost = _beauty.sellPrice * _beauty.inputCount;

        // 总数量
        $scope.beauty.totalNum += _beauty.inputCount;

        // 总金额
        $scope.beauty.totalCost += _beauty.totalCost;
      });
    }
});
<|endoftext|>


<commit_before>/*
  Similar to meteor.methods
*/
var serverAPI = require('./server_api.js');

function MethodCall(message){
  this.id = message.id;
  this.ws = message.ws;
  this.name = message.name;
  this.data = message.data;
}

MethodCall.prototype.exec = function(){
  var that = this;
  var result;
  try{
      result = methods.list[this.name](this.data,this,function(e,result){
      if(e) return that.sendErr(e);
      if(result) return that.sendResult(result);
      console.log("no error, no result");
    });
  }catch(e){
    console.log('error in method ' + this.name);
    console.log(e.stack);
    return this.sendErr(e);
  }
  if(typeof result != "undefined")
    this.sendResult(result);
};

MethodCall.prototype.sendErr = function (e){
  process.send({cmd:"send",message:{
    id: this.id,
    ws: this.ws.id,
    error: e.toString(),
    data: null
  }});
};
MethodCall.prototype.sendResult = function (result){
  process.send({cmd:"send",message:{
    id: this.id,
    ws: this.ws.id,
    error: null,
    data: result
  }});
};

var methods = {};

// object of all methods
methods.list = {};
methods.users = {};

// function to add method to methods.list
methods.add = function (array) {

  for (var method in array) {
    methods.list[method] = array[method];
    process.send({cmd:"add",name:method});
  }

};

// execute method when called by client
methods.call = function(ws,message){
  var meth;
  try{
    meth = new MethodCall(ws,message);
  }catch(e){
    return console.log("error: "+e+", message: "+ JSON.stringify(message));
  }
  meth.exec();
};
var User = require(__dirname+"/ws_puppet.js");
process.on("message",function(message){
  if(!(message.ws in methods.users))
    methods.users[message.ws] = new User(message.ws);
  message.ws  = methods.users[message.ws];
  /*
  Commands:
    disconnect: Head is closed
    server api: return value for silk api method
  */
  if(!("cmd" in message)){
    var meth = new MethodCall(message);
    return meth.exec();
  }
  switch(message.cmd){
    case "disconnect": message.ws.emit("close"); break;
    case "close": break; //expected to close, will close forcfully in 5 seconds
    case "sleep": break; //Head is removed from the window manager so updates are impossible
    case "minimize": break; //Head is not removed but updates to the head will not be seen
    case "server api": Silk.api.done(message);
  }
});

// make global because it will be used in most files.
global.Silk = {};
Silk.methods = methods;
Silk.api = serverAPI;
global.methods = methods;

process.nextTick(function(){
  require(process.env.start);
});

process.send({cmd:"ready"});
<commit_msg>apps using fork framework have title set to app's name<commit_after>/*
  Similar to meteor.methods
*/
var serverAPI = require('./server_api.js');

function MethodCall(message){
  this.id = message.id;
  this.ws = message.ws;
  this.name = message.name;
  this.data = message.data;
}

MethodCall.prototype.exec = function(){
  var that = this;
  var result;
  try{
      result = methods.list[this.name](this.data,this,function(e,result){
      if(e) return that.sendErr(e);
      if(result) return that.sendResult(result);
      console.log("no error, no result");
    });
  }catch(e){
    console.log('error in method ' + this.name);
    console.log(e.stack);
    return this.sendErr(e);
  }
  if(typeof result != "undefined")
    this.sendResult(result);
};

MethodCall.prototype.sendErr = function (e){
  process.send({cmd:"send",message:{
    id: this.id,
    ws: this.ws.id,
    error: e.toString(),
    data: null
  }});
};
MethodCall.prototype.sendResult = function (result){
  process.send({cmd:"send",message:{
    id: this.id,
    ws: this.ws.id,
    error: null,
    data: result
  }});
};

var methods = {};

// object of all methods
methods.list = {};
methods.users = {};

// function to add method to methods.list
methods.add = function (array) {

  for (var method in array) {
    methods.list[method] = array[method];
    process.send({cmd:"add",name:method});
  }

};

// execute method when called by client
methods.call = function(ws,message){
  var meth;
  try{
    meth = new MethodCall(ws,message);
  }catch(e){
    return console.log("error: "+e+", message: "+ JSON.stringify(message));
  }
  meth.exec();
};
var User = require(__dirname+"/ws_puppet.js");
process.on("message",function(message){
  if(!(message.ws in methods.users))
    methods.users[message.ws] = new User(message.ws);
  message.ws  = methods.users[message.ws];
  /*
  Commands:
    disconnect: Head is closed
    server api: return value for silk api method
  */
  if(!("cmd" in message)){
    var meth = new MethodCall(message);
    return meth.exec();
  }
  switch(message.cmd){
    case "disconnect": message.ws.emit("close"); break;
    case "close": break; //expected to close, will close forcfully in 5 seconds
    case "sleep": break; //Head is removed from the window manager so updates are impossible
    case "minimize": break; //Head is not removed but updates to the head will not be seen
    case "server api": Silk.api.done(message);
  }
});

// make global because it will be used in most files.
global.Silk = {};
Silk.methods = methods;
Silk.api = serverAPI;
global.methods = methods;

process.nextTick(function(){
  process.title = process.env.app;
  require(process.env.start);
});

process.send({cmd:"ready"});
<|endoftext|>