angular.module('footyroom').controller('NoSpoilersController', ['$scope', 'noSpoilers', function ($scope, noSpoilersService) { var ctrl = this; ctrl.change = change; ctrl.isEnabled = noSpoilersService.get(); $scope.$on('noSpoilers', function (event, isEnabled) { ctrl.isEnabled = isEnabled; }); function change() { noSpoilersService.set(ctrl.isEnabled); } }]); angular.module('footyroom').service('noSpoilers', ['$rootScope', '$http', '$window', function ($rootScope, $http, $window) { var service = this; var isEnabled = DataStore.noSpoilers; service.set = set; service.get = get; // For guests we want to persist query string override of local storage // setting so that subsequent page requests continue to hide spoilers. if (DataStore.isGuest) { persistForGuest(); } return service; function set(newValue) { isEnabled = newValue; noSpoilers(isEnabled); if (DataStore.isGuest) { persistForGuest(); } else if (!DataStore.isGuest) { $http.post('/profile/settings/no-spoilers', { enabled: isEnabled }); } $rootScope.$broadcast('noSpoilers', isEnabled); } function persistForGuest() { if ($window.localStorage && $window.localStorage.noSpoilers !== isEnabled) { $window.localStorage.setItem('noSpoilers', JSON.stringify(isEnabled)); } } function get() { return isEnabled; } }]); function noSpoilers(enabled) { if (enabled) { $('html').addClass('no-spoilers'); document.title = document.title .replace(/ [0-9]+ \- [0-9]+ /g, ' vs ') .replace(/ \[PEN: [0-9]+\-[0-9]+\]/g, ''); } else { $('html').removeClass('no-spoilers'); } } (function initNoSpoilers() { if (DataStore.isGuest && !DataStore.noSpoilers) { try { DataStore.noSpoilers = window.localStorage ? JSON.parse(window.localStorage.noSpoilers || false) : false; } catch (e) { DataStore.noSpoilers = false; } } // Run this before page is loaded to prevent flash of spoilers. noSpoilers(DataStore.noSpoilers); }());