<commit_before>/* File: app.js.tpl
 *
 * Copyright (c) 2013-2016
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */
'use strict';
/* global io  */

var testEnv = false;
var cnedApp = angular.module('cnedApp', [
    'templates',
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ui.router',
    'gettext',
    'ui.bootstrap',
    'angular-md5',
    'services.config',
    'ngAudio',
    'LocalForageModule',
    'angular-google-analytics',
    '720kb.socialshare',
    'slick',
    'textAngular',
    'sticky',
    'angular-cookie-law',
    'ngDragDrop'
]);

cnedApp.config(function ($stateProvider, $urlRouterProvider, $sceDelegateProvider, $sceProvider,
                         $httpProvider, AnalyticsProvider, $logProvider,
                         configuration) {

    // Log enable / disable
    $logProvider.debugEnabled(true);

    // Google analytics account settings
    AnalyticsProvider.setAccount(configuration.GOOGLE_ANALYTICS_ID);
    AnalyticsProvider.trackPages(true);
    AnalyticsProvider.trackUrlParams(true);
    AnalyticsProvider.setPageEvent('$stateChangeSuccess');

    // HttpProvider settings
    $sceDelegateProvider.resourceUrlWhitelist([
        '**'
    ]);
    $httpProvider.defaults.useXDomain = true;
    $httpProvider.interceptors.push('app.httpinterceptor');
    delete $httpProvider.defaults.headers.common['X-Requested-With'];

    $urlRouterProvider.otherwise('/');

    $stateProvider
        .state('app', {
            url: '',
            abstract: true,
            controller: 'CommonCtrl',
            resolve: {
                tags: function (tagsService) {
                    return tagsService.getTags();
                },
                userData: function (UserService, $log) {
                    $log.debug('Init user data');
                    return UserService.init();
                }
            }
        })
        .state('app.home', {
            url: '/',
            templateUrl: 'views/index/home.html'
        })
        .state('app.overview', {
            url: '/apercu?idDocument&tmp&url&title&annotation',
            templateUrl: 'views/workspace/apercu.html',
            controller: 'ApercuCtrl',
            pageTrack: '/overview.html'  // angular-google-analytics extension
        })
        .state('app.edit-document', {
            url: '/addDocument?idDocument&title&url',
            templateUrl: 'views/addDocument/addDocument.html',
            controller: 'AddDocumentCtrl',
            pageTrack: '/document/edit.html',  // angular-google-analytics extension,
            params: {
                file: null,
                folder: null
            }
        })
        .state('app.print-document', {
            url: '/print?documentId&plan&mode',
            templateUrl: 'views/workspace/print.html',
            controller: 'PrintCtrl',
            pageTrack: '/print.html'  // angular-google-analytics extension
        })
        .state('app.list-profile', {
            url: '/profiles',
            templateUrl: 'views/profiles/profiles.html',
            controller: 'ProfilesCtrl',
            pageTrack: '/profile/list.html',  // angular-google-analytics extension
            params: {
                file: null
            }
        })
        .state('app.detail-profile', {
            url: '/detailProfil?url&idProfil',
            templateUrl: 'views/profiles/detailProfil.html',
            controller: 'ProfilesCtrl',
            pageTrack: '/profile/detail.html'  // angular-google-analytics extension
        })
        .state('app.list-style', {
            url: '/tag',
            templateUrl: 'views/tag/tag.html',
            controller: 'TagCtrl',
            pageTrack: '/style/list.html'  // angular-google-analytics extension
        })
        .state('app.list-document', {
            url: '/listDocument',
            templateUrl: 'views/listDocument/listDocument.html',
            controller: 'listDocumentCtrl',
            pageTrack: '/document/list.html'  // angular-google-analytics extension
        })

        .state('app.legal-notice', {
            url: '/mentions',
            templateUrl: 'views/infoPages/mentions.html',
            pageTrack: '/legal-notice.html'  // angular-google-analytics extension
        })
        .state('app.presentation', {
            url: '/a-propos',
            templateUrl: 'views/infoPages/about.html',
            pageTrack: '/presentation.html'  // angular-google-analytics extension
        })
        .state('app.contribute', {
            url: '/contribuer',
            templateUrl: 'views/infoPages/contribute.html',
            pageTrack: '/contribute.html'  // angular-google-analytics extension
        })

        .state('app.faq', {
            url: '/faq',
            templateUrl: 'views/infoPages/faq.html',
            pageTrack: '/faq.html'  // angular-google-analytics extension
        })

        .state('app.404', {
            url: '/404',
            templateUrl: 'views/404/404.html'
        })

        .state('app.my-backup', {
            url: '/ma-sauvegarde.html?auth',
            templateUrl: 'views/backup/my-backup.html',
            controller: 'MyBackupCtrl',
            pageTrack: '/overview.html',  // angular-google-analytics extension,
            params: {
                prevState: null,
                file: null
            },
            resolve: {
                auth: function ($state, $stateParams, UserService, OauthService, $log, CacheProvider, fileStorageService, $q, $rootScope) {

                    return CacheProvider.getItem('myBackupRouteData').then(function (routeData) {

                        CacheProvider.setItem(null, 'myBackupRouteData');
                        if ($stateParams.auth) {

                            return OauthService.token().then(function (res) {
                                return UserService.saveData(res.data).then(function () {

                                    UserService.init().then(function (userData) {
                                        $rootScope.userData = userData;

                                        fileStorageService.synchronizeFiles().then(function (res) {
                                            if (res && res.profilesCount > 0) {
                                                $rootScope.initCommon();
                                            }
                                        });

                                    });

                                    if (routeData) {
                                        $state.go(routeData.prevState, {file: routeData.file});
                                    } else {
                                        return res.data;
                                    }
                                });
                            }, function () {
                                return null; // TODO display error message
                            });

                        } else {
                            if (routeData) {
                                $state.go(routeData.prevState, {file: routeData.file});
                            } else {
                                return null;
                            }
                        }
                    });

                }
            }
        });
});

angular.module('cnedApp').run(function (gettextCatalog) {

    gettextCatalog.currentLanguage = 'fr_FR';
    localStorage.setItem('langueDefault', JSON.stringify({
        name: 'FRANCAIS',
        shade: 'fr_FR'
    }));
    gettextCatalog.debug = true;
});

//Secure the links
angular.module('cnedApp').config(['$compileProvider',

    function ($compileProvider) {
        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|javascript):/);
    }
]);

angular.module('cnedApp').config(function ($provide) {
    $provide.decorator('taOptions', ['taRegisterTool', 'taSelection', 'taBrowserTag', 'taTranslations',
        'taToolFunctions', '$delegate', '$window', 'UtilsService',
        function (taRegisterTool, taSelection, taBrowserTag, taTranslations,
                  taToolFunctions, taOptions, $window, UtilsService) {

            var blockJavascript = function (link) {
                if (link.toLowerCase().indexOf('javascript') !== -1) {
                    return true;
                }
                return false;
            };

            // $delegate is the taOptions we are decorating
            // register the tool with textAngular
            taRegisterTool('pageBreak', {
                buttontext: 'Saut de page',
                action: function () {
                    this.$editor().wrapSelection('insertHtml', '

');
                }
            });
            // add the button to the default toolbar definition
            taOptions.toolbar[1].push('pageBreak');

            taTranslations.insertLink.dialogPrompt = 'Veuillez insérer votre url';
            taTranslations.insertLink.tooltip = 'Insérer / éditer un lien';
            taTranslations.editLink.unLinkButton.tooltip = 'Supprimer le lien';
            taTranslations.editLink.reLinkButton.tooltip = 'Editer';
            taTranslations.editLink.targetToggle.buttontext = 'Ouvrir dans une nouvelle fenêtre';

            taRegisterTool('insertLinkCustom', {
                tooltiptext: taTranslations.insertLink.tooltip,
                iconclass: 'fa fa-link',
                action: function () {
                    var urlLink;
                    // if this link has already been set, we need to just edit the existing link
                    /* istanbul ignore if: we do not test this */
                    if (taSelection.getSelectionElement().tagName && taSelection.getSelectionElement().tagName.toLowerCase() === 'a') {
                        urlLink = $window.prompt(taTranslations.insertLink.dialogPrompt, taSelection.getSelectionElement().href);
                    } else {
                        urlLink = $window.prompt(taTranslations.insertLink.dialogPrompt, 'http://');
                    }
                    if (urlLink && urlLink !== '' && urlLink !== 'http://' && urlLink !== 'https://') {
                        // block javascript here
                        /* istanbul ignore else: if it's javascript don't worry - though probably should show some kind of error message */
                        if (!blockJavascript(urlLink)) {
                            return this.$editor().wrapSelection('createLink', urlLink, true);
                        }
                    }
                },
                activeState: function (commonElement) {
                    if (commonElement) return commonElement[0].tagName === 'A';
                    return false;
                },
                onElementSelect: {
                    element: 'a',
                    action: taToolFunctions.aOnSelectAction
                }
            });

            taOptions.toolbar[1].push('insertLinkCustom');

            return taOptions;
        }]);
});

angular.module('cnedApp').run(function ($rootScope, configuration, $timeout, $interval, serviceCheck) {
    //Delay between every check of session.
    $rootScope.sessionTime = 43200000;
    $rootScope.checkIsOnline = function () {
        return serviceCheck.isOnline().then(function () {
            //Useful test for the need for the preservation of the disconnected mode, once we have entered this mode.
            if (!$rootScope.isAppOnline) {
                $rootScope.isAppOnline = true;
            }
        }, function () {
            $rootScope.isAppOnline = false;
        });
    };

    //environment variable for testing.
    if (!testEnv) {
        $rootScope.checkIsOnline().then(function () {
            //
        });
        $interval($rootScope.checkIsOnline, 5000);
    } else {
        $rootScope.isAppOnline = true;
    }

    if (typeof io !== 'undefined') {
        $rootScope.socket = io.connect('https://localhost:3000', {secure: true});
    }

});
<commit_msg>revert debug<commit_after>/* File: app.js.tpl
 *
 * Copyright (c) 2013-2016
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */
'use strict';
/* global io  */

var testEnv = false;
var cnedApp = angular.module('cnedApp', [
    'templates',
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ui.router',
    'gettext',
    'ui.bootstrap',
    'angular-md5',
    'services.config',
    'ngAudio',
    'LocalForageModule',
    'angular-google-analytics',
    '720kb.socialshare',
    'slick',
    'textAngular',
    'sticky',
    'angular-cookie-law',
    'ngDragDrop'
]);

cnedApp.config(function ($stateProvider, $urlRouterProvider, $sceDelegateProvider, $sceProvider,
                         $httpProvider, AnalyticsProvider, $logProvider,
                         configuration) {

    // Log enable / disable
    $logProvider.debugEnabled(false);

    // Google analytics account settings
    AnalyticsProvider.setAccount(configuration.GOOGLE_ANALYTICS_ID);
    AnalyticsProvider.trackPages(true);
    AnalyticsProvider.trackUrlParams(true);
    AnalyticsProvider.setPageEvent('$stateChangeSuccess');

    // HttpProvider settings
    $sceDelegateProvider.resourceUrlWhitelist([
        '**'
    ]);
    $httpProvider.defaults.useXDomain = true;
    $httpProvider.interceptors.push('app.httpinterceptor');
    delete $httpProvider.defaults.headers.common['X-Requested-With'];

    $urlRouterProvider.otherwise('/');

    $stateProvider
        .state('app', {
            url: '',
            abstract: true,
            controller: 'CommonCtrl',
            resolve: {
                tags: function (tagsService) {
                    return tagsService.getTags();
                },
                userData: function (UserService, $log) {
                    $log.debug('Init user data');
                    return UserService.init();
                }
            }
        })
        .state('app.home', {
            url: '/',
            templateUrl: 'views/index/home.html'
        })
        .state('app.overview', {
            url: '/apercu?idDocument&tmp&url&title&annotation',
            templateUrl: 'views/workspace/apercu.html',
            controller: 'ApercuCtrl',
            pageTrack: '/overview.html'  // angular-google-analytics extension
        })
        .state('app.edit-document', {
            url: '/addDocument?idDocument&title&url',
            templateUrl: 'views/addDocument/addDocument.html',
            controller: 'AddDocumentCtrl',
            pageTrack: '/document/edit.html',  // angular-google-analytics extension,
            params: {
                file: null,
                folder: null
            }
        })
        .state('app.print-document', {
            url: '/print?documentId&plan&mode',
            templateUrl: 'views/workspace/print.html',
            controller: 'PrintCtrl',
            pageTrack: '/print.html'  // angular-google-analytics extension
        })
        .state('app.list-profile', {
            url: '/profiles',
            templateUrl: 'views/profiles/profiles.html',
            controller: 'ProfilesCtrl',
            pageTrack: '/profile/list.html',  // angular-google-analytics extension
            params: {
                file: null
            }
        })
        .state('app.detail-profile', {
            url: '/detailProfil?url&idProfil',
            templateUrl: 'views/profiles/detailProfil.html',
            controller: 'ProfilesCtrl',
            pageTrack: '/profile/detail.html'  // angular-google-analytics extension
        })
        .state('app.list-style', {
            url: '/tag',
            templateUrl: 'views/tag/tag.html',
            controller: 'TagCtrl',
            pageTrack: '/style/list.html'  // angular-google-analytics extension
        })
        .state('app.list-document', {
            url: '/listDocument',
            templateUrl: 'views/listDocument/listDocument.html',
            controller: 'listDocumentCtrl',
            pageTrack: '/document/list.html'  // angular-google-analytics extension
        })

        .state('app.legal-notice', {
            url: '/mentions',
            templateUrl: 'views/infoPages/mentions.html',
            pageTrack: '/legal-notice.html'  // angular-google-analytics extension
        })
        .state('app.presentation', {
            url: '/a-propos',
            templateUrl: 'views/infoPages/about.html',
            pageTrack: '/presentation.html'  // angular-google-analytics extension
        })
        .state('app.contribute', {
            url: '/contribuer',
            templateUrl: 'views/infoPages/contribute.html',
            pageTrack: '/contribute.html'  // angular-google-analytics extension
        })

        .state('app.faq', {
            url: '/faq',
            templateUrl: 'views/infoPages/faq.html',
            pageTrack: '/faq.html'  // angular-google-analytics extension
        })

        .state('app.404', {
            url: '/404',
            templateUrl: 'views/404/404.html'
        })

        .state('app.my-backup', {
            url: '/ma-sauvegarde.html?auth',
            templateUrl: 'views/backup/my-backup.html',
            controller: 'MyBackupCtrl',
            pageTrack: '/overview.html',  // angular-google-analytics extension,
            params: {
                prevState: null,
                file: null
            },
            resolve: {
                auth: function ($state, $stateParams, UserService, OauthService, $log, CacheProvider, fileStorageService, $q, $rootScope) {

                    return CacheProvider.getItem('myBackupRouteData').then(function (routeData) {

                        CacheProvider.setItem(null, 'myBackupRouteData');
                        if ($stateParams.auth) {

                            return OauthService.token().then(function (res) {
                                return UserService.saveData(res.data).then(function () {

                                    UserService.init().then(function (userData) {
                                        $rootScope.userData = userData;

                                        fileStorageService.synchronizeFiles().then(function (res) {
                                            if (res && res.profilesCount > 0) {
                                                $rootScope.initCommon();
                                            }
                                        });

                                    });

                                    if (routeData) {
                                        $state.go(routeData.prevState, {file: routeData.file});
                                    } else {
                                        return res.data;
                                    }
                                });
                            }, function () {
                                return null; // TODO display error message
                            });

                        } else {
                            if (routeData) {
                                $state.go(routeData.prevState, {file: routeData.file});
                            } else {
                                return null;
                            }
                        }
                    });

                }
            }
        });
});

angular.module('cnedApp').run(function (gettextCatalog) {

    gettextCatalog.currentLanguage = 'fr_FR';
    localStorage.setItem('langueDefault', JSON.stringify({
        name: 'FRANCAIS',
        shade: 'fr_FR'
    }));
    gettextCatalog.debug = true;
});

//Secure the links
angular.module('cnedApp').config(['$compileProvider',

    function ($compileProvider) {
        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|javascript):/);
    }
]);

angular.module('cnedApp').config(function ($provide) {
    $provide.decorator('taOptions', ['taRegisterTool', 'taSelection', 'taBrowserTag', 'taTranslations',
        'taToolFunctions', '$delegate', '$window', 'UtilsService',
        function (taRegisterTool, taSelection, taBrowserTag, taTranslations,
                  taToolFunctions, taOptions, $window, UtilsService) {

            var blockJavascript = function (link) {
                if (link.toLowerCase().indexOf('javascript') !== -1) {
                    return true;
                }
                return false;
            };

            // $delegate is the taOptions we are decorating
            // register the tool with textAngular
            taRegisterTool('pageBreak', {
                buttontext: 'Saut de page',
                action: function () {
                    this.$editor().wrapSelection('insertHtml', '

');
                }
            });
            // add the button to the default toolbar definition
            taOptions.toolbar[1].push('pageBreak');

            taTranslations.insertLink.dialogPrompt = 'Veuillez insérer votre url';
            taTranslations.insertLink.tooltip = 'Insérer / éditer un lien';
            taTranslations.editLink.unLinkButton.tooltip = 'Supprimer le lien';
            taTranslations.editLink.reLinkButton.tooltip = 'Editer';
            taTranslations.editLink.targetToggle.buttontext = 'Ouvrir dans une nouvelle fenêtre';

            taRegisterTool('insertLinkCustom', {
                tooltiptext: taTranslations.insertLink.tooltip,
                iconclass: 'fa fa-link',
                action: function () {
                    var urlLink;
                    // if this link has already been set, we need to just edit the existing link
                    /* istanbul ignore if: we do not test this */
                    if (taSelection.getSelectionElement().tagName && taSelection.getSelectionElement().tagName.toLowerCase() === 'a') {
                        urlLink = $window.prompt(taTranslations.insertLink.dialogPrompt, taSelection.getSelectionElement().href);
                    } else {
                        urlLink = $window.prompt(taTranslations.insertLink.dialogPrompt, 'http://');
                    }
                    if (urlLink && urlLink !== '' && urlLink !== 'http://' && urlLink !== 'https://') {
                        // block javascript here
                        /* istanbul ignore else: if it's javascript don't worry - though probably should show some kind of error message */
                        if (!blockJavascript(urlLink)) {
                            return this.$editor().wrapSelection('createLink', urlLink, true);
                        }
                    }
                },
                activeState: function (commonElement) {
                    if (commonElement) return commonElement[0].tagName === 'A';
                    return false;
                },
                onElementSelect: {
                    element: 'a',
                    action: taToolFunctions.aOnSelectAction
                }
            });

            taOptions.toolbar[1].push('insertLinkCustom');

            return taOptions;
        }]);
});

angular.module('cnedApp').run(function ($rootScope, configuration, $timeout, $interval, serviceCheck) {
    //Delay between every check of session.
    $rootScope.sessionTime = 43200000;
    $rootScope.checkIsOnline = function () {
        return serviceCheck.isOnline().then(function () {
            //Useful test for the need for the preservation of the disconnected mode, once we have entered this mode.
            if (!$rootScope.isAppOnline) {
                $rootScope.isAppOnline = true;
            }
        }, function () {
            $rootScope.isAppOnline = false;
        });
    };

    //environment variable for testing.
    if (!testEnv) {
        $rootScope.checkIsOnline().then(function () {
            //
        });
        $interval($rootScope.checkIsOnline, 5000);
    } else {
        $rootScope.isAppOnline = true;
    }

    if (typeof io !== 'undefined') {
        $rootScope.socket = io.connect('https://localhost:3000', {secure: true});
    }

});
<|endoftext|>


<commit_before>'use strict';

angular.module('confRegistrationWebApp', [])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/register/:conferenceId', {
        controller: 'RegisterCtrl',
        template: '',
        resolve: {
          conference: function (Conferences, $route) {
            return Conferences.getById($route.current.params.conferenceId); // todo handle a not found conference
          }
        }
      })
      .when('/register/:conferenceId/page/:pageId', {
        templateUrl: 'views/page.html',
        controller: 'PageCtrl',
        resolve: {
          conference: function ($route, Conferences) {
            return Conferences.getById($route.current.params.conferenceId); // todo handle a not found conference
          }
        }
      })
      .otherwise({
        redirectTo: '/'
      });
  });
<commit_msg>resolve needs to be explicitly injected<commit_after>'use strict';

angular.module('confRegistrationWebApp', [])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/register/:conferenceId', {
        controller: 'RegisterCtrl',
        template: '',
        resolve: {
          conference: ['$route', 'Conferences', function (Conferences, $route) {
            return Conferences.getById($route.current.params.conferenceId); // todo handle a not found conference
          }]
        }
      })
      .when('/register/:conferenceId/page/:pageId', {
        templateUrl: 'views/page.html',
        controller: 'PageCtrl',
        resolve: {
          conference: ['$route', 'Conferences', function ($route, Conferences) {
            return Conferences.getById($route.current.params.conferenceId); // todo handle a not found conference
          }]
        }
      })
      .otherwise({
        redirectTo: '/'
      });
  });
<|endoftext|>


<commit_before>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

(function(document) {
  'use strict';

  // Grab a reference to our auto-binding template
  // and give it some initial binding values
  // Learn more about auto-binding templates at http://goo.gl/Dx1u2g
  var app = document.querySelector('#app');

  app.displayInstalledToast = function() {
    document.querySelector('#caching-complete').show();
  };

  // Listen for template bound event to know when bindings
  // have resolved and content has been stamped to the page
  app.addEventListener('dom-change', function() {
    console.log('Our app is ready to rock!');
  });

  // See https://github.com/Polymer/polymer/issues/1381
  window.addEventListener('WebComponentsReady', function() {
    // imports are loaded and elements have been registered
  });

  // Main area's paper-scroll-header-panel custom condensing transformation of
  // the appName in the middle-container and the bottom title in the bottom-container.
  // The appName is moved to top and shrunk on condensing. The bottom sub title
  // is shrunk to nothing on condensing.
  addEventListener('paper-header-transform', function(e) {
    var appName = document.querySelector('.app-name');
    var middleContainer = document.querySelector('.middle-container');
    var bottomContainer = document.querySelector('.bottom-container');
    var detail = e.detail;
    var heightDiff = detail.height - detail.condensedHeight;
    var yRatio = Math.min(1, detail.y / heightDiff);
    var maxMiddleScale = 0.50;  // appName max size when condensed. The smaller the number the smaller the condensed size.
    var scaleMiddle = Math.max(maxMiddleScale, (heightDiff - detail.y) / (heightDiff / (1-maxMiddleScale))  + maxMiddleScale);
    var scaleBottom = 1 - yRatio;

    // Move/translate middleContainer
    Polymer.Base.transform('translate3d(0,' + yRatio * 100 + '%,0)', middleContainer);

    // Scale bottomContainer and bottom sub title to nothing and back
    Polymer.Base.transform('scale(' + scaleBottom + ') translateZ(0)', bottomContainer);

    // Scale middleContainer appName
    Polymer.Base.transform('scale(' + scaleMiddle + ') translateZ(0)', appName);
  });

  // Close drawer after menu item is selected if drawerPanel is narrow
  app.onMenuSelect = function() {
    var drawerPanel = document.querySelector('#paperDrawerPanel');
    if (drawerPanel.narrow) {
      drawerPanel.closeDrawer();
    }
  };

})(document);
<commit_msg>Removes annoying console message<commit_after>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

(function(document) {
  'use strict';

  // Grab a reference to our auto-binding template
  // and give it some initial binding values
  // Learn more about auto-binding templates at http://goo.gl/Dx1u2g
  var app = document.querySelector('#app');

  app.displayInstalledToast = function() {
    document.querySelector('#caching-complete').show();
  };

  // Listen for template bound event to know when bindings
  // have resolved and content has been stamped to the page
  app.addEventListener('dom-change', function() {

  });

  // See https://github.com/Polymer/polymer/issues/1381
  window.addEventListener('WebComponentsReady', function() {
    // imports are loaded and elements have been registered
  });

  // Main area's paper-scroll-header-panel custom condensing transformation of
  // the appName in the middle-container and the bottom title in the bottom-container.
  // The appName is moved to top and shrunk on condensing. The bottom sub title
  // is shrunk to nothing on condensing.
  addEventListener('paper-header-transform', function(e) {
    var appName = document.querySelector('.app-name');
    var middleContainer = document.querySelector('.middle-container');
    var bottomContainer = document.querySelector('.bottom-container');
    var detail = e.detail;
    var heightDiff = detail.height - detail.condensedHeight;
    var yRatio = Math.min(1, detail.y / heightDiff);
    var maxMiddleScale = 0.50;  // appName max size when condensed. The smaller the number the smaller the condensed size.
    var scaleMiddle = Math.max(maxMiddleScale, (heightDiff - detail.y) / (heightDiff / (1-maxMiddleScale))  + maxMiddleScale);
    var scaleBottom = 1 - yRatio;

    // Move/translate middleContainer
    Polymer.Base.transform('translate3d(0,' + yRatio * 100 + '%,0)', middleContainer);

    // Scale bottomContainer and bottom sub title to nothing and back
    Polymer.Base.transform('scale(' + scaleBottom + ') translateZ(0)', bottomContainer);

    // Scale middleContainer appName
    Polymer.Base.transform('scale(' + scaleMiddle + ') translateZ(0)', appName);
  });

  // Close drawer after menu item is selected if drawerPanel is narrow
  app.onMenuSelect = function() {
    var drawerPanel = document.querySelector('#paperDrawerPanel');
    if (drawerPanel.narrow) {
      drawerPanel.closeDrawer();
    }
  };

})(document);
<|endoftext|>


<commit_before>'use strict';

angular.module('guityApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute',
  'google-maps',
  'wu.masonry'
])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/search.html',
        controller: 'searchCtrl'
      })
      .when('/artist/:mbid', {
        templateUrl: 'views/artist.html',
        controller: 'artistCtrl'
      })
      .when('/artist/similar/:mbid', {
        templateUrl: 'views/similar.html',
        controller: 'similarCtrl'
      })
      .when('/artist/events/:mbid', {
        templateUrl: 'views/events.html',
        controller: 'eventsCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });

  });
<commit_msg>Added appCtrl<commit_after>'use strict';

angular.module('guityApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute',
  'google-maps',
  'wu.masonry'
])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/search.html',
        controller: 'searchCtrl'
      })
      .when('/artist/:mbid', {
        templateUrl: 'views/artist.html',
        controller: 'artistCtrl'
      })
      .when('/artist/similar/:mbid', {
        templateUrl: 'views/similar.html',
        controller: 'similarCtrl'
      })
      .when('/artist/events/:mbid', {
        templateUrl: 'views/events.html',
        controller: 'eventsCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  })
  .controller('appCtrl', function ($scope) {
    $scope.$on('load', function() {
      $scope.loading = true;
    });
    $scope.$on('unload', function() {
      $scope.loading = false;
    });
  });
<|endoftext|>


<commit_before>$(function(){
    // create the app
    var multitasq = new Multitasq_Sandbox();

    // help button listener
    $(".helpToggle").on("click", function() {
        if ($("#content_overlay").css("display") === "block") {
            history.pushState(null, "", "/");
            multitasq.render();
            $("#content_tasksvg").show();
            $("#content_overlay").hide();
        }
        else {
            history.pushState(null, "", "/help");
            multitasq.clear();
            $("#content_tasksvg").hide();
            $("#content_overlay").show();
        }
    });
});
<commit_msg>removed direct push state, will try backbone router later<commit_after>$(function(){
    // create the app
    var multitasq = new Multitasq_Sandbox();

    // help button listener
    $(".helpToggle").on("click", function() {
        if ($("#content_overlay").css("display") === "block") {
            multitasq.render();
            $("#content_tasksvg").show();
            $("#content_overlay").hide();
        }
        else {
            multitasq.clear();
            $("#content_tasksvg").hide();
            $("#content_overlay").show();
        }
    });
});
<|endoftext|>


<commit_before>/*global define */
define([], function () {
    'use strict';

    $('input').keyup(function () {
        var url = 'https://www.facebook.com/dialog/pagetab?' +
            'app_id=' + $('input.appid').val() + '&' +
            'redirect_uri=' + encodeURIComponent($('input.uri').val());
        $('#pagetab_uri').html('
' + url + '
');
    });
});<commit_msg>use http://www.facebook.com as the default redirect URI<commit_after>/*global define */
define([], function () {
    'use strict';

    var updateURL = function () {
        var appId = $('input.appid').val();
        var uri = $('input.uri').val() || 'http://www.facebook.com/';
        var url = 'https://www.facebook.com/dialog/pagetab?' +
            'app_id=' + appId + '&' +
            'redirect_uri=' + encodeURIComponent(uri);
        $('#pagetab_uri').html('
' + url + '
');
    };

    $('input').keyup(updateURL);
    updateURL();
});<|endoftext|>


<commit_before>var jamsMetrics = angular.module('jamsMetrics', ['ui.router']);

jamsMetrics.config(function ($stateProvider, $locationProvider) {
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });

    $stateProvider.state('landing', {
            url: '/',
            controller: 'Landing.controller',
            templateUrl: '/templates/landing.html'
        })
        .state('collection', {
            url: '/collection',
            controller: 'Collection.controller',
            templateUrl: '/templates/collection.html'
        })
        .state('album', {
            url: '/album',
            controller: 'Album.controller',
            templateUrl: '/templates/album.html'
        })
        .state('metrics', {
            url: '/metrics',
            controller: 'Metrics.controller',
            templateUrl: '/templates/metrics.html'
        });
});

//Controllers

jamsMetrics.controller('Metrics.controller', ['$scope', function ($scope) {

}]);

jamsMetrics.controller('Landing.controller', ['$scope', function ($scope) {
    $scope.welcome = 'Turn the music up!';
}]);

jamsMetrics.controller('Collection.controller', ['$scope', function ($scope) {
    var albumsArray = [];
    for (var i = 0; i < 8; i++) {
        var currentAlbum = angular.copy(albumPicasso);
        albumsArray.push(currentAlbum);
    }

    $scope.albums = albumsArray;
}]);

jamsMetrics.controller('Album.controller', ['$scope', 'filteredTimeFilter', 'Player', function ($scope, filteredTimeFilter, Player) {
    $scope.currentAlbum = Player.currentAlbum;
    $scope.currentSoundFile = Player.currentSoundFile;
    $scope.isPlaying = Player.playing;
    $scope.currentSongInAlbum = $scope.currentAlbum.songs[Player.currentSongIndex];
    $scope.duration = null;
    $scope.prog = 0;
    $scope.vol = Player.currentVolume;
    window.scope = $scope;
    $scope.$on('newValue', function (event, data) {
        if (data.element.attr('bound-value') === 'prog') {
            Player.seek(data.value);
        } else if (data.element.attr('bound-value') === 'vol') {
            Player.setVolume(data.value);
        }
    });

    $scope.playPause = function (songIndex) {
        if (Player.currentSongIndex === songIndex) {
            if (Player.playing) {
                Player.pause();
            } else {
                Player.play();
            }
        } else {
            Player.setSong(songIndex);
            Player.getSongDuration()
            $scope.currentSongTime();
            Player.play();
        }
    };

    $scope.currentSongTime = function () {
        Player.currentSoundFile.unbind('timeupdate');
        Player.currentSoundFile.bind('timeupdate', function timeUpdate(event) {
            $scope.$apply(function () {
                $scope.currentTime = filteredTimeFilter(Player.currentSoundFile.getTime());
                $scope.duration = filteredTimeFilter(Player.getSongDuration());
            })
        });
    };

    var hoverSongIndex = null;

    $scope.hoverIn = function (songIndex) {
        hoverSongIndex = songIndex;
    };

    $scope.hoverOut = function () {
        hoverSongIndex = null;
    };

    $scope.getState = function (songIndex) {
        if (Player.playing && songIndex === Player.currentSongIndex) {
            return 'playing';
        } else if (songIndex === hoverSongIndex) {
            return 'hovering';
        }
        return 'default';
    };

    $scope.nextSong = function () {
        Player.nextSong();
        $scope.currentSongInAlbum = $scope.currentAlbum.songs[Player.currentSongIndex];
        $scope.currentSongTime();
    };

    $scope.previousSong = function () {
        Player.previousSong();
        $scope.currentSongInAlbum = $scope.currentAlbum.songs[Player.currentSongIndex];
        $scope.currentSongTime();

    };

    $scope.playSong = function () {
        $scope.isPlaying = Player.playing;
        if (Player.playing) {
            Player.pause();
        } else {
            Player.play();
            $scope.currentSongTime();
        }
        $scope.isPlaying = Player.playing;
        $scope.$on('song:timeupdate', function (event, data) {
            $timeout(function () {
                $scope.currentTimeSecs = data;
                $scope.currentTime = formatTimeFilter(data);
            }, 0);
            $scope.prog = ($scope.currentTimeSecs / $scope.totalTimeSecs) * 100;
        });
    };
}]);

//Services

//Player Service
jamsMetrics.factory('Player', function () {
    var playButtonTemplate = '';
    var pauseButtonTemplate = '';
    var playerBarPlayButton = '';
    var playerBarPauseButton = '';

    return {
        currentAlbum: albumPicasso,
        currentSoundFile: null,
        currentSongIndex: 0,
        currentSongInAlbum: null,
        currentVolume: 80,
        currentSongTime: 0,
        playing: false,
        pause: function () {
            this.playing = false;
            this.paused = true;
            this.currentSoundFile.pause();
        },

        play: function () {
            this.playing = true;
            this.paused = false;
            if (this.currentSoundFile === null) {
                this.setSong(this.currentSongIndex);
            }
            this.currentSoundFile.play();
            this.setVolume(this.currentVolume);

        },

        nextSong: function () {
            this.currentSongIndex++;
            if (this.currentSongIndex === this.currentAlbum.songs.length) {
                this.currentSongIndex = 0;
            }
            this.setSong(this.currentSongIndex);
            this.play();

        },

        previousSong: function () {
            this.currentSongIndex--;
            if (this.currentSongIndex === -1) {
                this.currentSongIndex = this.currentAlbum.songs.length - 1;
            }
            this.setSong(this.currentSongIndex);
            this.play();

        },

        setSong: function (songIndex) {
            if (this.currentSoundFile) {
                this.currentSoundFile.stop();
            }
            this.currentSongIndex = songIndex;
            this.currentSongFromAlbum = this.currentAlbum.songs[songIndex];
            this.currentSoundFile = new buzz.sound(albumPicasso.songs[songIndex].audioUrl, {
                formats: ['mp3'],
                preload: true
            });
            this.setVolume(this.currentVolume);
        },

        isPlaying: function (songIndex) {
            if (this.currentSongIndex === songIndex && this.paused === false) {
                this.playing = true;
            } else
                this.playing = false;
        },

        setVolume: function (value) {
            if (this.currentSoundFile) {
                this.currentSoundFile.setVolume(value);
                this.volume = value;
            }
        },

        updateSeekBarWhileSongPlays: function () {

            if (this.currentSoundFile) {

                this.currentSoundFile.bind('timeupdate', function timeUpdate(event) {

                });
            }
        },

        getSongDuration: function () {
            if (this.currentSoundFile) {
                return this.currentSoundFile.getDuration();
            }
        },

        seek: function (percent) {
            if (this.currentSoundFile) {
                var ratio = percent / 100;
                var newTime = this.currentSoundFile.getDuration() * ratio;
                this.currentSoundFile.setTime(newTime);
            }
        },
        duration: function () {
            if (currentSoundFile) {
                return currentSoundFile.getDuration();
            }
        }
    }
});

//Metrics Capture Service
jamsMetrics.service('Metric', ['$rootScope', function ($rootScope) {
    $rootScope.songPlays = [];

    return {
        // Function that records a metric object by pushing it to the $rootScope array
        registerSongPlay: function (songObj) {
            // Add time to event register
            songObj['playedAt'] = new Date();
            $rootScope.songPlays.push(songObj);
        },
        listSongsPlayed: function () {
            var songs = [];
            angular.forEach($rootScope.songPlays, function (song) {
                songs.push(song.name);
            });
            return songs;
        }
    };
}]);

//Directives

jamsMetrics.directive('slider', ['$document', function ($document) {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            boundValue: '='
        },
        templateUrl: '/templates/slider.html',
        link: function (scope, element, attrs) {
            scope.value = 0;

            scope.setThumb = function (value) {
                $(element).find('.thumb').css({
                    left: parseInt(value) + '%'
                });
            };

            scope.setFill = function (value) {
                $(element).find('.fill').css({
                    width: parseInt(value) + '%'
                });
            };

            scope.setValue = function (newVal) {
                scope.value = parseInt(newVal);
                scope.$emit('newValue', {
                    value: scope.value,
                    element: element
                });
            };

            scope.setSeek = function (ratio) {
                var offsetPercent = ratio * 100;
                offsetPercent = Math.max(0, offsetPercent);
                offsetPercent = Math.min(100, offsetPercent);
                scope.setThumb(offsetPercent);
                scope.setFill(offsetPercent);
                scope.setValue(offsetPercent);
            };

            scope.setSeek(scope.boundValue / 100);

            $(element).on('click', function (event) {
                var offset = event.pageX - $(element).offset().left;
                var barWidth = $(element).width();
                var ratio = offset / barWidth;
                scope.setSeek(ratio);
            });

            scope.seek = function (event) {
                $(document).bind('mousemove.thumb', function (event) {
                    var offset = event.pageX - $(element).offset().left;
                    var barWidth = $(element).width();
                    var ratio = offset / barWidth;
                    scope.setSeek(ratio);
                });
                $(document).bind('mouseup.thumb', function () {
                    $(document).unbind('mousemove.thumb');
                    $(document).unbind('mouseup.thumb');
                });
            };

            scope.$watch('boundValue', function ($slider) {
                scope.setThumb(scope.boundValue);
                scope.setFill(scope.boundValue);

            });
        }
    };
}]);

//Filter

jamsMetrics.filter('filteredTime', function () {
    return function (input) {
        var time = parseFloat(input);
        var minutes = Math.floor(input / 60);
        var seconds = Math.floor(input - minutes * 60);
        if (seconds >= 10) {
            var input = minutes + ":" + seconds;
        } else {
            var input = minutes + ":0" + seconds;
        }

        return input;
    };
});
<commit_msg>added root scope to metrics controller<commit_after>var jamsMetrics = angular.module('jamsMetrics', ['ui.router']);

jamsMetrics.config(function ($stateProvider, $locationProvider) {
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });

    $stateProvider.state('landing', {
            url: '/',
            controller: 'Landing.controller',
            templateUrl: '/templates/landing.html'
        })
        .state('collection', {
            url: '/collection',
            controller: 'Collection.controller',
            templateUrl: '/templates/collection.html'
        })
        .state('album', {
            url: '/album',
            controller: 'Album.controller',
            templateUrl: '/templates/album.html'
        })
        .state('metrics', {
            url: '/metrics',
            controller: 'Metrics.controller',
            templateUrl: '/templates/metrics.html'
        });
});

//Controllers

jamsMetrics.controller('Metrics.controller', ['$rootScope', function ($rootScope) {

}]);

jamsMetrics.controller('Landing.controller', ['$scope', function ($scope) {
    $scope.welcome = 'Turn the music up!';
}]);

jamsMetrics.controller('Collection.controller', ['$scope', function ($scope) {
    var albumsArray = [];
    for (var i = 0; i < 8; i++) {
        var currentAlbum = angular.copy(albumPicasso);
        albumsArray.push(currentAlbum);
    }

    $scope.albums = albumsArray;
}]);

jamsMetrics.controller('Album.controller', ['$scope', 'filteredTimeFilter', 'Player', function ($scope, filteredTimeFilter, Player) {
    $scope.currentAlbum = Player.currentAlbum;
    $scope.currentSoundFile = Player.currentSoundFile;
    $scope.isPlaying = Player.playing;
    $scope.currentSongInAlbum = $scope.currentAlbum.songs[Player.currentSongIndex];
    $scope.duration = null;
    $scope.prog = 0;
    $scope.vol = Player.currentVolume;
    window.scope = $scope;
    $scope.$on('newValue', function (event, data) {
        if (data.element.attr('bound-value') === 'prog') {
            Player.seek(data.value);
        } else if (data.element.attr('bound-value') === 'vol') {
            Player.setVolume(data.value);
        }
    });

    $scope.playPause = function (songIndex) {
        if (Player.currentSongIndex === songIndex) {
            if (Player.playing) {
                Player.pause();
            } else {
                Player.play();
            }
        } else {
            Player.setSong(songIndex);
            Player.getSongDuration()
            $scope.currentSongTime();
            Player.play();
        }
    };

    $scope.currentSongTime = function () {
        Player.currentSoundFile.unbind('timeupdate');
        Player.currentSoundFile.bind('timeupdate', function timeUpdate(event) {
            $scope.$apply(function () {
                $scope.currentTime = filteredTimeFilter(Player.currentSoundFile.getTime());
                $scope.duration = filteredTimeFilter(Player.getSongDuration());
            })
        });
    };

    var hoverSongIndex = null;

    $scope.hoverIn = function (songIndex) {
        hoverSongIndex = songIndex;
    };

    $scope.hoverOut = function () {
        hoverSongIndex = null;
    };

    $scope.getState = function (songIndex) {
        if (Player.playing && songIndex === Player.currentSongIndex) {
            return 'playing';
        } else if (songIndex === hoverSongIndex) {
            return 'hovering';
        }
        return 'default';
    };

    $scope.nextSong = function () {
        Player.nextSong();
        $scope.currentSongInAlbum = $scope.currentAlbum.songs[Player.currentSongIndex];
        $scope.currentSongTime();
    };

    $scope.previousSong = function () {
        Player.previousSong();
        $scope.currentSongInAlbum = $scope.currentAlbum.songs[Player.currentSongIndex];
        $scope.currentSongTime();

    };

    $scope.playSong = function () {
        $scope.isPlaying = Player.playing;
        if (Player.playing) {
            Player.pause();
        } else {
            Player.play();
            $scope.currentSongTime();
        }
        $scope.isPlaying = Player.playing;
        $scope.$on('song:timeupdate', function (event, data) {
            $timeout(function () {
                $scope.currentTimeSecs = data;
                $scope.currentTime = formatTimeFilter(data);
            }, 0);
            $scope.prog = ($scope.currentTimeSecs / $scope.totalTimeSecs) * 100;
        });
    };
}]);

//Services

//Player Service
jamsMetrics.factory('Player', function () {
    var playButtonTemplate = '';
    var pauseButtonTemplate = '';
    var playerBarPlayButton = '';
    var playerBarPauseButton = '';

    return {
        currentAlbum: albumPicasso,
        currentSoundFile: null,
        currentSongIndex: 0,
        currentSongInAlbum: null,
        currentVolume: 80,
        currentSongTime: 0,
        playing: false,
        pause: function () {
            this.playing = false;
            this.paused = true;
            this.currentSoundFile.pause();
        },

        play: function () {
            this.playing = true;
            this.paused = false;
            if (this.currentSoundFile === null) {
                this.setSong(this.currentSongIndex);
            }
            this.currentSoundFile.play();
            this.setVolume(this.currentVolume);

        },

        nextSong: function () {
            this.currentSongIndex++;
            if (this.currentSongIndex === this.currentAlbum.songs.length) {
                this.currentSongIndex = 0;
            }
            this.setSong(this.currentSongIndex);
            this.play();

        },

        previousSong: function () {
            this.currentSongIndex--;
            if (this.currentSongIndex === -1) {
                this.currentSongIndex = this.currentAlbum.songs.length - 1;
            }
            this.setSong(this.currentSongIndex);
            this.play();

        },

        setSong: function (songIndex) {
            if (this.currentSoundFile) {
                this.currentSoundFile.stop();
            }
            this.currentSongIndex = songIndex;
            this.currentSongFromAlbum = this.currentAlbum.songs[songIndex];
            this.currentSoundFile = new buzz.sound(albumPicasso.songs[songIndex].audioUrl, {
                formats: ['mp3'],
                preload: true
            });
            this.setVolume(this.currentVolume);
        },

        isPlaying: function (songIndex) {
            if (this.currentSongIndex === songIndex && this.paused === false) {
                this.playing = true;
            } else
                this.playing = false;
        },

        setVolume: function (value) {
            if (this.currentSoundFile) {
                this.currentSoundFile.setVolume(value);
                this.volume = value;
            }
        },

        updateSeekBarWhileSongPlays: function () {

            if (this.currentSoundFile) {

                this.currentSoundFile.bind('timeupdate', function timeUpdate(event) {

                });
            }
        },

        getSongDuration: function () {
            if (this.currentSoundFile) {
                return this.currentSoundFile.getDuration();
            }
        },

        seek: function (percent) {
            if (this.currentSoundFile) {
                var ratio = percent / 100;
                var newTime = this.currentSoundFile.getDuration() * ratio;
                this.currentSoundFile.setTime(newTime);
            }
        },
        duration: function () {
            if (currentSoundFile) {
                return currentSoundFile.getDuration();
            }
        }
    }
});

//Metrics Capture Service
jamsMetrics.service('Metric', ['$rootScope', function ($rootScope) {
    $rootScope.songPlays = [];

    return {
        // Function that records a metric object by pushing it to the $rootScope array
        registerSongPlay: function (songObj) {
            // Add time to event register
            songObj['playedAt'] = new Date();
            $rootScope.songPlays.push(songObj);
        },
        listSongsPlayed: function () {
            var songs = [];
            angular.forEach($rootScope.songPlays, function (song) {
                songs.push(song.name);
            });
            return songs;
        }
    };
}]);

//Directives

jamsMetrics.directive('slider', ['$document', function ($document) {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            boundValue: '='
        },
        templateUrl: '/templates/slider.html',
        link: function (scope, element, attrs) {
            scope.value = 0;

            scope.setThumb = function (value) {
                $(element).find('.thumb').css({
                    left: parseInt(value) + '%'
                });
            };

            scope.setFill = function (value) {
                $(element).find('.fill').css({
                    width: parseInt(value) + '%'
                });
            };

            scope.setValue = function (newVal) {
                scope.value = parseInt(newVal);
                scope.$emit('newValue', {
                    value: scope.value,
                    element: element
                });
            };

            scope.setSeek = function (ratio) {
                var offsetPercent = ratio * 100;
                offsetPercent = Math.max(0, offsetPercent);
                offsetPercent = Math.min(100, offsetPercent);
                scope.setThumb(offsetPercent);
                scope.setFill(offsetPercent);
                scope.setValue(offsetPercent);
            };

            scope.setSeek(scope.boundValue / 100);

            $(element).on('click', function (event) {
                var offset = event.pageX - $(element).offset().left;
                var barWidth = $(element).width();
                var ratio = offset / barWidth;
                scope.setSeek(ratio);
            });

            scope.seek = function (event) {
                $(document).bind('mousemove.thumb', function (event) {
                    var offset = event.pageX - $(element).offset().left;
                    var barWidth = $(element).width();
                    var ratio = offset / barWidth;
                    scope.setSeek(ratio);
                });
                $(document).bind('mouseup.thumb', function () {
                    $(document).unbind('mousemove.thumb');
                    $(document).unbind('mouseup.thumb');
                });
            };

            scope.$watch('boundValue', function ($slider) {
                scope.setThumb(scope.boundValue);
                scope.setFill(scope.boundValue);

            });
        }
    };
}]);

//Filter

jamsMetrics.filter('filteredTime', function () {
    return function (input) {
        var time = parseFloat(input);
        var minutes = Math.floor(input / 60);
        var seconds = Math.floor(input - minutes * 60);
        if (seconds >= 10) {
            var input = minutes + ":" + seconds;
        } else {
            var input = minutes + ":0" + seconds;
        }

        return input;
    };
});
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc overview
 * @name pattyApp
 * @description
 * # pattyApp
 *
 * Main module of the application.
 */
angular
  .module('pattyApp', [
    'ngAnimate',
    'ngSanitize',
    'ngTouch',
    'ui.bootstrap',
    'pattyApp.searchbox',
    'pattyApp.minimap',
    'pattyApp.pointcloud'
  ])
  .config(function() {

  }).run(function(SitesService, DrivemapService) {
    DrivemapService.load();
    SitesService.load();
  });

angular.module('pattyApp.templates', []);
angular.module('pattyApp.utils', ['pattyApp.templates']);
angular.module('pattyApp.core', ['pattyApp.utils'])
  .factory('proj4', function($window) {
    return $window.proj4;
  });
angular.module('pattyApp.minimap', ['pattyApp.core'])
  .factory('ol', function($window) {
    return $window.ol;
  });
angular.module('pattyApp.pointcloud', ['pattyApp.core'])
  .factory('THREE', function($window) {
    return $window.THREE;
  })
  .factory('POCLoader', function($window) {
    return $window.POCLoader;
  })
  .factory('Potree', function($window) {
    return $window.Potree;
  });
angular.module('pattyApp.searchbox', ['pattyApp.core', 'pattyApp.pointcloud']);
<commit_msg>Create an Angular Constant for vendor libraries' global variables.<commit_after>// The app

/* global proj4:false, ol:false, THREE:false, POCLoader:false, Potree:false */
(function() {
  'use strict';

  /**
   * @ngdoc overview
   * @name pattyApp
   * @description
   * # pattyApp
   *
   * Main module of the application.
   */
  angular
    .module('pattyApp', [
      'ngAnimate',
      'ngSanitize',
      'ngTouch',
      'ui.bootstrap',
      'pattyApp.searchbox',
      'pattyApp.minimap',
      'pattyApp.pointcloud'
    ])
    .config(function() {

    }).run(function(SitesService, DrivemapService) {
      DrivemapService.load();
      SitesService.load();
    });

  angular.module('pattyApp.templates', []);
  angular.module('pattyApp.utils', ['pattyApp.templates']);
  angular.module('pattyApp.core', ['pattyApp.utils'])
    .constant('proj4', proj4);
  angular.module('pattyApp.minimap', ['pattyApp.core'])
    .constant('ol', ol);
  angular.module('pattyApp.pointcloud', ['pattyApp.core'])
    .constant('THREE', THREE)
    .constant('POCLoader', POCLoader)
    .constant('Potree', Potree);
  angular.module('pattyApp.searchbox', ['pattyApp.core', 'pattyApp.pointcloud']);
})();
<|endoftext|>


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

  // Grab a reference to our auto-binding template
  // and give it some initial binding values
  // Learn more about auto-binding templates at http://goo.gl/Dx1u2g
  var app = document.querySelector('#app');

  // Let the user know that offline caching has worked and their
  // app is available offline
  // app.displayInstalledToast = function() {
  //   document.querySelector('#caching-complete').show();
  // };

})(document);
<commit_msg>got rid of reference in app.js to the app. Not needed<commit_after>(function(document) {
  // 'use strict';

  // Grab a reference to our auto-binding template
  // and give it some initial binding values
  // Learn more about auto-binding templates at http://goo.gl/Dx1u2g
  // var app = document.querySelector('#app');

  // Let the user know that offline caching has worked and their
  // app is available offline
  // app.displayInstalledToast = function() {
  //   document.querySelector('#caching-complete').show();
  // };

})(document);
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.view1', ['ngRoute'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/view1', {
            templateUrl: 'view1/view1.html',
            controller: 'View1Ctrl',
            resolve: {
                weatherData: ['$q', 'weatherSvc', function ($q, weatherSvc) {
                    var deferred = $q.defer();

                    navigator.geolocation.getCurrentPosition(
                        deferred.resolve,
                        deferred.reject);

                    return deferred.promise.then(function (position) {
                            return weatherSvc.query(position.coords.latitude, position.coords.longitude);
                        }
                    );
                }]
            }
        });
    }])

    .controller('View1Ctrl', ['$scope', '$animate', 'weatherData', function ($scope, $animate, weatherData) {
        $scope.weatherData = weatherData.data;
        $scope.day = 0;
        $scope.tempMode = 'c';

        // todo remove
        console.log($scope.weatherData);

        var getBG = function (day) {
            var id = $scope.weatherData.list[day].weather[0].id;

            // http://openweathermap.org/weather-conditions
            switch (true) {
                case (id >= 200 && id < 300):
                    return "https://static.pexels.com/photos/799/city-lights-night-clouds.jpg";
                case (id >= 300 && id < 400):
                    return "https://static.pexels.com/photos/1551/field-thunderstorm-rainy-meadow.jpg";
                case (id >= 500 && id < 600):
                    return "https://static.pexels.com/photos/639/clouds-rainy-rain-asia-large.jpg";
                case (id >= 600 && id < 700):
                    return "https://static.pexels.com/photos/374/snow-dawn-sunset-winter-large.jpg";
                case (id === 701):
                    return "https://static.pexels.com/photos/5052/road-fog-bend-foggy-large.jpg";
                case (id >= 702 && id < 800):
                    return "https://static.pexels.com/photos/4241/cold-snow-black-and-white-road-large.jpg";
                case (id === 800):
                    return "https://static.pexels.com/photos/180/wood-sea-landscape-nature-large.jpg";
                case (id >= 801 && id < 804):
                    return "https://static.pexels.com/photos/215/road-sky-clouds-cloudy.jpg";
                case (id >= 804 && id < 900):
                    return "https://static.pexels.com/photos/1679/sea-nature-beach-clouds-large.jpg";
                case (id === 900): // tornado
                    return "";
                case (id === 901):
                    return "https://static.pexels.com/photos/6648/sea-water-ocean-storm-large.jpg";
                case (id === 902):
                    return "https://static.pexels.com/photos/3927/storm-hotel-waves-windy-large.jpeg";
                case (id === 903):
                    return "https://static.pexels.com/photos/2969/climate-cold-glacier-iceberg-large.jpg";
                case (id === 904):
                    return "https://static.pexels.com/photos/607/sea-beach-sand-ocean-large.jpg";
                case (id === 905):
                    return "https://static.pexels.com/photos/1549/nature-fashion-person-red-large.jpg";
                case (id === 906):
                    return "https://static.pexels.com/photos/3935/cold-snow-black-and-white-train-large.jpeg";

                case (id === 951):
                    return "https://static.pexels.com/photos/6643/sea-dawn-sunset-cloudy-large.jpg";
                case (id >= 952 && id < 956):
                    return "https://static.pexels.com/photos/1206/person-woman-girl-blonde-large.jpg";
                case (id >= 956 && id < 960):
                    return "https://static.pexels.com/photos/2635/sea-beach-storm-tree-large.jpg";
                case (id >= 960 && id < 963):
                    return "https://static.pexels.com/photos/2271/clouds-cloudy-field-meadow-large.jpg";
            }
        };

        var activeImg = '.bgImgOne';
        var inactiveImg = '.bgImgTwo';
        $scope.bgOne = getBG($scope.day);
        $scope.bgTwo = getBG($scope.day);

        var toggleImg = function() {
            if (activeImg === '.bgImgOne') {
                $scope.bgTwo = getBG($scope.day);
            } else {
                $scope.bgOne = getBG($scope.day);
            }

            if ($scope.bgOne !== $scope.bgTwo) {
                $animate.addClass(angular.element(activeImg), 'transparent', {});
                $animate.removeClass(angular.element(inactiveImg), 'transparent', {});

                var tmp = activeImg;
                activeImg = inactiveImg;
                inactiveImg = tmp;
            }
        };

        $scope.next = function () {
            $scope.day = (++$scope.day < $scope.weatherData.list.length) ? $scope.day : $scope.weatherData.list.length - 1;
            toggleImg();
        };
        $scope.prev = function () {
            $scope.day = (--$scope.day >= 0) ? $scope.day : 0;
            toggleImg();
        };

        var kelvinToCelsius = function (k) {
            return k - 273.15;
        };
        var kelvinToFahrenheit = function (k) {
            return ((k - 273.15) * 9 / 5) + 32;
        };
        $scope.degToCompassDir = function (deg) {
            var dir = Math.round(deg / 45);

            switch (dir) {
                case 0:
                    return 'N';
                case 1:
                    return 'NE';
                case 2:
                    return 'E';
                case 3:
                    return 'SE';
                case 4:
                    return 'S';
                case 5:
                    return 'SW';
                case 6:
                    return 'W';
                case 7:
                    return 'NW';
                case 8:
                    return 'N';
            }
        };
        $scope.mpsToKph = function (mps) {
            return mps * 3.6;
        };
        $scope.tempMin = function (day, mode) {
            switch (mode) {
                case 'c':
                    return kelvinToCelsius($scope.weatherData.list[day].temp.min);
                case 'k':
                    return $scope.weatherData.list[day].temp.min;
                case 'f':
                    return kelvinToFahrenheit($scope.weatherData.list[day].temp.min);
            }
        };
        $scope.tempMax = function (day, mode) {
            switch (mode) {
                case 'c':
                    return kelvinToCelsius($scope.weatherData.list[day].temp.max);
                case 'k':
                    return $scope.weatherData.list[day].temp.max;
                case 'f':
                    return kelvinToFahrenheit($scope.weatherData.list[day].temp.max);
            }
        };
        $scope.toTitleCase = function (str) {
            return str.replace(/\w\S*/g, function (txt) {
                return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
            });
        };

    }]);<commit_msg>enabled button delay when animating<commit_after>'use strict';

angular.module('myApp.view1', ['ngRoute'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/view1', {
            templateUrl: 'view1/view1.html',
            controller: 'View1Ctrl',
            resolve: {
                weatherData: ['$q', 'weatherSvc', function ($q, weatherSvc) {
                    var deferred = $q.defer();

                    navigator.geolocation.getCurrentPosition(
                        deferred.resolve,
                        deferred.reject);

                    return deferred.promise.then(function (position) {
                            return weatherSvc.query(position.coords.latitude, position.coords.longitude);
                        }
                    );
                }]
            }
        });
    }])

    .controller('View1Ctrl', ['$scope', '$animate', '$timeout', 'weatherData', function ($scope, $animate, $timeout, weatherData) {
        $scope.weatherData = weatherData.data;
        $scope.day = 0;
        $scope.tempMode = 'c';

        // todo remove
        console.log($scope.weatherData);

        var getBG = function (day) {
            var id = $scope.weatherData.list[day].weather[0].id;

            // http://openweathermap.org/weather-conditions
            switch (true) {
                case (id >= 200 && id < 300):
                    return "https://static.pexels.com/photos/799/city-lights-night-clouds.jpg";
                case (id >= 300 && id < 400):
                    return "https://static.pexels.com/photos/1551/field-thunderstorm-rainy-meadow.jpg";
                case (id >= 500 && id < 600):
                    return "https://static.pexels.com/photos/639/clouds-rainy-rain-asia-large.jpg";
                case (id >= 600 && id < 700):
                    return "https://static.pexels.com/photos/374/snow-dawn-sunset-winter-large.jpg";
                case (id === 701):
                    return "https://static.pexels.com/photos/5052/road-fog-bend-foggy-large.jpg";
                case (id >= 702 && id < 800):
                    return "https://static.pexels.com/photos/4241/cold-snow-black-and-white-road-large.jpg";
                case (id === 800):
                    return "https://static.pexels.com/photos/180/wood-sea-landscape-nature-large.jpg";
                case (id >= 801 && id < 804):
                    return "https://static.pexels.com/photos/215/road-sky-clouds-cloudy.jpg";
                case (id >= 804 && id < 900):
                    return "https://static.pexels.com/photos/1679/sea-nature-beach-clouds-large.jpg";
                case (id === 900): // tornado
                    return "";
                case (id === 901):
                    return "https://static.pexels.com/photos/6648/sea-water-ocean-storm-large.jpg";
                case (id === 902):
                    return "https://static.pexels.com/photos/3927/storm-hotel-waves-windy-large.jpeg";
                case (id === 903):
                    return "https://static.pexels.com/photos/2969/climate-cold-glacier-iceberg-large.jpg";
                case (id === 904):
                    return "https://static.pexels.com/photos/607/sea-beach-sand-ocean-large.jpg";
                case (id === 905):
                    return "https://static.pexels.com/photos/1549/nature-fashion-person-red-large.jpg";
                case (id === 906):
                    return "https://static.pexels.com/photos/3935/cold-snow-black-and-white-train-large.jpeg";

                case (id === 951):
                    return "https://static.pexels.com/photos/6643/sea-dawn-sunset-cloudy-large.jpg";
                case (id >= 952 && id < 956):
                    return "https://static.pexels.com/photos/1206/person-woman-girl-blonde-large.jpg";
                case (id >= 956 && id < 960):
                    return "https://static.pexels.com/photos/2635/sea-beach-storm-tree-large.jpg";
                case (id >= 960 && id < 963):
                    return "https://static.pexels.com/photos/2271/clouds-cloudy-field-meadow-large.jpg";
            }
        };

        var activeImg = '.bgImgOne';
        var inactiveImg = '.bgImgTwo';
        $scope.bgOne = getBG($scope.day);
        $scope.bgTwo = getBG($scope.day);
        $scope.btnDisabled = false;

        var toggleImg = function() {
            if ($scope.btnDisabled) return;

            if (activeImg === '.bgImgOne') {
                $scope.bgTwo = getBG($scope.day);
            } else {
                $scope.bgOne = getBG($scope.day);
            }

            if ($scope.bgOne !== $scope.bgTwo) {
                $scope.btnDisabled = true;
                $animate.addClass(angular.element(activeImg), 'transparent', {});
                $animate.removeClass(angular.element(inactiveImg), 'transparent', {});

                var tmp = activeImg;
                activeImg = inactiveImg;
                inactiveImg = tmp;

                $timeout(function() {
                    $scope.btnDisabled = false;
                }, 1000);
            }
        };

        $scope.next = function () {
            if ($scope.btnDisabled) return;
            $scope.day = (++$scope.day < $scope.weatherData.list.length) ? $scope.day : $scope.weatherData.list.length - 1;
            toggleImg();
        };
        $scope.prev = function () {
            if ($scope.btnDisabled) return;
            $scope.day = (--$scope.day >= 0) ? $scope.day : 0;
            toggleImg();
        };

        var kelvinToCelsius = function (k) {
            return k - 273.15;
        };
        var kelvinToFahrenheit = function (k) {
            return ((k - 273.15) * 9 / 5) + 32;
        };
        $scope.degToCompassDir = function (deg) {
            var dir = Math.round(deg / 45);

            switch (dir) {
                case 0:
                    return 'N';
                case 1:
                    return 'NE';
                case 2:
                    return 'E';
                case 3:
                    return 'SE';
                case 4:
                    return 'S';
                case 5:
                    return 'SW';
                case 6:
                    return 'W';
                case 7:
                    return 'NW';
                case 8:
                    return 'N';
            }
        };
        $scope.mpsToKph = function (mps) {
            return mps * 3.6;
        };
        $scope.tempMin = function (day, mode) {
            switch (mode) {
                case 'c':
                    return kelvinToCelsius($scope.weatherData.list[day].temp.min);
                case 'k':
                    return $scope.weatherData.list[day].temp.min;
                case 'f':
                    return kelvinToFahrenheit($scope.weatherData.list[day].temp.min);
            }
        };
        $scope.tempMax = function (day, mode) {
            switch (mode) {
                case 'c':
                    return kelvinToCelsius($scope.weatherData.list[day].temp.max);
                case 'k':
                    return $scope.weatherData.list[day].temp.max;
                case 'f':
                    return kelvinToFahrenheit($scope.weatherData.list[day].temp.max);
            }
        };
        $scope.toTitleCase = function (str) {
            return str.replace(/\w\S*/g, function (txt) {
                return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
            });
        };

    }]);

<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.view1', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}])
.value('notification_timeout', 5000)

.controller('View1Ctrl', ['$scope', '$timeout', 'notification_timeout', function($scope, $timeout, notification_timeout) {
  var promise;
  $scope.notificationVisible = false;
  /**
   * Shows update notification
   * @param  {Number} profileId profile being rated
   * @param  {Number} profileRating profile rating
   */
  $scope.showUpdate = function (profileId, profileRating) {
    $scope.profileRating = profileRating;
    $scope.profileId = profileId;
    $scope.notificationVisible = true;
    setNotificationTimeout();
  }
/**
 * Hides profile rating after a delay
 */
  function setNotificationTimeout () {
    // Cancel a current timeout
    $timeout.cancel(promise);
    // Start notification timeout
    promise = $timeout(function () {
      $scope.notificationVisible = false;
    }, notification_timeout);
  }
}]);
<commit_msg>add myApp.profile dependency to myApp.view1<commit_after>'use strict';

angular.module('myApp.view1', ['ngRoute', 'myApp.profile'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}])
.value('notification_timeout', 5000)

.controller('View1Ctrl', ['$scope', '$timeout', 'notification_timeout', function($scope, $timeout, notification_timeout) {
  var promise;
  $scope.notificationVisible = false;
  /**
   * Shows update notification
   * @param  {Number} profileId profile being rated
   * @param  {Number} profileRating profile rating
   */
  $scope.showUpdate = function (profileId, profileRating) {
    $scope.profileRating = profileRating;
    $scope.profileId = profileId;
    $scope.notificationVisible = true;
    setNotificationTimeout();
  }
/**
 * Hides profile rating after a delay
 */
  function setNotificationTimeout () {
    // Cancel a current timeout
    $timeout.cancel(promise);
    // Start notification timeout
    promise = $timeout(function () {
      $scope.notificationVisible = false;
    }, notification_timeout);
  }
}]);
<|endoftext|>


<commit_before>/* jshint jquery: true */
'use strict';

const IpcRenderer = require('electron').ipcRenderer;
const Shell = require('electron').shell;
var Remote = require('remote');
var Dialog = Remote.require('dialog');
window.$ = window.jQuery = require('jquery');

var foldersToAdd = [];

document.ondragover = document.ondrop = function(e) {
  e.preventDefault();
  return false;
};

function addFolder(path) {
	if(path) {
		foldersToAdd.push(path);

		var folderElementHtml = $('<li/>');

		folderElementHtml
			.attr('class', 'valid-path icon-teal')
			.html(path);

		$('#folders-to-add-list').prepend(folderElementHtml);
	}
}

function makeDoubleClickHandler() {
    return function() {
        console.log('plop');
        Shell.showItemInFolder(this.innerHTML + '/' + '.');
    };
}

IpcRenderer.on('data-folders', function(event, folders) {
	var arrayLength = folders.length;
	var foldersListHtml = $('#folders-list').empty();

	if(arrayLength > 0) {
		for (var i = 0; i < arrayLength; i++) {
			var folderElementHtml = $('<li/>');

			if(folders[i].exists) {
				folderElementHtml
                    .attr('class', 'valid-path icon-teal')
                    .dblclick(makeDoubleClickHandler());
			} else {
				folderElementHtml
                    .attr('class', 'invalid-path icon-red');
			}

			folderElementHtml
				.html(folders[i].path);
				// .prepend(iconHtml);
			$('.loader').hide();
			foldersListHtml.prepend(folderElementHtml);
		}
	} else {
		foldersListHtml.after($('<p/>').html('Error'));
	}
});

$('.choose-folder').on('click', function() {
	var folderPath = Dialog.showOpenDialog({ properties: [ 'openDirectory']});

	if(folderPath.length > 0){
		addFolder(folderPath[0]);
	}
});

$('.folder-input button').on('click', function() {
	IpcRenderer.send('add-folders', foldersToAdd);
	$('.loader').show();
	$('#folders-to-add-list').empty();
	return false;
});

$('#holder').on("drop", function(event) {
    event.preventDefault();
	event.stopPropagation();
    console.log('success');
	var folderPath = event.originalEvent.dataTransfer.files[0].path;

	addFolder(folderPath);
});

$('.refresh-list').on("click", function() {
	IpcRenderer.send('refresh-folders', true);
	$('.loader').show();
});
<commit_msg>[DOC] Replace all tabs by spaces in index.js<commit_after>/* jshint jquery: true */
'use strict';

const IpcRenderer = require('electron').ipcRenderer;
const Shell = require('electron').shell;
var Remote = require('remote');
var Dialog = Remote.require('dialog');
window.$ = window.jQuery = require('jquery');

var foldersToAdd = [];

document.ondragover = document.ondrop = function(e) {
    e.preventDefault();
    return false;
};

function addFolder(path) {
    if(path) {
        foldersToAdd.push(path);

        var folderElementHtml = $('<li/>');

        folderElementHtml
            .attr('class', 'valid-path icon-teal')
            .html(path);

        $('#folders-to-add-list').prepend(folderElementHtml);
    }
}

function makeDoubleClickHandler() {
    return function() {
        console.log('plop');
        Shell.showItemInFolder(this.innerHTML + '/' + '.');
    };
}

IpcRenderer.on('data-folders', function(event, folders) {
    var arrayLength = folders.length;
    var foldersListHtml = $('#folders-list').empty();

    if(arrayLength > 0) {
        for (var i = 0; i < arrayLength; i++) {
            var folderElementHtml = $('<li/>');

            if(folders[i].exists) {
                folderElementHtml
                    .attr('class', 'valid-path icon-teal')
                    .dblclick(makeDoubleClickHandler());
            } else {
                folderElementHtml
                    .attr('class', 'invalid-path icon-red');
            }

            folderElementHtml
                .html(folders[i].path);
                // .prepend(iconHtml);
            $('.loader').hide();
            foldersListHtml.prepend(folderElementHtml);
        }
    } else {
        foldersListHtml.after($('<p/>').html('Error'));
    }
});

$('.choose-folder').on('click', function() {
    var folderPath = Dialog.showOpenDialog({ properties: [ 'openDirectory']});

    if(folderPath.length > 0){
        addFolder(folderPath[0]);
    }
});

$('.folder-input button').on('click', function() {
    IpcRenderer.send('add-folders', foldersToAdd);
    $('.loader').show();
    $('#folders-to-add-list').empty();
    return false;
});

$('#holder').on("drop", function(event) {
    event.preventDefault();
    event.stopPropagation();
    console.log('success');
    var folderPath = event.originalEvent.dataTransfer.files[0].path;

    addFolder(folderPath);
});

$('.refresh-list').on("click", function() {
    IpcRenderer.send('refresh-folders', true);
    $('.loader').show();
});
<|endoftext|>


<commit_before>const html = require('choo/html')
const css = require('csjs-inject')
const C = require('../lib/constants')

const isString = require('lodash/isString')

const width = 160

const shared = css`

.base {
  position: absolute;
  font-family: Aleo-Regular;
  text-align: left;
  font-size: 14px;
}

`

const style = css`

.paper {
  position: relative;
  width: ${width}px;
  height: ${width * 1.31}px;
  display: flex;
  flex-direction: row;
  justify-items: flex-start;
  align-items: flex-start;
  background: ${C.DARKBLUE};
  margin: 10px;
  color: ${C.LIGHTGREY};
}

.title extends ${shared.base} {
  left: 10px;
  right: 10px;
  top: 10px;
  bottom: 50px;
  overflow-y: scroll;
  overflow-x: hidden;
}

.author extends ${shared.base} {
  font-size: 10px;
  left: 10px;
  right: 44px;
  bottom: 10px;
  font-family: CooperHewitt-MediumItalic;
  flex-wrap: wrap;
}

.author > span {
  padding: 0;
  margin-right: 3px;
}

.year extends ${shared.base} {
  left: 120px;
  right: 10px;
  bottom: 10px;
  justify-content: flex-end;
  font-family: CooperHewitt-Medium;
}

.selected {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 20px 20px 0;
  border-color: transparent ${C.YELLOW} transparent transparent;
  position: absolute;
  top: 0;
  right: 0;
}

.progressbar {
  position: absolute;
  left: 0;
  bottom: 0;
  height: 8px;
  width: 0;
  background-color: ${C.YELLOW};
}

`

module.exports = (result, state, prev, send) => {
  const selected = state.selection.lookup[result.paper.key]
  const downloading = state.downloads.lookup[result.paper.key]
  const progress = downloading ? Math.max(downloading.progress, 20) : result.paper.progress

  const paper = html`

      ${selectedmark(selected)}

${result.paper.title}

        ${renderAuthor(result.paper.author)}

        ${result.paper.date ? result.paper.date.year : 'none'}

  `

  const singleClick = e => send('paper_select_show', {
    index: result.index,
    paper: result.paper,
    shift: e.shiftKey,
    ctrl: e.ctrlKey,
    meta: e.metaKey
  })

  const doubleClick = event => send('read_selection')

  paper.onclick = e => {
    e.preventDefault()
    singleClick(e)
  }

  paper.ondblclick = e => {
    e.preventDefault()
    doubleClick(e)
  }

  return paper
}

function renderAuthor (author) {
  const authors = isString(author)
    ? author.split(/,\s?/)
    : author.map(a => a.surname)
  if (authors.length === 1) {
    return html`<span>${authors[0]}`
  } else if (authors.length < 4) {
    return html`

        ${authors.slice(0, -1).join(', ') + ' and ' + authors.slice(-1)[0]}

    `
  } else {
    return html`<span>${authors[0]} et al.</span>`
  }
}

function selectedmark (selected) {
  return selected ? html`<div class=${style.selected}></div>` : null
}
<commit_msg>Only read on double click if downloaded<commit_after>const html = require('choo/html')
const css = require('csjs-inject')
const C = require('../lib/constants')

const isString = require('lodash/isString')

const width = 160

const shared = css`

.base {
  position: absolute;
  font-family: Aleo-Regular;
  text-align: left;
  font-size: 14px;
}

`

const style = css`

.paper {
  position: relative;
  width: ${width}px;
  height: ${width * 1.31}px;
  display: flex;
  flex-direction: row;
  justify-items: flex-start;
  align-items: flex-start;
  background: ${C.DARKBLUE};
  margin: 10px;
  color: ${C.LIGHTGREY};
}

.title extends ${shared.base} {
  left: 10px;
  right: 10px;
  top: 10px;
  bottom: 50px;
  overflow-y: scroll;
  overflow-x: hidden;
}

.author extends ${shared.base} {
  font-size: 10px;
  left: 10px;
  right: 44px;
  bottom: 10px;
  font-family: CooperHewitt-MediumItalic;
  flex-wrap: wrap;
}

.author > span {
  padding: 0;
  margin-right: 3px;
}

.year extends ${shared.base} {
  left: 120px;
  right: 10px;
  bottom: 10px;
  justify-content: flex-end;
  font-family: CooperHewitt-Medium;
}

.selected {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 20px 20px 0;
  border-color: transparent ${C.YELLOW} transparent transparent;
  position: absolute;
  top: 0;
  right: 0;
}

.progressbar {
  position: absolute;
  left: 0;
  bottom: 0;
  height: 8px;
  width: 0;
  background-color: ${C.YELLOW};
}

`

module.exports = (result, state, prev, send) => {
  const selected = state.selection.lookup[result.paper.key]
  const downloading = state.downloads.lookup[result.paper.key]
  const progress = downloading ? Math.max(downloading.progress, 20) : result.paper.progress

  const paper = html`

      ${selectedmark(selected)}

${result.paper.title}

        ${renderAuthor(result.paper.author)}

        ${result.paper.date ? result.paper.date.year : 'none'}

  `

  const singleClick = e => send('paper_select_show', {
    index: result.index,
    paper: result.paper,
    shift: e.shiftKey,
    ctrl: e.ctrlKey,
    meta: e.metaKey
  })

  const doubleClick = event => {
    if (result.paper.progress === 100) send('read_selection')
  }

  paper.onclick = e => {
    e.preventDefault()
    singleClick(e)
  }

  paper.ondblclick = e => {
    e.preventDefault()
    doubleClick(e)
  }

  return paper
}

function renderAuthor (author) {
  const authors = isString(author)
    ? author.split(/,\s?/)
    : author.map(a => a.surname)
  if (authors.length === 1) {
    return html`<span>${authors[0]}`
  } else if (authors.length < 4) {
    return html`

        ${authors.slice(0, -1).join(', ') + ' and ' + authors.slice(-1)[0]}

    `
  } else {
    return html`<span>${authors[0]} et al.</span>`
  }
}

function selectedmark (selected) {
  return selected ? html`<div class=${style.selected}></div>` : null
}
<|endoftext|>