<commit_before>var line = [];
var backstory = null;

var wordIndex = 0;
var lineIndex = 0;

var wordDelay = 120;
var lineDelay = 400;
var content = [
    "Ivan the Terrible, you do not judge like your comrades",
    "Americanski says you take bribe, are not fit to judge",
    "You disgrace mother Russia!",
    "Interpretive dance serious business!",
    "We send you back to beginning, learn judging all over again",
    "Only then can you return for next Olympics"
];

var startMenu = function(game) {
    return {
        preload: function() {
            game.stage.backgroundColor = "#aaaaaa";
            this.game.scale.pageAlignHorizontally = true;
            this.game.scale.pageAlignVertically = true;
            this.game.scale.refresh();

            this.centeredText("Russian Judge Redemption", 20);
            this.loadingText = this.centeredText("Loading", game.world.centerY);
            game.load.image('floor', 'assets/floorTile/draftFloor.png');
            game.load.image('judgeResponseGood', 'assets/judgeResponseGood.jpg');
            game.load.image('judgeResponseBad', 'assets/judgeResponseBad.jpg');
            game.load.image('feedbackResultGood', 'assets/vaultBoyGood.jpg');
            game.load.image('feedbackResultBad', 'assets/vaultBoyBad.jpg');
            game.load.image('meterArrow', 'assets/meter-arrow.png');
            game.load.image('voteScoreBar', 'assets/vote-score-bar.png');
            game.load.image('russianJudge', 'assets/judge/russianJudge/normalSprite.png');
            game.load.image('draftJudge', 'assets/judge/draftJudge/normalSprite.png');
            game.load.image('judge1', 'assets/judge/1Judge/normalSprite.png');
            game.load.image('judge2', 'assets/judge/2Judge/normalSprite.png');
            game.load.image('judge3', 'assets/judge/3Judge/normalSprite.png');
            game.load.image('audience', 'assets/audience/audience.png');

            game.load.image('dancer-head', 'assets/dancer/mikeDancer/head.png');
            game.load.image('dancer-leftArm', 'assets/dancer/mikeDancer/leftArm.png');
            game.load.image('dancer-rightArm', 'assets/dancer/mikeDancer/rightArm.png');
            game.load.image('dancer-leftHand', 'assets/dancer/mikeDancer/leftHand.png');
            game.load.image('dancer-rightHand', 'assets/dancer/mikeDancer/rightHand.png');
            game.load.image('dancer-leftFoot', 'assets/dancer/mikeDancer/leftFoot.png');
            game.load.image('dancer-rightFoot', 'assets/dancer/mikeDancer/rightFoot.png');
            game.load.image('dancer-leftLeg', 'assets/dancer/mikeDancer/leftLeg.png');
            game.load.image('dancer-rightLeg', 'assets/dancer/mikeDancer/rightLeg.png');
            game.load.image('dancer-torso', 'assets/dancer/mikeDancer/torso.png');

            game.load.onLoadComplete.add(function() {
                // TODO kill this so you have an actual start menu
                //game.state.start('dancing');

                this.loadingText.destroy();
                var startButton = this.centeredText("Start Judging", game.world.centerY);
                startButton.inputEnabled = true;
                startButton.events.onInputDown.add(
                    function() {
                      game.stage.backgroundColor = "black";
                      var style = {
                          font: "32px Arial",
                          fill: "#19de65",
                          wordWrap: false,
                          //align: "center",
                          backgroundColor: "black"
                      };

                        backstory = game.add.text(32, 32, '', style);
                        startButton.destroy();
                        displayBackstory();

                    });
            }, this);
        },
        centeredText: function(ctext, y) {
            ctext = game.add.text(game.world.centerX, y, ctext);
            ctext.anchor.setTo(0.5, 0.5);
            return ctext;
        },
    };
};

function displayBackstory() {
  nextLine();

}

function nextLine() {

    if (lineIndex === content.length)
    {
        //  We're finished
        game.time.events.loop(Phaser.Timer.SECOND * 3, function() {
        game.state.start('dancing');
        }, this);
        return;
    }

    //  Split the current line on spaces, so one word per array element
    line = content[lineIndex].split(' ');

    //  Reset the word index to zero (the first word in the line)
    wordIndex = 0;

    //  Call the 'nextWord' function once for each word in the line (line.length)
    game.time.events.repeat(wordDelay, line.length, nextWord, this);

    //  Advance to the next line
    lineIndex++;

}

function nextWord() {

    //  Add the next word onto the text string, followed by a space
    backstory.text = backstory.text.concat(line[wordIndex] + " ");

    //  Advance the word index to the next word in the line
    wordIndex++;

    //  Last word?
    if (wordIndex === line.length)
    {
        //  Add a carriage return
        backstory.text = backstory.text.concat("\n");

        //  Get the next line after the lineDelay amount of ms has elapsed
        game.time.events.add(lineDelay, nextLine, this);
    }

}

game.state.add('startMenu', startMenu);
<commit_msg>Improved intro message<commit_after>var line = [];
var backstory = null;

var wordIndex = 0;
var lineIndex = 0;

var wordDelay = 120;
var lineDelay = 400;
var content = [
    "Ivan, ",
    "You are terrible.",
    "You do not judge like your comrades.",
    "Americanski says you either take bribe",
    "  or never learn how to judge.",
    "You disgrace mother Russia!",
    "Interpretive dance serious business!",
    "We send you back to beginning, ",
    "  learn judging all over again.",
    "Then MAYBE you return for next Olympics.",
    "",
    "-- Minister of Cultural Emergencies"
];

var startMenu = function(game) {
    return {
        preload: function() {
            game.stage.backgroundColor = "#aaaaaa";
            this.game.scale.pageAlignHorizontally = true;
            this.game.scale.pageAlignVertically = true;
            this.game.scale.refresh();

            this.centeredText("Russian Judge Redemption", 20);
            this.loadingText = this.centeredText("Loading", game.world.centerY);
            game.load.image('floor', 'assets/floorTile/draftFloor.png');
            game.load.image('judgeResponseGood', 'assets/judgeResponseGood.jpg');
            game.load.image('judgeResponseBad', 'assets/judgeResponseBad.jpg');
            game.load.image('feedbackResultGood', 'assets/vaultBoyGood.jpg');
            game.load.image('feedbackResultBad', 'assets/vaultBoyBad.jpg');
            game.load.image('meterArrow', 'assets/meter-arrow.png');
            game.load.image('voteScoreBar', 'assets/vote-score-bar.png');
            game.load.image('russianJudge', 'assets/judge/russianJudge/normalSprite.png');
            game.load.image('draftJudge', 'assets/judge/draftJudge/normalSprite.png');
            game.load.image('judge1', 'assets/judge/1Judge/normalSprite.png');
            game.load.image('judge2', 'assets/judge/2Judge/normalSprite.png');
            game.load.image('judge3', 'assets/judge/3Judge/normalSprite.png');
            game.load.image('audience', 'assets/audience/audience.png');

            game.load.image('dancer-head', 'assets/dancer/mikeDancer/head.png');
            game.load.image('dancer-leftArm', 'assets/dancer/mikeDancer/leftArm.png');
            game.load.image('dancer-rightArm', 'assets/dancer/mikeDancer/rightArm.png');
            game.load.image('dancer-leftHand', 'assets/dancer/mikeDancer/leftHand.png');
            game.load.image('dancer-rightHand', 'assets/dancer/mikeDancer/rightHand.png');
            game.load.image('dancer-leftFoot', 'assets/dancer/mikeDancer/leftFoot.png');
            game.load.image('dancer-rightFoot', 'assets/dancer/mikeDancer/rightFoot.png');
            game.load.image('dancer-leftLeg', 'assets/dancer/mikeDancer/leftLeg.png');
            game.load.image('dancer-rightLeg', 'assets/dancer/mikeDancer/rightLeg.png');
            game.load.image('dancer-torso', 'assets/dancer/mikeDancer/torso.png');

            game.load.onLoadComplete.add(function() {
                // TODO kill this so you have an actual start menu
                //game.state.start('dancing');

                this.loadingText.destroy();
                var startButton = this.centeredText("Start Judging", game.world.centerY);
                startButton.inputEnabled = true;
                startButton.events.onInputDown.add(
                    function() {
                      game.stage.backgroundColor = "black";
                      var style = {
                          font: "32px Arial",
                          fill: "#19de65",
                          wordWrap: false,
                          //align: "center",
                          backgroundColor: "black"
                      };

                        backstory = game.add.text(32, 32, '', style);
                        startButton.destroy();
                        displayBackstory();

                    });
            }, this);
        },
        centeredText: function(ctext, y) {
            ctext = game.add.text(game.world.centerX, y, ctext);
            ctext.anchor.setTo(0.5, 0.5);
            return ctext;
        },
    };
};

function displayBackstory() {
  nextLine();

}

function nextLine() {

    if (lineIndex === content.length)
    {
        //  We're finished
        game.time.events.loop(Phaser.Timer.SECOND * 3, function() {
        game.state.start('dancing');
        }, this);
        return;
    }

    //  Split the current line on spaces, so one word per array element
    line = content[lineIndex].split(' ');

    //  Reset the word index to zero (the first word in the line)
    wordIndex = 0;

    //  Call the 'nextWord' function once for each word in the line (line.length)
    game.time.events.repeat(wordDelay, line.length, nextWord, this);

    //  Advance to the next line
    lineIndex++;

}

function nextWord() {

    //  Add the next word onto the text string, followed by a space
    backstory.text = backstory.text.concat(line[wordIndex] + " ");

    //  Advance the word index to the next word in the line
    wordIndex++;

    //  Last word?
    if (wordIndex === line.length)
    {
        //  Add a carriage return
        backstory.text = backstory.text.concat("\n");

        //  Get the next line after the lineDelay amount of ms has elapsed
        game.time.events.add(lineDelay, nextLine, this);
    }

}

game.state.add('startMenu', startMenu);
<|endoftext|>


<commit_before><commit_msg>Fixing Japanese Favela translation<commit_after><|endoftext|>


<commit_before>/* global Swiper*/
(function($) {
    'use strict';

    // document load event
    $(document).ready(function() {

        // initialize swiper when document ready
        // http://idangero.us/swiper/api/
        var swiper = new Swiper('.js__img-slider', {
            nextButton: '.js__img-slider__btn-next',
            prevButton: '.js__img-slider__btn-prev',
            pagination: '.js__img-slider__pagination',
            paginationClickable: true,
            preloadImages: false,
            lazyLoading: true,
            watchSlidesVisibility: true,
            lazyLoadingInPrevNext: true,
            speed: 600
        });
        // Makes it possible to skip between slider images if they have links, using the tab button
        swiper.container.on('focus', 'a', function(e) {
            //Index of focused slide
            var focusIndex = $(e.target).parents('.swiper-slide').index();
            //Reset scrollLeft set by browser on focus
            swiper.container.scrollLeft(0);
            //Slide to focused slide
            swiper.slideTo(focusIndex);
        });
    });

})(jQuery);
<commit_msg>[FIX] IE fix, Use tab to navigate slider<commit_after>/* global Swiper*/
(function($) {
    'use strict';

    // document load event
    $(document).ready(function() {

        // initialize swiper when document ready
        // http://idangero.us/swiper/api/
        var swiper = new Swiper('.js__img-slider', {
            nextButton: '.js__img-slider__btn-next',
            prevButton: '.js__img-slider__btn-prev',
            pagination: '.js__img-slider__pagination',
            paginationClickable: true,
            preloadImages: false,
            lazyLoading: true,
            watchSlidesVisibility: true,
            lazyLoadingInPrevNext: true,
            speed: 600
        });
        // Makes it possible to skip between slider images if they have links, using the tab button
        swiper.container.on('focus', 'a', function(e) {
            //Index of focused slide
            var focusIndex = $(e.target).parents('.swiper-slide').index();
            //Reset scrollLeft set by browser on focus
            swiper.container.scrollLeft(0);

            // IE fix
            setTimeout(function() {
                swiper.container.scrollLeft(0);
            }, 0);

            //Slide to focused slide
            swiper.slideTo(focusIndex);
        });
    });

})(jQuery);
<|endoftext|>


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

    angular
        .module('dpDataSelection')
        .component('dpDataSelection', {
            templateUrl: 'modules/data-selection/components/data-selection/data-selection.html',
            bindings: {
                boundingBox: '<',
                catalogFilters: '<',
                filters: '<',
                state: '<',
                user: '<',
                zoomLevel: '<'
            },
            controller: DpDataSelectionController,
            controllerAs: 'vm'
        });

    DpDataSelectionController.$inject = [
        '$scope',
        'userSettings',
        'dataSelectionApi',
        'DATA_SELECTION_CONFIG',
        'TabHeader',
        'store',
        'ACTIONS'
    ];

    function DpDataSelectionController (
        $scope,
        userSettings,
        dataSelectionApi,
        DATA_SELECTION_CONFIG,
        TabHeader,
        store,
        ACTIONS
    ) {
        const vm = this;

        vm.showCatalogusIntroduction = vm.state.view === 'CATALOG' &&
            userSettings.showCatalogusIntroduction.value === true.toString();

        $scope.$watch('vm.showCatalogusIntroduction', function () {
            userSettings.showCatalogusIntroduction.value = vm.showCatalogusIntroduction.toString();
        });

        $scope.$watchGroup([
            // Watching all state variables except markers and isLoading
            'vm.boundingBox',
            'vm.catalogFilters',
            'vm.filters',
            'vm.state.dataset',
            'vm.state.geometryFilter',
            'vm.state.page',
            'vm.state.query',
            'vm.state.view',
            'vm.user.scopes',
            'vm.zoomLevel'
        ], fetchData);

        vm.tabHeader = new TabHeader('data-datasets');
        vm.tabHeader.activeTab = vm.tabHeader.getTab('datasets');

        function updateTabHeader (query, count) {
            if (vm.showTabHeader()) {
                vm.tabHeader.userScopes = vm.user.scopes;
                vm.tabHeader.query = query;
                vm.tabHeader.getTab('datasets').count = count;
            }
        }

        function fetchData () {
            const config = DATA_SELECTION_CONFIG.datasets[vm.state.dataset];
            const isListView = vm.state.view === 'LIST';
            vm.view = vm.state.view;

            const isQueryView = angular.isDefined(vm.state.query) && vm.state.query.trim().length >= 1;
            vm.showTabHeader = () => (vm.view === 'CATALOG') && isQueryView;
            vm.currentPage = vm.state.page;

            vm.numberOfRecords = null;
            vm.numberOfPages = null;

            vm.showContent = false;
            vm.disabled = false;

            if (config.AUTH_SCOPE && !vm.user.scopes.includes(config.AUTH_SCOPE)) {
                vm.disabled = true;
                vm.notAuthorizedMessageSrc =
                    `modules/data-selection/components/data-selection/not-authorized-message/${vm.state.dataset}.html`;
                vm.availableFilters = [];
                store.dispatch({
                    type: ACTIONS.SHOW_DATA_SELECTION,
                    payload: []
                });
                return;
            }

            vm.isLoading = true;

            dataSelectionApi
                .query(
                    vm.state.dataset,
                    vm.state.view,
                    vm.filters,
                    vm.currentPage,
                    vm.state.query,
                    vm.state.geometryFilter.markers,
                    vm.catalogFilters
                ).then(data => {
                    vm.availableFilters = data.filters;
                    vm.data = data.data;
                    vm.numberOfRecords = data.numberOfRecords;
                    vm.numberOfPages = data.numberOfPages;

                    vm.showFilters = !isListView && vm.numberOfRecords > 0;

                    // determine if warning messages should be shown
                    vm.maxAvailablePages = DATA_SELECTION_CONFIG.datasets[vm.state.dataset].MAX_AVAILABLE_PAGES;
                    vm.showMessageMaxPages = vm.maxAvailablePages && vm.state.page > vm.maxAvailablePages;

                    vm.maxNumberOfClusteredMarkers =
                        DATA_SELECTION_CONFIG.datasets[vm.state.dataset].MAX_NUMBER_OF_CLUSTERED_MARKERS;
                    vm.showMessageClusteredMarkers = isListView && vm.numberOfRecords > vm.maxNumberOfClusteredMarkers;

                    updateTabHeader(vm.state.query, vm.numberOfRecords);

                    vm.showContent =
                        vm.numberOfRecords &&
                        (
                            angular.isUndefined(vm.maxAvailablePages) ||
                            vm.state.page <= vm.maxAvailablePages
                        );

                    const activeFilters = angular.extend({
                        shape: angular.toJson(vm.state.geometryFilter.markers.map(([lat, lng]) => [lng, lat]))
                    }, vm.filters);

                    if (isListView && vm.numberOfRecords <= vm.maxNumberOfClusteredMarkers) {
                        // Get marker data and update the state to show the
                        // data
                        dataSelectionApi
                            .getMarkers(vm.state.dataset, activeFilters, vm.zoomLevel, vm.boundingBox)
                            .then(markerData => {
                                store.dispatch({
                                    type: ACTIONS.SHOW_DATA_SELECTION,
                                    payload: markerData
                                });
                            });
                    } else if (vm.state.reset) {
                        // Update the state to show the data, do not trigger a
                        // url state change however
                        store.dispatch({
                            type: ACTIONS.RESET_DATA_SELECTION,
                            payload: []
                        });
                    } else {
                        // Update the state to show the data
                        store.dispatch({
                            type: ACTIONS.SHOW_DATA_SELECTION,
                            payload: []
                        });
                    }
                }).finally(() => {
                    vm.isLoading = false;
                });
        }
    }
})();
<commit_msg>DP-5983: Add async loading for api calls to get bag data and bag geolocation date<commit_after>(function () {
    'use strict';

    angular
        .module('dpDataSelection')
        .component('dpDataSelection', {
            templateUrl: 'modules/data-selection/components/data-selection/data-selection.html',
            bindings: {
                boundingBox: '<',
                catalogFilters: '<',
                filters: '<',
                state: '<',
                user: '<',
                zoomLevel: '<'
            },
            controller: DpDataSelectionController,
            controllerAs: 'vm'
        });

    DpDataSelectionController.$inject = [
        '$scope',
        'userSettings',
        'dataSelectionApi',
        'DATA_SELECTION_CONFIG',
        'TabHeader',
        'store',
        'ACTIONS'
    ];

    function DpDataSelectionController (
        $scope,
        userSettings,
        dataSelectionApi,
        DATA_SELECTION_CONFIG,
        TabHeader,
        store,
        ACTIONS
    ) {
        const vm = this;

        vm.showCatalogusIntroduction = vm.state.view === 'CATALOG' &&
            userSettings.showCatalogusIntroduction.value === true.toString();

        $scope.$watch('vm.showCatalogusIntroduction', function () {
            userSettings.showCatalogusIntroduction.value = vm.showCatalogusIntroduction.toString();
        });

        $scope.$watchGroup([
            // Watching all state variables except markers and isLoading
            'vm.boundingBox',
            'vm.catalogFilters',
            'vm.filters',
            'vm.state.dataset',
            'vm.state.geometryFilter',
            'vm.state.page',
            'vm.state.query',
            'vm.state.view',
            'vm.user.scopes',
            'vm.zoomLevel'
        ], fetchData);

        vm.tabHeader = new TabHeader('data-datasets');
        vm.tabHeader.activeTab = vm.tabHeader.getTab('datasets');

        function updateTabHeader (query, count) {
            if (vm.showTabHeader()) {
                vm.tabHeader.userScopes = vm.user.scopes;
                vm.tabHeader.query = query;
                vm.tabHeader.getTab('datasets').count = count;
            }
        }

        async function fetchData () {
            const config = DATA_SELECTION_CONFIG.datasets[vm.state.dataset];
            const isListView = vm.state.view === 'LIST';
            vm.view = vm.state.view;

            const isQueryView = angular.isDefined(vm.state.query) && vm.state.query.trim().length >= 0;
            vm.showTabHeader = () => (vm.view === 'CATALOG') && isQueryView;
            vm.currentPage = vm.state.page;

            vm.numberOfRecords = null;
            vm.numberOfPages = null;

            vm.showContent = false;
            vm.isLoading = !vm.showContent;
            vm.disabled = false;

            if (config.AUTH_SCOPE && !vm.user.scopes.includes(config.AUTH_SCOPE)) {
                vm.disabled = true;
                vm.notAuthorizedMessageSrc =
                    `modules/data-selection/components/data-selection/not-authorized-message/${vm.state.dataset}.html`;
                vm.availableFilters = [];
                store.dispatch({
                    type: ACTIONS.SHOW_DATA_SELECTION,
                    payload: []
                });
                return;
            }

            const activeFilters = angular.extend({
                shape: angular.toJson(vm.state.geometryFilter.markers.map(([lat, lng]) => [lng, lat]))
            }, vm.filters);

            const getData = dataSelectionApi.query(
                vm.state.dataset,
                vm.state.view,
                vm.filters,
                vm.currentPage,
                vm.state.query,
                vm.state.geometryFilter.markers,
                vm.catalogFilters
            );

            const getMarkers = isListView && dataSelectionApi.getMarkers(
                vm.state.dataset,
                activeFilters,
                vm.zoomLevel,
                vm.boundingBox
            );

            const data = await getData;

            if (data) {
                vm.showContent = true;
                vm.isLoading = !vm.showContent;

                vm.availableFilters = data.filters;
                vm.data = data.data;
                vm.numberOfRecords = data.numberOfRecords;
                vm.numberOfPages = data.numberOfPages;

                vm.showFilters = !isListView && vm.numberOfRecords > 0;

                /** Determine if warning messages should be shown */
                vm.maxAvailablePages = DATA_SELECTION_CONFIG.datasets[vm.state.dataset].MAX_AVAILABLE_PAGES;
                vm.showMessageMaxPages = vm.maxAvailablePages && vm.state.page > vm.maxAvailablePages;

                vm.maxNumberOfClusteredMarkers =
                    DATA_SELECTION_CONFIG.datasets[vm.state.dataset].MAX_NUMBER_OF_CLUSTERED_MARKERS;
                vm.showMessageClusteredMarkers = isListView && vm.numberOfRecords > vm.maxNumberOfClusteredMarkers;

                updateTabHeader(vm.state.query, vm.numberOfRecords);

                if (vm.numberOfRecords <= vm.maxNumberOfClusteredMarkers) {
                    /** Update state  with clusters only when maximum records isnt exceeded */
                    const markers = await getMarkers;

                    store.dispatch({
                        type: ACTIONS.SHOW_DATA_SELECTION,
                        payload: markers
                    });
                } else if (vm.state.reset) {
                    /** Update state to show the data, do not trigger a url state change however */
                    store.dispatch({
                        type: ACTIONS.RESET_DATA_SELECTION,
                        payload: []
                    });
                } else {
                    store.dispatch({ /** Update state to show the data */
                        type: ACTIONS.SHOW_DATA_SELECTION,
                        payload: []
                    });
                }
            }
      }
    }
})();
<|endoftext|>


<commit_before>function setFavourite(name, type, image){
    AjaxServices.setFavourite(name, type);
    image.src='images/star_active.gif';
    image.onclick='';
    image.style.cursor='';
    image.title='This is a favourite';
}

function precomputeTemplate(templateName){
    document.getElementById('precompute_'+templateName).innerHTML="Precomputing..";
    AjaxServices.preCompute(templateName,function(str) {
        document.getElementById('precompute_'+templateName).style.color="#777";
        document.getElementById('precompute_'+templateName).innerHTML="Precomputed";
     });
}

function summariseTemplate(templateName){
    document.getElementById('summarise_'+templateName).innerHTML="Summarising..";
    AjaxServices.summarise(templateName,function(str) {
        document.getElementById('summarise_'+templateName).style.color="#777";
        document.getElementById('summarise_'+templateName).innerHTML="Summarised";
    });
}

function editName(name){
  document.getElementById('form_'+name).style.display="block";
  document.getElementById('name_'+name).style.display="none";
}

function renameElement(name, type, index){
    document.getElementById('form_'+name).style.display="none";
    document.getElementById('name_'+name).innerHTML="saving...";
    document.getElementById('name_'+name).style.display="block";
    AjaxServices.rename(name,type, (document.getElementById('newName_'+name).value).replace(/^\s*|\s*$/g,""), function(str){
        document.getElementById('name_'+name).innerHTML=str;
        document.getElementById('selected_user_' + type + '_' + index).value=str;
    });
}

function changeViewPathDescription(pathName){
    var pathString = pathName.replace(/\@sep\@/g,".");
    var pathEnd = pathString.substring(pathString.lastIndexOf('.') + 1);
    document.getElementById('form_'+pathName).style.display = "none";
    document.getElementById('name_'+pathName+'_inner').innerHTML = "saving...";
    document.getElementById('name_'+pathName).style.display = "block";
    var newDescription = document.getElementById('newName_' + pathName).value;
    var callBack = function(prefixDescription){
        if (prefixDescription == null) {
            prefixDescription = '(no description)';
        }
        document.getElementById('name_' + pathName + '_inner').innerHTML =
          '' + prefixDescription +
          ' > ' + pathEnd;
    }
    AjaxServices.changeViewPathDescription(pathString, newDescription, callBack);
}

function saveBagDescription(bagName){
    var textarea = document.getElementById('textarea').value;
    textarea = textarea.replace(/[\n\r]+/g, "\n\r
");
    document.getElementById('bagDescriptionDiv').innerHTML = 'Saving...';
    AjaxServices.saveBagDescription(bagName,textarea, function(str){
        document.getElementById('bagDescriptionDiv').innerHTML = str;
    });
    swapDivs('bagDescriptionTextarea','bagDescriptionDiv');
}

function swapDivs(div1,div2){
    document.getElementById(div1).style.display = 'none';
    document.getElementById(div2).style.display = 'block';
}

function roundToSignificantDecimal(n) {
    var log10n = Math.log(Math.abs(n)) / Math.log(10);
    if(log10n<1 && n!=0) {
        var rf = 100*Math.pow(10,-Math.round(log10n));
        return rf;
    } else return 100;
}

function updateCountInColumnSummary() {
    var countString = document.resultsCountText;
    if (countString == null) {
        setTimeout("updateCountInColumnSummary()", 1000);
        return;
    }

    document.getElementById('summary_row_count').innerHTML = "
" + countString + "
";

    var est = document.getElementById('resultsCountEstimate');
    if (est == null || est.style.display != 'none') {
        setTimeout("updateCountInColumnSummary()", 500);
        return;
    }
}

function updateUniqueCountInColumnSummary(uniqueCountQid) {
    getResults(uniqueCountQid, 1000, resultsCountCallback, null);
}

function resultsCountCallback(results) {
    var size = results[0][0];

    if (size > 1) {
        var summaryUniqueCountElement = document.getElementById('summary_unique_count');
        summaryUniqueCountElement.style.display='inline';
        summaryUniqueCountElement.innerHTML='Total unique values: ' + size;
    }
    return true;
}

function getColumnSummary(tableName, columnName, columnDisplayName) {
    document.getElementById('summary_loaded').style.display = "none";
    document.getElementById('summary_loading').style.display = "block";
    Effect.Appear('summary', { duration: 0.30 });
    AjaxServices.getColumnSummary(tableName, columnName, function(str){
        var rows = str[0];
        function rounder(cell) {
            if (cell==null) {
                return "[no value]" ;
            } if (! isNaN(cell)) {
                var rf = roundToSignificantDecimal(cell+0);
                return Math.round(cell*rf)/rf;
            } else {
                return cell;
            }
        }
        var headerText;
        if(rows[0].length == 2){
            headerText = '
Value	Count
';
        } else {
            headerText = '
Min	Max	Sample Mean	Standard Deviation
';
        }

        document.getElementById('summary_loading').style.display = "none";
        document.getElementById('summary_loaded').style.display = "block";

        var bodyText = '';

        for (rowIndex = 0; rowIndex < rows.length; rowIndex++) {
            var row = rows[rowIndex];
            bodyText += '
';
            for (colIndex = 0; colIndex < row.length; colIndex++) {
                var cellValue = rounder(row[colIndex]);
                bodyText += '' + cellValue + '	';
            }
            bodyText += '
';
        }

        var html = '
                                         \

                                     \
                        Column Summary for ' + columnDisplayName + '          \

                                                  \

                      \

                   \

                                                   \

 \

' + headerText +'
    \

' + bodyText + '
    \

                                                \

';

        var summaryLoadedElement = document.getElementById('summary_loaded');
        summaryLoadedElement.innerHTML = html;
        var uniqueCountQid = str[1];
        setTimeout("updateCountInColumnSummary()", 200);
        setTimeout("updateUniqueCountInColumnSummary(" + uniqueCountQid + ")", 300);
    });
}

function getResultsPoller(qid, timeout, userCallback, userData) {
    var callback = function(results) {
        if (results == null) {
            // try again
            getResults(qid, timeout, userCallback, userData);
        } else {
            if (!userCallback(results, userData)) {
                getResults(qid, timeout, userCallback, userData);
            }
        }
    }

    AjaxServices.getResults(qid, callback);
}

function getResults(qid, timeout, userCallback, userData) {
    setTimeout("getResultsPoller(" + qid + ", " + timeout + ", " + userCallback + ","
               + userData + ")", timeout);
}

// delete all the child nodes of the node given by parentElement and create a child
// element of type childTag, setting the text in the new child element to be
// childText
function setChild(parentElement, childText, childTag) {
    var newChild = document.createElement(childTag);
    newChild.innerHTML = childText;
    if (parentElement.firstChild != null) {
        while (parentElement.hasChildNodes()) {
            parentElement.removeChild(parentElement.firstChild);
        }
    }
    parentElement.appendChild(newChild);
    return newChild;
}

var callId = 1;

// Give each ajax call an id and remember what our current pending id is
var currentFilterCallbacks = new Array();

// Give each setTimeout call an id and remember what our current pending id is
var futureFilterCalls = new Array();

function filterWebSearchablesHandler(event, object, scope, type, tags) {
    if (window.event) {
        event = window.event;
    }
    if (event) {
	    if (event.keyCode == 27) {
	        object.value = '';
	        return;
	    }
	    if (event.keyCode == 13) {
	        return;
	    }
	}

    futureFilterCalls[scope + "_" + type] = callId;

    if (tags == null) {
        tags = [];
    }

    setTimeout('filterWebSearchables("' + object.id + '", "' + scope + '","' + type + '",' +
               callId + ",'" + tags + "')", 500);
    callId++;
}

// given a list of WebSearchables names,scores and descriptions, filter the
// wsFilterList given by the scope and type parameters
function do_filtering(filteredList, scope, type) {
    if (filteredList.length == 0) {
        showAll(scope, type);
    } else {
        var scoreHash = new Array();
        var descHash = new Array();
        var hitHash = new Array();

        for (var el in filteredList) {
            var wsName = filteredList[el][0];
            var wsDesc = filteredList[el][1];
            descHash[scope + '_' + type + '_item_line_' + wsName] = wsDesc;
            var wsScore = filteredList[el][2];
            scoreHash[scope + '_' + type + '_item_line_' + wsName] = wsScore;
            hitHash[scope + '_' + type + '_item_line_' + wsName] = 1;
        }

        var pattern = new RegExp('^' + scope + '_' + type + '_item_line_(.*)');
        var inputArray = document.getElementsByTagName("div");
        for(var i=0; i<inputArray.length; i++) {
            if ((result = pattern.exec(inputArray[i].id)) != null) {
                if (hitHash[inputArray[i].id]) {
                    inputArray[i].style.display='block';
                    var highlightText = descHash[inputArray[i].id];

                    if (highlightText) {
                        var descId = scope + '_' + type + '_item_description_' + result[1];
                        var desc = $(descId);

                        var descChild = setChild(desc, highlightText, 'p');
                        descChild.className = 'description';
                    }

                    if (scoreHash[inputArray[i].id]) {
                        var scoreWsName = result[1];
                        var score = scoreHash[inputArray[i].id];
                        var intScore = parseInt(score * 10);
                        var scoreId = scope + '_' + type + '_item_score_' + scoreWsName;
                        var scoreSpan = $(scoreId);
                        // we do this instead of scoreSpan.innerHTML = "stuff"
                        // because it's buggy in Internet Explorer
                        var heatImage = 'heat' + intScore + '.gif';
                        var heatText = '';
                        setChild(scoreSpan, heatText, 'span');
                    }
                } else {
                    inputArray[i].style.display='none';
                }
            }
        }

        function sortWsFilter(el1, el2) {
            var el1score = scoreHash[el1.id];
            var el2score = scoreHash[el2.id]
                if (el1score > el2score) {
                    return -1;
                } else {
                    if (el1score < el2score) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
        }

        var parent = $(scope + '_' + type + '_ws_list');
        var divs = new Array();

        for (var i in parent.childNodes) {
            var child = parent.childNodes[i];
            if (child.tagName == 'DIV' && scoreHash[child.id]) {
                divs.push(child);
            }
        }

        divs.sort(sortWsFilter);

        for (var i = 0; i < divs.length; i++) {
            parent.appendChild(divs[i]);
        }

        $(scope + '_' + type + '_spinner').style.visibility = 'hidden';
    }
}

// un-hide all the rows in the webSearchableList
function showAll(scope, type) {
    var pattern = new RegExp('^' + scope + '_' + type + '_item_line_(.*)');
    var inputArray = document.getElementsByTagName("div");
    for(var i=0; i<inputArray.length; i++) {
        var result;
        if ((result = pattern.exec(inputArray[i].id)) != null) {
            inputArray[i].style.display='block';
        }
    }
    $(scope + '_' + type + '_spinner').style.visibility = 'hidden';
}

// call AjaxServices.filterWebSearchables() then hide those WebSearchables in
// the webSearchableList that don't match
function filterWebSearchables(objectId, scope, type, callId, tags) {

        // filterWebSearchablesHandler() has been called again since this
        // timeout was set, so ignore as another timeout will be along
        // shortly
        return;
    }

    var object = document.getElementById(objectId);
    var value = object.value;
    var filterAction = document.getElementById('filterAction' + '_' + scope + '_' + type).value;

    if ((value != null && value.length > 1) || (tags != null && tags.length > 1)) {
        function filterCallBack(cbResult) {
            var callId = cbResult[0];
            var filteredList = cbResult.slice(1);

            if (currentFilterCallbacks[scope + "_" + type] != callId) {
                // we've started another call since this one started, so
                // ignore this one
                return;
            }

            do_filtering(filteredList, scope, type);
        }

        $(scope + '_' + type + '_spinner').style.visibility = 'visible';
        currentFilterCallbacks[scope + "_" + type] = callId;
        var tagList = null;

        /*  can only be one of these options:
        1. favourite
        2. aspect:<aspect>
        3. aspect:<aspect>|favourite
        4. null
         */

        if(tags != null && tags.length > 1) {
	        tagList = new Array();
			if (tags.match("|")) {
	        	var a = new Array();

    	    	a = tags.split('|');
        		for (var i=0, l=a.length; i<l; ++i) {
        			tagList[i] = a[i];
        		}
        	} else {
        		tagList[0] = tags;
        	}
        }

        /*  filterAction toggles favourites off and on */
        AjaxServices.filterWebSearchables(scope, type, tagList, object.value, filterAction,
                                          callId++, filterCallBack);
    } else {
        showAll(scope, type);
    }

    futureFilterCalls[scope + "_" + type] = 0;
}

function filterFavourites(scope,type) {
    var id = 'filterAction_'+scope+'_'+type;
    var tags = '';

    // aspect selected
    if (document.getElementById(scope+'_'+type+'_filter_aspect').value != '') {
    	tags = 'aspect:'+document.getElementById(scope+'_'+type+'_filter_aspect').value;
    }
    // favourites OFF
    if(document.getElementById(id).value == "favourites") {
        document.getElementById(id).value = "";
        document.getElementById('filter_favourites_'+scope+'_'+type).src = 'images/filter_favourites_ico.gif';
    // favourites ON
    } else {
        document.getElementById(id).value = "favourites";
        document.getElementById('filter_favourites_'+scope+'_'+type).src = 'images/filter_favourites_act_ico.gif';
        tags = (tags == '' ? 'favourite' : tags + '|favourite');
    }
    return filterWebSearchablesHandler(null,document.getElementById(scope+'_'+type+'_filter_text'),
    								   scope, type, tags);
}

function filterAspect(scope,type) {
	var tags = null;
	var id = 'filterAction_'+scope+'_'+type;
	var aspect = document.getElementById(scope+'_'+type+'_filter_aspect').value;

	// filter by favourites
    if(document.getElementById(id).value == "favourites") {
    	tags = 'favourite';
    }

    // aspects ON
    if(aspect != null && aspect.length > 1) {
        aspect = 'aspect:'+ aspect;
        tags = (tags == 'favourite' ? tags + '|' + aspect : aspect);
    }

    return filterWebSearchablesHandler(null,document.getElementById(scope+'_'+type+'_filter_text'),
                                       scope, type, tags);
}

<commit_msg>Fixed typo from previous check-in.<commit_after>function setFavourite(name, type, image){
    AjaxServices.setFavourite(name, type);
    image.src='images/star_active.gif';
    image.onclick='';
    image.style.cursor='';
    image.title='This is a favourite';
}

function precomputeTemplate(templateName){
    document.getElementById('precompute_'+templateName).innerHTML="Precomputing..";
    AjaxServices.preCompute(templateName,function(str) {
        document.getElementById('precompute_'+templateName).style.color="#777";
        document.getElementById('precompute_'+templateName).innerHTML="Precomputed";
     });
}

function summariseTemplate(templateName){
    document.getElementById('summarise_'+templateName).innerHTML="Summarising..";
    AjaxServices.summarise(templateName,function(str) {
        document.getElementById('summarise_'+templateName).style.color="#777";
        document.getElementById('summarise_'+templateName).innerHTML="Summarised";
    });
}

function editName(name){
  document.getElementById('form_'+name).style.display="block";
  document.getElementById('name_'+name).style.display="none";
}

function renameElement(name, type, index){
    document.getElementById('form_'+name).style.display="none";
    document.getElementById('name_'+name).innerHTML="saving...";
    document.getElementById('name_'+name).style.display="block";
    AjaxServices.rename(name,type, (document.getElementById('newName_'+name).value).replace(/^\s*|\s*$/g,""), function(str){
        document.getElementById('name_'+name).innerHTML=str;
        document.getElementById('selected_user_' + type + '_' + index).value=str;
    });
}

function changeViewPathDescription(pathName){
    var pathString = pathName.replace(/\@sep\@/g,".");
    var pathEnd = pathString.substring(pathString.lastIndexOf('.') + 1);
    document.getElementById('form_'+pathName).style.display = "none";
    document.getElementById('name_'+pathName+'_inner').innerHTML = "saving...";
    document.getElementById('name_'+pathName).style.display = "block";
    var newDescription = document.getElementById('newName_' + pathName).value;
    var callBack = function(prefixDescription){
        if (prefixDescription == null) {
            prefixDescription = '(no description)';
        }
        document.getElementById('name_' + pathName + '_inner').innerHTML =
          '' + prefixDescription +
          ' > ' + pathEnd;
    }
    AjaxServices.changeViewPathDescription(pathString, newDescription, callBack);
}

function saveBagDescription(bagName){
    var textarea = document.getElementById('textarea').value;
    textarea = textarea.replace(/[\n\r]+/g, "\n\r
");
    document.getElementById('bagDescriptionDiv').innerHTML = 'Saving...';
    AjaxServices.saveBagDescription(bagName,textarea, function(str){
        document.getElementById('bagDescriptionDiv').innerHTML = str;
    });
    swapDivs('bagDescriptionTextarea','bagDescriptionDiv');
}

function swapDivs(div1,div2){
    document.getElementById(div1).style.display = 'none';
    document.getElementById(div2).style.display = 'block';
}

function roundToSignificantDecimal(n) {
    var log10n = Math.log(Math.abs(n)) / Math.log(10);
    if(log10n<1 && n!=0) {
        var rf = 100*Math.pow(10,-Math.round(log10n));
        return rf;
    } else return 100;
}

function updateCountInColumnSummary() {
    var countString = document.resultsCountText;
    if (countString == null) {
        setTimeout("updateCountInColumnSummary()", 1000);
        return;
    }

    document.getElementById('summary_row_count').innerHTML = "
" + countString + "
";

    var est = document.getElementById('resultsCountEstimate');
    if (est == null || est.style.display != 'none') {
        setTimeout("updateCountInColumnSummary()", 500);
        return;
    }
}

function updateUniqueCountInColumnSummary(uniqueCountQid) {
    getResults(uniqueCountQid, 1000, resultsCountCallback, null);
}

function resultsCountCallback(results) {
    var size = results[0][0];

    if (size > 1) {
        var summaryUniqueCountElement = document.getElementById('summary_unique_count');
        summaryUniqueCountElement.style.display='inline';
        summaryUniqueCountElement.innerHTML='Total unique values: ' + size;
    }
    return true;
}

function getColumnSummary(tableName, columnName, columnDisplayName) {
    document.getElementById('summary_loaded').style.display = "none";
    document.getElementById('summary_loading').style.display = "block";
    Effect.Appear('summary', { duration: 0.30 });
    AjaxServices.getColumnSummary(tableName, columnName, function(str){
        var rows = str[0];
        function rounder(cell) {
            if (cell==null) {
                return "[no value]" ;
            } if (! isNaN(cell)) {
                var rf = roundToSignificantDecimal(cell+0);
                return Math.round(cell*rf)/rf;
            } else {
                return cell;
            }
        }
        var headerText;
        if(rows[0].length == 2){
            headerText = '
Value	Count
';
        } else {
            headerText = '
Min	Max	Sample Mean	Standard Deviation
';
        }

        document.getElementById('summary_loading').style.display = "none";
        document.getElementById('summary_loaded').style.display = "block";

        var bodyText = '';

        for (rowIndex = 0; rowIndex < rows.length; rowIndex++) {
            var row = rows[rowIndex];
            bodyText += '
';
            for (colIndex = 0; colIndex < row.length; colIndex++) {
                var cellValue = rounder(row[colIndex]);
                bodyText += '' + cellValue + '	';
            }
            bodyText += '
';
        }

        var html = '
                                         \

                                     \
                        Column Summary for ' + columnDisplayName + '          \

                                                  \

                      \

                   \

                                                   \

 \

' + headerText +'
    \

' + bodyText + '
    \

                                                \

';

        var summaryLoadedElement = document.getElementById('summary_loaded');
        summaryLoadedElement.innerHTML = html;
        var uniqueCountQid = str[1];
        setTimeout("updateCountInColumnSummary()", 200);
        setTimeout("updateUniqueCountInColumnSummary(" + uniqueCountQid + ")", 300);
    });
}

function getResultsPoller(qid, timeout, userCallback, userData) {
    var callback = function(results) {
        if (results == null) {
            // try again
            getResults(qid, timeout, userCallback, userData);
        } else {
            if (!userCallback(results, userData)) {
                getResults(qid, timeout, userCallback, userData);
            }
        }
    }

    AjaxServices.getResults(qid, callback);
}

function getResults(qid, timeout, userCallback, userData) {
    setTimeout("getResultsPoller(" + qid + ", " + timeout + ", " + userCallback + ","
               + userData + ")", timeout);
}

// delete all the child nodes of the node given by parentElement and create a child
// element of type childTag, setting the text in the new child element to be
// childText
function setChild(parentElement, childText, childTag) {
    var newChild = document.createElement(childTag);
    newChild.innerHTML = childText;
    if (parentElement.firstChild != null) {
        while (parentElement.hasChildNodes()) {
            parentElement.removeChild(parentElement.firstChild);
        }
    }
    parentElement.appendChild(newChild);
    return newChild;
}

var callId = 1;

// Give each ajax call an id and remember what our current pending id is
var currentFilterCallbacks = new Array();

// Give each setTimeout call an id and remember what our current pending id is
var futureFilterCalls = new Array();

function filterWebSearchablesHandler(event, object, scope, type, tags) {
    if (window.event) {
        event = window.event;
    }
    if (event) {
	    if (event.keyCode == 27) {
	        object.value = '';
	        return;
	    }
	    if (event.keyCode == 13) {
	        return;
	    }
	}

    futureFilterCalls[scope + "_" + type] = callId;

    if (tags == null) {
        tags = [];
    }

    setTimeout('filterWebSearchables("' + object.id + '", "' + scope + '","' + type + '",' +
               callId + ",'" + tags + "')", 500);
    callId++;
}

// given a list of WebSearchables names,scores and descriptions, filter the
// wsFilterList given by the scope and type parameters
function do_filtering(filteredList, scope, type) {
    if (filteredList.length == 0) {
        showAll(scope, type);
    } else {
        var scoreHash = new Array();
        var descHash = new Array();
        var hitHash = new Array();

        for (var el in filteredList) {
            var wsName = filteredList[el][0];
            var wsDesc = filteredList[el][1];
            descHash[scope + '_' + type + '_item_line_' + wsName] = wsDesc;
            var wsScore = filteredList[el][2];
            scoreHash[scope + '_' + type + '_item_line_' + wsName] = wsScore;
            hitHash[scope + '_' + type + '_item_line_' + wsName] = 1;
        }

        var pattern = new RegExp('^' + scope + '_' + type + '_item_line_(.*)');
        var inputArray = document.getElementsByTagName("div");
        for(var i=0; i<inputArray.length; i++) {
            if ((result = pattern.exec(inputArray[i].id)) != null) {
                if (hitHash[inputArray[i].id]) {
                    inputArray[i].style.display='block';
                    var highlightText = descHash[inputArray[i].id];

                    if (highlightText) {
                        var descId = scope + '_' + type + '_item_description_' + result[1];
                        var desc = $(descId);

                        var descChild = setChild(desc, highlightText, 'p');
                        descChild.className = 'description';
                    }

                    if (scoreHash[inputArray[i].id]) {
                        var scoreWsName = result[1];
                        var score = scoreHash[inputArray[i].id];
                        var intScore = parseInt(score * 10);
                        var scoreId = scope + '_' + type + '_item_score_' + scoreWsName;
                        var scoreSpan = $(scoreId);
                        // we do this instead of scoreSpan.innerHTML = "stuff"
                        // because it's buggy in Internet Explorer
                        var heatImage = 'heat' + intScore + '.gif';
                        var heatText = '';
                        setChild(scoreSpan, heatText, 'span');
                    }
                } else {
                    inputArray[i].style.display='none';
                }
            }
        }

        function sortWsFilter(el1, el2) {
            var el1score = scoreHash[el1.id];
            var el2score = scoreHash[el2.id]
                if (el1score > el2score) {
                    return -1;
                } else {
                    if (el1score < el2score) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
        }

        var parent = $(scope + '_' + type + '_ws_list');
        var divs = new Array();

        for (var i in parent.childNodes) {
            var child = parent.childNodes[i];
            if (child.tagName == 'DIV' && scoreHash[child.id]) {
                divs.push(child);
            }
        }

        divs.sort(sortWsFilter);

        for (var i = 0; i < divs.length; i++) {
            parent.appendChild(divs[i]);
        }

        $(scope + '_' + type + '_spinner').style.visibility = 'hidden';
    }
}

// un-hide all the rows in the webSearchableList
function showAll(scope, type) {
    var pattern = new RegExp('^' + scope + '_' + type + '_item_line_(.*)');
    var inputArray = document.getElementsByTagName("div");
    for(var i=0; i<inputArray.length; i++) {
        var result;
        if ((result = pattern.exec(inputArray[i].id)) != null) {
            inputArray[i].style.display='block';
        }
    }
    $(scope + '_' + type + '_spinner').style.visibility = 'hidden';
}

// call AjaxServices.filterWebSearchables() then hide those WebSearchables in
// the webSearchableList that don't match
function filterWebSearchables(objectId, scope, type, callId, tags) {
    if (futureFilterCalls[scope + "_" + type] != callId) {
        // filterWebSearchablesHandler() has been called again since this
        // timeout was set, so ignore as another timeout will be along
        // shortly
        return;
    }

    var object = document.getElementById(objectId);
    var value = object.value;
    var filterAction = document.getElementById('filterAction' + '_' + scope + '_' + type).value;

    if ((value != null && value.length > 1) || (tags != null && tags.length > 1)) {
        function filterCallBack(cbResult) {
            var callId = cbResult[0];
            var filteredList = cbResult.slice(1);

            if (currentFilterCallbacks[scope + "_" + type] != callId) {
                // we've started another call since this one started, so
                // ignore this one
                return;
            }

            do_filtering(filteredList, scope, type);
        }

        $(scope + '_' + type + '_spinner').style.visibility = 'visible';
        currentFilterCallbacks[scope + "_" + type] = callId;
        var tagList = null;

        /*  can only be one of these options:
        1. favourite
        2. aspect:<aspect>
        3. aspect:<aspect>|favourite
        4. null
         */

        if(tags != null && tags.length > 1) {
	        tagList = new Array();
			if (tags.match("|")) {
	        	var a = new Array();

    	    	a = tags.split('|');
        		for (var i=0, l=a.length; i<l; ++i) {
        			tagList[i] = a[i];
        		}
        	} else {
        		tagList[0] = tags;
        	}
        }

        /*  filterAction toggles favourites off and on */
        AjaxServices.filterWebSearchables(scope, type, tagList, object.value, filterAction,
                                          callId++, filterCallBack);
    } else {
        showAll(scope, type);
    }

    futureFilterCalls[scope + "_" + type] = 0;
}

function filterFavourites(scope,type) {
    var id = 'filterAction_'+scope+'_'+type;
    var tags = '';

    // aspect selected
    if (document.getElementById(scope+'_'+type+'_filter_aspect').value != '') {
    	tags = 'aspect:'+document.getElementById(scope+'_'+type+'_filter_aspect').value;
    }
    // favourites OFF
    if(document.getElementById(id).value == "favourites") {
        document.getElementById(id).value = "";
        document.getElementById('filter_favourites_'+scope+'_'+type).src = 'images/filter_favourites_ico.gif';
    // favourites ON
    } else {
        document.getElementById(id).value = "favourites";
        document.getElementById('filter_favourites_'+scope+'_'+type).src = 'images/filter_favourites_act_ico.gif';
        tags = (tags == '' ? 'favourite' : tags + '|favourite');
    }
    return filterWebSearchablesHandler(null,document.getElementById(scope+'_'+type+'_filter_text'),
    								   scope, type, tags);
}

function filterAspect(scope,type) {
	var tags = null;
	var id = 'filterAction_'+scope+'_'+type;
	var aspect = document.getElementById(scope+'_'+type+'_filter_aspect').value;

	// filter by favourites
    if(document.getElementById(id).value == "favourites") {
    	tags = 'favourite';
    }

    // aspects ON
    if(aspect != null && aspect.length > 1) {
        aspect = 'aspect:'+ aspect;
        tags = (tags == 'favourite' ? tags + '|' + aspect : aspect);
    }

    return filterWebSearchablesHandler(null,document.getElementById(scope+'_'+type+'_filter_text'),
                                       scope, type, tags);
}

<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.ui.form");

frappe.ui.form.AssignTo = Class.extend({
	init: function(opts) {
		var me = this;

		$.extend(this, opts);
		this.btn = this.parent.find(".add-assignment").on("click", function() { me.add(); });
		this.btn_wrapper = this.btn.parent();

		this.refresh();
	},
	refresh: function() {
		if(this.frm.doc.__islocal) {
			this.parent.toggle(false);
			return;
		}
		this.parent.toggle(true);
		this.render(this.frm.get_docinfo().assignments);
	},
	render: function(d) {
		var me = this;
		this.frm.get_docinfo().assignments = d;
		this.parent.find(".assignment-row").remove();

		if(me.primary_action) {
			me.primary_action.remove();
			me.primary_action = null;
		}

		if(this.dialog) {
			this.dialog.hide();
		}

		if(d && d.length) {
			for(var i=0; i<d.length; i++) {
				var info = frappe.user_info(d[i].owner);
				info.assign_to_name = d[i].name
				info.owner = d[i].owner;
				info.avatar = frappe.avatar(d[i].owner);
				info.description = d[i].description || "";

				info._fullname = info.fullname;
				if(info.fullname.length > 10) {
					info._fullname = info.fullname.substr(0, 10) + '...';
				}

				$(repl('
\
					×\
					%(avatar)s\
					%(_fullname)s\

', info))
					.insertBefore(this.parent.find('.add-assignment'));

				if(d[i].owner===frappe.session.user) {
					me.primary_action = this.frm.page.add_menu_item(__("Assignment Complete"), function() {
						me.remove(frappe.session.user);
					}, "fa fa-check", "btn-success")
				}

				if(!(d[i].owner === frappe.session.user || me.frm.perm[0].write)) {
					me.parent.find('a.close').remove();
				}
			}

			// set remove
			this.parent.find('a.close').click(function() {
				me.remove($(this).attr('data-owner'));
				return false;
			});

			//this.btn_wrapper.addClass("hide");
		} else {
			//this.btn_wrapper.removeClass("hide");
		}
	},
	add: function() {
		var me = this;

		if(this.frm.is_new()) {
			frappe.throw(__("Please save the document before assignment"));
			return;
		}

		if(!me.assign_to) {
			me.assign_to = new frappe.ui.form.AssignToDialog({
				obj: me,
				method: 'frappe.desk.form.assign_to.add',
				doctype: me.frm.doctype,
				docname: me.frm.docname,
				callback: function(r) {
					me.render(r.message);
				}
			});
		}
		me.assign_to.dialog.clear();

		if(me.frm.meta.title_field) {
			me.assign_to.dialog.set_value("description", me.frm.doc[me.frm.meta.title_field])
		}

		me.assign_to.dialog.show();
	},
	remove: function(owner) {
		var me = this;

		if(this.frm.is_new()) {
			frappe.throw(__("Please save the document before removing assignment"));
			return;
		}

		frappe.call({
			method:'frappe.desk.form.assign_to.remove',
			args: {
				doctype: me.frm.doctype,
				name: me.frm.docname,
				assign_to: owner
			},
			callback:function(r,rt) {
				me.render(r.message);
			}
		});
	}
});

frappe.ui.form.AssignToDialog = Class.extend({
	init: function(opts){
		var me = this
		var dialog = new frappe.ui.Dialog({
			title: __('Add to To Do'),
			fields: [
				{fieldtype: 'Link', fieldname:'assign_to', options:'User',
					label:__("Assign To"), reqd:true, filters: {'user_type': 'System User'}},
				{fieldtype:'Check', fieldname:'myself', label:__("Assign to me"), "default":0},
				{fieldtype:'Small Text', fieldname:'description', label:__("Comment")},
				{fieldtype: 'Section Break'},
				{fieldtype: 'Column Break'},
				{fieldtype:'Date', fieldname:'date', label: __("Complete By")},
				{fieldtype:'Check', fieldname:'notify',
					label:__("Notify by Email")},
				{fieldtype: 'Column Break'},
				{fieldtype:'Select', fieldname:'priority', label: __("Priority"),
					options:[
						{value:'Low', label:__('Low')},
						{value:'Medium', label:__('Medium')},
						{value:'High', label:__('High')}],
					'default':'Medium'},
			],
			primary_action: function() { frappe.ui.add_assignment(opts, me) },
			primary_action_label: __("Add")
		})
		$.extend(me, dialog);

		me.dialog = dialog;

		me.dialog.fields_dict.assign_to.get_query = "frappe.core.doctype.user.user.user_query";

		var myself = me.dialog.get_input("myself").on("click", function() {
			me.toggle_myself(this);
		});
		me.toggle_myself(myself);
	},
	toggle_myself: function(myself) {
		var me = this;
		if($(myself).prop("checked")) {
			me.dialog.set_value("assign_to", frappe.session.user);
			me.dialog.set_value("notify", 0);
			me.dialog.get_field("notify").$wrapper.toggle(false);
			me.dialog.get_field("assign_to").$wrapper.toggle(false);
		} else {
			me.dialog.set_value("assign_to", "");
			me.dialog.get_field("notify").$wrapper.toggle(true);
			me.dialog.get_field("assign_to").$wrapper.toggle(true);
		}
	},

});

frappe.ui.add_assignment = function(opts, dialog) {
	var assign_to = dialog.fields_dict.assign_to.get_value();
	var args = dialog.get_values();
	if(args && assign_to) {
		return frappe.call({
			method: opts.method,
			args: $.extend(args, {
				doctype: opts.doctype,
				name: opts.docname,
				assign_to: assign_to,
				bulk_assign:  opts.bulk_assign || false,
				re_assign: opts.re_assign || false
			}),
			callback: function(r,rt) {
				if(!r.exc) {
					if(opts.callback){
						opts.callback(r);
					}
					dialog && dialog.hide();
				}
			},
			btn: this
		});
	}
}
<commit_msg>fix: Hide dialog after assignment (#6696)<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.ui.form");

frappe.ui.form.AssignTo = Class.extend({
	init: function(opts) {
		var me = this;

		$.extend(this, opts);
		this.btn = this.parent.find(".add-assignment").on("click", function() { me.add(); });
		this.btn_wrapper = this.btn.parent();

		this.refresh();
	},
	refresh: function() {
		if(this.frm.doc.__islocal) {
			this.parent.toggle(false);
			return;
		}
		this.parent.toggle(true);
		this.render(this.frm.get_docinfo().assignments);
	},
	render: function(d) {
		var me = this;
		this.frm.get_docinfo().assignments = d;
		this.parent.find(".assignment-row").remove();

		if(me.primary_action) {
			me.primary_action.remove();
			me.primary_action = null;
		}

		if(this.dialog) {
			this.dialog.hide();
		}

		if(d && d.length) {
			for(var i=0; i<d.length; i++) {
				var info = frappe.user_info(d[i].owner);
				info.assign_to_name = d[i].name
				info.owner = d[i].owner;
				info.avatar = frappe.avatar(d[i].owner);
				info.description = d[i].description || "";

				info._fullname = info.fullname;
				if(info.fullname.length > 10) {
					info._fullname = info.fullname.substr(0, 10) + '...';
				}

				$(repl('
\
					×\
					%(avatar)s\
					%(_fullname)s\

', info))
					.insertBefore(this.parent.find('.add-assignment'));

				if(d[i].owner===frappe.session.user) {
					me.primary_action = this.frm.page.add_menu_item(__("Assignment Complete"), function() {
						me.remove(frappe.session.user);
					}, "fa fa-check", "btn-success")
				}

				if(!(d[i].owner === frappe.session.user || me.frm.perm[0].write)) {
					me.parent.find('a.close').remove();
				}
			}

			// set remove
			this.parent.find('a.close').click(function() {
				me.remove($(this).attr('data-owner'));
				return false;
			});

			//this.btn_wrapper.addClass("hide");
		} else {
			//this.btn_wrapper.removeClass("hide");
		}
	},
	add: function() {
		var me = this;

		if(this.frm.is_new()) {
			frappe.throw(__("Please save the document before assignment"));
			return;
		}

		if(!me.assign_to) {
			me.assign_to = new frappe.ui.form.AssignToDialog({
				obj: me,
				method: 'frappe.desk.form.assign_to.add',
				doctype: me.frm.doctype,
				docname: me.frm.docname,
				callback: function(r) {
					me.render(r.message);
				}
			});
		}
		me.assign_to.dialog.clear();

		if(me.frm.meta.title_field) {
			me.assign_to.dialog.set_value("description", me.frm.doc[me.frm.meta.title_field])
		}

		me.assign_to.dialog.show();
	},
	remove: function(owner) {
		var me = this;

		if(this.frm.is_new()) {
			frappe.throw(__("Please save the document before removing assignment"));
			return;
		}

		frappe.call({
			method:'frappe.desk.form.assign_to.remove',
			args: {
				doctype: me.frm.doctype,
				name: me.frm.docname,
				assign_to: owner
			},
			callback:function(r,rt) {
				me.render(r.message);
			}
		});
	}
});

frappe.ui.form.AssignToDialog = Class.extend({
	init: function(opts){
		var me = this
		var dialog = new frappe.ui.Dialog({
			title: __('Add to To Do'),
			fields: [
				{fieldtype: 'Link', fieldname:'assign_to', options:'User',
					label:__("Assign To"), reqd:true, filters: {'user_type': 'System User'}},
				{fieldtype:'Check', fieldname:'myself', label:__("Assign to me"), "default":0},
				{fieldtype:'Small Text', fieldname:'description', label:__("Comment")},
				{fieldtype: 'Section Break'},
				{fieldtype: 'Column Break'},
				{fieldtype:'Date', fieldname:'date', label: __("Complete By")},
				{fieldtype:'Check', fieldname:'notify',
					label:__("Notify by Email")},
				{fieldtype: 'Column Break'},
				{fieldtype:'Select', fieldname:'priority', label: __("Priority"),
					options:[
						{value:'Low', label:__('Low')},
						{value:'Medium', label:__('Medium')},
						{value:'High', label:__('High')}],
					'default':'Medium'},
			],
			primary_action: function() { frappe.ui.add_assignment(opts, this) },
			primary_action_label: __("Add")
		})
		$.extend(me, dialog);

		me.dialog = dialog;

		me.dialog.fields_dict.assign_to.get_query = "frappe.core.doctype.user.user.user_query";

		var myself = me.dialog.get_input("myself").on("click", function() {
			me.toggle_myself(this);
		});
		me.toggle_myself(myself);
	},
	toggle_myself: function(myself) {
		var me = this;
		if($(myself).prop("checked")) {
			me.dialog.set_value("assign_to", frappe.session.user);
			me.dialog.set_value("notify", 0);
			me.dialog.get_field("notify").$wrapper.toggle(false);
			me.dialog.get_field("assign_to").$wrapper.toggle(false);
		} else {
			me.dialog.set_value("assign_to", "");
			me.dialog.get_field("notify").$wrapper.toggle(true);
			me.dialog.get_field("assign_to").$wrapper.toggle(true);
		}
	},

});

frappe.ui.add_assignment = function(opts, dialog) {
	var assign_to = dialog.fields_dict.assign_to.get_value();
	var args = dialog.get_values();
	if(args && assign_to) {
		return frappe.call({
			method: opts.method,
			args: $.extend(args, {
				doctype: opts.doctype,
				name: opts.docname,
				assign_to: assign_to,
				bulk_assign:  opts.bulk_assign || false,
				re_assign: opts.re_assign || false
			}),
			callback: function(r,rt) {
				if(!r.exc) {
					if(opts.callback){
						opts.callback(r);
					}
					dialog && dialog.hide();
				}
			},
			btn: this
		});
	}
}
<|endoftext|>


<commit_before>/*****************************************************************************/
/* SupplementaryLeaveCreate: Event Handlers */
/*****************************************************************************/
import Ladda from 'ladda';
import _ from 'underscore';

Template.SupplementaryLeaveCreate.events({
    'click #TaxButton': (e, tmpl) => {
        event.preventDefault();
        let newTaxRuleName = $('[name="name"]').val();

        if(!newTaxRuleName || newTaxRuleName.trim().length < 1) {
            swal("Validation error", `Please enter a valid name`, "error");
            return;
        }
        let businessId = Session.get('context')
        //--
        let l = Ladda.create(tmpl.$('#TaxButton')[0]);
        l.start();
        //--
        let numberOfLeaveDays =  $('[name="numberOfLeaveDays"]').val()
        let numberOfLeaveDaysAsNumber = parseFloat(numberOfLeaveDays)

        let details = {
            businessId: businessId,
            name: $('[name="name"]').val(),
            numberOfLeaveDays: !isNaN(numberOfLeaveDaysAsNumber) ? numberOfLeaveDaysAsNumber : 0,
            employees: Core.returnSelection($('[name="employee"]')),
        };

        if(tmpl.data){//edit action for updating tax
            const tId = tmpl.data._id;
            const code = tmpl.data.code;
            Meteor.call("supplementaryLeave/update", tId, details, (err, res) => {
                l.stop();
                if(err){
                    swal("Update Failed", `Cannot update Leave Balance`, "error");
                } else {
                    swal("Successful Update!", `Leave Balance was updated successfully`, "success");
                    Modal.hide("TaxCreate");
                }
            });
        } else{ //New Action for creating paytype}
            Meteor.call('supplementaryLeave/create', details, (err, res) => {
                l.stop();
                if (res){
                    Modal.hide('SupplementaryLeaveCreate');
                    swal({
                        title: "Success",
                        text: `Leave Balance created`,
                        confirmButtonClass: "btn-success",
                        type: "success",
                        confirmButtonText: "OK"
                    });
                } else {
                    err = JSON.parse(err.details);

                    _.each(err, (obj) => {
                        $('[name=' + obj.name +']').addClass('errorValidation');
                        $('[name=' + obj.name +']').attr("placeholder", obj.name + ' ' + obj.type);
                    })
                }
            });
        }
    },
    'click #deleteTax': (e, tmpl) => {
        event.preventDefault();
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover from this",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes, delete it!",
            closeOnConfirm: false
        }, () => {
            //call backend method to delete the tax
            const ptId = tmpl.data._id;

            Meteor.call('supplementaryLeave/delete', ptId, (err, res) => {
                if(!err){
                    swal("Deleted!", `Delete successful`, "success");
                    Modal.hide("SupplementaryLeaveCreate");
                }
            });

        });
    }
});

/*****************************************************************************/
/* SupplementaryLeaveCreate: Helpers */
/*****************************************************************************/
Template.registerHelper('equals',(a,b)=>{
  return a == b;
});

Template.SupplementaryLeaveCreate.helpers({
    selected(context, val) {
        if(Template.instance().data){
            return Template.instance().data[context] === val ? selected="selected" : '';
        }
    },
    isSelected(context, val) {
        if(Template.instance().data){
            return Template.instance().data[context] === val ? true : false;
        }
    },
    selectedObj: function (x) {
        if(Template.instance().data){
            let self = this;
            let selected;
            let prop = Template.instance().data[x];
            selected = _.find(prop, function(r) {
                return r ===  self._id;
            });
            if (selected){
                return "selected"
            }
        }
    },
    modalHeaderTitle: function() {
      return Template.instance().data.modalHeaderTitle || "New Leave Balance";
    },
    edit() {
        return Template.instance().data ? true : false
    },
    employees: () => {
        return Meteor.users.find({"employee": true});
    }
});

/*****************************************************************************/
/* SupplementaryLeaveCreate: Lifecycle Hooks */
/*****************************************************************************/
Template.SupplementaryLeaveCreate.onCreated(function () {
    let self = this
    let businessUnitId = Session.get('context');

    self.subscribe("allEmployees", businessUnitId);
    //--
    this.dict = new ReactiveDict();

    //--
    if(self.data){

    } else {

    }

    self.autorun(function() {
        if (Template.instance().subscriptionsReady()){
            self.paytypes.set(PayTypes.find({'status': 'Active'}).fetch())
        }
    })
});

Template.SupplementaryLeaveCreate.onRendered(function () {
    let self = this;
    self.$('select.dropdown').dropdown();
});

Template.SupplementaryLeaveCreate.onDestroyed(function () {
});
<commit_msg>leave balance modal header text<commit_after>/*****************************************************************************/
/* SupplementaryLeaveCreate: Event Handlers */
/*****************************************************************************/
import Ladda from 'ladda';
import _ from 'underscore';

Template.SupplementaryLeaveCreate.events({
    'click #TaxButton': (e, tmpl) => {
        event.preventDefault();
        let newTaxRuleName = $('[name="name"]').val();

        if(!newTaxRuleName || newTaxRuleName.trim().length < 1) {
            swal("Validation error", `Please enter a valid name`, "error");
            return;
        }
        let businessId = Session.get('context')
        //--
        let l = Ladda.create(tmpl.$('#TaxButton')[0]);
        l.start();
        //--
        let numberOfLeaveDays =  $('[name="numberOfLeaveDays"]').val()
        let numberOfLeaveDaysAsNumber = parseFloat(numberOfLeaveDays)

        let details = {
            businessId: businessId,
            name: $('[name="name"]').val(),
            numberOfLeaveDays: !isNaN(numberOfLeaveDaysAsNumber) ? numberOfLeaveDaysAsNumber : 0,
            employees: Core.returnSelection($('[name="employee"]')),
        };

        if(tmpl.data){//edit action for updating tax
            const tId = tmpl.data._id;
            const code = tmpl.data.code;
            Meteor.call("supplementaryLeave/update", tId, details, (err, res) => {
                l.stop();
                if(err){
                    swal("Update Failed", `Cannot update Leave Balance`, "error");
                } else {
                    swal("Successful Update!", `Leave Balance was updated successfully`, "success");
                    Modal.hide("TaxCreate");
                }
            });
        } else{ //New Action for creating paytype}
            Meteor.call('supplementaryLeave/create', details, (err, res) => {
                l.stop();
                if (res){
                    Modal.hide('SupplementaryLeaveCreate');
                    swal({
                        title: "Success",
                        text: `Leave Balance created`,
                        confirmButtonClass: "btn-success",
                        type: "success",
                        confirmButtonText: "OK"
                    });
                } else {
                    err = JSON.parse(err.details);

                    _.each(err, (obj) => {
                        $('[name=' + obj.name +']').addClass('errorValidation');
                        $('[name=' + obj.name +']').attr("placeholder", obj.name + ' ' + obj.type);
                    })
                }
            });
        }
    },
    'click #deleteTax': (e, tmpl) => {
        event.preventDefault();
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover from this",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes, delete it!",
            closeOnConfirm: false
        }, () => {
            //call backend method to delete the tax
            const ptId = tmpl.data._id;

            Meteor.call('supplementaryLeave/delete', ptId, (err, res) => {
                if(!err){
                    swal("Deleted!", `Delete successful`, "success");
                    Modal.hide("SupplementaryLeaveCreate");
                }
            });

        });
    }
});

/*****************************************************************************/
/* SupplementaryLeaveCreate: Helpers */
/*****************************************************************************/
Template.registerHelper('equals',(a,b)=>{
  return a == b;
});

Template.SupplementaryLeaveCreate.helpers({
    selected(context, val) {
        if(Template.instance().data){
            return Template.instance().data[context] === val ? selected="selected" : '';
        }
    },
    isSelected(context, val) {
        if(Template.instance().data){
            return Template.instance().data[context] === val ? true : false;
        }
    },
    selectedObj: function (x) {
        if(Template.instance().data){
            let self = this;
            let selected;
            let prop = Template.instance().data[x];
            selected = _.find(prop, function(r) {
                return r ===  self._id;
            });
            if (selected){
                return "selected"
            }
        }
    },
    modalHeaderTitle: function() {
    //   return Template.instance().data.modalHeaderTitle || "New Leave Balance";
      return "Leave Balance";
    },
    edit() {
        return Template.instance().data ? true : false
    },
    employees: () => {
        return Meteor.users.find({"employee": true});
    }
});

/*****************************************************************************/
/* SupplementaryLeaveCreate: Lifecycle Hooks */
/*****************************************************************************/
Template.SupplementaryLeaveCreate.onCreated(function () {
    let self = this
    let businessUnitId = Session.get('context');

    self.subscribe("allEmployees", businessUnitId);
    //--
    this.dict = new ReactiveDict();

    //--
    if(self.data){

    } else {

    }

    self.autorun(function() {
        if (Template.instance().subscriptionsReady()){
            self.paytypes.set(PayTypes.find({'status': 'Active'}).fetch())
        }
    })
});

Template.SupplementaryLeaveCreate.onRendered(function () {
    let self = this;
    self.$('select.dropdown').dropdown();
});

Template.SupplementaryLeaveCreate.onDestroyed(function () {
});
<|endoftext|>


<commit_before>'use strict';
import ReactDOM from 'react-dom';

var checkSpecKeys = function (spec, keysArray) {
  return keysArray.reduce((value, key) => {
    return value && spec.hasOwnProperty(key);
  }, true) ? null : console.error('Keys Missing', spec);
};

export var getTrackCSS = function(spec) {
  checkSpecKeys(spec, [
    'left', 'variableWidth', 'slideCount', 'slidesToShow', 'slideWidth'
  ]);

  var trackWidth;

  if (spec.variableWidth) {
    trackWidth = (spec.slideCount + 2*spec.slidesToShow) * spec.slideWidth;
  } else if (spec.centerMode) {
    trackWidth = (spec.slideCount + 2*(spec.slidesToShow + 1)) * spec.slideWidth;
  } else {
    trackWidth = (spec.slideCount + 2*spec.slidesToShow) * spec.slideWidth;
  }

  var style = {
    opacity: 1,
    width: trackWidth,
    WebkitTransform: 'translate3d(' + spec.left + 'px, 0px, 0px)',
    transform: 'translate3d(' + spec.left + 'px, 0px, 0px)',
    transition: '',
    WebkitTransition: '',
    msTransform: 'translateX(' + spec.left + 'px)'
  };

  // Fallback for IE8
  if (window && !window.addEventListener && window.attachEvent) {
    style.marginLeft = spec.left + 'px';
  }

  return style;
};

export var getTrackAnimateCSS = function (spec) {
  checkSpecKeys(spec, [
    'left', 'variableWidth', 'slideCount', 'slidesToShow', 'slideWidth', 'speed', 'cssEase'
  ]);

  var style = getTrackCSS(spec);
  // useCSS is true by default so it can be undefined
  style.WebkitTransition = '-webkit-transform ' + spec.speed + 'ms ' + spec.cssEase;
  style.transition = 'transform ' + spec.speed + 'ms ' + spec.cssEase;
  return style;
};

export var getTrackLeft = function (spec) {

  checkSpecKeys(spec, [
   'slideIndex', 'trackRef', 'infinite', 'centerMode', 'slideCount', 'slidesToShow',
   'slidesToScroll', 'slideWidth', 'listWidth', 'variableWidth']);

  var slideOffset = 0;
  var targetLeft;
  var targetSlide;

  if (spec.fade) {
    return 0;
  }

  if (spec.infinite) {
    if (spec.slideCount > spec.slidesToShow) {
     slideOffset = (spec.slideWidth * spec.slidesToShow) * -1;
    }
    if (spec.slideCount % spec.slidesToScroll !== 0) {
      if (spec.slideIndex + spec.slidesToScroll > spec.slideCount && spec.slideCount > spec.slidesToShow) {
          if(spec.slideIndex > spec.slideCount) {
            slideOffset = ((spec.slidesToShow - (spec.slideIndex - spec.slideCount)) * spec.slideWidth) * -1;
          } else {
            slideOffset = ((spec.slideCount % spec.slidesToScroll) * spec.slideWidth) * -1;
          }
      }
    }
  } else {

    if (spec.slideCount % spec.slidesToScroll !== 0) {
      if (spec.slideIndex + spec.slidesToScroll > spec.slideCount && spec.slideCount > spec.slidesToShow) {
          var slidesToOffset = spec.slidesToShow - (spec.slideCount % spec.slidesToScroll);
          slideOffset = slidesToOffset * spec.slideWidth;
      }
    }
  }

  if (spec.centerMode) {
    if(spec.infinite) {
      slideOffset += spec.slideWidth * Math.floor(spec.slidesToShow / 2);
    } else {
      slideOffset = spec.slideWidth * Math.floor(spec.slidesToShow / 2);
    }
  }

  targetLeft = ((spec.slideIndex * spec.slideWidth) * -1) + slideOffset;

  if (spec.variableWidth === true) {
      var targetSlideIndex;
      if(spec.slideCount <= spec.slidesToShow || spec.infinite === false) {
          targetSlide = ReactDOM.findDOMNode(spec.trackRef).childNodes[spec.slideIndex];
      } else {
          targetSlideIndex = (spec.slideIndex + spec.slidesToShow);
          targetSlide = ReactDOM.findDOMNode(spec.trackRef).childNodes[targetSlideIndex];
      }
      targetLeft = targetSlide ? targetSlide.offsetLeft * -1 : 0;
      if (spec.centerMode === true) {
          if(spec.infinite === false) {
              targetSlide = ReactDOM.findDOMNode(spec.trackRef).children[spec.slideIndex];
          } else {
              targetSlide = ReactDOM.findDOMNode(spec.trackRef).children[(spec.slideIndex + spec.slidesToShow + 1)];
          }

          targetLeft = targetSlide ? targetSlide.offsetLeft * -1 : 0;
          targetLeft += (spec.listWidth - targetSlide.offsetWidth) / 2;
      }
  }

  return targetLeft;
};
<commit_msg>incorporated fix from #430<commit_after>'use strict';
import ReactDOM from 'react-dom';

var checkSpecKeys = function (spec, keysArray) {
  return keysArray.reduce((value, key) => {
    return value && spec.hasOwnProperty(key);
  }, true) ? null : console.error('Keys Missing', spec);
};

export var getTrackCSS = function(spec) {
  checkSpecKeys(spec, [
    'left', 'variableWidth', 'slideCount', 'slidesToShow', 'slideWidth'
  ]);

  var trackWidth;

  if (spec.variableWidth) {
    trackWidth = (spec.slideCount + 2*spec.slidesToShow) * spec.slideWidth;
  } else if (spec.centerMode) {
    trackWidth = (spec.slideCount + 2*(spec.slidesToShow + 1)) * spec.slideWidth;
  } else {
    trackWidth = (spec.slideCount + 2*spec.slidesToShow) * spec.slideWidth;
  }

  var style = {
    opacity: 1,
    width: trackWidth,
    WebkitTransform: 'translate3d(' + spec.left + 'px, 0px, 0px)',
    transform: 'translate3d(' + spec.left + 'px, 0px, 0px)',
    transition: '',
    WebkitTransition: '',
    msTransform: 'translateX(' + spec.left + 'px)'
  };

  // Fallback for IE8
  if (window && !window.addEventListener && window.attachEvent) {
    style.marginLeft = spec.left + 'px';
  }

  return style;
};

export var getTrackAnimateCSS = function (spec) {
  checkSpecKeys(spec, [
    'left', 'variableWidth', 'slideCount', 'slidesToShow', 'slideWidth', 'speed', 'cssEase'
  ]);

  var style = getTrackCSS(spec);
  // useCSS is true by default so it can be undefined
  style.WebkitTransition = '-webkit-transform ' + spec.speed + 'ms ' + spec.cssEase;
  style.transition = 'transform ' + spec.speed + 'ms ' + spec.cssEase;
  return style;
};

export var getTrackLeft = function (spec) {

  checkSpecKeys(spec, [
   'slideIndex', 'trackRef', 'infinite', 'centerMode', 'slideCount', 'slidesToShow',
   'slidesToScroll', 'slideWidth', 'listWidth', 'variableWidth']);

  var slideOffset = 0;
  var targetLeft;
  var targetSlide;

  if (spec.fade) {
    return 0;
  }

  if (spec.infinite) {
    if (spec.slideCount >= spec.slidesToShow) {
     slideOffset = (spec.slideWidth * spec.slidesToShow) * -1;
    }
    if (spec.slideCount % spec.slidesToScroll !== 0) {
      if (spec.slideIndex + spec.slidesToScroll > spec.slideCount && spec.slideCount > spec.slidesToShow) {
          if(spec.slideIndex > spec.slideCount) {
            slideOffset = ((spec.slidesToShow - (spec.slideIndex - spec.slideCount)) * spec.slideWidth) * -1;
          } else {
            slideOffset = ((spec.slideCount % spec.slidesToScroll) * spec.slideWidth) * -1;
          }
      }
    }
  } else {

    if (spec.slideCount % spec.slidesToScroll !== 0) {
      if (spec.slideIndex + spec.slidesToScroll > spec.slideCount && spec.slideCount > spec.slidesToShow) {
          var slidesToOffset = spec.slidesToShow - (spec.slideCount % spec.slidesToScroll);
          slideOffset = slidesToOffset * spec.slideWidth;
      }
    }
  }

  if (spec.centerMode) {
    if(spec.infinite) {
      slideOffset += spec.slideWidth * Math.floor(spec.slidesToShow / 2);
    } else {
      slideOffset = spec.slideWidth * Math.floor(spec.slidesToShow / 2);
    }
  }

  targetLeft = ((spec.slideIndex * spec.slideWidth) * -1) + slideOffset;

  if (spec.variableWidth === true) {
      var targetSlideIndex;
      if(spec.slideCount <= spec.slidesToShow || spec.infinite === false) {
          targetSlide = ReactDOM.findDOMNode(spec.trackRef).childNodes[spec.slideIndex];
      } else {
          targetSlideIndex = (spec.slideIndex + spec.slidesToShow);
          targetSlide = ReactDOM.findDOMNode(spec.trackRef).childNodes[targetSlideIndex];
      }
      targetLeft = targetSlide ? targetSlide.offsetLeft * -1 : 0;
      if (spec.centerMode === true) {
          if(spec.infinite === false) {
              targetSlide = ReactDOM.findDOMNode(spec.trackRef).children[spec.slideIndex];
          } else {
              targetSlide = ReactDOM.findDOMNode(spec.trackRef).children[(spec.slideIndex + spec.slidesToShow + 1)];
          }

          targetLeft = targetSlide ? targetSlide.offsetLeft * -1 : 0;
          targetLeft += (spec.listWidth - targetSlide.offsetWidth) / 2;
      }
  }

  return targetLeft;
};
<|endoftext|>


<commit_before>import React from 'react';
import { func } from 'prop-types';
import { connect } from 'react-redux';
import { AppBar as LibAppBar } from 'veritone-react-common';
import { modules } from 'veritone-redux-common';
const { user } = modules;

import appConfig from '../../../config.json';
import widget from '../../shared/widget';

@connect(
  state => ({
    user: user.selectUser(state),
    enabledApps: user.selectEnabledApps(state),
    enabledAppsFailedLoading: user.enabledAppsFailedLoading(state),
    isFetchingApps: user.isFetchingApps(state)
  }),
  { fetchEnabledApps: user.fetchEnabledApps },
  null,
  { withRef: true }
)
class AppBar extends React.Component {
  static propTypes = {
    fetchEnabledApps: func
  };

  componentDidMount() {
    this.props.fetchEnabledApps();
  }

  veritoneAppDidAuthenticate = () => {
    this.props.fetchEnabledApps();
  };

  handleSwitchApp = id => {
    window.location = `${appConfig.switchAppRoute}/${id}`;
  };

  render() {
    return <LibAppBar {...this.props} onSwitchApp={this.handleSwitchApp} />;
  }
}

export default widget(AppBar);
<commit_msg>get config from app<commit_after>import React from 'react';
import { func, string } from 'prop-types';
import { connect } from 'react-redux';
import { AppBar as LibAppBar } from 'veritone-react-common';
import { modules } from 'veritone-redux-common';
const { user, config } = modules;

import widget from '../../shared/widget';

@connect(
  state => ({
    user: user.selectUser(state),
    enabledApps: user.selectEnabledApps(state),
    enabledAppsFailedLoading: user.enabledAppsFailedLoading(state),
    isFetchingApps: user.isFetchingApps(state),
    switchAppRoute: config.getConfig(state).switchAppRoute
  }),
  { fetchEnabledApps: user.fetchEnabledApps },
  null,
  { withRef: true }
)
class AppBar extends React.Component {
  static propTypes = {
    fetchEnabledApps: func,
    switchAppRoute: string.isRequired
  };

  componentDidMount() {
    this.props.fetchEnabledApps();
  }

  veritoneAppDidAuthenticate = () => {
    this.props.fetchEnabledApps();
  };

  handleSwitchApp = id => {
    window.location = `${this.props.switchAppRoute}/${id}`;
  };

  render() {
    return <LibAppBar {...this.props} onSwitchApp={this.handleSwitchApp} />;
  }
}

export default widget(AppBar);
<|endoftext|>


<commit_before>/*
 * This file is part of Search NEU and licensed under AGPL3.
 * See the license file in the root folder for details.
 */

import React from 'react';
import PropTypes from 'prop-types';
import { Icon } from 'semantic-ui-react';

import WeekdayBoxes from './WeekdayBoxes';
import LocationLinks from './LocationLinks';
import macros from '../macros';

import globe from './globe.svg';

// TODO:
// Waitlist UI/wording could be cleaned up/simplified a bit.

// MobileSectionPanel page component
export default class MobileSectionPanel extends React.Component {
  static propTypes = {
    section: PropTypes.object.isRequired,
  };

  // This is different than the one in ClassPanel.js because this can show and hide the waitlist based on a per-section basis
  // and ClassPanel.js is show it for all sections or none.
  shouldShowWaitlist() {
    return this.props.section.getHasWaitList()
      && this.props.section.seatsRemaining < 10;
  }

  render() {
    // Add another row for seats remaining on the waitlist if any exist.
    let waitlistRow = null;
    const hasWaitList = this.shouldShowWaitlist();
    if (hasWaitList) {
      waitlistRow = (

          Wait

            {this.props.section.waitRemaining}/{this.props.section.waitCapacity} Waitlist Seats Available

      );
    }

    // Create the 4:35 - 5:40 pm string.
    const meetingMoments = this.props.section.getAllMeetingMoments();
    const times = [];
    meetingMoments.forEach((time) => {
      const startString = time.start.format('h:mm');
      const endString = time.end.format('h:mm a');
      const combinedString = `${startString} - ${endString}`;
      if (!times.includes(combinedString)) {
        times.push(combinedString);
      }
    });

    const fullTimesString = (times.length > 0) ? times.join(', ') : 'TBA';

    // Add a row for exam, if the section has an exam.
    let examRow = null;
    if (this.props.section.getHasExam()) {
      const examMeeting = this.props.section.getExamMeeting();
      if (examMeeting) {
        const examDayMoment = examMeeting.endDate;
        const examTimeMoment = examMeeting.times[0][0].start;

        examRow = (

            Exam

              {examDayMoment.format('MMMM Do @ ') + examTimeMoment.format('h:mm a')}

        );
      }
    }

    // Calculate the end of the title, which depends on whether the class is an online class and whether it has a start time yet.
    let titleEnding;
    if (this.props.section.online) {
      titleEnding = '-  Online Class';
    } else if (meetingMoments.length > 0) {
      titleEnding = `@ ${meetingMoments[0].start.format('h:mm a')}`;
    } else {
      titleEnding = '@ TBA';
    }

    if (this.props.section.honors) {
      titleEnding += ' (hon)';
    }

    let honorsSection = null;
    if (this.props.section.honors) {
      honorsSection = (

          Honors

            <Icon name='check' />

      );
    }

    return (

{`${macros.stripMiddleName(this.props.section.getProfs()[0])} ${titleEnding}`}

              CRN
              {this.props.section.crn}

            {honorsSection}

              Profs
              {this.props.section.getProfs().join(', ')}

              Place

                <LocationLinks section={ this.props.section } />

              Times

                {fullTimesString}

              Days

                <WeekdayBoxes section={ this.props.section } />

            {examRow}

              Seats

                {this.props.section.seatsRemaining}/{this.props.section.seatsCapacity} Available

            {waitlistRow}

    );
  }
}
<commit_msg>Basic functionallity works, going to add link<commit_after>/*
 * This file is part of Search NEU and licensed under AGPL3.
 * See the license file in the root folder for details.
 */

import React from 'react';
import PropTypes from 'prop-types';
import { Icon } from 'semantic-ui-react';

import WeekdayBoxes from './WeekdayBoxes';
import LocationLinks from './LocationLinks';
import macros from '../macros';

import globe from './globe.svg';

// TODO:
// Waitlist UI/wording could be cleaned up/simplified a bit.

// MobileSectionPanel page component
export default class MobileSectionPanel extends React.Component {
  static propTypes = {
    section: PropTypes.object.isRequired,
  };

  // This is different than the one in ClassPanel.js because this can show and hide the waitlist based on a per-section basis
  // and ClassPanel.js is show it for all sections or none.
  shouldShowWaitlist() {
    return this.props.section.getHasWaitList()
      && this.props.section.seatsRemaining < 10;
  }

  render() {
    // Add another row for seats remaining on the waitlist if any exist.
    let waitlistRow = null;
    const hasWaitList = this.shouldShowWaitlist();
    if (hasWaitList) {
      waitlistRow = (

          Wait

            {this.props.section.waitRemaining}/{this.props.section.waitCapacity} Waitlist Seats Available

      );
    }

    // Create the 4:35 - 5:40 pm string.
    const meetingMoments = this.props.section.getAllMeetingMoments();
    const times = [];
    meetingMoments.forEach((time) => {
      const startString = time.start.format('h:mm');
      const endString = time.end.format('h:mm a');
      const combinedString = `${startString} - ${endString}`;
      if (!times.includes(combinedString)) {
        times.push(combinedString);
      }
    });

    const fullTimesString = (times.length > 0) ? times.join(', ') : 'TBA';

    // Add a row for exam, if the section has an exam.
    let examRow = null;
    if (this.props.section.getHasExam()) {
      const examMeeting = this.props.section.getExamMeeting();
      if (examMeeting) {
        const examDayMoment = examMeeting.endDate;
        const examTimeMoment = examMeeting.times[0][0].start;

        examRow = [

            Exam

              {examDayMoment.format('MMMM Do @ ') + examTimeMoment.format('h:mm a')}

,

            Room

              {examMeeting.where}

        ];
      }
    }

    // Calculate the end of the title, which depends on whether the class is an online class and whether it has a start time yet.
    let titleEnding;
    if (this.props.section.online) {
      titleEnding = '-  Online Class';
    } else if (meetingMoments.length > 0) {
      titleEnding = `@ ${meetingMoments[0].start.format('h:mm a')}`;
    } else {
      titleEnding = '@ TBA';
    }

    if (this.props.section.honors) {
      titleEnding += ' (hon)';
    }

    let honorsSection = null;
    if (this.props.section.honors) {
      honorsSection = (

          Honors

            <Icon name='check' />

      );
    }

    return (

{`${macros.stripMiddleName(this.props.section.getProfs()[0])} ${titleEnding}`}

              CRN
              {this.props.section.crn}

            {honorsSection}

              Profs
              {this.props.section.getProfs().join(', ')}

              Place

                <LocationLinks section={ this.props.section } />

              Times

                {fullTimesString}

              Days

                <WeekdayBoxes section={ this.props.section } />

              Seats

                {this.props.section.seatsRemaining}/{this.props.section.seatsCapacity} Available

            {waitlistRow}
            {examRow}

    );
  }
}
<|endoftext|>