PageSourceSearch

https://static.goodgame.ru/js/minified/all.js?y2wyro

js goodgame.ru collected 2026-09-24 08:49:02 UTC 853,413 bytes, 29 lines download raw bytes

1"use strict";function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++)arr2[i]=arr[i];return arr2}return Array.from(arr)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function FeedController($scope,StreamService,$rootScope){function check(){var theatre=document.body.classList.contains("theatre");return window.innerWidth>HIDE_FEED_WIDTH||(!!theatre||void 0)}function waitForSelector(selector){var timeout=arguments.length>1&&void 0!==arguments[1]?arguments[1]:15e3;return new Promise(function(resolve,reject){var endTime=Number(new Date)+timeout,checkInterval=setInterval(function(){document.querySelector(selector)?(clearInterval(checkInterval),resolve()):Number(new Date)>endTime&&(clearInterval(checkInterval),reject(new Error("Timeout waiting for selector "+selector)))},100)})}function userSubscribe(){lastUser!=UserService.id&&(lastUser&&NotifyProxy.unsubscribe("private:9:"+lastUser),UserService.id&&NotifyProxy.subscribe("private:9:"+UserService.id)),lastUser=UserService.id}function showTab(tab){return 0==tab&&screen.width<1191?(vm.currentTab="stream",$scope.$root.hideFeed=!0):0==tab&&screen.width>=1191?(vm.currentTab="favorites",$scope.$root.hideFeed=!1):$scope.$root.hideFeed?(vm.currentTab=tab,void($scope.$root.hideFeed=!1)):(vm.currentTab==tab&&($scope.$root.hideFeed=!0),void(vm.currentTab=tab))}function openDialog(userId){$scope.$root.hideFeed=!1,vm.currentDialog={user:{id:userId}},vm.currentTab="mails"}function clickOutside(){vm.hasChat()||($scope.$root.hideFeed=!0)}var lastUser,vm=this,HIDE_FEED_WIDTH=location.href.indexOf("stream")>-1?768:1190;vm.currentTab="favorites",vm.showTab=showTab,vm.openDialog=openDialog,vm.hasChat=check,vm.toggleMenu=!1,vm.clickOutside=clickOutside,vm.isMobile=$rootScope.isMobile,$scope.$root.feed=vm,$scope.$watch(function(){return $scope.$root.hideFeed},function(newValue){UserService.id&&Utils.lsSet("hideFeed",newValue?1:0)});var lastState=!1,lastTab="";$scope.$watch(function(){return window.innerWidth},function(newValue,oldValue){oldValue>HIDE_FEED_WIDTH&&newValue<=HIDE_FEED_WIDTH&&(lastState=$scope.$root.hideFeed,lastTab=vm.currentTab,$scope.$root.hideFeed=!0,vm.currentTab="favorites"),oldValue<=HIDE_FEED_WIDTH&&newValue>HIDE_FEED_WIDTH&&$scope.$root.hideFeed&&($scope.$root.hideFeed=lastState,vm.currentTab=lastTab||"favorites")}),function(){userSubscribe(),$scope.$root.hideFeed=!UserService.id||1==Utils.lsGet("hideFeed"),UserService.onLoginChange(function(user){$scope.$root.hideFeed=!(user&&0!==user.id||vm.stream.visible),userSubscribe()}),vm.isMobile&&waitForSelector(".tab-panel.content-container").then(function(){$scope.$root.hideFeed=!0})}()}function GGCupMatch(data){data||(data={}),this.$cup=data.stage.$cup,this.$stage=data.stage,this.bo=this.$stage.bo,this.n=data.n||0,this.dbid=data.dbid||!1,this.losers=data.losers||!1,this.score=data.score||[],this._score=angular.copy(this.score),this.score[0]||this.score[1]||(this.score=[]),data.players?this.players=!1===data.players[0]?[data.players[1],!1]:data.players:data._players?this.players=[this.$cup.getPlayer(data._players[0]),this.$cup.getPlayer(data._players[1])]:this.players=[],this.winner=!!data.closed&&(!this.players[1]||this.score[0]>this.score[1]?this.players[0]:this.players[1]),this.loser=!!data.closed&&(this.score[0]<this.score[1]?this.players[0]:this.players[1]),this.closed=!!data.closed,this.first=data.first||!1,this.third=data.third||!1,this.$cup&&this.third&&(this.$cup.grid.$third=this),this.$cup&&this.first&&(this.$cup.grid.$first=this),this.opened=!!data.opened&&new Date(1e3*data.opened),this.chat=data.chat||!1,this.data=data.data}function GGCupStage(data){data||(data={}),this.n=data.n||0,this.bo=data.bo||1,this.$cup=data.cup||!1,this.matches=data.matches||[],this.group=data.group||0,this.losers=data.losers||0}function GGCupGroupStage(data){GGCupStage.apply(this,arguments)}function GGCupGridSingle(cup,stages){this.$cup=cup,this.$cup.grid=this,this._data=stages,this.data={},this.$first=!1,this.$third=!1}function GGCupGridDouble(cup,stages){GGCupGridSingle.apply(this,arguments)}function GGCupGridGroups(cup,stages){GGCupGridSingle.apply(this,arguments),cup.grid_data&&(this.data=angular.fromJson(cup.grid_data)),this.data.playoff||(this.data.playoff={type:1}),this.hasPlayoff=!0}function GGCupGridEventGroups(cup,stages){GGCupGridSingle.apply(this,arguments),cup.grid_data&&(this.data=angular.fromJson(cup.grid_data))}function GGCupGridFFA10(cup,stages){GGCupGridSingle.apply(this,arguments),stages&&stages.length&&!cup.grid_data&&(this.data=stages),this.qual
1ies=6,this.qualyToFinal=10,this.ffa=!0,cup.grid_data&&(this.data=angular.fromJson(cup.grid_data))}function GGCupGridFFAM(cup,stages){GGCupGridSingle.apply(this,arguments),stages&&stages.length&&!cup.grid_data&&(this.data=stages),this.qualies=6,this.ffa=!0,cup.grid_data&&(this.data=angular.fromJson(cup.grid_data))}function GGCupGridOverwatch(cup,stages){GGCupGridSingle.apply(this,arguments),this._data=stages}function GGCupGridRRGroups(cup,stages){GGCupGridSingle.apply(this,arguments),this._data=stages}var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[],_n=!0,_d=!1,_e=void 0;try{for(var _s,_i=arr[Symbol.iterator]();!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{!_n&&_i.return&&_i.return()}finally{if(_d)throw _e}}return _arr}return function(arr,i){if(Array.isArray(arr))return arr;if(Symbol.iterator in Object(arr))return sliceIterator(arr,i);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();"serviceWorker"in navigator&&navigator.serviceWorker.register("/service-worker.js");var app=angular.module("GG");app.config(["$locationProvider","$urlRouterProvider",function($locationProvider,$urlRouterProvider){$locationProvider.html5Mode({enabled:!0,requireBase:!1}),$urlRouterProvider.otherwise(function($injector,$location){if("/jobs/"===$location.path().substring(0,6)){return $injector.get("$state").go("error_404"),$location.path()}})}]).run(function($rootScope,$interval,DateFunctions,$transitions,$timeout){$rootScope.$on("$stateChangeSuccess",function(event,toState){toState.data&&toState.data.noscroll||Utils.scrollToElement(!1,0)}),$interval(function(){},1e3),$rootScope.User=UserService,$rootScope.DateFunctions=DateFunctions,$rootScope.now=new Date,$rootScope.showLogin=function(message,eventSource){window.openLogin({message:message,eventSource:eventSource})};var loaderTimeout,started=!1;$transitions.onStart({},function(trans){loaderTimeout=$timeout(function(){started=!0,PageLoader.showLoader()},250),trans.promise.finally(function(){$timeout.cancel(loaderTimeout),started&&(PageLoader.hideLoader(),started=!1);try{var title=trans.injector().get("$title");title&&(document.title=title)}catch(e){window.DEV&&console.log(e)}})});$rootScope.isMobile=window.innerWidth<=767,$rootScope.$on("$stateChangeStart",function(event,url){url.redirectTo&&(event.preventDefault(),$state.go(url.redirectTo,params,{location:"replace"}))}),$interval(function(){$rootScope.isMobile=window.innerWidth<=767},2500),("?en"==window.location.search||UserService&&UserService.settings&&UserService.settings.beta[11])&&($rootScope.lang="en")}),"undefined"!=typeof CKEDITOR&&(CKEDITOR.disableAutoInline=!0),angular.module("GG").config(function($stateProvider,$urlRouterProvider,$locationProvider,$urlMatcherFactoryProvider){}),function(){var translations=[["Помощь","Help"],["Регистрация","Sign up"],["Вход","Sign in"],["Логин","Login"],["После завершения регистрации логин сменить нельзя","You can't change your login after registration is complete"],["Пароль","Password"],["Принимаю условия","I accept the terms of"],["«Пользовательского соглашения»",'"User Agreement"'],["«Политики конфиденциальности»",'"Privacy policy"'],["«Политики конфиденциальности»",'"Privacy policy"'],["и даю согласие на обработку моих персональных данных","and allow processing my personal data"],["Зарегистрироваться","Register"],["Войти через социальные сети","Sign in via social media"],["Войти, используя логин и пароль","Sign in via login/password"],["Вход через","Sign in via"],["Оставаться авторизованным","Keep me authorized"],["Забыли пароль?","Forgot your password?"],["Войти","Sign in"],["О турнире","About"],["Участники","Participants"],["Группы","Groups"],["Сетка","Bracket"],["Результаты","Results"],["Организатор","Organizer"],["Начало турнира","Tourney starts at:"],["Игра","Game"],["Призовой фонд","Prize pool"],["Призовые места","Prize places"],["Участвовать","Join"],["Отказаться",""],["Этот турнир еще никто не поддержал. Станьте первым!","No one has donated to this tournament yet. Be the first one!"],["Тип турнира","Tournament system"],["Судьи","Referees"],["Турнир опубликован","Tournament is published"],["Стримы","Streams"],["Этот турнир пока никто не планирует стримить. Станьте первым!","No one is going to stream the tournament. Be the first one!"],["Сообщения о пополнении призового фонда будут дублироваться в ваш чат.","Alerts of prize pool donations will be copied to your chat."],["Поддержавший","Donator"],["Пополнить","Donate"],["Список всех турниров","Other tournaments"],["Подтвердили участие","Checked-in"],["Зарегистрировались на турнире","Signed up for participation"],["Создать команду","Create new team"],["Название команды","Team name"],["Логотип команды","Team logo"],["Рекомендуемый формат и размеры:","Recommended image type and size:"],["Выбрать файл","Upload a file"],["Удалить","Delete"],["Добавить участника","Add new member"],["Сохранить","Save"],["Капитан","Team Captain"],["В составе","Roster"],["Игрок","Player"],["Игрока","Players"],["Игроков","Players"],["Состав команды","Team Roster"],["Команда для участия в турнире","Team for tournament"],["Капитан","Team Captain"],["В составе","Roster"],["Выбрать команду","Choose Team"],["Подтвердить состав","Confirm roster"],["Найти или создать команду","Find or create team"],["Указать свой никнейм в игре:","Your game ID"],["Подтвердить участие можно будет через","Check-in starts in"],["Подтвердить участие","Check-in"],["Отказаться от участия","Cancel participation"],["Я проиграл","Report lose"],["Чат с противником","Chat with your opponent"],["ВНИМАНИЕ! Если вы не успеете вовремя подтвердить участие, то вы не сможете принять участие в турнире","Attention! You won't be able to participate in the tournament if you don't check-in in time."],["Неправильный формат email","Wrong e-mail format"],["Минимальная длина пароля - 4 символа","Minimal password length - 4 characters"],["Пользователь с таким никнеймом уже зарегистрирован","Nickname is already in use"],["Неверная капча","Wrong captcha"],["Пользователь с таким адресом уже зарегистрирован","E-mail address is already in use"],["Мои турниры","My tournaments"],["Текущие турниры","Current tournaments"],["Игра","Game"],["Название","Tournament name"],["Призовой","Prize pool"],["Дата","Date"],["Участники","Players"],["Уже идет","In process"],["Другая","Other games"],["Открытые турниры","Open tournaments"],["Предстоящие турниры","Upcoming tournaments"],["Открытые турниры","Open tournaments"],["Предстоящие турниры","Upcoming tournaments"],["Организовать турнир","Organize tournament"],["Игровой профиль","Player profile"],["Место","Place"],["Рейтинг","Rating"],["Турнир","Tournament"],["Результат","Results"],["Приз","Prize"],["Вывести","Withdraw money"],["На счету","Money available"],["Мои команды","My teams"],["Показать прошедшие турниры","Show past tournaments"],["Буду стримить","I will stream"],["Сумма","Donated"],["Формат","Format"],["Недостаточно участников","Not enough participants"],["Всего:","Total"]];window._translate=function(string,lang){if(1!=("en"==lang?1:0))return string;var translation=translations.find(function(pair){return pair[0]===string});return translation&&translation[1]?translation[1]:string}}(),function(angular){function ggBan($scope,$element,$attrs){function onLoadedData(_data){var data=angular.fromJson(_data);vm.sign=data.nickname,vm.reasons=data.reasons,vm.loading=!1}var vm=this;vm.reason=0,vm.deleteMsg=0,vm.deleteMsgWithClean=0,vm.ipBan=0,vm.loading=!0,vm.init=function(){Utils.post("/ajax/moderation/get-ban-data/",{id:vm.objId,type:vm.objType}).then(onLoadedData)},vm.close=function(){BanPopup.close()},vm.makeBan=function(){confirm("Вы действительно хотите забанить этого пользователя?")&&Utils.post("/ajax/make_ban/",{obj_type:vm.objType,obj_id:vm.objId,reason:vm.reason,with_cleaning:vm.deleteMsgWithClean,ip_ban:vm.ipBan,delete_msg:vm.deleteMsg}).then(vm.callbackFunc)},vm.makeWarn=function(){confirm("Вы действительно хотите вынести предупреждение пользователю?")&&Utils.post("/ajax/make_warning/",{obj_type:vm.objType,obj_id:vm.objId,reason:vm.reason,with_cleaning:vm.deleteMsgWithClean,ip_ban:vm.ipBan,delete_msg:vm.deleteMsg}).then(vm.callbackFunc)},vm.callbackFunc=function(){vm.callback&&vm.args&&vm.callback(vm.args),vm.close()}}angular.module("GG").controller("ggBan",ggBan)}(angular),function(angular){function ggComplaint($scope){var vm=this;vm.reason=0,vm.text="",vm.loading=!0,vm.close=function(){ComplaintPopup.close()},vm.makeClaim=function(){Utils.post("/ajax/make-claim/",{id:vm.objId,type:vm.objType,reason:vm.reason,msg:vm.text}).then(vm.callbackFunc)},vm.callbackFunc=function(_data){var data=angular.fromJson(_data);alert(data.msg),data.success&&vm.close()}}angular.module("GG").controller("ggComplaint",ggComplaint)}
1(angular),function(angular){function ggDeactivationChannel($scope){var vm=this;vm.reason=1,vm.more={status:!1,text:""},vm.texts={1:"Спорт",2:"Порно",3:"Жалоба правообладателя",4:"Кривые настройки",5:"Отключение по запросу пользователя"},vm.close=function(){$(".subscribe-popup").fadeOut(300,function(){this.remove()})},vm.makeChange=function(){var oth=(vm.reason?vm.texts[vm.reason]:"")+" "+vm.more.text;Utils.post("/ajax/moderation/unpublish/",{key:vm.id,reason:vm.reason,other:oth}).then(function(){vm.callback&&vm.callback(vm.id),vm.close()})}}angular.module("GG").controller("ggDeactivationChannel",ggDeactivationChannel)}(angular),function(angular){function ggDeactivation($scope){var vm=this;vm.reason=1,vm.more={status:!1,text:""},vm.texts={1:"смурф",2:"систематическое нарушение правил",3:"систематический спам",4:"контент, нарушающий правила портала"},vm.close=function(){$(".subscribe-popup").fadeOut(300,function(){this.remove()})},vm.makeChange=function(){var oth=vm.reason?vm.texts[vm.reason]:vm.more.text;Utils.post("/ajax/user/"+vm.id+"/deactivate/",{reason:vm.reason,other:oth}).then(function(){vm.callback&&vm.callback(vm.id),vm.close()})},$scope.$watch("vm.status",function(value){1==value&&Utils.get("/ajax/user/"+vm.id+"/activate/").then(function(){vm.callback&&vm.callback(vm.id),vm.close()})}),$scope.$watch("vm.id",function(value){var url=window.url("1");value&&("moderation"==url?(vm.reason=1,vm.more.text="",vm.makeChange()):Utils.post("/ajax/user/info/id/",{id:vm.id}).then(function(data){data=angular.fromJson(data),vm.sign=data.nickname}))})}angular.module("GG").controller("ggDeactivation",ggDeactivation)}(angular),function(angular){function ggPremiumKeys($scope){function loadKeys(){vm.loading=!0,vm.data={keys:{},payments:{}},Utils.get("/ajax/premium/keycheck/",{key:vm.key,user:vm.user}).then(onLoadedData)}function onLoadedData(_data){_data.keys.sort(function(a,b){return a.activated<b.activated?-1:a.activated>b.activated?1:a.expire>b.expire?-1:a.expire<b.expire?1:0}),angular.extend(vm.data,angular.fromJson(_data)),vm.loading=!1}function resetKey(key){Utils.post("/ajax/premium/keyreset/?key="+vm.key+"&user="+vm.user,{key:key.key}).then(onLoadedData)}function deleteKey(key){Utils.post("/ajax/premium/keydelete/?key="+vm.key+"&user="+vm.user,{key:key.key}).then(onLoadedData)}function generateKeys(){var args={action:"generate",type:vm.type,number:vm.number,sendfile:vm.sendfile,forsale:vm.forsale,tier:vm.tier,duration:vm.duration};Utils.post("/premium/keygen/",args).then(function(data){vm.generated=data})}var vm=this;vm.data={keys:{},payments:{}},vm.key="",vm.user="",vm.type=1,vm.number=100,vm.forsale=1,vm.sendfile=1,vm.generated="",vm.duration=1,vm.tier=1,vm.load=loadKeys,vm.reset=resetKey,vm.delete=deleteKey,vm.generate=generateKeys}angular.module("GG").controller("ggPremiumKeys",ggPremiumKeys),ggPremiumKeys.$inject=["$scope"]}(angular),function(){function ggSmilesAdmin($scope){function loadData(){Utils.get("/ajax/smiles/list/").then(onLoad)}function onLoad(raw){var data=angular.fromJson(raw);data.smiles&&(vm.smiles=data.smiles),data.admin&&(vm.isAdmin=!0),$scope.$apply(),vm.isLoading=!1}function addSmile(){vm.showEdit=!0,vm.currentSmile={},vm.errors=[]}function editSmile(smile){vm.showEdit=!0,vm.currentSmile=angular.copy(smile),vm.errors=[]}function saveSmile(smile){if(!(vm.errors.img||vm.errors.img_big||vm.errors.img_gif)){if(!smile.name)return void(vm.errors.name="Код не может быть пустым");var data=new FormData;data.append("id",smile.id||0),data.append("name",smile.name||""),data.append("bind",smile.bind||"");var channelId=0;smile.channel&&(channelId=smile.channel_id),data.append("channel_id",channelId),data.append("donat",smile.donat),data.append("premium",+smile.premium),data.append("paid",+smile.paid),_files[0]&&data.append("smile",_files[0]),_files[1]&&data.append("big_smile",_files[1]),_files[2]&&data.append("gif_smile",_files[2]),$.ajax({url:"/ajax/smile/save/",type:"POST",data:data,dataType:"json",processData:!1,contentType:!1}).success(function(data){if(data&&data.errors)return vm.errors=data.errors,void vm.$scope.$apply();if(data&&"OK"==data.status){vm.errors=[],_files=[!1,!1],smile=data.smile;
1var index=findRowBySmileId(smile.id);index>-1?vm.smiles[index]=smile:vm.smiles.push(smile),vm.showEdit=!1,vm.$scope.$apply()}else console.log(data)}).error(function(e){console.error(e)})}}function deleteSmile(smile){if(smile&&smile.id)return!!confirm("Вы действительно хотите удалить смайл "+smile.name+"?")&&void $.post("/ajax/smile/delete/",{id:smile.id},function(data){if(data.status&&"OK"==data.status){var index=findRowBySmileId(smile.id);index>-1&&(vm.smiles.splice(index,1),vm.$scope.$apply())}},"json")}function upload(event){var block=$(event.target).closest(".smile-upload"),targetId=$(event.target).attr("id"),webUrl=window.URL||window.webkitURL;"upload-static"==targetId?(vm.currentSmile.img=webUrl.createObjectURL(event.target.files[0]),_files[0]=event.target.files[0]):"upload-static-big"==targetId?(vm.currentSmile.img_big=webUrl.createObjectURL(event.target.files[0]),_files[1]=event.target.files[0]):"upload-gif"==targetId&&(vm.currentSmile.img_gif=webUrl.createObjectURL(event.target.files[0]),_files[2]=event.target.files[0]),block.find("img").on("load",function(){$(this).show(),doCheck(block)}),vm.$scope.$apply()}function doCheck(block){var img,sizes=!1;0!=_files[0]&&(img=block.find(".upload-image img")[0],sizes=!!img.naturalHeight&&[img.naturalHeight,img.naturalWidth],"image/png"==_files[0].type&&sizes?sizes&&18!=sizes[0]?vm.errors.img="Неверные размеры":vm.errors.img=!1:vm.errors.img="Неверный формат"),0!=_files[1]&&(img=block.find(".upload-image img")[1],sizes=!!img.naturalHeight&&[img.naturalHeight,img.naturalWidth],"image/png"==_files[1].type&&sizes?sizes&&(36!=sizes[0]||sizes[1]<10||sizes[1]>72)?vm.errors.img_big="Неверные размеры":vm.errors.img_big=!1:vm.errors.img_big="Неверный формат"),0!=_files[2]&&(img=block.find(".upload-image img")[2],sizes=!!img.naturalHeight&&[img.naturalHeight,img.naturalWidth],"image/gif"==_files[2].type&&sizes?sizes&&(36!=sizes[0]||sizes[1]<10||sizes[1]>72)?vm.errors.img_gif="Неверные размеры":vm.errors.img_gif=!1:vm.errors.img_gif="Неверный формат"),vm.$scope.$apply()}function autocompleteChannel(channel){vm.currentSmile.channel=channel.title,vm.currentSmile.channel_id=channel.id,vm.$scope.$apply()}function findRowBySmileId(smileId){for(var index=-1,i=0,len=vm.smiles.length;i<len;i++)if(vm.smiles[i].id==smileId){index=i;break}return index}var vm=this;vm.$scope=$scope;var root,_files=[!1,!1,!1];vm.smiles=[],vm.currentSmile=null,vm.isAdmin=!1,vm.isLoading=!0,vm.addSmile=addSmile,vm.editSmile=editSmile,vm.saveSmile=saveSmile,vm.deleteSmile=deleteSmile,vm.acChannel=autocompleteChannel,function(){root=$("gg-modal-window"),root.on("change",".upload-form input",upload).find(".upload-image").find("img").on("error",function(event){$(event.target).hide()}),loadData()}()}angular.module("GG").controller("ggSmilesAdmin",ggSmilesAdmin).directive("convertToNumber",function(){return{require:"ngModel",link:function(scope,element,attrs,ngModel){ngModel.$parsers.push(function(val){return parseInt(val,10)}),ngModel.$formatters.push(function(val){return""+val})}}})}(),function(angular){function ggUnpaidPayments($scope){function loadData(){0==vm.currentPage&&(vm.currentPage=1);var query={ajax:!0,page:vm.currentPage};""!=vm.user&&(query.user=vm.user),""!=vm.channel&&(query.channel=vm.channel),""!=vm.streamer&&(query.streamer=vm.streamer),vm.data={},vm.loaded=!1;var ajaxUrl=window.all?"/payments/all/":"/payments/unpaid/";Utils.get(ajaxUrl,query).then(onLoadedData)}function onLoadedData(_data){angular.extend(vm,angular.fromJson(_data)),vm.loaded=!0}function getProvider(provider){switch(parseInt(provider)){case 0:return"Че за хрень?";case 1:return"Банк (старый)";case 2:return"WebMoney";case 3:return"Яндекс.Деньги";case 4:return"QIWI";case 5:return"PayPal";case 6:return"Кошелек GG";case 7:return"Xsolla";case 8:return"Карта";case 17:return"Intervale";case 21:return"Smartglocal";case 22:return"Intervale QR Code";case 26:return"Ckassa";case 99:case 100:case 101:case 102:case 103:return"Заглушка-согласушка";default:return provider}}function setPaid(payment){Utils.post("/ajax/payment/paid/",{id:payment.id}).then(function(){payment.paid=!0})}function check(payment){Utils.post("/ajax/payment/check/",{id:payment.id}).then(function(data){!0===data.success?payment.paid=!0:alert(payment.message||"Фатальная ошибка")})}var vm=this;vm.data={},vm.user="",vm.channel="",vm.streamer="",vm.loaded=!1,vm.load=loadData,vm.provider=getProvider,vm.paid=setPaid,vm.check=check,vm.currentPage=0,vm.totalPages=0;var pageTimeout=0;$scope.$watch("vm.currentPage",function(newValue,oldValue){oldValue&&newValue&&newValue!=oldValue&&(clearTimeout(pageTimeout),pageTimeout=setTimeout(loadData,150))}),loadData()}angular.module("GG").controller("ggUnpaidPayments",ggUnpaidPayments),ggUnpaidPayments.$inject=["$scope"]}(angular),function(){angular.module("GG").config(["$stateProvider","$urlRouterProvider",function($stateProvider,$urlRouterProvider){$urlRouterProvider.when("/channels","/channels/"),$stateProvider.state("channelsList",{url:"/channels/",controller:"ggChannelsList",controllerAs:"$ctrl",templateUrl:"/html/channels/list.html",resolve:{gameUrl:function(){return null},genreId:function(){return null},$title:function(){return"Стримы прохождения игр. Трансляции онлайн-игр"}}}).state("channelsList.Games",{url:"games/"}).state("channelsList.Genres",{url:"genres/",resolve:{$title:function(){return"Стримы прохождения игр: поиск по жанру игры"}}}).state("channelsListGame",{url:"/channels/games/{game}",controller:"ggChannelsList",controllerAs:"$ctrl",templateUrl:"/html/channels/list.html",resolve:{gameUrl:["$stateParams",function($stateParams){return $stateParams.game}],genreId:function(){return null},$title:["gameUrl",function(gameUrl){return"Стримы прохождения игр. Трансляции онлайн-игр. Все трансляции по "+gameUrl}
1]}}).state("channelsListGenre",{url:"/channels/genres/{genreId}",controller:"ggChannelsList",controllerAs:"$ctrl",templateUrl:"/html/channels/list.html",resolve:{genreId:["$stateParams",function($stateParams){return $stateParams.genreId}],gameUrl:function(){return null},$title:function(){return"Стримы прохождения игр: поиск по жанру"}}})}])}(),function(){function ggChannelsService(){function getChannelsList(byGame,page){return byGame=byGame||0,page=page||1,Utils.get(AJAX_PATH+"/channels/get",{game:byGame,page:page}).then(function(data){return angular.fromJson(data)})}function getChannelsListByGenre(genreId,page){return genreId=genreId||0,page=page||1,Utils.get(AJAX_PATH+"/channels/get-by-genres",{genre:genreId,page:page}).then(function(data){return angular.fromJson(data)})}this.getChannelsList=getChannelsList,this.getChannelsListByGenre=getChannelsListByGenre}angular.module("GG").service("ggChannelsService",ggChannelsService),ggChannelsService.$inject=[]}(),function(){function ggChannelsList($scope,$rootScope,gameUrl,genreId,channelsService,$timeout){function onLoadData(data){if(vm.isLoadingMore=!1,!data)return void(vm.isShowMoreButton=!1);for(var item in data.channels)vm.channels.push(data.channels[item]);vm.game=data.game||!1,vm.genre=data.genre||!1,Object.keys(data.channels).length>=CHANNELS_LIMIT?vm.isShowMoreButton||(vm.isInfiniteScrollEnabled=!0):vm.isShowMoreButton=!1}function loadMoreStreams(){vm.isLoadingMore=!0,vm.isShowMoreButton=!1,vm.isInfiniteScrollEnabled=!1,_loadMoreData()}function _loadMoreData(){vm.genre?channelsService.getChannelsListByGenre(vm.genre.id,++vm.page).then(function(data){return onLoadData(data)}):channelsService.getChannelsList(!!vm.game&&vm.game.url,++vm.page).then(function(data){return onLoadData(data)})}var CHANNELS_LIMIT=40,vm=this;vm.loadMoreStreams=loadMoreStreams,function(){vm.page=0,vm.channels=[],vm.isShowMoreButton=!0,vm.isInfiniteScrollEnabled=!1,vm.game=gameUrl?{url:gameUrl}:null,vm.genre=genreId?{id:genreId}:null,console.log(vm),_loadMoreData(),$timeout(function(){$rootScope.$broadcast("ggCarouselScrollToSelectedOnce")},500)}()}angular.module("GG").controller("ggChannelsList",ggChannelsList),ggChannelsList.$inject=["$scope","$rootScope","gameUrl","genreId","ggChannelsService","$timeout"]}(),function(){function ggClip($scope,$attrs){var clip=this;clip.OBJ_CLIP=28,clip.deleted=1==$attrs.deleted,clip.save=function(){Utils.post("/ajax/clip/save/",{id:$attrs.clipId,title:clip.title,adult:clip.adult}),clip.edit=!1},clip.delete=function(){Utils.post("/ajax/moderation/unpublish/",{key:"28-"+$attrs.clipId}).then(function(data){return clip.deleted=!0})},clip.undelete=function(){Utils.post("/ajax/moderation/publish/",{key:"28-"+$attrs.clipId}).then(function(data){return clip.deleted=!1})},clip.complain=function($event){if(!UserObj.id)return void $scope.$root.showLogin("Чтобы отправить жалобу на клип, нужен аккаунт. Войдите или зарегистрируйтесь: мы учтем ваше обращение и быстрее разберемся в ситуации.","auth_source_clip_report");ComplaintPopup.open(clip.OBJ_CLIP,$attrs.clipId,$event.currentTarget)}}angular.module("GG").controller("ggClip",ggClip)}(),angular.module("GG").config(function($stateProvider){$stateProvider.state("clips",{url:"/clips",redirectTo:"clips.new",data:{noscroll:!0},abstract:!0,views:{list:{templateUrl:"/html/clips/list.html",controller:"ggClipsList",controllerAs:"$ctrl"}}}).state("clips.rootSlash",{url:"/",redirectTo:"clips.new",data:{noscroll:!0}}).state("clips.new",{url:"",data:{noscroll:!0}}).state("clips.new2",{url:"new/",redirectTo:"clips.new",data:{noscroll:!0}}).state("clips.favorites",{url:"favorites/",data:{noscroll:!0}}).state("clips.mine",{url:"mine/",data:{noscroll:!0}}).state("clips.channel",{url:"channel/",data:{noscroll:!0}}).state("clips.nostalgy",{url:"nostalgy/",data:{noscroll:!0}})}),function(angular){var ggClipsCarousel=function(){function ggClipsCarousel($scope){_classCallCheck(this,ggClipsCarousel),this.classes=["first","second","third"]}return _createClass(ggClipsCarousel,[{key:"$onInit",value:function(){this.list=angular.fromJson(this.clips),this.list.map(function(item,index){return item.$index=index}),this.titles=[this.list[2],this.list[0],this.list[1]],this.setClasses()}},{key:"setClasses",value:function(){var _this=this;this.list.map(function(item,index){return item.class=_this.classes[index]})}},{key:"rotate",value:function(index){var first=this.list.shift();first.$index=this.list[this.list.length-1].$index+1,this.list.push(first),this.titles=[this.list[2],this.list[0],this.list[1]],this.setClasses(),2==index&&this.rotate(1)}}]),ggClipsCarousel}();angular.module("GG").component("ggClipsCarousel",{controller:ggClipsCarousel,templateUrl:"/html/clips/clipsOfTheDay.html",bindings:{clips:"@"}})}(angular),function(){var ggClipsList=function(){function ggClipsList($state,$scope){var _this2=this;_classCallCheck(this,ggClipsList),this.loading=!1,this.empty=!1,this.more=!1,this.page=1,this.tab=null,this.days={},this.list=[],$scope.$watch(function(){return $state.current.name},function(stateName){_this2.loadData(stateName)});var currentState=$state.current&&$state.current.name;this.loadData(currentState)}
1return _createClass(ggClipsList,[{key:"loadData",value:function(tab){var _this3=this;tab&&(this.loading&&this.tab===tab||(this.list=[],this.days={},this.loading=!0,this.tab=tab,Utils.get("/ajax/clips/",{tab:this.tab}).then(function(response){return _this3.onLoadTab(response)}).catch(function(){return _this3.loading=!1})))}},{key:"onLoadTab",value:function(response){var list=response&&response.list?response.list:[],total=response&&response.total?response.total:0;this.loading=!1,this.page=1,this.list=list,this.parseDays(list,!0),this.empty=0===list.length,this.more=total>this.list.length}},{key:"onLoadPage",value:function(response){var list=response&&response.list?response.list:[],total=response&&response.total?response.total:0;this.list=this.list.concat(list),this.parseDays(list),this.more=total>this.list.length}},{key:"loadMore",value:function(){var _this4=this;this.page++,Utils.get("/ajax/clips/",{tab:this.tab,page:this.page}).then(function(response){return _this4.onLoadPage(response)}).catch(function(){_this4.loading=!1})}},{key:"parseDays",value:function(list){var _this5=this;arguments.length>1&&void 0!==arguments[1]&&arguments[1]&&(this.days={}),list.forEach(function(clip){var day=new Date(1e3*clip.created);day.setHours(0,0,0,0);var dayInt=+day,dayStr=_this5.getDateString(day);_this5.days[dayInt]||(_this5.days[dayInt]={title:dayStr,clips:[]}),_this5.days[dayInt].clips.push(clip)})}},{key:"getDateString",value:function(date){var months=["января","февраля","марта","апреля","мая","июня","июля","августа","сентября","октября","ноября","декабря"],dateStr=date.getDate()+" "+months[date.getMonth()],today=new Date;return today.setHours(0,0,0,0),+date==+today?"Сегодня, "+dateStr:today-date==864e5?"Вчера, "+dateStr:(date.getFullYear()!=today.getFullYear()&&(dateStr+=" "+date.getFullYear()),dateStr)}}]),ggClipsList}();angular.module("GG").controller("ggClipsList",ggClipsList)}(),function(){function BanController($scope,PopupService){var ban=this,BanTypes={duration:0,stream:1,permanent:2};ban.duration2="20min",ban.reason=1,ban.deleteMessage=!0,ban.hideBan=!1,ban.allChats=!1,ban.reasons={1:{duration:20,min:0,max:30},2:{duration:60,min:0,max:120},3:{duration:2880,min:30,max:4320},4:{duration:120,min:0,max:43200}},ban.customValue=20,ban.textValue="20 минут",$scope.$watch("vm.view.banUser",function(){$scope.user=$scope.vm.view.banUser,$scope.message=$scope.vm.view.message}),$scope.$watch("ban.reason",function(data){ban.customValue=ban.reasons[data].duration}),$scope.makeBan=function(){var data={userId:$scope.user.id,hidden:ban.hideBan,roomId:"",reason:"",comment:"",type:BanTypes.duration,
2duration:0,deleteMessage:!0};if($scope.vm.room.user.rights<=20)switch(ban.duration2){case"20min":data.duration=20;break;case"stream":data.duration=0,data.type=BanTypes.stream;break;case"month":data.duration=43200;break;case"unlim":data.duration=0,data.type=BanTypes.permanent}else{switch(parseInt(ban.reason)){case 1:data.reason="Смайлабуз, флуд";break;case 2:data.reason="Провоцирование";break;case 3:data.reason="Маты, оскорбления";break;case 4:data.reason=ban.comment}$scope.vm.view.banUserTillStreamEnd?(data.duration=0,data.type=BanTypes.stream):data.duration=ban.customValue}data.deleteMessage=ban.deleteMessage,data.hidden=ban.showBan,$scope.message?(data.comment=$scope.message.text||"",$scope.vm.Chat.room().banUser(data,$scope.message)):(data.comment="",data.deleteMessage=!1,$scope.vm.Chat.room().banUser(data,null)),$scope.vm.view.banUser=!1,PopupService.close("ban-user")}}angular.module("GG").controller("ggChatBan",BanController),BanController.$inject=["$scope","PopupService"]}(),function(){function BannedListController($scope){function unban(user){$scope.vm.room.unBanUser(user.id),list.banned=list.banned.filter(function(u){return u!=user})}function _filterUsers(){list.banned=_getBanned(all)}function _getBanned(users){return users.filter(function(user){return user&&user.nickname&&-1!==user.nickname.toUpperCase().indexOf(list.search.toUpperCase())})}var list=this;list.unban=unban,list.search="";var room=$scope.vm.room,all=(room.user.rights,[]);!function(){room.getBannedList().then(function(users){all=users,_filterUsers(),$scope.$applyAsync()})}(),$scope.$watch("list.search",_filterUsers)}angular.module("GG").controller("ggChatBannedList",BannedListController),BannedListController.$inject=["$scope"]}(),function(){function ChatController($scope,$rootScope,$timeout,SmilesService,SettingsService,PopupService,gg4UserService){function privateMessage(){SettingsService.sound&&(soundMsg.loop=!1,soundMsg.volume=SettingsService.soundVolume/100,soundMsg.play())}function _showDayMessage(){$timeout(function(){var motd=document.querySelector(".day-message");motd&&motd.classList.remove("closed")})}function cancelMotd(){if(timeout&&$timeout.cancel(timeout),vm.room.motd){var motd=document.querySelector(".day-message");motd?motd.classList.add("closed"):timeout=$timeout(function(){return vm.cancelMotd()},3e3)}}function toggleSmiles(){vm.view.smiles=!vm.view.smiles,vm.selectorSmiles=!vm.selectorSmiles,$timeout(function(){vm.view.smiles?PopupService.open("smiles"):PopupService.close("smiles")})}function selectedSmile(smile){console.log("selectedSmile",smile),vm.view.smiles=!vm.view.smiles,vm.selectorSmiles=!vm.selectorSmiles,vm.view.pasteSmile(smile)}function trackEvent(event){Utils.reachGoal(event)}function greetingDone(event){vm.newUserPopup=0,console.log("greetingDone",{event:event});var greetingMessage=vm.room.streamer.nickname+", привет! :"+event.smile+":";console.log(vm.room,vm.Chat.room()),vm.room.on("joined",function(){if(console.log("after join:",greetingMessage),!greetingMessage)return!1;vm.room.sendMessage(greetingMessage,{color:"simple",icon:"none",mobile:0}),greetingMessage=""})}function inviteAuthDone(event){var inviteMessage=vm.room.streamer.nickname+", привет! :"+event.smile+":. Меня пригласил "+event.inviter+".";vm.room.on("joined",function(){vm.room.sendMessage(inviteMessage,{color:"simple",icon:"none",mobile:0}),inviteMessage=""})}function closeGreeting(){vm.newUserPopup=0}function startGreeting(){vm.newUserPopup=1,Utils.reachGoal("chat_greeting_start")}function toggleUsersList(){vm.view.usersList?_closeUsersList():_openUsersList()}function setCountPinnedQuest(event){vm.countPinnedQuest=event}function _openUsersList(){vm.view.usersList=!0,$timeout(function(){PopupService.open("users-list")})}function _closeUsersList(){vm.view.usersList=!1,PopupService.close("users-list")}function parseEvent(type,data){switch(type){case"task":vm.questId=data,_openTaskList();break;case"pasteNick":pasteNick(data);break;case"pasteGiftNick":vm.view.pasteNick(data,!1,!1,"user")}}function toggleTaskList(){vm.questId=0,vm.view.taskList?_closeTaskList():_openTaskList()}function toggleFriendInvite(){vm.questId=0,vm.view.friendInvite?_closeFriendInvite():_openFriendInvite()}function toggleDonat(){vm.view.donat?_closeDonat():_openDonat()}function _openDonat(){vm.view.donat=!0,PopupService.open("donat")}function _closeDonat(){vm.view.donat=!1,PopupService.close("donat")}function _openTaskList(){vm.view.taskList=!0,$timeout(function(){PopupService.open("task-list")})}function replenish(data){vm.questId=data,_openTaskList()}function _closeTaskList(){vm.view.taskList=!1,PopupService.close("task-list")}function _openFriendInvite(){vm.view.friendInvite=!0,$timeout(function(){PopupService.open("friend-invite")})}function _closeFriendInvite(){vm.view.friendInvite=!1,PopupService.close("friend-invite")}function openSettings(){vm.view.settings?PopupService.close("chat-settings"):PopupService.open("chat-settings"),vm.view.settings=!vm.view.settings}function openPoll(){vm.view.pollWindow=!0,$timeout(function(){PopupService.open("poll")}
2)}function banUser(user,message){vm.view.banUser=user,message&&(vm.view.message=message),$timeout(function(){PopupService.open("ban-user")})}function banUserTillStreamEnd(user,message){vm.view.banUser=user,vm.view.banUserTillStreamEnd=!0,message&&(vm.view.message=message),$timeout(function(){PopupService.open("ban-user")})}function unBanUser(user){$scope.vm.Chat.room().unBanUser(user.id,$scope.message),_closeUsersList()}function showIgnoreList(){vm.view.igroneList=!0,$timeout(function(){PopupService.open("ignore-list")})}function showHelpersList(){vm.view.helpersList=!0,$timeout(function(){PopupService.open("helpers-list")})}function openRandomizer(){vm.view.randomizer=!0,$timeout(function(){PopupService.open("randomizer")})}function warnUser(userId){vm.Chat.room().warnUser(userId)}function chatInWindow(){var chatDimensions={},left=chatDimensions.left||"0",top=chatDimensions.top||"0",height=chatDimensions.height||"750",width=chatDimensions.width||"450",winParams="left="+left+",top="+top+",height="+height+",width="+width+",location=0,menubar=0,resizable=1,scrollbars=0,status=0",url="/chat/"+vm.room.id;vm.room.isStream()&&(url="/"+(vm.room.streamer.username||vm.room.streamer.name)+"/chat");var nwin=window.open(url,"chat",winParams);nwin.onload=function(){console.log(),nwin.document.getElementsByTagName("body")[0].classList.add("old-site"),nwin.focus()}}function showBanned(){vm.view.bannedList=!0,$timeout(function(){PopupService.open("banned-list")})}function donateRng(){var colorArr=["#a06108","#565656","#808400","#484599","#108c86","#0079a4"],btn=document.querySelector(".control-panel .donate-block"),rnd=colorArr[Math.floor(Math.random()*colorArr.length)],feedBtn=document.querySelector(".head-container .nav-tabs");btn&&(btn.style.backgroundColor=rnd),feedBtn&&feedBtn.addEventListener("click",function(){rnd=colorArr[Math.floor(Math.random()*colorArr.length)],btn.style.backgroundColor=rnd})}function pasteNick(event){vm.view.pasteNick(event,!1,!0)}var motd,timeout,vm=this;vm.view={},vm.Chat=Chat.on("update",function(){return $scope.$applyAsync()}),Chat.on("updateChannelJobs",function(room,jobs){window.DEV&&console.log(room,jobs,vm.room.jobs),vm.room.jobs=jobs.enabled,$scope.$applyAsync()}),$scope.PremiumPopup=PremiumPopup,$scope.DonatPopup=DonatPopup,$scope.$root.chat=vm,vm.smiles=SmilesService,vm.settings=SettingsService,vm.chatShow=0,vm.premHide=!1,vm.questId=0,vm.view.friendInvite=!1,vm.chatInWindow=chatInWindow,vm.cancelMotd=cancelMotd,vm.openSettings=openSettings,vm.openPoll=openPoll,vm.toggleSmiles=toggleSmiles,vm.toggleUsersList=toggleUsersList,vm.toggleTaskList=toggleTaskList,vm.toggleFriendInvite=toggleFriendInvite,vm.toggleDonat=toggleDonat,vm.parseEvent=parseEvent,vm.banUser=banUser,vm.banUserTillStreamEnd=banUserTillStreamEnd,vm.unBanUser=unBanUser,vm.showIgnoreList=showIgnoreList,vm.showHelpersList=showHelpersList,vm.warnUser=warnUser,vm.showBanned=showBanned,vm.openRandomizer=openRandomizer,vm.donateRng=donateRng,vm.pasteNick=pasteNick,vm.setCountPinnedQuest=setCountPinnedQuest,vm.replenish=replenish,vm.selectedSmile=selectedSmile,vm.trackEvent=trackEvent,vm.greetingDone=greetingDone,vm.closeGreeting=closeGreeting,vm.inviteAuthDone=inviteAuthDone,vm.startGreeting=startGreeting,vm.selectorSmiles=!1,vm.pinnedQuests=[],vm.countPinnedQuest=0,vm.isSafari=!1,vm.isChrome=!1,vm.newUserPopup=0,vm.isChrome=window.navigator.userAgent.indexOf("Chrome")>-1,vm.isSafari=window.navigator.userAgent.indexOf("Safari")>-1,vm.isChrome&&vm.isSafari&&(vm.isSafari=!1),$scope.$parent.chatRoom?(vm.room=Chat.room($scope.$parent.chatRoom),vm.room&&vm.room.on("private_message",privateMessage)):$scope.$watch(function(){return Chat.room()},function(){vm.room=Chat.room(),vm.room&&vm.room.on("private_message",privateMessage)}),$scope.$watch("vm.room.streamer",function(streamer){if(!streamer||!vm.room.isStream())return void(vm.pinnedQuests=[]);Utils.get("/api/4/jobs/forchat",{user:streamer.id}).then(function(data){vm.pinnedQuests=data.pinned,vm.activeQuests=data.active,vm.countPinnedQuest=(vm.pinnedQuests||[]).length,$scope.$applyAsync()})}),$scope.$watch("vm.room.user",function(){vm.room&&vm.room.user&&(vm.room.user.settings=SettingsService),SmilesService.resetCache()}),$scope.$watch("vm.room.poll",function(data,oldData,scope){data&&data.channel_id&&!scope.vm.view.pollWindow&&openPoll()},!0),$scope.$watch("vm.room.motd",function(data){motd!=data&&(_showDayMessage(),$scope.$broadcast("chat-settings-motd-edit",data),motd=data,timeout=$timeout(function(){vm.cancelMotd()},3e3))}),vm.view.nickAdditionalMargin=!1,$rootScope.$on("nickAutocompleteSettings",function(event,args){vm.view.nickAdditionalMargin=args.additionalMargin,$scope.$applyAsync()}),$rootScope.$on("popup.close",function(e,id){"poll"===id&&(vm.view.pollWindow=!1),"users-list"===id&&(vm.view.usersList=!1),"task-list"===id&&(vm.view.taskList=!1),"ignore-list"===id&&(vm.view.igroneList=!1),"donat"===id&&(vm.view.donat=!1),"helpers-list"===id&&(vm.view.helpersList=!1),"banned-list"===id&&(vm.view.bannedList=!1),"day-message"===id&&cancelMotd(),"randomizer"
2===id&&(vm.view.randomizer=!0)}),Chat.on("updateStreamerInRoom",function(data){vm.room=Chat.room(),$scope.$applyAsync()});var soundMsg=new Audio("/files/msg2.mp3")}angular.module("GG").controller("ggChat",ChatController),ChatController.$inject=["$scope","$rootScope","$timeout","SmilesService","SettingsService","PopupService","gg4UserService"]}(),function(){function HelpersListController($scope){function deleteHelper(user){room.deleteHelper(user.id).then(function(){$scope.$apply()})}var list=this,room=$scope.vm.room;list.users=room.getHelpers(),list.delete=deleteHelper}angular.module("GG").controller("ggChatHelpersList",HelpersListController),HelpersListController.$inject=["$scope"]}(),function(){function IconService(SettingsService){function _adminColor(rights){return{10:"streamer",20:"streamer",30:"moderator",40:"moderator",50:"moderator"}[rights]}function _adminIcon(rights){return{10:"helper",30:"moderator",40:"moderator",50:"moderator"}[rights]}function _isColorAvaiable(user,color){return(-1!=["simple","premium","premium-personal","streamer","moderator"].indexOf(color)||-1!=paymentsColors.indexOf(color))&&("simple"==color||!("premium"==color&&!user.commonPremium)&&(!("premium-personal"==color&&!user.roomPremium)&&(!("streamer"==color&&user.rights<20)&&(!("moderator"==color&&user.rights<30)&&!(paymentsColors.indexOf(color)>user.payments)))))}function _isIconAvaiable(user,icon){if(-1===["none","staff","lawyer","star","moderator","ggplus"].concat(paymentsIcons,inviteIcons).indexOf(icon))return!1;if("none"==icon)return!0;if("staff"==icon&&!user.staff)return!1;if("lawyer"==icon&&!user.lawyer)return!1;if("star"==icon&&!user.premium)return!1;if("moderator"==icon&&user.rights<=20)return!1;if("ggplus"==icon&&user.ggPlusTier>0)return!0;if(icon.indexOf("invite")>-1){return(icon.match(/invite-(\d+)$/)[1]||0)<=user.inviteLevels[0]}return!(paymentsIcons.indexOf(icon)>user.payments)}function _getCustomColor(user){if(!user||!user.settings)return!1;try{return!!user.roomid&&user.settings.customColors[user.roomid]}catch(e){return!1}}function _getCustomIcon(user){if(!user||!user.settings)return!1;try{return!!user.roomid&&user.settings.customIcons[user.roomid]}catch(e){return!1}}var service=this;service.getColor=function(user,data){var userColor=user.color||(data?data.color:""),isNewGuy=Date.now()/1e3-user.regtime<86400;return!user.staff&&_adminColor(user.rights)?_adminColor(user.rights):isNewGuy?"newguy":userColor&&(user.staff||_isColorAvaiable(user,userColor))?userColor:_getCustomColor(user)?_getCustomColor(user):_adminColor(user)?_adminColor(user):paymentsColors[user.payments]?paymentsColors[user.payments]:user.roomPremium?"premium-personal":user.commonPremium?"premium":"simple"},service.getRole=function(user){return user.ggPlusTier<7?"":user.role?user.role:user.settings?user.settings.role:""},service.getIcon=function(user,data){var userIcon=user.icon||(data?data.icon:"");return 1===user.mobile?"phone":2===user.mobile?"ios":3===user.mobile?"win":4===user.mobile?"android":userIcon&&_isIconAvaiable(user,userIcon)?userIcon:_getCustomIcon(user)?_getCustomIcon(user):user.staff?"staff":user.lawyer?"lawyer":_adminIcon(user.rights)?_adminIcon(user.rights):paymentsIcons[user.payments]?paymentsIcons[user.payments]:user.roomPremium?"star":user.ggPlusTier>=0?"ggplus":user.commonPremium?"star":"none"};var paymentsColors=["","bronze","silver","gold","diamond","king","undead","gradient-fire","gradient-cherry","gradient-mushroom","top-one"],paymentsIcons=["","coin","eagle","cup","diamond","crown","undead","fire","cherry","mushroom","top1"],inviteIcons=["invite","invite-1","invite-2","invite-3"];this.colors=paymentsColors,this.icons=paymentsIcons,this.inviteIcons=inviteIcons}angular.module("GG").service("IconService",IconService),IconService.$inject=["SettingsService"]}(),function(){function IgnoreListController($scope){function _filter(){if(list.users=[],list.search)for(var i in users)-1!=users[i].nickname.toUpperCase().indexOf(list.search.toUpperCase())&&list.users.push(users[i]);else list.users=users}function deleteFromIgnore(user){rooms.deleteFromIgnoreList(user.id).then(function(){$scope.$apply()})}var list=this,rooms=$scope.vm.Chat.rooms,users=rooms.ignoreList;$scope.$watch("list.search",function(){_filter()}),list.delete=deleteFromIgnore}angular.module("GG").controller("ggChatIgnoreList",IgnoreListController),IgnoreListController.$inject=["$scope"]}(),function(angular){angular.module("GG").directive("chatMessages",function(){function chatMessages($scope,element){function scrollDown(){if(!isScrollable())return void($scope.vm.room&&($scope.vm.room.newmsg++,$scope.$applyAsync()));$scope.vm.room&&($scope.vm.room.newmsg=0,$scope.$applyAsync()),content.stop().animate({scrollTop:content[0].scrollHeight-content[0].clientHeight}
2,ANIMATION_SPEED,"linear"),clearTimeout(clearOldTimeout),clearOldTimeout=setTimeout(function(){return clearOldMessages()},ANIMATION_SPEED)}function mouseWheel(){if(!(performance.now()-lastMouseWheel<100)){lastMouseWheel=performance.now(),content.stop();var scrollDiff=content[0].scrollHeight-content[0].clientHeight-content.scrollTop();stopScrolling=scrollDiff>30,stopScrollingExternal=!1,$scope.vm.room.newmsg&&!stopScrolling&&($scope.vm.room.newmsg=0,$scope.$applyAsync())}}function clearOldMessages(){isScrollable()&&$scope.vm.room&&($scope.vm.room.messages.splice(0,$scope.vm.room.messages.length-MAX_MESSAGES),$scope.$applyAsync())}function isScrollable(){return!(stopScrolling||stopScrollingExternal||$scope.vm.view.user||$scope.vm.room&&$scope.vm.room.newmsg>2)}var MAX_MESSAGES=100,ANIMATION_SPEED=330,stopScrolling=!1,stopScrollingExternal=!1;$scope.vm.view.doScroll=scrollDown;var content=element.find(".tse-scroll-content");content.length||(content=element.find(".tse-scrollable")),content[0].addEventListener("wheel",mouseWheel,{passive:!0}),content[0].addEventListener("DOMMouseScroll",mouseWheel,{passive:!0});var dragHandle=element.find(".tse-scrollbar .drag-handle");dragHandle.on("mousedown",function(){return stopScrollingExternal=!0}),dragHandle.on("mouseup",function(){mouseWheel(),stopScrollingExternal=!1}),$scope.$on("$destroy",function(){content.off("wheel"),content.off("DOMMouseScroll")});var lastScrollTime=0,nextScrollTimeout=0;$scope.$watch("vm.room.messages.length",function(){performance.now()-lastScrollTime>=ANIMATION_SPEED?(setTimeout(function(){return scrollDown()},100),clearTimeout(nextScrollTimeout),lastScrollTime=performance.now()):nextScrollTimeout=setTimeout(function(){return scrollDown()},ANIMATION_SPEED)});var clearOldTimeout=0,lastMouseWheel=0;$scope.vm.view.justScroll=function(){stopScrolling=!1,stopScrollingExternal=!1,$scope.vm.view.user=!1,$scope.vm.room.newmsg=0,scrollDown()},$scope.vm.view.stopScrolling=function(value){content.stop(),stopScrollingExternal=value}}return{restrict:"A",link:chatMessages}})}(angular),function(angular){angular.module("GG").directive("parseMessage",function($compile,SmilesService){function parseMessage(scope,element,attrs){function isAnimated(smile,room){return!!smile.animated&&(!!smile.channelId||(!!room.private||(!!(room&&room.user&&room.user.ggPlusTier>=2)||!(!(room&&room.user&&room.user.premiums&&-1!==room.user.premiums.indexOf("0"))||room.user.ggPlusTier))))}function longLinkReplacer(parametr){var hellip="&hellip;",url=Utils.parseUrl(parametr);if(!url.hostname)return parametr;var getVisibleUrl=function(){return dirname+filename!=="/"?host+dirname+filename+query:host+query},proURIDecoder=function(val){try{return decodeURIComponent((val+"").replace(/%(?![\da-f]{2})/gi,function(){return"%25"}).replace(/\+/g,"%20"))}catch(e){return val}},host="",query="",pathname="",filename="",dirname="",_temp=null;try{host=decodeURI(url.host)}catch(e){host=url.host}try{query=decodeURI(url.search)}catch(e){_temp=proURIDecoder(url.search),query=_temp||url.search}try{pathname=decodeURI(url.pathname)}catch(e){_temp=proURIDecoder(url.pathname),pathname=_temp||url.pathname}finally{if(pathname||(pathname="/"),_temp=pathname.split("/"),!_temp.length)return parametr;filename=_temp.pop(),dirname=_temp.join("/")+"/"}var visibleUrl=getVisibleUrl();if(visibleUrl.length<=36)return visibleUrl;if(/^www\.[^\.]+\../i.test(host)&&(host=host.substr(4),visibleUrl=getVisibleUrl()),visibleUrl.length>36&&host.length>18){var subs=host.split("."),scnt=subs.length,main=subs.slice(subs[scnt-1]?-2:-3).join("."),mlen=main.length;if(mlen>28)host=mlen>36?main.substr(0,2)+hellip+main.substr(mlen-36+2+3):main,visibleUrl=getVisibleUrl();else{var over=host.length-(mlen+36)/2-4,_cnt=scnt;if(over>0)for(;_cnt>4&&over>-2;)over-=subs.splice(1,1)[0].length+1,_cnt--;if(over>0){var hlim=Math.floor((36-mlen)/4);host=subs[0].substr(0,hlim)+hellip+subs[_cnt-3].substr(subs[_cnt-3].length-hlim)+"."+main,visibleUrl=getVisibleUrl()}else _cnt<scnt&&(subs.splice(1,0,"."),host=subs.join("."),visibleUrl=getVisibleUrl())}}if((host+"/"+filename).length>36&&filename.length>3){var flim=36-(host+(dirname="/")).length-3;filename=flim>=2?hellip+filename.substr(filename.length-flim):hellip,visibleUrl=getVisibleUrl()}else if((host+dirname+filename).length>36&&dirname.length>5){var dlim=Math.floor((36-(host+filename).length-3)/2);dirname=dlim>=3?dirname.substr(0,dlim)+hellip+dirname.substr(dirname.length-dlim):"/&hellip;/",visibleUrl=getVisibleUrl()}if(visibleUrl.length>36&&query.length>4){var qlim=36-(visibleUrl.length-query.length)-3;query=qlim>=3?query.substr(0,qlim)+hellip:filename!==hellip?"?"+hellip:"?",visibleUrl=getVisibleUrl()}return visibleUrl}scope.reinit=function(event,data){console.log("parseMessage reinit"),element.empty(),scope.parseMessageEvent=d
2ata||"",parseMessage(scope,element,attrs)},scope.$on("parse-message-reload",function(event,data){scope.reinit(event,data)});var isChat=!(!scope.$parent.vm||!scope.$parent.vm.settings),chatPekamod=isChat&&scope.$parent.vm.settings.pekaMod,isDialog=scope.$parent.dialogs,msgText=scope.parseMessageEvent||scope.parseMessage;if(scope.preserveHtml||(msgText=function(text){var map={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return text.replace(/[&<>"']/g,function(m){return map[m]})}(msgText)),(scope.parseMessageEvent||scope.nl2br)&&(msgText=msgText.replace(/\n/g,"<br />")),(isDialog||scope.$parent.vm&&scope.$parent.vm.settings&&0!=scope.$parent.vm.settings.smilesType||scope.parseMessageSmiles)&&(msgText=function(msgText){var allSmiles=SmilesService.AllSmiles,room=!(!isChat||!scope.$parent.message)&&{id:scope.$parent.message.user.roomid,user:scope.$parent.message.user,private:!!scope.$parent.message.private},rsp=["rock","scissors","paper"];return msgText.match(/:.+?:/)&&(allSmiles.forEach(function(smile){if(-1!=rsp.indexOf(smile.name))return!1;if(-1!=msgText.toLowerCase().indexOf(":"+smile.name.toLowerCase()+":")&&SmilesService.isSmileAvailable(smile,room)){var animated=!isChat||isAnimated(smile,room)?' animated="true"':"",regex=new RegExp("(:"+smile.name+":)","gi");msgText=msgText.replace(regex,'<smile name="'+smile.name+'"'+animated+"></smile>"),isChat&&scope.$parent.vm.room.user.id===(room.user?room.user.id:null)&&smile.channelId&&smile.channelId!=room.id&&Utils.post("/api/4/achievements/report",{id:"PremSmileGuest"})}}),rsp.forEach(function(smile){-1!=msgText.indexOf(":"+smile+":")&&(msgText=msgText.split(":"+smile+":").join('<img src="/images/anismiles/'+smile+"-gif.gif?rnd="+Math.random()+'" class="smile" tooltip=":'+smile+':"><span class="smile-name">:'+smile+":</span>"))})),msgText}(msgText)),msgText=function(text){var urlRegex=/((https?|ftp)?:\/\/[^\s<]+)/gi;return text.replace(urlRegex,function(url){return'<a href="'+url+'" rel="noopener noreferrer" target="_blank">'+url+"</a>"})}(msgText),(chatPekamod||isDialog)&&(msgText=function(msgText){try{msgText=msgText.replace(/</gi,"\r\n<");var testRegex=/>(http.+?(?:jpe?g|gif|png)(?:\?\S*)?)\r\n</gi;msgText=msgText.replace(testRegex,'><img referrerpolicy="no-referrer" src="$1" /><'),msgText=msgText.replace(/\r\n</gi,"<")}catch(e){console.error(e)}return msgText}(msgText)),msgText=function(msgText){var reg=/<a+[^>]+>(https?[^<]+)<\/a>/gi;return msgText=msgText.replace(reg,function(match,match_sub1){if(!match_sub1)return match;if(!Utils.parseUrl(match_sub1).hostname)return match;try{var rf=longLinkReplacer(match_sub1);return match.replace(">"+match_sub1+"<",">"+rf+"<")}catch(e){return console.log(e),match}})}(msgText),element.append(msgText),-1!=msgText.indexOf("<gg-chat-gift")){var eventData=scope.eventData;setTimeout(function(){element.find(".donor, .your-nick").each(function(idx,el){el.addEventListener("click",function(data){return eventData("pasteGiftNick",el.innerText.replace(",",""))})})},0)}if(-1!=msgText.indexOf("<gg4-teleport-streamer-welcome")){var _eventData=scope.eventData;setTimeout(function(){element.find(".user-nickname-teleport-welcome").each(function(idx,el){el.addEventListener("click",function(event){window.DEV,_eventData("pasteNick",el.innerText.replace(",","")),event.preventDefault(),event.stopPropagation()})})},0)}if(-1!=msgText.indexOf("<gg-quest-task")){var _eventData2=scope.eventData;element.find("gg-quest-task").each(function(idx,el){el.addEventListener("replenish",function(data){return _eventData2("task",data)}),el.addEventListener("pasteNick",function(data){return _eventData2("pasteNick",data)})})}-1!=msgText.indexOf("<smile")&&element.find("smile").each(function(idx,el){$compile(el)(scope)})}return{restrict:"A",scope:{eventData:"=",parseMessage:"=",parseMessageSmiles:"=",preserveHtml:"=",nl2br:"="},link:parseMessage}})}(angular),function(){function ggChatPoll($scope,$rootScope,$interval,PopupService){function onData(){poll.data.answers?(poll.percentages={},poll.data.voters=poll.data.voters||"0",poll.data.answers.forEach(function(ans){poll.percentages[ans.id]=ans.voters&&poll.data.voters?Math.round(100*ans.voters/poll.data.voters):0})):poll.data.answers=[]}function onAnswersChange(){poll.edit&&poll.data&&poll.data.answers&&(0==poll.data.answers.length||poll.data.answers[poll.data.answers.length-1].text)&&poll.data.answers.push({})}
2function createPoll(){poll.data.answers=poll.data.answers.filter(function(ans){return ans.text&&""!=ans.text}),room.createPoll(poll.data),poll.edit=!1,$scope.vm.view.pollWindow=!1}function deleteAnswer(answer){poll.data.answers.splice(poll.data.answers.indexOf(answer),1)}function reloadPoll(){poll.edit=!1,room.getPoll()}function makeVote(){console.log("makeVote"),room.makeVote(poll.myvote)}function isResults(){return!(!poll||!room)&&(!poll.edit&&(!room.user||(void 0!==poll.data.voted||poll.data.mine)))}var poll=this,room=$scope.vm.room;poll.data=room.poll,poll.data.channel_id||room.getPoll(),poll.create=createPoll,poll.deleteAnswer=deleteAnswer,poll.back=reloadPoll,poll.vote=makeVote,poll.isResults=isResults,$scope.$watch("poll.data",onData,!0),$scope.$watch(function(){return[poll.data.answers,poll.edit]},onAnswersChange,!0);var func_interval=function(){$scope.vm.view.pollWindow&&isResults()&&room.getPoll()},func_interval_result=$interval(func_interval,2e3);$scope.$on("$destroy",function(){$interval.cancel(func_interval_result)})}angular.module("GG").controller("ggChatPoll",ggChatPoll),ggChatPoll.$inject=["$scope","$rootScope","$interval","PopupService"]}(),function(){function ggRandomizer($scope){function choose(){var already,room=$scope.vm.room,params=randomizer.params;already=randomizer.users.map(function(user){return user.id}),room.getRandomUser({already:already,version:2,premiums:params.premiums,donaters:params.donaters,others:params.others,noModers:params.noModers})}function clean(){$scope.vm.room.cleanRandomizerUsers()}var randomizer=this;randomizer.params={premiums:!0,donaters:!0,others:!0,noModers:!0},randomizer.users=[],randomizer.choose=choose,randomizer.clean=clean,$scope.$watch("vm.room.randomizerUsers",function(data){randomizer.users=data},!0)}angular.module("GG").controller("ggRandomizer",ggRandomizer),ggRandomizer.$inject=["$scope"]}(),function(){function ggChatSettings($scope,IconService,SettingsService){function canChangeAppearance(){return user.id&&(user.staff||-1==[10,20,30,40,50].indexOf(user.rights))}function checkIfColorEqual(color){return IconService.getColor(user,room)==color}function checkIfIconEqual(icon){return IconService.getIcon(user,room)==icon}function setColor(color){return SettingsService.setRoomColor(room.id,color)}function setIcon(icon){return SettingsService.setRoomIcon(room.id,icon)}function getColor(){return IconService.getColor(user,SettingsService)}function getIcon(){return IconService.getIcon(user,SettingsService)}var settings=this,oldMotd="",room=$scope.vm.room;settings.srv=IconService,settings.colorIs=checkIfColorEqual,settings.iconIs=checkIfIconEqual,settings.canChangeAppearance=canChangeAppearance,settings.setColor=setColor,settings.setIcon=setIcon,settings.getColor=getColor,settings.getIcon=getIcon,settings.motdText=angular.element("<p>"+room.motd+"</p>").text();var user=$scope.user=room.user;$scope.$watch("vm.room.user",function(){room=$scope.vm.room,(user=$scope.user=room.user)&&(user.settings=SettingsService)}),$scope.$on("popup.open",function(event,data){"chat-settings"==data&&(oldMotd=settings.motdText)}),$scope.$on("popup.close",function(event,data){"chat-settings"==data&&oldMotd!=settings.motdText&&room.setMotd(settings.motdText)})}angular.module("GG").controller("ggChatSettings",ggChatSettings),ggChatSettings.$inject=["$scope","IconService","SettingsService","PopupService"]}(),function(){function SettingsService($rootScope){function createSaveSettingsWatcher(){$rootScope.$watch(function(){return service},function(newValue,oldValue){newValue!=oldValue&&saveThrottled()},!0)}function init(user){defaults(user.settings?user.settings.chat:{})}function defaults(options){var defaultOptions={alignType:0,pekaMod:!1,sound:!1,soundVolume:100,smilesType:4,hide:!1,quickBan:!1,quickDelete:1};angular.extend(service,defaultOptions,options)}function setRoomColor(roomId,color){service.customColors||(service.customColors={}),service.customColors[roomId]=color}function setRoomIcon(roomId,icon){service.customIcons||(service.customIcons={}),service.customIcons[roomId]=icon}function saveSettings(){UserObj.id&&(Utils.post("/ajax/chat/save_settings/",{s:angular.toJson(service)}),UserObj.settings.chat.hide!=service.hide&&(UserObj.settings.chat.hide=service.hide,$rootScope.User.settings.chat.hide=service.hide,Chat&&Chat.rejoin()),UserObj.settings.chat.role!=service.role&&(UserObj.settings.chat.role=service.role,$rootScope.User.settings.chat.role=service.role,Chat&&Chat.rejoin()))}var service=this;init(UserObj),UserService.onLoginChange(init),service.setRoomColor=setRoomColor,service.setRoomIcon=setRoomIcon,service.createSaveSettingsWatcher=createSaveSettingsWatcher;var saveThrottled=Utils.throttle(saveSettings,1e3)}angular.module("GG").service("SettingsService",SettingsService)}(),function(){function Slider($document,TextFormat){function link(scope,element,attrs,controller,$transclude){var handle=$(element).find(".slider-value"),handleRange=$
2(element).find(".slider-range-value"),range=$(element).find(".slider-range"),clickable=$(element).find(".clickable"),moving=!1,startPos=0,startLeft=0,_movingRange=function(value){return Math.min(range.width()-handle.width(),Math.max(0,value))},calcValue=function(targetValue){var value=0;return targetValue?(value=scope.min+targetValue/(range.width()-handle.width())*(scope.max-scope.min),value=Math.max(scope.min,Math.min(value,scope.max))):value=scope.value,scope.value=TextFormat.roundBanTime(value),scope.textValue=TextFormat.getBanTimeFormatted(value),targetValue&&scope.$apply(),value};handle.on("mousedown",function(event){moving=!0,startPos=event.clientX,startLeft=handle.position().left,event.preventDefault()}),clickable.on("click",function(event){if((event.originalEvent.srcElement||event.originalEvent.originalTarget)!=handle[0]){var target=event.offsetX-handle.width()/2;calcValue(target)}}),$document.on("mouseup",function(){moving=!1}),$document.on("mousemove",function(e){if(e.which||(moving=!1),moving){var targetValue=startLeft+(e.clientX-startPos);handle.css({left:_movingRange(targetValue)+"px"}),handleRange.css({width:_movingRange(targetValue)+"px"}),calcValue(targetValue)}}),scope.$watch("value",function(data){var target=(range.width()-handle.width())*(data-scope.min)/(scope.max-scope.min);moving||(handle.css({left:target+"px"},300),handleRange.css({width:target+"px"})),calcValue(!1)})}return{restrict:"E",scope:{value:"=",min:"=",max:"=",textValue:"="},link:link,template:'<div class="slider-range ui-slider"><div class="slider-range-value"></div><div class="slider-value ui-slider-handle"></div> </div>'}}angular.module("GG").directive("slider",Slider)}(angular),function(angular){angular.module("GG").directive("smile",function(){return{restrict:"E",scope:{name:"@",animated:"@"},template:'<img src="/images/chat/blank.gif" class="smile {{::getName(name)}}" tooltip=":{{::name}}:" ng-class="::{\'animated\':animated==\'true\'}"><span class="smile-name">:{{::name}}:</span>',link:function($scope){$scope.getName=function(name){var n=name[0];return""==n||isNaN(n)||Math.round(n)!=n?name:"s"+name}}}})}(angular),function(){function SmilesService(){function resetCache(){smilesCache={}}function getLockedSmiles(room){if(smilesCache[room.id]&&smilesCache[room.id].locked)return smilesCache[room.id].locked;var channelSmiles=Global.Channel_Smiles[room.id],ret=[];return channelSmiles&&(ret=channelSmiles.filter(function(smile){return!smile.donat&&!isAvailable(smile,room)}).sort(function(smile1,smile2){return smile1.internal_id-smile2.internal_id})),smilesCache[room.id]=smilesCache[room.id]||{},smilesCache[room.id].locked=ret,ret}function getAvailableCommonSmiles(room){if(smilesCache[room.id]&&smilesCache[room.id].common)return smilesCache[room.id].common;var ret=service.CommonSmiles.filter(function(smile){
3return isAvailable(smile,room)}).sort(function(smile1,smile2){return smile1.internal_id-smile2.internal_id});return smilesCache[room.id]=smilesCache[room.id]||{},smilesCache[room.id].common=ret,ret}function getCurrentChannelAvailableSmiles(room){if(smilesCache[room.id]&&smilesCache[room.id].current)return smilesCache[room.id].current;var ret=service.ChannelSmiles.filter(function(smile){return room.id==smile.channelId&&isAvailable(smile,room)}).sort(function(smile1,smile2){return smile1.internal_id-smile2.internal_id});return smilesCache[room.id]=smilesCache[room.id]||{},smilesCache[room.id].current=ret,ret}function getAvailableChannelsSmiles(room){if(smilesCache[room.id]&&smilesCache[room.id].channel)return smilesCache[room.id].channel;var ret=service.ChannelSmiles.filter(function(smile){return room.id!=smile.channelId&&isAvailable(smile,room)}).sort(function(smile1,smile2){return smile1.internal_id-smile2.internal_id}).sort(function(smile1,smile2){return smile1.channelId-smile2.channelId}),retChannels={};return ret.forEach(function(smile){retChannels[smile.channel]||(retChannels[smile.channel]=[]),retChannels[smile.channel].push(smile)}),smilesCache[room.id]=smilesCache[room.id]||{},smilesCache[room.id].channel=retChannels,retChannels}function isAvailable(smile,room){return!1===room||(smile.channelId==room.id&&room.user.rights>
3=10||(!(!smile.premium||!room.user.premium||smile.channelId)||(!(!smile.premium||!room.user.premiums||-1==room.user.premiums.indexOf(smile.channelId))||(!!(smile.donat&&smile.channelId&&room.user.paymentsAll&&room.user.paymentsAll[smile.channelId]&&room.user.paymentsAll[smile.channelId]>=smile.donat)||(!!(smile.donat&&!smile.channelId&&room.user.payments>=smile.donat)||!smile.donat&&!smile.premium&&!smile.channelId)))))}function pushToStats(smile){window._gaq&&Math.random()>.8&&window._gaq.push(["_trackEvent","Chat","Smiles",smile]);var today=(new Date).setHours(0,0,0,0),stats=angular.fromJson(Utils.lsGet("chat3.smilesstats"))||[];stats.length&&stats[stats.length-1].date==today||stats.push({date:today}),stats=stats.slice(-7),stats[stats.length-1][smile]=stats[stats.length-1][smile]+1||1,Utils.lsSet("chat3.smilesstats",JSON.stringify(stats));for(var key in smilesCache)smilesCache[key].favorite=!1}var service=this,smilesCache={};service.ChannelSmiles=[],service.AllSmiles=[],service.CommonSmiles=[],service.getLockedSmiles=getLockedSmiles,service.getAvailableChannelsSmiles=getAvailableChannelsSmiles,service.getCurrentChannelAvailableSmiles=getCurrentChannelAvailableSmiles,service.getAvailableCommonSmiles=getAvailableCommonSmiles,service.isSmileAvailable=isAvailable,service.pushToStats=pushToStats,service.resetCache=resetCache,function(){if(!window.Global)return void(service.CommonSmiles=service.ChannelSmiles=[]);service.CommonSmiles=Global.Smiles,service.ChannelSmiles=[];for(var chId in Global.Channel_Smiles)Global.Channel_Smiles[chId].forEach(function(smile){smile.channelId=chId,service.ChannelSmiles.push(smile)});service.AllSmiles=service.CommonSmiles.concat(service.ChannelSmiles)}()}angular.module("GG").service("SmilesService",SmilesService)}(),function(){function TextFormat(){var service=this;service.units=[["минуту","минуты","минут"],["час","часа","часов"],["день","дня","дней"]],service.decl=function(number){var cases=[2,0,1,1,1,2];return number%100>4&&number%100<20?2:cases[number%10<5?number%10:5]},service.getBanTimeFormatted=function(value){var uvalue;return value>=1440?" "+(uvalue=Math.ceil(value/1440))+" "+service.units[2][service.decl(uvalue)]:value>=60?" "+(uvalue=Math.ceil(value/60))+" "+service.units[1][service.decl(uvalue)]:" "+(uvalue=Math.ceil(value)||0)+" "+service.units[0][service.decl(uvalue)]},service.roundBanTime=function(value){return value>=1440?1440*Math.ceil(value/1440):value>=60?60*Math.ceil(value/60):Math.ceil(value)},service.convertTimeFormat=function(value,units){return value+" "+service.units[units][service.decl(value)]}}angular.module("GG").service("TextFormat",TextFormat)}(angular),function(angular){angular.module("GG").directive("tooltip",function(){function tooltip(scope,element,attrs){function show(){if(!scope.$root.tooltipShowBind)return!1;var chatPosition=chatRoot.offset(),position={top:event.clientY,left:event.clientX},tooltipHalfWidth=tooltipElement.width()/2,leftSpaceAvailible=position.left-(chatPosition?chatPosition.left:0);tooltipElement.css({display:"block",left:leftSpaceAvailible-Math.min(tooltipHalfWidth,leftSpaceAvailible),top:position.top-chatPosition.top-40}),tooltipElement.html(scope.tooltip)}function hide(){tooltipElement.css({display:"none"})}var event,chatRoot=element.closest(".chat-container"),tooltipElement=angular.element(".chat-container").find(".help-block");scope.tooltip&&element.on("mouseover",function(e){e.stopPropagation(),scope.$root.tooltipShowBind=show}).on("mouseout",function(e){e.stopPropagation(),scope.$root.tooltipShowBind=!1}).on("mousemove",function(e){hide(),clearTimeout(scope.$root.tooltipShowTimeout),scope.$root.tooltipShowBind&&(event=e,scope.$root.tooltipShowTimeout=setTimeout(scope.$root.tooltipShowBind,1e3))})}return{restrict:"A",scope:{tooltip:"@"},link:tooltip}})}(angular),function(){function TrustFilter($sce){return function(input){return $sce.trustAsHtml(input)}}angular.module("GG").filter("trust",TrustFilter),TrustFilter.$inject=["$sce"]}(),function(angular){angular.module("GG").directive("chatUser",function($document,IconService){function ChatUser(scope,element,attrs){var chatRoot=element.closest(".chat-container"),tooltips={helper:"Помощник стримера",moderator:"Модератор сайта",phone:"Пользователь мобильного устройства",ios:"iOS зритель",android:"Android зритель",star:"Премиум зритель",coin:"Бронзовый статус",eagle:"Серебряный статус",cup:"Золотой статус",diamond:"Алмазный статус",crown:"Царский статус",undead:"Бессмертный статус",fire:"Огненный статус",cherry:"Черри статус",mushroom:"Грибной статус",top1:"Супер-статус",staff:"Сотрудник GoodGame",lawyer:"Адвокат",ggPlus:"GG Плюс",ggPlus1:"GG Плюс 1 тир",ggPlus2:"GG Плюс 2 тир",ggPlus3:"GG Плюс 3 тир",ggPlus4:"GG Плюс 4 тир",ggPlus5:"GG Плюс 5 тир",ggPlus6:"GG Плюс 6 тир",ggPlus7:"GG Плюс 7 тир",invite:"Приглашенных","invite-1":"Призрак","invite-2":"Инвейдер","invite-3":"Танчик"},menu=chatRoot.find(".user-context-menu");scope.vm=scope.$parent.vm,scope.$watch("userObj",function(){if(scope.userObj){scope.userObj.color=IconService.getColor(scope.userObj,scope.message),scope.userObj.icon=IconService.getIcon(scope.userObj,scope.message);var role=IconService.getRole(scope.userObj,scope.message);if(scope.userObj.iconTooltip=role||tooltips[scope.userObj.icon]||scope.userObj.icon,"star"==scope.userObj.icon)scope.userObj.resub?scope.userObj.premType="type-"+scope.userObj.resub:scope.userObj.premType="";else if("ggplus"==scope.userObj.icon)scope.userObj.ggresub?(scope.userObj.ggPlusType="icon-ggplus-"+scope.userObj.ggresub,scope.userObj.iconTooltip=role||tooltips["ggPlus"+scope.userObj.ggresub]||tooltips.ggPlus):(scope.userObj.ggPlusType="",scope.userObj.icon="none");
3else if(0===scope.userObj.icon.indexOf("invite-")){var iconLevel=+scope.userObj.icon.substring("invite-".length),userLevel=scope.userObj.inviteLevels&&scope.userObj.inviteLevels[0]||0;iconLevel&&userLevel>=iconLevel?scope.userObj.iconTooltip=tooltips["invite-"+iconLevel]||tooltips.invite:scope.userObj.icon="none"}else scope.userObj.premType=scope.userObj.ggPlusType=""}}),element[0].addEventListener("mouseenter",function(){return scope.vm.view.stopScrolling(!0)}),element[0].addEventListener("mouseleave",function(){return scope.vm.view.stopScrolling(!1)}),element.bind("contextmenu",function(event){event.preventDefault(),window.getSelection&&window.getSelection().removeAllRanges(),scope.vm.view.user=scope.userObj,scope.vm.view.user.isCup=!!window.cup,scope.vm.view.user.showInGrid=function(){window.cup.grid.find(scope.vm.view.user.id)},scope.vm.view.message=scope.message;var chatPosition=chatRoot.offset(),content=chatRoot.find(".content-window")[0],menuTop=event.clientY-chatPosition.top,menuLeft=event.clientX-chatPosition.left;menuTop+186>content.clientHeight&&(menuTop=content.clientHeight-186),content.clientWidth-menuLeft<186&&(menuLeft=content.clientWidth-186),menu.css({top:menuTop,left:menuLeft}),scope.vm.profileClick=function(e){e.preventDefault();var $target=$(e.target).attr("href");window.open($target,"_blank")},scope.vm.nicknamehistoryClick=function(e){e.preventDefault();var $target=$(e.target).attr("href");window.open($target,"_blank")},scope.$applyAsync()})}return{restrict:"E",scope:{userObj:"=",message:"="},link:ChatUser,template:'<a ng-href="/user/{{::userObj.id}}" href="/user/{{::userObj.id}}" ng-click="$event.preventDefault();vm.view.pasteNick(userObj.nickname, userObj.private, false, \'user\')" class="nick {{::userObj.color}}" ng-class="{\'nickNoAfter\': message.donateValue && !message.voice && !message.text, \'donate-message\': message.donateValue}"><span class="icon icon-{{::userObj.icon}} {{::userObj.premType}} {{::userObj.ggPlusType}}" tooltip=" {{::userObj.iconTooltip}}"></span>{{::userObj.nickname }}</a>'}})}(angular),function(angular){angular.module("GG").directive("chatInput",function(IconService,SmilesService,$compile,$timeout,PopupService){function ChatInput(scope,element,attrs,controller){function preventCutTextDefaultBehaviour(){input.on("cut",function(e){setTimeout(function(){"<br>"===input.html()&&input.html("")},0)})}function filterUsers(username){return 0==scope.vm.room.users.length&&scope.vm.room.getUsersList(),scope.vm.room.users.filter(function(u){return-1!=u.nickname.toLowerCase().indexOf(username.toLowerCase())})}function filterCommands(command){return Object.values(COMMANDS).filter(function(c){return-1!=c.toLowerCase().indexOf(command.toLowerCase())})}function showSmiles(){PopupService.open("smiles"),scope.vm.view.smiles=!0,listenSearchInputForTab()}function listenSearchInputForTab(){try{var smileSearch=document.getElementById("smile-search"),eventTabHandler=function eventTabHandler(event){"Tab"===event.key&&(hideSmiles(),smileSearch.removeEventListener("keydown",eventTabHandler),setTimeout(function(){return input.focus()},100))};smileSearch.addEventListener("keydown",eventTabHandler)}catch(e){console.error("ERROR WHILE SETTING LISTENER TO SMILES SEARCH",e)}}function hideSmiles(){PopupService.close("smiles"),scope.vm.view.smiles=!1}function toggleTasks(){scope.vm.view.taskList=!scope.vm.view.taskList,scope.vm.view.taskList?PopupService.open("task-list"):PopupService.close("task-list")}function checkCommands(text){if(window.DEV_CHAT,"!"!=text[0]&&"/"!=text[0])return!1;var checkText=text.substring(1).split(/[\s\u00A0]+/,1);switch(checkText[0].trim()){case COMMANDS.RAID:case COMMANDS.TELEPORT:return handleRaidAndTeleport(text,checkText[0]);case COMMANDS.SMILEONLY:return canManageSmileOnlyMode()?scope.vm.Chat.room().setSmileOnlyMode(!0):scope.vm.Chat.room().message({color:"system moderator",user_rights:30,text:'У вас недостаточно прав для включения режима "Только смайлы"'}),!0;case COMMANDS.SMILEONLYOFF:return canManageSmileOnlyMode()?scope.vm.Chat.room().setSmileOnlyMode(!1):scope.vm.Chat.room().message({color:"system moderator",user_rights:30,text:'У вас недостаточно прав для отключения режима "Только смайлы"'}),!0;case COMMANDS.GIFT:return Utils.post("/ajax/gifts/send/",{channel:scope.vm.Chat.room().id,message:text.substring(6)}).then(function(data){data.success||scope.vm.Chat.room().message({color:"system moderator",user_rights:30,text:data.gifts?"Не получилось отправить подарок":"У вас закончились подарки"});var giftsScope=$("div.popup-block.gift-block").scope().$ctrl;giftsScope.count=data.gifts,giftsScope.empty=0==data.gifts,giftsScope.visible=data.visible}),!0;case COMMANDS.snow:return window.Snowy(document.getElementById("snow")),!0;case COMMANDS.gif:var message=text.substring(5);return(new Gfycat).textToGif(message).then(function(url){if(!url)return alert("Ничего не найдено :("),!1;var msg="gif:"+url;scope.vm.Chat.room().sendMessage(msg,{color:IconService.getColor(scope.vm.Chat.room().user),icon:IconService.getIcon(scope.vm.Chat.room().user),mobile:0})}),!0;case COMMANDS.VJUH:return window.StreamController.showGame(),!0;case COMMANDS.MOTD:if(console.log(scope.vm.Chat.room().motd.length,"мы ввели команду motd"),scope.vm.Chat.room().motd){var motd=$(".day-message");return motd.addClass("active"),setTimeout(function(){motd.removeClass("active")},3e3),!0}console.log("motd net");case COMMANDS.CLEAR:return scope.vm.Chat.room().clearMessage(),!0}}function canManageSmileOnlyMode(){var room=scope.vm.Chat.room(),user=room.user;if(!user)return!1;var isStreamer=user.id===room.streamer.id,isModerator=user.rights>0,isHelper=room.helpers.some(function(helper){return helper.id===user.id});return isStreamer||isModerator||isHelper}function pasteNick(nickname,isPrivate,fromSuggest,mention){isPrivate=isPrivate||!1,fromSuggest=fromSuggest||!1,fromSuggest&&(isPrivate=0==input.text().indexOf("@"),input.html("")),-1==input.html().indexOf(nickname+",")&&input.html((isPrivate?"@":"")+nickname+",&nbsp;"+input.html()),input.focus(),htmlPaste.toEnd(),mention&&(mentionStreamer="streamer"===mention&&!reportedMentionStreamer,mentionUser="user"===mention&&!reportedMentionUser),scope.vm.view.suggestSelected=0,scope.vm.view.suggest={}}function pasteCommand(command){input.html(input.text()[0]+command+" "),input.focus(),htmlPaste.toEnd(),scope.vm.view.suggestSelected=0,scope.vm.view.suggest={}}function pasteSmile(smile){var range=htmlPaste.getRange();range&&$(range.startContainer).closest(input).length||htmlPaste.toEnd(),input.focus(),htmlPaste.pasteCode('<smile contenteditable="false" name="'+smile.name+'"></smile>'),htmlPaste.pasteCode("&nbsp;"),hideSmiles(),$compile(element.contents())(scope),SmilesService.pushToStats(smile.name)}function replaceStrWithImage(smile){var range=htmlPaste.getRange();range&&$(range.startContainer).closest(input).length||htmlPaste.toEnd(),input.focus(),htmlPaste.deleteLastParsedWord('<smile contenteditable="false" name="'+smile.name+'"></smile>'),hideSmiles(),$compile(element.contents())(scope),SmilesService.pushToStats(smile.name)}var input=element,COMMANDS={snow:"snow",VJUH:"вжух",gif:"gif",UP:"up",MOTD:"motd",GIFT:"gift",CLEAR:"clear",RAID:"raid",TELEPORT:"teleport",SMILEONLY:"smileonly",SMILEONLYOFF:"smileonlyoff"};scope.vm.view.pasteNick=pasteNick,scope.vm.view.pasteSmile=pasteSmile,scope.vm.view.replaceStrWithImage=replaceStrWithImage,scope.vm.view.pasteCommand=pasteCommand,function(){preventCutTextDefaultBehaviour(),input.on("key
3down",function(event){var suggest=scope.vm.view.suggest;33!=event.which&&34!=event.which||event.preventDefault(),8==event.which&&(input.html().length<=1||0==input.text().length&&input.find("*").length<=1)&&(input.html(""),event.preventDefault()),9==event.which&&(event.preventDefault(),scope.vm.view.smiles?hideSmiles():showSmiles()),74==event.which&&event.altKey&&(event.preventDefault(),toggleTasks()),40==event.which&&suggest.value&&suggest.value.length&&(event.preventDefault(),scope.vm.view.suggestSelected=Math.min(suggest.length,scope.vm.view.suggestSelected+1),scope.$applyAsync()),38==event.which&&suggest.value&&suggest.value.length&&(event.preventDefault(),scope.vm.view.suggestSelected=Math.max(1,scope.vm.view.suggestSelected-1),scope.$applyAsync()),scope.$apply()}).on("keypress",function(event){var suggestSelectedValue,suggest=scope.vm.view.suggest;if(8!=event.keyCode&&input.text().length>1024&&event.preventDefault(),13==event.keyCode){if(scope.vm.view.suggestSelected)return event.preventDefault(),suggestSelectedValue=suggest.value[scope.vm.view.suggestSelected-1],void("user"===suggest.type?pasteNick(suggestSelectedValue.nickname,!0,!0):pasteCommand(suggestSelectedValue));if(scope.vm.view.suggest={},scope.vm.view.suggestSelected=0,!UserObj.id)return event.preventDefault(),void scope.$root.showLogin();if(checkCommands(input.text().trim()))return input.html(""),event.preventDefault(),void scope.$applyAsync();cleanHtml(input,!0);var onlySmiles=input.find("img").length&&""==input.text().trim(),upTime="/up"==input.text().trim(),tmp=angular.element("<div></div>").html(input.html());cleanHtml(tmp,!1);var kran=-1!==tmp.text().indexOf(":kran:"),re=new RegExp(String.fromCharCode(160),"g"),msg=tmp.text().replace(re," ").replace(/\s{2,}/g," ").replace(/\n/g," ");if(scope.vm.room.smilesOnlyMod&&!onlySmiles&&!canManageSmileOnlyMode())return event.preventDefault(),scope.vm.Chat.room().message({color:"system moderator",user_rights:30,text:"Режим чата — только для смайлов!"}),!1;if(!msg.trim())return!1;window.DEV;var privateMsgReg=/^@([a-zа-я\.*,\-_0-9\|]{2,16}),(.+)$/i;if("@"==msg[0]&&privateMsgReg.test(msg)){var match=msg.match(privateMsgReg);if(match&&match[1]&&match[2]){var nick=match[1],message=match[2].trim();scope.vm.Chat.sendPrivateMessage(nick,message.trim())}else alert("Ошибка при отправке личного сообщения")}else(mentionStreamer||mentionUser)&&(Utils.post("/api/4/achievements/report",{id:mentionStreamer?"MentionStreamer":"MentionUser"}),reportedMentionStreamer=reportedMentionStreamer||mentionStreamer,reportedMentionUser=reportedMentionUser||mentionUser),onlySmiles&&Utils.post("/api/4/achievements/report",{id:"SmilesOnly"}),upTime&&Utils.post("/api/4/achievements/report",{id:"UpTime"}),kran&&Utils.post("/api/4/achievements/report",{id:"UnpopularSmile"}),scope.vm.Chat.room().sendMessage(msg,{color:IconService.getColor(scope.vm.Chat.room().user),icon:IconService.getIcon(scope.vm.Chat.room().user),role:IconService.getRole(scope.vm.Chat.room().user),mobile:0});input.html(""),event.preventDefault()}}).on("paste",function(event){var range=htmlPaste.getRange();if(document.selection)$timeout(function(){cleanHtml(input,!0)});else{var tmpPaste=angular.element('<div contenteditable="true" id="tmptxt"></div>');tmpPaste.insertAfter(element),tmpPaste.focus(),setTimeout(function(){cleanHtml(tmpPaste,!0),input.focus(),input.text().length+input.text().length>1024&&tmpPaste.html(tmpPaste.html().substring(0,1024-input.text().length));var text=tmpPaste.html();tmpPaste.remove(),text&&(input.focus(),htmlPaste.setRange(range),htmlPaste.insertHTML(tmpPaste.html()))},0)}}).on("keyup",function(event){var text,match;38!=event.which&&40!=event.which&&(text=input.text(),match=text.replace("!","").replace("/","").replace("@",""),text.length>=2&&-1==text.indexOf(",")?(scope.vm.view.suggestSelected=0,"!"===text[0]||"/"===text[0]?scope.vm.view.suggest={value:filterCommands(match),type:"command"}:scope.vm.view.suggest={value:filterUsers(match).slice(0,11),type:"user"}):scope.vm.view.suggest={},scope.$applyAsync())}).on("input",function(event){})}();var htmlPaste=new HtmlPaste(input),mentionStreamer=!1,mentionUser=!1,reportedMentionStreamer=!1,reportedMentionUser=!1,cleanHtml=function(elem,leaveSmiles){elem.find("*").each(function(ind,item){if(3!=this.nodeType){var $item=$(item);return"STYLE"==$item.prop("tagName")?void $item.remove():"SMILE"==$item.prop("tagName")?void $item.replaceWith($item.find(".smile")):void($item.hasClass("smile")?leaveSmiles?$item.removeAttr("style"):$item.replaceWith($item.attr("tooltip")):$item.replaceWith($item.text()))}})}}function handleRaidAndTeleport(text,command){var parts=text.trim().split(/\s+/),id=parts.length>1?parts[1]:null;if(id){Utils.reachGoal("teleport_command");
3var message={type:"chatTeleportCommand",detail:{command:command.toLowerCase(),id:id}};window.parent!==window?window.parent.postMessage(message,"*"):document.dispatchEvent(new CustomEvent("chatTeleportCommand",{detail:message.detail}))}return!0}return{restrict:"A",link:ChatInput}})}(angular),function(){function UsersListController($scope){function _order(users){return users&&users.slice(0).sort(function(a,b){var i=100*b.payments+(b.roomPremium?10:0)+(b.commonPremium?1:0)-100*a.payments-(a.roomPremium?10:0)-(a.commonPremium?1:0);return 0==i?a.nickname.toLowerCase()<b.nickname.toLowerCase()?-1:1:i})}function _filter(){list.banned=[],list.streamers=[],list.organizers=[],list.judges=[],list.helpers=[],list.moders=[],list.others=[],list.customs=new Map,list.customKeys=[];var users=_order(list.users);if(users)for(var rights=room.user.rights,i=0;i<users.length;i++){var u=users[i];if(!(u.hidden&&u.rights>20&&rights<=20))if(window.cup&&rights&&window.cup.addChatData(u),u.banned&&rights)__filter(list.userSearch,u.nickname,"забанены")&&list.banned.push(u);else{if(22==u.rights){__filter(list.userSearch,u.nickname,"судьи")&&list.judges.push(u);continue}if(20==u.rights||room.streamer&&u.id==room.streamer.id){__filter(list.userSearch,u.nickname,"стримеры")&&list.streamers.push(u);continue}if(10==u.rights){__filter(list.userSearch,u.nickname,"помощники")&&list.helpers.push(u);continue}if(u.rights>25){__filter(list.userSearch,u.nickname,"модераторы")&&list.moders.push(u);continue}if(u.role&&u.ggPlusTier>=7){var role=u.role.substring(0,16);list.customs.get(role)||list.customs.set(role,[]),list.customs.set(role,[].concat(_toConsumableArray(list.customs.get(role)),[u])),list.customKeys=Array.from(list.customs.keys());continue}__filter(list.userSearch,u.nickname,"зрители")&&list.others.push(u)}}}function __filter(pattern,nickname,section){return!pattern||-1!=section.toUpperCase().indexOf(pattern.toUpperCase())||-1!=nickname.toUpperCase().indexOf(pattern.toUpperCase())}var list=this,room=$scope.vm.room;list.othersLimit=200,list.users=room.getUsersList(),$scope.$watch("list.users",function(){_filter()},!0),$scope.$watch("list.userSearch",function(){_filter()})}angular.module("GG").controller("ggChatUsersList",UsersListController),UsersListController.$inject=["$scope"]}(),function(angular){var ggGifts=function(){function ggGifts($scope){_classCallCheck(this,ggGifts),this.empty=!1,this.visible=!1,this.count=0}return _createClass(ggGifts,[{key:"$onInit",value:function(){this.loadData()}},{key:"loadData",value:function(){var _this6=this;Utils.get("/ajax/gifts/info/",{channel:this.channel}).then(function(data){_this6.count=data.gifts,_this6.empty=0==data.gifts,_this6.visible=data.visible})}},{key:"makeGift",value:function(){if(this.empty)return!1;var input=$(".textarea[chat-input]"),html=new HtmlPaste(input);input.html();input.html("/gift&nbsp;"),input.focus(),html.toEnd()}}]),ggGifts}();angular.module("GG").component("ggGifts",{controller:ggGifts,template:'<div class="popup-block gift-block" ng-mouseenter="$ctrl.loadData()" ng-class="{empty: $ctrl.empty}" ng-if="$ctrl.visible" ng-click="$ctrl.makeGift()">\n    <div class="gift">\n        <div class="gift-img"><div class="count">{{ $ctrl.count }}</div></div>\n    </div>\n    <div class="text-block">\n        <div class="full">\n            Подари подарок любимому стримеру с сообщением в чате!\n        </div>\n        <div class="empty">\n            У вас закончились подарки. Узнать как вы можете получить больше подарков можно в\n            <a target="_blank" href="/news/27805/">новости</a>\n        </div>\n    </div>\n</div>\n',bindings:{channel:"="}})}(angular),function(angular){var ggMotd=function(){function ggMotd($scope){_classCallCheck(this,ggMotd),this.scroll=0,this.isOpen=!1,$scope.$on("chat-settings-motd-edit",function(event,data){$scope.$broadcast("parse-message-reload",data)})}return _createClass(ggMotd,[{key:"scrollLogic",value:function(){var contentWindow=document.querySelector(".content-window"),motd=document.querySelector(".day-message .text-block"),motdText=document.querySelector(".day-message .text-block .text");document.querySelector("body");contentWindow.clientHeight<motdText.clientHeight+36?(this.scroll=1,motd.style.height=contentWindow.clientHeight-36+"px",motd.style.width=contentWindow.clientWidth-99+"px"):(this.scroll=0,motd.style.height="",motd.style.width=contentWindow.clientWidth-94+"px")}},{key:"showMotd",value:function(){this.isOpen=!0}},{key:"hideMotd",value:function(){this.isOpen=!1}}]),ggMotd}();angular.module("GG").component("ggMotd",{controller:ggMotd,controllerAs:"motd",template:'<div id="day-message-block" \n            class="popup-block day-message" \n             ng-if="motd.room.motd" \n             ng-mouseover="motd.scrollLogic()"\n             ng-mouseleave="motd.hideMotd();"\n             ng-class="{\'active\': motd.isOpen}"\n             >\n    <div class="streamer-avatar online" ng-if="motd.room.streamer.avatar">
3\n        <img class="online" src="" ng-src="/files/avatars/av_{{ motd.room.streamer.avatar }}" alt="">\n    </div>\n    <div class="text-block" >\n        <div class="motd-scroll" gg-scrollable="" ng-if="motd.scroll">\n            <div class="text" parse-message="motd.room.motd" parse-message-smiles="true" nl2br="true">\n            </div>\n        </div>\n        <div class="text" ng-if="!motd.scroll" parse-message="motd.room.motd" parse-message-smiles="true" nl2br="true"></div>\n\n    </div>\n    \x3c!--<a href="" ng-click="closePopup($event)" class="icon icon-close2"></a>--\x3e\n    <span class="icon icon-motd-icon" ng-mouseover="motd.showMotd()"></span>\n</div>',bindings:{room:"="}})}(angular),function(angular){var betaFeatures=function(){function betaFeatures($scope){var _this7=this;_classCallCheck(this,betaFeatures),this.$scope=$scope,Utils.get("/ajax/user/beta/").then(function(data){return _this7.onLoad(angular.fromJson(data))})}return _createClass(betaFeatures,[{key:"onLoad",value:function(data){this.features=data.features,this.counts=this.parseInts(data.cnt),this.values=this.parseInts(data.values),this.$scope.$apply()}},{key:"setFeature",value:function(fId){var _this8=this;Utils.post("/ajax/user/beta/",{feature:fId,value:this.values[fId]}).then(function(data){return _this8.onLoad(angular.fromJson(data))})}},{key:"parseInts",value:function(obj){for(var key in obj)obj[key]=parseInt(obj[key]);return obj}}]),betaFeatures}();angular.module("GG").component("betaFeatures",{controller:betaFeatures,template:'\n            <div class="option" ng-repeat="feature in $ctrl.features">\n                <div class="total">{{ $ctrl.counts[feature.id] }}</div>\n                <div class="checkbox" ng-class="{disabled: feature.disabled}">\n                    <input id="checkbox{{ $index }}" type="checkbox" name="" \n                        ng-model="$ctrl.values[feature.id]" \n                        ng-true-value="1" \n                        ng-false-value="0"\n                        ng-disabled="{{ feature.disabled }}"\n                        ng-change="$ctrl.setFeature(feature.id)">\n                    <label for="checkbox{{ $index }}">{{ feature.title }}</label>\n                </div>\n\n                <p>{{ feature.text }}</p>\n            </div>\n            '})}(angular),function(angular){var ggAdsBlock=function(){function ggAdsBlock($element,Reklama){_classCallCheck(this,ggAdsBlock),this.$elem=$element,this.Reklama=Reklama,this.zoneId=null}return _createClass(ggAdsBlock,[{key:"$onInit",value:function(){if(!this.zoneId)return!1;this.$elem.attr("id","adzone_"+this.zoneId);try{this.Reklama.loadBanner(this.zoneId)}catch(e){}}},{key:"getData",value:function(){}}]),ggAdsBlock}();angular.module("GG").component("ggAdsBlock",{template:"",controller:ggAdsBlock,bindings:{zoneId:"="}})}(angular),function(angular){var ggChangeParent=function(){function ggChangeParent($scope,$element){_classCallCheck(this,ggChangeParent),this.$scope=$scope,this.$element=$element}return _createClass(ggChangeParent,[{key:"$onInit",value:function(){var changeParentEl=angular.element("gg-change-parent");this.oldParent=changeParentEl[0].parentNode,this.oldParent.insertBefore(this.$element[0],changeParentEl[0]);var content=changeParentEl.children();this.$element.append(content),changeParentEl.remove();var $newParent=angular.element(this.newParent);angular.element($newParent).append(this.$element)}},{key:"$onDestroy",value:function(){this.returnElementBack()}},{key:"returnElementBack",value:function(){var changeParentEl=angular.element("gg-change-parent"),content=changeParentEl.children(),el=changeParentEl[0].parentNode.insertBefore(content[0],changeParentEl[0]);angular.element(this.oldParent).append(el),changeParentEl.remove()}}]),ggChangeParent}();ggChangeParent.$$ngIsClass=!0,angular.module("GG").component("ggChangeParent",{controller:["$scope","$element",ggChangeParent],bindings:{newParent:"@"}})}(angular),function(angular){var ggCircleProgress=function(){function ggCircleProgress($scope,$element){_classCallCheck(this,ggCircleProgress),this.$scope=$scope,this.$elem=$element[0],this._progress=30,this.lineWidth=26,this.size=184,this.color="#FFFFFF",this.background="#4f5975"}return _createClass(ggCircleProgress,[{key:"$onInit",value:function(){this.init(),this.draw()}},{key:"$onChanges",value:function(){this.ctx&&this.draw()}},{key:"init",value:function(){var canvas=document.createElement("canvas"),ctx=canvas.getContext("2d");
3canvas.width=canvas.height=this.size,this.$elem.appendChild(canvas),ctx.translate(this.size/2,this.size/2),ctx.rotate(-.5*Math.PI),this.ctx=ctx,this.canvas=canvas}},{key:"clear",value:function(){this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.restore()}},{key:"draw",value:function(){this.clear(),this.drawCircle(this.background,this.lineWidth,1),this.progress>0&&this.drawCircle(this.color,this.lineWidth,this.progress/100)}},{key:"drawCircle",value:function(color,lineWidth,percent){percent=Math.min(Math.max(0,percent||1),1);var radius=(this.size-this.lineWidth)/2;this.ctx.beginPath(),this.ctx.arc(0,0,radius,0,2*Math.PI*percent,!1),this.ctx.strokeStyle=color,this.ctx.lineCap="round",this.ctx.lineWidth=lineWidth,this.ctx.stroke()}},{key:"progress",set:function(value){this._progress=value,this.ctx&&this.draw()},get:function(){return this._progress}}]),ggCircleProgress}();angular.module("GG").component("ggCircleProgress",{controller:ggCircleProgress,template:"",bindings:{progress:"=",color:"@?",background:"@?",size:"=",lineWidth:"=?"}})}(angular),function(angular){var ggComplaintCtrl=function(){function ggComplaintCtrl(){_classCallCheck(this,ggComplaintCtrl)}return _createClass(ggComplaintCtrl,[{key:"$onInit",value:function(){this.reason=0}},{key:"sendComplaint",value:function(){var _this9=this;Utils.post("/ajax/make-claim/",{id:this.objId,type:this.objType,reason:this.reason,msg:this.text}).then(function(data){data=angular.fromJson(data),data&&data.msg&&alert(data.msg),_this9.close()})}},{key:"close",value:function(){this.showComplaint=!1}}]),ggComplaintCtrl}();angular.module("GG").component("ggComplaint",{bindings:{showComplaint:"=",objType:"=",objId:"="},
4template:'<div class="popup-block report-popup" ng-show="$ctrl.showComplaint">\n    <div class="loading" ng-if="vm.loading"></div>\n    <div class="content" ng-if="!vm.loading">\n        <div class="title">Жалоба</div>\n        <div class="form-group">\n            <label class="title">Причина</label>\n            <div gg-select ng-if="$ctrl.objType == 7">\n                <select ng-model="$ctrl.reason" convert-to-number>\n                    <option selected value="0">Выбрать причину</option>\n                    <option value="1">Постоянные оскорбления</option>\n                    <option value="2" ng-if="!$ctrl.adult">Нецензурная лексика</option>\n                    <option value="3">Курение, употребление алкоголя</option>\n                    <option value="4">Эротика или порнография</option>\n                    <option value="5">Нарушение прав третьих лиц</option>\n                    <option value="6">Нарушение законов РФ</option>\n                    <option value="7">Другое</option>\n                </select>\n            </div>\n        </div>\n        <div class="form-group ng-hide" ng-show="$ctrl.reason == 7">\n            <textarea name="other" ng-model="$ctrl.text"></textarea>\n        </div>\n        <div class="form-group btn-block">\n            <a href="" class="btn btn-blue" ng-click="$ctrl.sendComplaint()">Отправить</a>\n            <a href="" class="btn btn-gray cancel" ng-click="$ctrl.close()">Отмена</a>\n        </div>\n    </div>\n</div>\n',controller:ggComplaintCtrl})}(angular),function(angular){var ggCopyClipboard=function(){function ggCopyClipboard($element){_classCallCheck(this,ggCopyClipboard),this.$element=$element}return _createClass(ggCopyClipboard,[{key:"copy",value:function(event){window.getSelection().removeAllRanges();var range=document.createRange(),node=jQuery(event.currentTarget).parent().find("input").get(0);jQuery(node).select(),node||(console.log("Нечего копировать по селектору"),node=event.currentTarget),range.selectNode(node),window.getSelection().addRange(range);try{var successful=document.execCommand("copy"),msg=successful?"успешно":"неуспешно";this.$element.find("a").addClass("copy").text("Скопировано"),console.log("Копирование в буфер прошло "+msg)}catch(err){this.$element.find("input").addClass("error"),alert("Упс, не могу скопировать! Попробуйте еще раз нажать на кнопку."),console.log("Упс, не могу скопировать! Попробуйте еще раз нажать на кнопку.")}return window.getSelection().removeAllRanges(),!1}}]),ggCopyClipboard}();angular.module("GG").component("ggCopyClipboard",{controller:ggCopyClipboard,template:'<div class="sharing-input">\n                                <input type="text" value="{{$ctrl.contents}}" contenteditable="true" />\n                                <a ng-click="$event.preventDefault();
4$ctrl.copy($event)" href="#" class="btn btn-transparent btn-copy-clipboard">Копировать</a>\n                            </div>',bindings:{contents:"@"}})}(angular),function(angular){var ggEditsHistory=function(){function ggEditsHistory(DateFunctions){_classCallCheck(this,ggEditsHistory),this.formatDate=DateFunctions.formatDate,this.page=1,this.history=[],this.more=!0}return _createClass(ggEditsHistory,[{key:"$onInit",value:function(){this.loadData()}},{key:"loadData",value:function(){var _this10=this;Utils.get("/ajax/edits/history/",{type:this.objType,id:this.objId,page:this.page}).then(function(data){var _history;0==data.length&&(_this10.more=!1),(_history=_this10.history).push.apply(_history,_toConsumableArray(data))})}},{key:"loadMore",value:function(){this.page++,this.loadData()}},{key:"ipToggle",value:function(line){line.ip_show=!line.ip_show}}]),ggEditsHistory}();angular.module("GG").component("ggEditsHistory",{bindings:{objType:"=",objId:"="},templateUrl:"/html/history-changes-page.html",controller:ggEditsHistory})}(angular),function(angular){var ggFeaturedBlock=function(){function ggFeaturedBlock(){_classCallCheck(this,ggFeaturedBlock),this.streams=null}return _createClass(ggFeaturedBlock,[{key:"$onInit",value:function(){this.streams=MainPage.Selector.featured.filter(function(item){return 1==item.channelObj.status&&1!=item.channelObj.hidden}).filter(function(item){return!UserService.bl||-1==UserService.bl_data.indexOf(item.channelObj.id.toString())})}}]),ggFeaturedBlock}();angular.module("GG").component("ggFeaturedBlock",{bindings:{},templateUrl:"/html/channels/featured-streams.html",controller:ggFeaturedBlock})}(angular),function(angular){var ggInfiniteScroll=function(){function ggInfiniteScroll($element){_classCallCheck(this,ggInfiniteScroll),this.$element=$element}return _createClass(ggInfiniteScroll,[{key:"$onInit",value:function(){var _this11=this;this.scrollableElement=this._getFirstScrollableElement(this.$element[0]),this.scrollHandler=Utils.throttle(function(){return _this11._scrollHandler()},500),$(this.scrollableElement).on("scroll",this.scrollHandler),$(this.scrollableElement).on("touchmove",this.scrollHandler)}},{key:"_scrollHandler",value:function(){this.enabled&&this._isBottomReached(this.$element[0])&&this.nextPage()}},{key:"_isBottomReached",value:function(element){return element.getBoundingClientRect().bottom<=window.innerHeight}},{key:"_getFirstScrollableElement",value:function(element){var style=getComputedStyle(element),excludeStaticParent="absolute"===style.position,overflowRegex=/(auto|scroll)/;if("fixed"===style.position)return document.body;for(var parent=element;parent=parent.parentElement;)if(style=getComputedStyle(parent),(!excludeStaticParent||"static"!==style.position)&&overflowRegex.test(style.overflow+style.overflowY+style.overflowX))return parent;return document.body}},{key:"$onDestroy",value:function(){this.scrollableElement&&($(this.scrollableElement).off("scroll",this.scrollHandler),$(this.scrollableElement).off("touchmove",this.scrollHandler))}}]),ggInfiniteScroll}();angular.module("GG").component("ggInfiniteScroll",{controller:["$element",ggInfiniteScroll],bindings:{nextPage:"&",enabled:"<"}})}(angular),function(angular){var ggLoadMore=function(){function ggLoadMore($scope,$timeout){_classCallCheck(this,ggLoadMore),this.active=!0,this.$scope=$scope,this.$timeout=$timeout}return _createClass(ggLoadMore,[{key:"$onInit",value:function(){var _this12=this;this.$timeout(function(){_this12.$list=$(_this12.list)}),this.page=1}},{key:"loadMore",value:function(){var _this13=this;Utils.get("/ajax"+window.location.pathname,{page:++this.page}).then(function(data){data=angular.fromJson(data),data.html&&_this13.$list.append(data.html),_this13.active=data.more,_this13.$scope.$applyAsync()}).catch(function(e){console.error(e)})}}]),ggLoadMore}();angular.module("GG").component("ggLoadMore",{template:'<a href="" ng-click="$ctrl.loadMore()" ng-if="$ctrl.active" class="btn btn-transparent more">{{ $ctrl.text }}</a>',controller:ggLoadMore,bindings:{list:"@",text:"@"}})}(angular),function(angular){var ggNotifySender=function(){function ggNotifySender(){_classCallCheck(this,ggNotifySender),this.icon="info",this.type=0,this.doNotSave=0,this.selected={},this.sendNow=!0,this.dateSend=new Date,this.timers=[],this.history=[],this.text="Это **тестовое** уведомление. Из него следует, что можно прикрепить [ссылку](https://goodgame.ru) или вставить картинку:\n\n{http://i.imgur.com/TfV3xGt.png}"}return _createClass(ggNotifySender,[{key:"$onInit",value:function(){var _this14=this;Utils.get("/ajax/notify/timer/").then(function(data){_this14.timers=data}),Utils.get("/ajax/notify/history/").then(function(data){_this14.history=data})}},{key:"send",value:function(isReal){var _this15=this,padL=function(nr){arguments.length>1&&void 0!==arguments[1]&&arguments[1];return(""+nr).padStart(2,arguments.length>2&&void 0!==arguments[2]?arguments[2]:"0")};
4Utils.post("/ajax/notify/send/",{test:isReal?0:1,type:this.type,groups:this.selected,save:this.doNotSave?0:1,email:this.email,title:this.title,text:this.text,icon:this.icon,dateSend:isReal?this.sendNow?"now":this.dateSend.getFullYear()+"-"+padL(this.dateSend.getMonth()+1)+"-"+padL(this.dateSend.getDate())+" "+padL(this.dateSend.getHours())+":"+padL(this.dateSend.getMinutes())+":00":"now"}).then(function(data){console.log(data),data.success?alert(data.message||"Успешно"):data.success||alert(data.message||"Что-то пошло не так"),_this15.$onInit()})}},{key:"sendTest",value:function(){this.send(!1)}},{key:"sendReal",value:function(){this.send(!0)}}]),ggNotifySender}();angular.module("GG").component("ggNotifySender",{templateUrl:"/html/feed/send-notify.html",controller:ggNotifySender})}(angular),function(angular){var ggPlayerStart=function(){function ggPlayerStart(){_classCallCheck(this,ggPlayerStart)}return _createClass(ggPlayerStart,[{key:"$onInit",value:function(){var url=document.location.href,autoplay=-1!=url.indexOf("#autoplay")&&!(window.StreamController&&window.StreamController.player),apidata=ApiData,src=this.key;Utils.queryParam("random",1)&&(autoplay=!0);var player=new GGPlayer2InWindowAdapter({container:document.getElementById("html5player"),autoplay:autoplay,streamKey:src,apiData:apidata}).getInstance();window.ggplayer=player;var playerDiv=document.getElementById("player-channel-root");playerDiv&&playerDiv.addEventListener("touchmove",function(event){event.preventDefault()},!1)}},{key:"$onDestroy",value:function(){window.ggplayer&&(window.ggplayer.destroy(),window.ggplayer=null)}}]),ggPlayerStart}();angular.module("GG").component("ggPlayerStart",{bindings:{key:"@"},template:"",controller:ggPlayerStart})}(angular),function(angular){var ggPoll=function(){function ggPoll(){var _this16=this;_classCallCheck(this,ggPoll),this.loading=!0,this.blank(),this.canVote=UserService.logged(),NotifyProxy.on("update_object",function(data){return _this16.onObjectUpdate(data)})}return _createClass(ggPoll,[{key:"blank",value:function(){this.errors={},this._hasDate=!1,this.endDate=new Date,this.answers=[],this.question="",this.myVote=0,this.setVote=0,this.hidden=0,this._save=!1,this._subscribed&&NotifyProxy.unsubscribe("10:"+this._subscribed)}},{key:"$onInit",value:function(){this.pollId=parseInt(this.pollId),this.pollId?this.loadData():this.loading=!1}},{key:"create",value:function(){this._edit=!0,this._save=!1,this.admin=!0}},{key:"cancelEdit",value:function(){var _this17=this;0!=this.pollId?(this.loading=!0,this.loadData().then(function(){return _this17._edit=!1})):this._edit=!1}},{key:"save",value:function(){var _this18=this;if(!this.check())return!1;var data={till:this._hasDate?Utils.toMysqlDate(this.endDate):0,hidden:this.hidden,question:this.question,answers:angular.toJson(this.answers.filter(function(value){return value.trim()})),obj:this.obj};this.loading=!0,Utils.post("/ajax/poll/save",data).then(function(data){return _this18.onLoadData(data)}).then(function(){_this18._save=!1,_this18._edit=!1})}},{key:"check",value:function(){return this.errors={},this.question||(this.errors.question=!0),this.answers.filter(function(value){return value.trim()}).length<2&&(this.errors.answers=!0),this._hasDate&&this.endDate<Utils.moscowTime()&&(this.errors.endDate=!0),0==Object.keys(this.errors).length}},{key:"delete",value:function(){var _this19=this;Utils.post("/ajax/poll/"+this.pollId+"/delete/",{obj:this.obj}).then(function(data){_this19.pollId=0,_this19._delete=0,_this19.blank()})}},{key:"loadData",value:function(){var _this20=this;return Utils.get("/ajax/poll/"+this.pollId+"/").then(function(data){return _this20.onLoadData(data)})}},{key:"onLoadData",value:function(data){this.question=data.poll.question,this.answers=data.poll.answers,this.endDate=data.poll.till?new Date(1e3*data.poll.till):new Date,this._hasDate=0!=data.poll.till,this.hidden=data.poll.hidden,this.myVote=data.vote,this.admin=data.admin,this.pollId=data.poll.id,this._hasDate&&this.endDate<new Date&&(this.myVote=-1),this.parseResults(data.results),this.loading=!1,this.pollId&&NotifyProxy&&this._subscribed!=this.pollId&&(this._subscribed&&NotifyProxy.unsubscribe("10:"+this._subscribed),NotifyProxy.subscribe("10:"+this.pollId),this._subscribed=this.pollId)}},{key:"parseResults",value:function(results){if(results){this.results={total:0,percents:[],values:[]};for(var i=1;i<=this.answers.length;i++){var value=results[i-1]||0;this.results.values[i]=value,this.results.total+=value}for(var i=1;i<=this.answers.length;i++)this.results.percents[i]=this.results.total?Math.round(100*this.results.values[i]/this.results.total):0}else this.results=!1}},{key:"vote",value:function(){var _this21=this;if(!UserService.id)return LoginPopup.open("Залогиньтесь, чтобы принять участие в голосовании"),!1;this.setVote&&(this.loading=!0,Utils.post("/ajax/poll/"+this.pollId+"/vote/",{vote:this.setVote}).then(function(data){return _this21.onLoadData(data)}))}},{key:"onLoginChange",value:function(){return this.loadData()}},{key:"onObjectUpdate",value:function(data){data.obj_key=="10:"+this._subscribed&&this.parseResults(data.results)}}]),ggPoll}();angular.module("GG").component("ggPoll",{controller:ggPoll,templateUrl:"/html/template/poll.html",bindings:{pollId:"@",obj:"@"}})}(angular),function(angular){function ggSocialsCtrl($timeout){function initSocialsList(){if(ctrl.enabledSocials=[],!ctrl.socials)return void Object.keys(ctrl.availableSocials).map(function(key){return ctrl.enabledSocials.push(ctrl.availableSocials[key])});ctrl.socials.split(",").forEach(function(item){item=item.replace(/^[\s]+|[\s]+$/g,""),ctrl.availableSocials[item]&&ctrl.enabledSocials.push(ctrl.availableSocials[item])})}
4var componentRenderedPromise,jsLoadedPromise,ctrl=this;ctrl.availableSocials={vkontakte:{name:"vkontakte",text:"Поделиться"},odnoklassniki:{name:"odnoklassniki",text:"Лайкнуть"}},ctrl.$onInit=function(){initSocialsList(),componentRenderedPromise=new Promise(function(resolve){ctrl.$postLink=function(){resolve()}}),jsLoadedPromise=ResourceLoader.loadJs("/js/libraries/likely.js"),Promise.all([componentRenderedPromise,jsLoadedPromise]).then(function(){likely.initiate()})},ctrl.reportClick=function(name){setTimeout(function(){Utils.post("/ajax/news/reportShare/",{name:name,link:ctrl.shareLink})},5e3)}}angular.module("GG").component("ggSocials",{controller:ggSocialsCtrl,bindings:{shareLink:"@",socials:"@"},template:'<div class="likely likely_gg">\n                            <div ng-click="$ctrl.reportClick(social.name)" ng-repeat="social in $ctrl.enabledSocials" data-url="{{ $ctrl.shareLink }}" class="{{ social.name }}">\n                                <span class="icon icon-{{ social.name }}"></span>\n                                \n                            </div>\n                        </div>'}),ggSocialsCtrl.$inject=["$timeout"]}(angular),function(angular){var ggSpoiler=function(){function ggSpoiler($scope){_classCallCheck(this,ggSpoiler),this.active=!1,this.$scope=$scope,$scope.$parent.editorCompile&&(this.active=!0)}return _createClass(ggSpoiler,[{key:"$onInit",value:function(){}}]),ggSpoiler}();angular.module("GG").component("ggSpoiler",{controller:ggSpoiler,template:'<div class="spoiler-block" ng-class="{active:$ctrl.active}">\n                           <div class="spoiler-head" ng-click="$ctrl.active=!$ctrl.active" data-show="показать" data-hide="скрыть">{{ $ctrl.title }}</div>\n                           <div class="spoiler-content" ng-transclude></div>\n                       </div>',transclude:!0,bindings:{title:"@"}})}(angular),function(){function EventsController($scope,$timeout,DateFunctions,$sce){function countLabel(){$scope.feed.newsfeedCnt=vm.list.filter(function(e){return!e.read}).length}function markAsRead(event){event.new=!1,event.read||(event.read=1,NotifyProxy.feedSetRead(event.time),countLabel())}function markAllAsRead(){vm.list.map(function(e){e.read=!0}),NotifyProxy.feedSetRead(0),countLabel()}function displayFeed(data){vm.loaded=!0,vm.list.length=0;for(var key in data)vm.list.push(data[key]);vm.list.forEach(function(item){item.data&&item.data.block&&item.data.block.date&&(item.data.block.date*=1e3)})}function getTemplate(event){return!!event&&"/html/feed/events/"+event.type+".html"}function formatDate(timestamp){return DateFunctions.formatDate(timestamp)}function addEvent(strData){window.DEV&&console.log("FEED","addEvent",strData);var event=strData;if("dialogMessage"==event.type&&"mails"==$scope.feed.currentTab)return event.defaultPrevented=!0,!1;this.last&&this.last==event.time||(event.new=!0,event.data.block&&event.data.block.date&&(event.data.block.date*=1e3),vm.list.unshift(event),this.last=event.time,$scope.$applyAsync())}function deleteEvent(event){var index=vm.list.indexOf(event);-1!=index&&vm.list.splice(index,1),NotifyProxy.feedDelete(event.time).then(displayFeed)}function deleteAll(){NotifyProxy.feedDelete(0).then(displayFeed)}function runAction(button,event){switch(button.action){case"goToPage":return PageLoader.go(button.href);case"goToPageBlank":return window.open(button.href,"_blank").focus();case"makeRequest":return Utils.post(button.url,{}).then(function(data){event.actionResult=data.message})}}var vm=this;vm.list=[],vm.list.update=countLabel,$scope.feed.events=vm.list,vm.loaded=!1,vm.formatDate=formatDate,vm.getTemplate=getTemplate,vm.delete=deleteEvent,vm.deleteAll=deleteAll,vm.setRead=markAsRead,vm.markAllAsRead=markAllAsRead,vm.action=runAction,vm.trustedHtml=function(plainText){return $sce.trustAsHtml(plainText)},$scope.feed.newsfeedCnt=0,function(){window.DEV&&console.log("init"),NotifyProxy.onConnect(function(){NotifyProxy.loadFeed().then(displayFeed)}),NotifyProxy.on("update_feed",addEvent,!0)}(),$scope.$watchGroup(["$root.hideFeed","feed.currentTab"],function(){"newsfeed"==$scope.feed.currentTab&&$scope.$root.hideFeed&&vm.list.map(function(e){e.new=!1})}),$scope.$watch("events.list.length",countLabel)}angular.module("GG").controller("ggEventsCtrl",EventsController),EventsController.$inject=["$scope","$timeout","DateFunctions","$sce"]}(),function(){function FavoritesController($scope,$filter,DateFunctions,$rootScope){function loadTwitchData(){Utils.get("/api/4/favorites/twitch/").then(function(data){vm.twitch=data})}function loadFromApi(){Utils.get("/api/4/favorites/").then(function(data){fillArrays(data,!1)})}function onObjectUpdate(data){window.DEV_FEED&&console.log("FEED","onObjectUpdate",data),allChannels[data.obj_key]&&(angular.merge(allChannels[data.obj_key],data),fillArrays(Object.keys(allChannels).map(function(key){return allChannels[key]}),!0))}function fillArrays(){var arr=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],partial=arguments[1];allChannels={},vm.loaded=!0,vm.isEmpty=!0,vm.online=[],vm.offline=[],vm.soon=[],vm.hosting=[],vm.channelsCount=0,partial||$scope.$apply();for(var i=0;i<arr.length;
4i++){var channel=arr[i];channel.online<0||!channel.streamer||!channel.streamer.nickname||(vm.isEmpty=!1,channel.obj_key&&(allChannels[channel.obj_key]=channel,vm.channelsCount++),window.DEV&&(channel.link=channel.link.replace("https://goodgame.ru/","http://localhost:3220/")),1==channel.online?vm.online.push(channel):(channel.hosting&&vm.hosting.push(channel),channel.broadcast&&(channel.broadcast.startDate=new Date(1e3*channel.broadcast.start)),channel.broadcast&&channel.broadcast.startDate>Date.now()?vm.soon.push(channel):vm.offline.push(channel)))}sort(vm.online,"viewers"),sort(vm.hosting,"viewers"),sort(vm.soon,"broadcast.start",!0),sort(vm.offline,"last_online"),$scope.$parent.feed.favoritesNum=vm.online.length,$scope.$apply()}function sort(array,field,reverse){array.sort(function(a,b){return deepFind(a,field)<deepFind(b,field)?1:-1}),reverse&&array.reverse()}function deepFind(obj,path){var i,paths=path.split("."),current=obj;for(i=0;i<paths.length;++i){if(void 0==current[paths[i]])return;current=current[paths[i]]}return current}function showBlacklist(){vm._blacklist=!vm._blacklist,vm._blacklist&&Utils.get("/ajax/channels/blacklist").then(function(data){vm.blacklist=angular.fromJson(data)})}function deleteFromBlacklist(channel){Utils.post("/ajax/moderation/stream-to-blacklist/",{id:channel.id,action:"unban"}).then(function(){return Utils.get("/ajax/channels/blacklist")}).then(function(data){vm.blacklist=angular.fromJson(data)})}function addToFavorites(channel){vm.twitch=vm.twitch.filter(function(ch){return ch!=channel}),Utils.post("/ajax/subscribe/",{obj_type:7,obj:channel.id})}function hideTwitch(channel){vm.twitch=vm.twitch.filter(function(ch){return ch!=channel}),Utils.post("/api/4/favorites/twitch/hide",{channel:channel.id})}var vm=this;vm.loaded=!1,vm.formatDate=DateFunctions.formatDate,vm.showBlacklist=showBlacklist,vm.deleteFromBlacklist=deleteFromBlacklist,vm.addToFavorites=addToFavorites,vm.hideTwitch=hideTwitch,vm.isReady=function(){return NotifyProxy.ready()},$rootScope.favorites=vm,function(){NotifyProxy.ready()||(console.log("NotifyProxy not ready. Ask API"),loadFromApi()),NotifyProxy.onConnect(function(){NotifyProxy.loadFavorites().then(fillArrays),NotifyProxy.userData&&NotifyProxy.userData.adtrack&&"twitch"==NotifyProxy.userData.adtrack&&loadTwitchData()}),NotifyProxy.on("update_favorites",function(){NotifyProxy.loadFavorites().then(fillArrays)}),NotifyProxy.on("update_object",onObjectUpdate),NotifyProxy.on("update_feed",function(event){"channelOnline"==event.type&&"favorites"==$scope.feed.currentTab&&(event.defaultPrevented=!0)})}(),function(){Utils.get("/ajax/channels/recently").then(function(data){vm.recently=angular.fromJson(data),sort(vm.recently,"viewers"),$scope.$applyAsync()})}();var allChannels={}}angular.module("GG").controller("ggFeedFavoritesCtrl",FavoritesController),FavoritesController.$inject=["$scope","$filter","DateFunctions","$rootScope"]}(),angular.module("GG").component("ggFeedCtrl",{controller:FeedController,controllerAs:"feed",templateUrl:"/html/feed/index.html"}),function(){function FloatingEventsController($scope,$timeout,DateFunctions){function markAsRead(event){$scope.feed.events.map(function(e){e.new=!1}),event.read=!0,vm.list=[],$scope.feed.events.update(),NotifyProxy.feedSetRead(event.time)}function clearEvents(){$scope.feed.events.map(function(e){e.new=!1}),vm.list=[]}function getTemplate(event){return!!event&&"/html/feed/events/"+event.type+".html"}function isVisible(){return vm.list.length&&($scope.$root.hideFeed||"newsfeed"!=$scope.feed.currentTab)}function showFullFeed(){$scope.$root.hideFeed=!1,$scope.feed.currentTab="newsfeed"}function formatDate(timestamp){var date=new Date(Math.min(Date.now(),1e3*timestamp));return DateFunctions.formatDate(date)}function runAction(button,event){switch(button.action){case"goToPage":return PageLoader.go(button.href);case"goToPageBlank":return window.open(button.href,"_blank").focus();case"makeRequest":return Utils.post(button.url,{}).then(function(data){return event.actionResult=data.message})}}var vm=this;vm.list=[],vm.loaded=!1,vm.formatDate=formatDate,vm.getTemplate=getTemplate,vm.showFullFeed=showFullFeed,vm.delete=markAsRead,vm.isVisible=isVisible,vm.action=runAction;var hideTimeout;$scope.$watchGroup(["feed.events.length","feed.currentTab","$root.hideFeed"],function(){$scope.feed.events&&(vm.list=$scope.feed.events.filter(function(e){return e.new}),vm.list.length&&(clearTimeout(hideTimeout),hideTimeout=setTimeout(clearEvents,1e4)))},!0)}angular.module("GG").controller("ggFloatingEventsCtrl",FloatingEventsController),FloatingEventsController.$inject=["$scope","$timeout","DateFunctions"]}(),function(){function StreamController($scope,StreamService){function showChat(roomId){if(vm.player)return currentChat=roomId,!1;Chat&&(roomId?Chat.openRoom(roomId):Chat.closeRoom(vm.chat)),vm.visible=!!roomId,vm.chat=roomId,$scope.$parent.feed.hasChat()&&($scope.$parent.feed.currentTab=vm.visible?"stream":"favorites",UserService.id||($scope.$root.hideFeed=!roomId))}function showPlayer(_player,title,link){StreamService.isTheatreMode()&&StreamService.closeTheatreMode(),1==vm.player&&(vm.player=!1,getPlayer().destroy(),playerPlace.innerHTML="",showChat(!1),showChat(currentChat)),vm.player=!0,vm.streamTitle=title,vm.channelLink=link,player=_player,attachToFeed()}function closePlayer(){0!=vm.player&&(vm.player=!1,checkPage(vm.channelLink)?(getPlayer().detach(),attachToChannel
4()):(getPlayer().destroy(),playerPlace.innerHTML="",currentChat&&currentChat!=vm.chat?(showChat(!1),showChat(currentChat)):showChat(!1)),document.querySelector(".channel-name-block .full-size").classList.remove("hide"))}function checkPage(link){return-1!==window.location.pathname.indexOf(link)}function goToChannel(){checkPage(vm.channelLink)?closePlayer():PageLoader.go(vm.channelLink,function(){document.getElementById("player-channel-root").innerHTML="",setTimeout(closePlayer,0)}),document.querySelector(".channel-name-block .full-size").classList.remove("hide")}function attachToFeed(){setTimeout(function(){Header.getScroller().trigger("scroll")},500),animatePlayer(playerPlace)}function attachToChannel(){var root=document.getElementById("player-channel-root");root.innerHTML="",animatePlayer(root)}function animatePlayer(place){var playerBlock=$(player),targetBlock=vm.player?$(place):$(place).closest(".player-tab"),playerSize=playerBlock.find(".player-block"),targetSize={width:targetBlock.width(),height:targetBlock.height()},targetPos=targetBlock.offset();targetPos.right=$(window).width()-(targetPos.left+targetSize.width);var currentPos=playerBlock.offset(),currentSize={width:playerSize.width(),height:playerSize.height()};currentPos.right=$(window).width()-(currentPos.left+playerBlock.outerWidth()),playerBlock.addClass("floating").css({top:currentPos.top,right:currentPos.right,width:currentSize.width,height:currentSize.height,"z-index":20}).animate({top:targetPos.top,right:targetPos.right,width:targetSize.width+"px",height:targetSize.height+"px"},300,function(){playerBlock.removeClass("floating").removeAttr("style"),place.appendChild(player)})}function getPlayer(){return playerPlace.firstElementChild._ggplayer.self?playerPlace.firstElementChild._ggplayer.self:document.querySelector("#html5player")._ggplayer.self}var vm=this;vm.visible=!1,vm.chat="",vm.player=!1,vm.game=!1,vm.showChat=showChat,vm.showPlayer=showPlayer,vm.closePlayer=closePlayer,vm.goToChannel=goToChannel;var player,currentChat,playerPlace=document.getElementById("player-feed-root");$scope.$parent.feed.stream=vm,window.StreamController.showPlayer=showPlayer,StreamService.detachPlayerFromFeed=closePlayer,window.StreamController.showGame=function(){vm.game=!0,window._gaq&&window._gaq.pu
4sh(["_trackEvent","Game","Vzhukh","start"]),$scope.$apply()},window.StreamController.closeGame=function(){vm.game=!1,$scope.$apply()},window.parent.StreamController.onScore=function(score){console.log("score",score),score>4&&(window.StreamController.closeGame(),alert("Теперь вы можете попробовать снова вбить никнейм"),document.location=document.location)},$scope.$watch(function(){return StreamService.roomId},function(){showChat(StreamService.roomId)})}angular.module("GG").controller("ggFeedStreamCtrl",StreamController)}(),function(){function StreamService($rootScope){var service=this;window.StreamController=service,service.showChat=function(roomId){service.roomId=roomId,$rootScope.$applyAsync()},service.isTheatreMode=function(){return!!$rootScope.theatre},service.closeTheatreMode=function(){$rootScope.theatre=!1}}angular.module("GG").service("StreamService",StreamService)}(),function(){function decl(){return function(number,array){return(number=number||0)+" "+array[Utils.decl(number)]}}angular.module("GG").filter("decl",decl)}(),function(){function escape(){return function(input){return input}}angular.module("GG").filter("escape",escape)}(),function(){function ggDate($filter,DateFunctions){function ggDateFilter(date,typeOrFormat){var time=0;if(isNumeric(date)?time=parseInt(date):"string"==typeof date?time=Utils.moscowToLocalDate(Utils.parseMysqlDate(date)):"object"==(void 0===date?"undefined":_typeof(date))&&(time=+date),time+=Utils.getUserTimezoneOffset(),!isNumeric(typeOrFormat))return $filter("date")(time,typeOrFormat);switch(typeOrFormat=parseInt(typeOrFormat)){case 1:return Utils.timeLeft(+time,Utils.getUserCurrentDate());case 5:if(time<=Utils.getUserCurrentDate())return"Уже в эфире";case 2:var today=Utils.getUserCurrentDate().setHours(0,0,0),target=new Date(time).setHours(0,0,0),days=Math.round((target-today)/864e5),day="d.MM";return 0==days&&(day="Сегодня"),1==days&&(day="Завтра"),$filter("date")(time,day+" в H:mm");case 3:return DateFunctions.getBroadcastsDate(time);case 4:return DateFunctions.getMaterialsDate(time);default:return $filter("date")(time,"H:mm, d.MM")}}function isNumeric(input){return input-0==input&&(""+input).trim().length>0}return ggDateFilter.$stateful=!0,ggDateFilter}angular.module("GG").filter("ggDate",ggDate)}(),function(){function translate(){return function(string,lang){return window._translate(string,lang)}}angular.module("GG").filter("ggTranslate",translate)}(),function(){function int(){return function(input){return Math.floor(input)}}angular.module("GG").filter("int",int)}(),function(){function nl2br(){return function(input){if(void 0!==input)return input.replace(/\n/g,"<br>")}}angular.module("GG").filter("nl2br",nl2br)}(),function(){function ggNumberFormat(){return function(input){return Math.round(input||0).toString().replace(/\B(?=(\d{3})+(?!\d))/g," ")}}angular.module("GG").filter("ggNumberFormat",ggNumberFormat)}(),function(){function orderObjectBy(){return function(input,attribute){if(!angular.isObject(input))return input;var array=[];for(var objectKey in input){var o=input[objectKey];o.__key=objectKey,array.push(o)}return array.sort(function(a,b){return a=parseInt(a[attribute]),b=parseInt(b[attribute]),a-b}),array}}angular.module("GG").filter("orderObjectBy",orderObjectBy)}(),function(){function ggUserDonateDate($filter){return function(input){var currentDate=new Date,inputDate=new Date(input),diffDays=Math.ceil(inputDate.getTime()-currentDate.getTime())/864e5;return $filter("ggDate")(currentDate,"dd.MM.yy")==$filter("ggDate")(inputDate,"dd.MM.yy")?$filter("ggDate")(inputDate,"H:mm"):diffDays>=-1?"Вчера":$filter("ggDate")(inputDate,"dd.MM.yy")}}angular.module("GG").filter("ggUserDonateDate",ggUserDonateDate)}(),function(){function ForumController($scope,$element,$attrs){function searchTopics(){!vm.searchTopicsText||vm.searchTopicsText.length<3||(vm.isLoading=!0,Utils.get("/ajax/forum/search",{id:FORUM_ID,search:vm.searchTopicsText}).then(onLoadSearchTopics))}function onLoadSearchTopics(raw){vm.searchTopicsList=angular.fromJson(raw),vm.isLoading=!1,$scope.$digest()}var FORUM_ID=0,vm=this;vm.isLoading=!1,vm.searchTopicsText="",vm.searchTopicsList=[],vm.searchTopics=searchTopics,function(){FORUM_ID=$attrs.forumId||0,vm.isLoading=!1,vm.searchTopicsText="",vm.searchTopicsList=[]}()}angular.module("GG").controller("ggForumCtrl",ForumController),ForumController.$inject=["$scope","$element","$attrs"]}(angular),function(){function TopicController($scope,$element,$attrs,$compile){function doClaim($event){if(!UserService.id)return $scope.$root.showLogin("Авторизуйтесь, чтобы подать жалобу.");ComplaintPopup.open(OBJ_COMMENT,$scope.first,$event.currentTarget)}function doPin(){Utils.post("/ajax/topic/"+$scope.topic+"/pin/").then(function(result){$scope.fixed=parseInt(result),$scope.$apply()})}function doClose(){Utils.post("/ajax/topic/"+$scope.topic+"/close/").then(function(result){$scope.status=parseInt(result),$scope.$apply()})}function doCheckDelete(){-1==$scope.status?doUndelete():doDelete()}function doDelete(){var id=$scope.topic;Utils.post("/ajax/topic/"+id+"/delete").then(function(){$(".topic-text").hide(),$(".undelete").show(),$scope.status=-1,$scope.$apply()})}function doUndelete(){var id=$scope.topic;Utils.post("/ajax/topic/"+id+"/undelete").then(function(){$(".topic-text").show(),$(".undelete").hide(),$scope.status=1,$scope.$apply()})}function doBan($event){BanPopup.open(OBJ_COMMENT,$scope.first,$event.currentTarget)}var OBJ_COMMENT=6,vm=this;vm.claim=doClaim,vm.pin=doPin,vm.close=doClose,vm.ban=doBan,vm.checkDelete=doCheckDelete,vm.delete=doDelete,vm.undelete=doUndelete,function(){
5$scope.topic=parseInt($attrs.topic),$scope.first=parseInt($attrs.first),$scope.ei_creator=parseInt($attrs.ei_creator),$scope.fixed=parseInt($attrs.fixed),$scope.status=parseInt($attrs.status)}()}angular.module("GG").controller("ggTopicCtrl",TopicController),TopicController.$inject=["$scope","$element","$attrs","$compile"]}(angular),function(){function ggTopicEditor($scope,$attrs){function onLoadData(data){editor.loaded=!0,data=angular.fromJson(data),editor.topic=data.topic,editor.forums=data.forums,!topicId&&forumId&&(editor.topic={forum:forumId,text:""}),$scope.$applyAsync()}function saveTopic(){if(!editor.topic.title.trim())return!1;editor.loaded=!1,editor.error=!1,PageLoader.showLoader();var form=new FormData;form.append("topic",topicId),form.append("data",angular.toJson(editor.topic)),form.append("g-recaptcha-response",editor.captcha?$("#g-recaptcha-response").val():""),Utils.postForm("/ajax/topic/"+topicId+"/save/",form).fail(function(e){PageLoader.hideLoader(),editor.loaded=!0,console.error(e),403==e.status&&(editor.error="Неверная капча")}).done(function(data){data.result&&PageLoader.go("/topic/"+data.result)})}var editor=this,topicId=0,forumId=0;editor.captcha=1==parseInt($attrs.captcha),editor.error=!1,window.location.href.match(/.+topic\/(\d+)\/edit\/?/gi)?topicId=window.location.href.replace(/.+topic\/(\d+)\/edit\/?/gi,"$1"):window.location.href.match(/.+forum\/(\d+)\/new\/?/gi)&&(forumId=window.location.href.replace(/.+forum\/(\d+)\/new\/?/gi,"$1")),function(){ResourceLoader.loadJs("https://www.google.com/recaptcha/api.js?onload=recaptchaOnloadCallback2&render=explicit"),window.recaptchaOnloadCallback2=function(){gre
5captcha.render("captcha-place",{sitekey:"6LenFQETAAAAAO1WCIo7HQhzxbzmzt-oBHV-FPcO",theme:"dark"})},Utils.get("/ajax/topic/"+topicId).then(onLoadData)}(),editor.save=saveTopic}angular.module("GG").controller("ggTopicEditor",ggTopicEditor)}(),function(angular){angular.module("GG").directive("ggContenteditable",function($sce){return{restrict:"A",require:"?ngModel",link:function(scope,element,attrs,ngModel){function read(){var html=element.html();attrs.stripBr&&"<br>"===html&&(html=""),ngModel.$setViewValue(html)}ngModel&&(ngModel.$render=function(){element.html($sce.getTrustedHtml(ngModel.$viewValue||""))},element.on("blur keyup change",function(){scope.$evalAsync(read)}),read())}}})}(angular),function(angular){function gg3dPoster(){function link(scope,element,attrs){function moveImgs(x,y){var moveX=x/10*3,moveY=y/10*3;Array.prototype.slice.call(elem.querySelectorAll("img"),0).forEach(function(img,index){var mx=moveX*index,my=moveY*index;img.style.transition=x?"none":"all 1s ease",img.style.transform="translateX("+my+"px) translateY("+mx+"px) translateZ(0)",img.style.webkitTransform="translateX("+my+"px) translateY("+mx+"px) translateZ(0)"});var blick=elem.querySelector(".blick");blick.style.transition=x?"none":"all 1s ease";var transform="translateX("+(-y*halfWindowW*1.5-100)+"px) translateY("+(-x*halfWindowH*1.5+550)+"px) translateZ(0)";blick.style.transform=transform,blick.style.webkitTransform=transform}var src=attrs.url,layers=attrs.layers,game=attrs.game,group=attrs.group;scope.imgs=[];for(var i=1;i<=layers;i++)group?scope.imgs.push("/images/posters3d/groups/group_"+group+"_"+i+"_poster.png"):game?scope.imgs.push("/images/posters3d/games/game_"+game+"_"+i+"_poster.png"):scope.imgs.push(src+"0"+i+".png");var wrapper=element.closest(".poster-wrapper")[0]||element[0],halfWindowW=wrapper.clientWidth/2,halfWindowH=wrapper.clientHeight/2,elem=element[0].querySelector(".cd-floating-background");elem.style.transform="rotateX(0) rotateY(0) translateZ(0)",elem.style.transformOrigin="50% 50% 20px",elem.style.webkitTransformOrigin="50% 50% 20px",wrapper.addEventListener("mousemove",function(event){var maxRotationX=elem.clientHeight/50,maxRotationY=elem.clientWidth/70,minRotationX=-maxRotationX,rect=wrapper.getBoundingClientRect(),x=event.clientX-rect.left,y=event.clientY-rect.top;halfWindowW||(halfWindowW=this.clientWidth/2),halfWindowH||(halfWindowH=this.clientHeight/2);var rotateY=+(x-halfWindowW)/halfWindowW*maxRotationY,rotateX=-(y-halfWindowH)/halfWindowH*maxRotationX,m=elem.style.transform.match(/rotateX\((.+)\)\s+rotateY\((.+)\) translateZ/);m&&(Math.abs(parseInt(m[2])-rotateY)>1&&(rotateY=(parseInt(m[2])>rotateY?parseInt(m[2])-1:parseInt(m[2])+1).toFixed(3),rotateY=rotateY>maxRotationY?maxRotationY:rotateY),Math.abs(parseInt(m[1])-rotateX)>1&&(rotateX=(parseInt(m[1],10)>rotateX?parseInt(m[1],10)-1:parseInt(m[1],10)+1).toFixed(3),rotateX>maxRotationX?rotateX=maxRotationX:rotateX<minRotationX&&(rotateX=minRotationX))),elem.style.transition="none",elem.style.transform="rotateX("+rotateX+"deg) rotateY("+rotateY+"deg) translateZ(0px)",elem.style.webkitTransform="rotateX("+rotateX+"deg) rotateY("+rotateY+"deg) translateZ(0px)",moveImgs(-rotateX,rotateY)}),wrapper.addEventListener("mouseleave",function(){elem.style.transition="all 1s ease",elem.style.transform="rotateX(0) rotateY(0) translateZ(0px)",elem.style.webkitTransform="rotateX(0) rotateY(0) translateZ(0px)",moveImgs(0,0)})}return{scope:!0,restrict:"E",transclude:!0,replace:!0,link:link,template:'<div class="ggposter"><figure class="cd-floating-background" style="rotateX(0) rotateY(0) translateZ(0)"><div class="inner"><img ng-src="{{ src }}" ng-repeat="src in imgs"><div class="blick"></div></div></figure></div>'}}angular.module("GG").directive("gg3dPoster",gg3dPoster)}(angular),function(){angular.module("GG").directive("ggAutoRepeat",function($parse){function compile($element,$attrs){var list=$attrs.ggAutoRepeat,rpt=document.createAttribute("ng-repeat");return rpt.nodeValue="item in list track by $index",$element[0].children[0].attributes.setNamedItem(rpt),function(scope){scope.list=$parse(list)(scope)}}function ggAutoRepeat($scope,$attrs){var newElem="";try{newElem=angular.fromJson($attrs.new)}catch(e){}$scope.$watch("list",function(){$scope.list&&$scope.list.length&&$scope.list[$scope.list.length-1]&&$scope.list[$scope.list.length-1]!=newElem&&$scope.list.push(newElem),$scope.list&&0==$scope.list.length&&$scope.list.push(newElem)},!0)}return{restrict:"A",scope:!0,controller:ggAutoRepeat,compile:compile}})}(),function(angular){angular.module("GG").directive("ggAutoselect",function($parse){return{restrict:"A",scope:!1,link:function(scope,$element,attrs){$element.on("click",function(){var range,selection;window.getSelection&&document.createRange?(selection=window.getSelection(),range=document.createRange(),range.selectNodeContents(this),selection.removeAllRanges(),selection.addRange(range)):document.selection&&document.body.createTextRange&&(range=document.body.createTextRange(),range.moveToElementText(this),range.select())})}}})}(angular),function(angular){angular.module("GG").directive("ggBanOld",function(){function ggBan($scope,$element){$scope.currentComment=$scope.comment,$scope.showBan=!0,function(){Utils.get("/ajax/get/ban_form_json/",{obj_id:$scope.objId,obj_type:$scope.objType}).then(function(data){try{$scope.data=angular.fromJson(data)}catch(e){alert("Недостаточно прав"),$scope.cancel()}}).then(function(){$scope.$apply()})}(),$scope.doBan=function(){confirm("Вы действительно хотите забанить этого пользователя?")&&Utils.post("/ajax/make_ban/",{obj_type:$scope.objType,obj_id:$scope.objId,reason:$scope.selectedReason,with_cleaning:+$scope.deleteMsgWithClean,ip_ban:+$scope.ipBan,delete_msg:+$scope.deleteMsg}).then(function(data){data=angular.fromJson(data),data&&data.delete_msg&&$scope.afterBan({comment:$scope.currentComment}),$scope.cancel()})},$scope.doWarning=function(){confirm("Вы действительно хотите выдать предупреждение этому пользователю?")&&Utils.post("/ajax/make_warning/",{obj_type:$scope.objType,obj_id:$scope.objId,reason:$scope.selectedReason,with_cleaning:+$scope.deleteMsgWithClean,ip_ban:+$scope.ipBan,delete_msg:+$scope.deleteMsg}).then(function(data){data=angular.fromJson(data),data&&data.delete_msg&&$scope.afterBan({comment:$scope.currentComment}),$scope.cancel()})},$scope.cancel=function(){$element.remove(),$scope.$destroy()}}return{restrict:"E",scope:{showBan:"=",objType:"@",objId:"@",comment:"=",afterBan:"&"},replace:!0,transclude:!0,controller:ggBan,templateUrl:"/html/template/ban.html"}})}(angular),function(angular){function ggCarousel($compile){function link(scope,element){function _unBindEvents(){controlLeft.off("click",_onControlClick),controlRight.off("click",_onControlClick),wrapper.off("scroll",_onScrollClb),_onScrollClb=void 0,window.removeEventListener("resize",_onResizeClb),_onResizeClb=void 0}function _onControlClick(e){var direction;$(e.currentTarget).hasClass("gg-carousel-control-disable")||(direction=$(e.currentTarget).hasClass("gg-carousel_control_right")?"right":"left")&&_canScroll(direction)&&_scroll(direction)}function _scroll(direction){var scrollLeft=wrapper.scrollLeft(),offset=scrollLeft+("left"===direction?-1:1)*scrollStep;wrapper.animate({scrollLeft:offset},ANIMATION_TIME,_updateScrollDirection)}function _scrollToSelectedPage(){var selectedItem=wrapper.find(".gg-carousel-item.selected");if(selectedItem.length>0){var scrollStep=wrapper.width(),items=wrapper.find(".gg-carousel-item"),itemWidth=items.width(),index=selectedItem.index(),pageN=Math.ceil(index/Math.round(scrollStep/itemWidth))||1,offset=(pageN-1)*scrollStep;wrapper.animate({scrollLeft:offset},ANIMATION_TIME,_updateScrollDirection)}}function _canScroll(direction){return"both"===currentScrollDirection||
5currentScrollDirection===direction}function _updateScrollDirection(){var direction,scrollLeft=wrapper.scrollLeft(),listWidth=wrapper[0].scrollWidth,contentWidth=wrapper.width();direction=listWidth-contentWidth<=0?"":0===scrollLeft?"right":scrollLeft+contentWidth<listWidth?"both":"left",element.removeClass("gg-carousel_scroll_"+currentScrollDirection),direction&&(element.addClass("gg-carousel_scroll_"+direction),currentScrollDirection=direction)}function _checkListOut(){var left=wrapper.scrollLeft(),listWidth=wrapper[0].scrollWidth,contentWidth=wrapper.width();left<=endListOffset&&_onListOut("left"),left+contentWidth>listWidth-endListOffset&&_onListOut("right")}function _onListOut(direction){"right"===direction&&_loadMoreItems()}function _loadMoreItems(){var promise=scope.ggCarouselLoadMore({page:++curPage});promise&&promise.then(_onMoreLoaded)}function _onMoreLoaded(html){html=$compile(html)(scope),wrapper.append(html),_updateScrollDirection()}function _updateScrollStep(){scrollStep=wrapper.width()}function _updateEndListOffset(){endListOffset=scrollStep||wrapper.width()}function _updateFirstVisibleItem(){var itemWidth,scrolledItems,left=wrapper.scrollLeft(),items=wrapper.find(".gg-carousel-item");if(!left)return void(curFirstVisibleItem=items.eq(0));itemWidth=items.width(),scrolledItems=Math.round(left/itemWidth),curFirstVisibleItem=items.eq(scrolledItems)}function _setProperPosToFirstVisibleItem(){wrapper.animate({scrollLeft:curFirstVisibleItem[0].offsetLeft},ANIMATION_TIME,_updateScrollDirection)}var currentScrollDirection,_onScrollClb,_onResizeClb,curFirstVisibleItem,endListOffset,scrollStep,ANIMATION_TIME=500,controlLeft=element.find(".gg-carousel_control_left"),controlRight=element.find(".gg-carousel_control_right"),wrapper=element.find(".gg-carousel-wrapper"),curPage=1;_updateScrollStep(),_updateEndListOffset(),_updateScrollDirection(),_updateFirstVisibleItem(),function(){controlLeft.on("click",_onControlClick),controlRight.on("click",_onControlClick),_onScrollClb=Utils.debounce(function(){_updateScrollDirection(),_updateFirstVisibleItem(),_checkListOut()},50),wrapper.on("scroll",_onScrollClb),_onResizeClb=Utils.throttle(function(){setTimeout(function(){_updateScrollStep(),_updateScrollDirection(),_setProperPosToFirstVisibleItem(),_updateScrollStep(),_updateEndListOffset()},500)},1e3),window.addEventListener("resize",_onResizeClb),scope.$on("$destroy",_unBindEvents)}(),function(){var isFirstCall=!0;scope.$on("ggCarouselScrollToSelectedOnce",function(event,args){isFirstCall&&(isFirstCall=!1,_scrollToSelectedPage())})}(),function(){element.find(".sections-control.mobile .btn").on("click",function(event){event.preventDefault(),_loadMoreItems()})}()}return{restrict:"A",scope:{ggCarouselLoadMore:"&"},link:link}}angular.module("GG").directive("ggCarousel",ggCarousel),ggCarousel.$inject=["$compile"]}(angular),function(angular){angular.module("GG").directive("ggCatchFocus",function(){return{restrict:"A",scope:!1,link:function(scope,$element){$element.focus()}}})}(angular),function(angular){function ggChannelSelector(){function link(scope,element){new ChannelsAutoComplete(element,function(title,elem,data){try{scope.ggChannelSelector({channel:{id:data.id,title:title}})}catch(e){}})}return{restrict:"A",scope:{ggChannelSelector:"&"},link:link}}angular.module("GG").directive("ggChannelSelector",ggChannelSelector)}(angular),function(){function ggCkEditor($compile,$timeout){function link($scope,elm,attr,ngModel){var data,ck,raw;ngModel.$render=function(){void 0!==ngModel.$modelValue&&($scope.editorCompile=1,raw=ngModel.$modelValue,data=$compile("<div>"+ngModel.$modelValue+"</div>")($scope),$scope.mode||($scope.mode="comments"),CKEDITOR.disableAutoInline=!0,CKEDITOR.timestamp=+new Date,ck="materials"==$scope.mode?CKEDITOR.inline(elm[0],{customConfig:"/js/libraries/ckeditor/config."+$scope.mode+".js"}):CKEDITOR.replace(elm[0],{customConfig:"/js/libraries/ckeditor/config."+$scope.mode+".js"}),ck.on("instanceReady",function(e){$("[mode=comments] .cke_button").removeAttr("title"),data=$("<div/>").html(data),ck.setData(data.html()),ngModel.$setViewValue(raw)}),ck.on("pasteState",function(){if($scope.$root&&$scope.$root.$$phase){var phase=$scope.$root.$$phase;"$apply"!=phase&&"$digest"!=phase?$scope.$apply(function(){ngModel.$setViewValue(ck.getData())}):ngModel.$setViewValue(ck.getData())}}),ck.on("change",function(){ngModel.$setViewValue(ck.getData())}))}}function controller($scope,$element){this.recompile=function($_element){return $compile($_element)($scope)},this.compile=function(html,on_set){var result=$compile(html)($scope);$timeout(function(){on_set(result.get(0).outerHTML)})}}return{restrict:"A",require:"?ngModel",scope:{mode:"@mode"},link:link,controller:controller}}angular.module("GG").directive("ggCkEditor",ggCkEditor)}(angular),function(angular){angular.module("GG").directive("ggClickOutside",function($parse){return{restrict:"A",scope:!1,link:function(scope,$element,attrs){function clickHandler(e){var elem=ignoreSelector?$element.add(ignoreSelector):$element;
5Utils.checkClickOutside(e.target,elem)&&(expressionHandler(scope,{event:e}),scope.$applyAsync(),0==$("body").has($element).length&&window.removeEventListener("mousedown",clickHandler))}var expressionHandler=$parse(attrs.ggClickOutside),ignoreSelector=attrs.ignore||!1;window.addEventListener("mousedown",clickHandler),scope.$on("$destroy",function(){return window.removeEventListener("mousedown",clickHandler)})}}})}(angular),function(angular){angular.module("GG").directive("ggComments",function(DateFunctions,$timeout,$compile,$sce){function ggComments($scope,$element){function onObjChange(a,b){a!=b&&(vm.data=!1,vm.currentPage=0,loadData())}function _loadPage(){expand(),vm.data.loading=!0,loadData(),$scope.$applyAsync()}function isVisible(){return $element[0].getBoundingClientRect().top<=window.innerHeight}function loadData(){if(!$scope.objId)return!1;window.location.hash.match(/#comment-(\d+)?/gi)&&!vm.loadComment?loadDataScroll():loadDataStd()}function loadDataStd(){return Utils.get("/ajax/comments/get/",{objId:$scope.objId,objType:$scope.objType,page:vm.currentPage}).then(onLoadPage).then(function(){$scope.$apply(),NotifyProxy&&!_subscribed&&(NotifyProxy.subscribe(objKey),NotifyProxy.on("update_object",onObjectUpdate),_subscribed=!0)})}function loadDataScroll(){vm.loadComment=!0;var idCommentMatch=window.location.hash.match(/(\d+)/gi),idCom=parseInt(idCommentMatch[0],10);idCom>0?Utils.get("/ajax/comments/get-comment-pager/",{objId:$scope.objId,objType:$scope.objType,comment:idCom}).then(function(data){data.page&&(vm.currentPage=data.page)}).then(function(){return loadDataStd()}).then(function(){return Utils.scrollToElement2($('*[gg-ancor="#comment-'+idCom+'"]'))}):loadDataStd()}function onLoadPage(data){try{var _data=angular.fromJson(data);_data.err&&"post comment no allow"==_data.msg?alert("Оставить комментарий запрещено"):vm.data=_data;for(var i=0;i<vm.data.comments.length;i++){vm.data.comments[i].edit=!1}for(var i=0;i<vm.data.top.length;i++){vm.data.top[i].top=1}vm.totalPages=Math.ceil(vm.data.info.qty/25),vm.currentPage=-1==vm.data.info.page?vm.totalPages:vm.data.info.page,vm.data.comments.length&&vm.data.comments[vm.data.comments.length-1].id==vm.data.info.comment&&(vm.data.info.comment=0),vm.data.user&&(vm.data.user.admin&&(vm.isAdmin=!0),vm.data.user.owner&&(vm.isOwner=!0)),vm.commentText="",vm.data.loading=!1,vm._posting=!1,vm.newCommentsCount=0}catch(e){}}function formatDate(timestamp){return DateFunctions.formatDate(1e3*timestamp||Utils.moscowTime())}function postComment(comment){if(!UserService.id)return void $scope.$root.showLogin("Авторизуйтесь, чтобы оставить комментарий.");var text,id=0;if(vm._posting=!0,comment?(text=comment.text,id=comment.id):(text=vm.commentText,id=0),!text||!text.trim())return void(vm._posting=!1);var scroller=Header.getScroller(),saveScroll=scroller.scrollTop();Utils.post("/ajax/comments/post/",{objId:$scope.objId,objType:$scope.objType,id:id,comment:text,currentPage:vm.data.info.page}).then(onLoadPage).then(function(){expand(),vm.commentText="",CKEDITOR.instances["comments-editor"].setData(""),id>0&&(comment.edit=!1),$scope.$applyAsync(function(){scroller.animate({scrollTop:saveScroll},5)})})}function makeAnswer(comment){if(!UserService.id)return void $scope.$root.showLogin("Авторизуйтесь, чтобы ответить на комментарий.");editorInsert('<a href="#c'+comment.id+'">#'+comment.i+"</a>,&nbsp;"),collapse(comment)}function isCreator(comment){return comment&&UserService.id&&comment.author.id==UserService.id}function deleteComment(comment){return UserService.id?(confirm("Вы действительно хотите удалить сообщение?")&&Utils.post("/ajax/comments/delete/",{id:comment.id}).then(function(response){response=angular.fromJson(response),response.result&&"ok"==response.result&&(response.deleted_by&&(comment.deleted_by=response.deleted_by),deleteCommentDom(comment),$scope.$apply())}),!1):void $scope.$root.showLogin("Авторизуйтесь, чтобы удалить сообщение.")}function deleteCommentDom(comment){comment.deleted=!0,$scope.$applyAsync()}function cancelDelete(comment){return UserObj.id?(confirm("Вы действительно хотите отменить удаление сообщения?")&&Utils.post("/ajax/comments/undelete/",{id:comment.id}).then(function(response){response=angular.fromJson(response),response.result&&"ok"==response.result&&(comment.deleted=!1)}),!1):void $scope.$root.showLogin("Авторизуйтесь, чтобы отменить удаление.")}
5function quoteComment(comment){if(!UserObj.id)return void $scope.$root.showLogin("Авторизуйтесь, чтобы процитировать сообщение.");var selection=getSelection();""===selection&&(selection=comment.text),editorInsert('<div class="cquote" contenteditable="false"><div class="cq-author"><a href="#c'+comment.id+'">#'+comment.i+"</a>,&nbsp;"+comment.author.nickname+"</div>"+selection+"</div><br />"),collapse(comment)}function editComment(comment){comment.edit=!0,backupComment["c"+comment.id]=comment.text}function complain(comment,$event){if(!UserObj.id)return void $scope.$root.showLogin("Авторизуйтесь, чтобы подать жалобу.");ComplaintPopup.open(OBJ_COMMENT,comment.id,$event.currentTarget)}function banWindow(comment,$event){if(!UserObj.id)return void $scope.$root.showLogin("Авторизуйтесь, чтобы была возможность банить.");BanPopup.open(OBJ_COMMENT,comment.id,$event.currentTarget,vm.afterBanDelete,comment)}function afterBanDelete(comment){comment.deleted_by=UserObj,deleteCommentDom(comment)}function getSelection(){var str;return document.getSelection?str=document.getSelection().toString():document.selection&&(str=document.selection.createRange().text),str}function editorInsert(text){var editor=CKEDITOR.instances["comments-editor"],beforeInsert=editor.getData(),element=editor.element.$.closest(".comments-block"),scroller=Header.getScroller(),scrollTop=scroller.scrollTop()-scroller.offset().top+$(element).offset().top;editor.setData(beforeInsert+text);var range=editor.createRange();range.moveToElementEditEnd(range.root),editor.getSelection().selectRanges([range]),scroller.animate({scrollTop:scrollTop},200)}function collapse(comment){var num,comm,offset,block=$element.find(".collapse");if(-1!=vm.data.top.indexOf(comment)?(num=vm.data.top.length-vm.data.top.indexOf(comment)-1+vm.data.comments.length,comm=block.find(".top").find("#comment-"+comment.id),offset=20):(num=vm.data.comments.length-vm.data.comments.indexOf(comment)-1,comm=block.find(".comments-list").find("#comment-"+comment.id),offset=0),num>0){vm.hiddenCnt=num,block.css({height:block.outerHeight()});var height=comm.position().top+comm.outerHeight()+comm.closest(".comments-block").position().top+offset;block.animate({height:height+"px"},300)}}function expand(){var list=$element.find(".collapse");list.animate({height:list[0].scrollHeight+"px"},300,function(){vm.hiddenCnt=0,list.css({height:"auto"}),$scope.$apply()})}function onObjectUpdate(data){if(data.obj_key==objKey){var hasNewComments=data.cqty&&data.cqty>vm.data.info.cqty,isLastPage=vm.currentPage==vm.totalPages;hasNewComments&&isLastPage&&(vm.newCommentsCount=data.cqty-vm.data.info.cqty)}}function _getCommentObjById(commentId){for(var commentObj,i=0;i<vm.data.top.length;i++)if(commentId==vm.data.top[i].id)return commentObj=vm.data.top[i];for(var i=0;i<vm.data.comments.length;i++)commentId==vm.data.comments[i].id&&(commentObj=vm.data.comments[i]);return commentObj}function cancelComment(comment){comment.edit=!1,comment.text=backupComment["c"+comment.id]}var OBJ_COMMENT=6,vm=this,_scrolled=!1,_subscribed=!1,objKey=$scope.objType+":"+$scope.objId,backupComment={};vm.isCreator=isCreator,vm.isAdmin=!1,vm.isOwner=!1,vm.isUserBanned=!(!window.UserObj||"boolean"!=typeof window.UserObj.is_banned)&&window.UserObj.is_banned,vm.formatDate=formatDate,vm.postComment=postComment,vm.deleteComment=deleteComment,vm.cancelDelete=cancelDelete,vm.makeAnswer=makeAnswer,vm.editComment=editComment,vm.quoteComment=quoteComment,vm.complain=complain,vm.banWindow=banWindow,vm.afterBanDelete=afterBanDelete,vm.expand=expand,vm.decl=Utils.decl,vm.reload=loadData,vm.cancelComment=cancelComment,vm.currentPage=0,vm.newCommentsCount=0,vm.closed=!!$scope.closed,vm.loadComment=!1,$scope.autoload?loadData():function(){$(function(){var func=function(){!_scrolled&&isVisible()&&(_scrolled=!0,loadData(),scrollableElement.off("scroll",handler),scrollableElement.off("touchmove",handler))},scrollableElement=Header.getScroller(),handler=Utils.debounce(func,100);scrollableElement.on("scroll",handler),scrollableElement.on("touchmove",handler),func()})}(),$scope.$watch("objId",Utils.debounce(onObjChange,100)),$scope.$watch("$destroy",function(){_subscribed&&NotifyProxy.unsubscribe(objKey)}),$scope.$watch("closed",function(v){vm.closed=!!v}),function(){var pageTimeout=0;$scope.$watch("vm.currentPage",function(newValue,oldValue){oldValue&&newValue&&newValue!=oldValue&&(clearTimeout(pageTimeout),pageTimeout=setTimeout(_loadPage,150))})}
5(),function(){$element.on("keydown",".editor",function(event){if(13==event.which&&(event.ctrlKey||event.metaKey)){event.preventDefault();var commentId,$comment,commentObj;$comment=$(event.currentTarget).closest(".comment-block").attr("id"),$comment&&(commentId=$comment.match(/\d+/)[0]),commentObj=_getCommentObjById(commentId),postComment(commentObj)}})}()}return{scope:{objType:"=",objId:"=",autoload:"=",closed:"="},restrict:"E",replace:!0,templateUrl:"/html/template/comments.html",controller:ggComments,controllerAs:"vm"}})}(angular),function(angular){angular.module("GG").directive("ggCompile",function($compile,SmilesService){function ggCompile(scope,element,attrs){element.html(scope.ggCompile),["div[gg-spoiler]","div[gg-youtube]","gg-spoiler","gg-media"].forEach(function(tag){element.find(tag).each(function(idx,el){$compile(el)(scope)})})}return{restrict:"A",scope:{ggCompile:"="},link:ggCompile}})}(angular),function(angular){angular.module("GG").directive("ggComplaintOld",function(){function ggComplaint($scope,$element){$scope.showComplaint=!0,$scope.sendComplaint=function(){Utils.post("/ajax/make-claim/",{claim_msg:$scope.complaint,type:$scope.objType,id:$scope.objId}).then(function(data){data=angular.fromJson(data),data&&data.msg&&alert(data.msg),$scope.cancel()})},$scope.cancel=function(){$element.remove(),$scope.$destroy()}}return{restrict:"E",scope:{showComplain:"=",objType:"@",objId:"@"},replace:!0,transclude:!0,controller:ggComplaint,templateUrl:"/html/template/complaint.html"}})}(angular),function(angular){angular.module("GG").directive("ggContent",function(){return{restrict:"A",scope:!0,link:function(scope){scope.ggContent=!0,window.pageScope=scope}}})}(angular),function(){function ggCropbox($document,$timeout){function link(scope,element,attrs){function checkXY(){scope.crop.x>0&&(scope.crop.x=0),scope.crop.x<250-w*scope.crop.s&&(scope.crop.x=250-w*scope.crop.s),scope.crop.y>0&&(scope.crop.y=0),scope.crop.y<250-h*scope.crop.s&&(scope.crop.y=250-h*scope.crop.s)}function mousemove(event){scope.crop.y=event.pageY-startY,scope.crop.x=event.pageX-startX,checkXY(),img.css({top:scope.crop.y+"px",left:scope.crop.x+"px"})}function mouseup(){$document.off("mousemove",mousemove),$document.off("mouseup",mouseup)}var w,h,img=element.find("img"),startX=0,startY=0;scope.scale=function(direction){if(!(1==scope.crop.s&&direction>0||.1==scope.crop.s&&direction<0)){var oldCrop=parseFloat(scope.crop.s),newCrop=parseFloat(scope.crop.s)+.1*direction;newCrop*w<250||newCrop*h<250||(scope.crop.s=newCrop,scope.crop.y=scope.crop.y+(oldCrop-scope.crop.s)*h/2,scope.crop.x=scope.crop.x+(oldCrop-scope.crop.s)*w/2,checkXY(),img.css({width:w*scope.crop.s,height:h*scope.crop.s,top:scope.crop.y+"px",left:scope.crop.x+"px"}))}},img.on("mousedown",function(event){event.preventDefault(),startX=event.pageX-scope.crop.x,startY=event.pageY-scope.crop.y,$document.on("mousemove",mousemove),$document.on("mouseup",mouseup)}),scope.$watch("src",function(newValue,oldValue){newValue!=oldValue&&img.one("load",function(){w=img[0].naturalWidth,h=img[0].naturalHeight,void 0!=oldValue&&(scope.crop.x=(250-w)/2,scope.crop.y=(250-h)/2,scope.crop.s=1),img.css({width:w*scope.crop.s,height:h*scope.crop.s,top:scope.crop.y+"px",left:scope.crop.x+"px"})})})}return{restrict:"A",scope:{file:"=",src:"=",crop:"="},transclude:!0,link:link,templateUrl:"/html/template/cropbox.html"}}angular.module("GG").directive("ggCropbox",ggCropbox)}(angular),function(angular){angular.module("GG").directive("ggDatePicker",function(DateFunctions){function ggDatePicker($scope,$element){function dateGetterSetter(newValue){if(void 0===newValue){var validCurDate=Utils.parseRussianDate(vm._handDate,!!vm.time);return vm.dateError=!validCurDate,vm._handDate}var validNewDate=Utils.parseRussianDate(newValue,!!vm.time);return vm.dateError=!validNewDate,validNewDate&&(vm._date=validNewDate),vm._handDate=newValue,vm._handDate}function hoursGetterSetter(newValue){var curHours=vm._date.getHours();if(void 0===newValue)return vm.withZero(curHours);vm._date.setHours(newValue),onChange()}function minutesGetterSetter(newValue){var curMinutes=vm._date.getMinutes();if(void 0===newValue)return vm.withZero(curMinutes);vm._date.setMinutes(newValue),onChange()}function onChange(){vm._handDate=DateFunctions.toRussianDate(vm._date,!!vm.time)}function getMonthName(){return["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь"][vm._date.getMonth()]}function plusMonth(value){vm._date.setMonth(vm._date.getMonth()+value),onChange()}function plusHour(value){vm._date.setHours(vm._date.getHours()+value),onChange()}
5function plusMinute(value){var next=5*Math.ceil((vm._date.getMinutes()+value)/5);vm._date.setMinutes(next),onChange()}function chunk(arr){for(var R=[],i=0;i<arr.length;i+=7)R.push(arr.slice(i,i+7));return R}function setDate(cday){vm._date.setFullYear(cday.getFullYear()),vm._date.setDate(1),vm._date.setMonth(cday.getMonth()),vm._date.setDate(cday.getDate()),onChange()}function setDay(){if(!vm._date)return!1;vm._day=new Date(vm._date.getFullYear(),vm._date.getMonth(),vm._date.getDate()),$scope.date="string"==typeof $scope.date?DateFunctions.toMysqlDate(vm._date):vm._date}function calendClick(event){event.stopImmediatePropagation(),event.stopPropagation(),this._show=!this._show}var vm=this;vm.date=dateGetterSetter,vm.getMonthName=getMonthName,vm.plusMonth=plusMonth,vm.plusHour=plusHour,vm.plusMinute=plusMinute,vm.setDate=setDate,vm.calendClick=calendClick,vm.withZero=Utils.withZero,vm.time=void 0===$scope.time?1:"true"==$scope.time,vm.hours=hoursGetterSetter,vm.minutes=minutesGetterSetter,$scope.min?vm.minTime="now"==$scope.min?(new Date).getTime():new Date($scope.min).getTime():vm.minTime=0,function(){vm._date="string"==typeof $scope.date?Utils.moscowToLocalDate(Utils.parseMysqlDate($scope.date)):Utils.toUserTimezoneDate($scope.date),vm._handDate=DateFunctions.toRussianDate(vm._date,!!vm.time),vm._show=!1}(),$scope.$watchGroup(["vm._date.getMonth()","vm._date.getFullYear()"],function(){if(!vm._date)return!1;var first=new Date(vm._date.getFullYear(),vm._date.getMonth(),1);first.setDate(first.getDate()-(first.getDay()||7)+1);var last=new Date(vm._date.getFullYear(),vm._date.getMonth()+1,0);if(last.setDate(last.getDate()+7-last.getDay()),vm.days=[],vm.minTime&&first.getTime()<vm.minTime){first=new Date(vm.minTime);for(var c=1,m=first.getDay();c<m;++c)vm.days.push(0)}for(var d=first;d<=last;)vm.days.push(new Date(+d)),d.setDate(d.getDate()+1);vm.days=chunk(vm.days)}),$scope.$watch("vm._date.getTime()",setDay)}return{scope:{date:"=",time:"@",min:"@"},restrict:"E",replace:!0,templateUrl:"/html/template/datetime.html",controller:ggDatePicker,controllerAs:"vm"}})}(angular),function(angular){function ggDropbox(scope,element){var catchPromise;document.addEventListener("dragover",function(event){event.preventDefault(),catchPromise&&clearTimeout(catchPromise)}),document.addEventListener("dragenter",function(event){element.addClass("catch")}),document.addEventListener("dragleave",function(event){catchPromise&&clearTimeout(catchPromise),catchPromise=setTimeout(function(){element.removeClass("catch")},10)}),element.on("dragover",function(){element.addClass("hover")}),element.on("dragleave",function(){element.removeClass("hover")}),element.on("drop",function(event){event.preventDefault(),$(".dropbox").removeClass("catch hover");var evt=event.originalEvent,file=evt.dataTransfer.files[0],webUrl=window.URL||window.webkitURL;scope.file=file,scope.src=webUrl.createObjectURL(file)})}angular.module("GG").directive("ggDropbox",function(){return{scope:{file:"=",src:"="},restrict:"A",link:ggDropbox}})}(angular),function(angular){function ggFileread(scope,element,attributes){element.bind("change",function(changeEvent){var webUrl=window.URL||window.webkitURL,image=changeEvent.target.files[0];scope.file=image,scope.filename=image.name,scope.src=webUrl.createObjectURL(image),scope.$applyAsync()})}angular.module("GG").directive("ggFileread",function(){return{scope:{file:"=",src:"=?",filename:"=?"},restrict:"A",link:ggFileread}})}(angular),function(angular){function ggGameSelector(){function link(scope,element){new GamesAutoComplete(element,function(title,elem,data){scope.game=data[1];try{scope.action({game:{id:scope.game,title:title}}),void 0!==scope.clear&&1!=scope.clear||(element.get(0).value="")}catch(e){}},!0,"1"==scope.genres)}return{restrict:"A",scope:{game:"=?",genres:"=?",action:"&",clear:"=?"},link:link}}angular.module("GG").directive("ggGameSelector",ggGameSelector)}(angular),function(angular){
6angular.module("GG").directive("ggHref",function($parse){return{restrict:"A",scope:!1,link:function(scope,$element,attrs){$element.on("click",function(){var link=attrs.ggHref;if("/"!==link.substr(0,1)){var base=document.location.pathname;link=("/"===base.slice(-1)?base:base+"/")+link}PageLoader.go(link)})}}})}(angular),function(angular){angular.module("GG").directive("sbLoad",["$parse",function($parse){return{restrict:"A",link:function(scope,elem,attrs){var fn=$parse(attrs.sbLoad);elem.on("load",function(event){scope.$apply(function(){fn(scope,{$event:event})})})}}}])}(angular),function(angular){angular.module("GG").directive("ggInit",function(){function ggInit($scope,$element,$attrs,$parse){var getter,setter,val;val=$attrs.ggInit||$attrs.value,getter=$parse($attrs.ngModel),(setter=getter.assign)($scope,val)}return{restrict:"A",controller:ggInit}})}(angular),function(angular){angular.module("GG").directive("ggLocalTime",function(ggDateFilter){function ggLocalTime($scope,$element,$filter){function init(
6){var localTime,utcTimestamp=1e3*$scope.utcTimestamp;localTime=ggDateFilter(utcTimestamp,$scope.format),$element.text(localTime)}init(),UserService.onLoginChange(init)}return{scope:{utcTimestamp:"@",format:"@"},restrict:"E",replace:!0,controller:ggLocalTime}})}(angular),function(){function ggMedia($sce){function link(scope,element,attr,controller,transclude){if(scope.edit=1==scope.$parent.editorCompile,scope.isVideoFile=!1,scope.trustedVideoSrc=null,!scope.edit)if(void 0!=scope.params){var a=scope.params.split(":"),type=parseInt(a[0])||0;switch(scope.src=a[1]||"",type){case 2:scope.fullSrc="youtube.com/watch?v="+scope.src,scope.src="//youtube.com/embed/"+scope.src;break;case 3:scope.fullSrc="twitch.tv/v/"+scope.src,scope.src="//player.twitch.tv/?video="+scope.src;break;default:scope.src="Данный тип видеозаписи не поддерживается для встраивания на сайт"}}else{var trans=transclude();switch(trans.get(0).innerHTML?scope.media=trans.get(0).innerHTML:scope.media=trans.get(0).data,window.url("hostname",scope.media)){case"www.goodgame.ru":case"goodgame.ru":var regExp=new RegExp(/.+\/clip\/(\d+)\/?/);if(scope.media.match(regExp)){var clipId=scope.media.replace(regExp,"$1");scope.src="/clip/"+clipId+"/embed/"}break;case"www.youtube.com":case"youtube.com":scope.fullSrc="youtube.com/watch?v="+window.url("?",scope.media).v,scope.src="//youtube.com/embed/"+window.url("?",scope.media).v;break;case"www.youtu.be":case"youtu.be":scope.fullSrc="youtube.com/watch?v="+window.url("1",scope.media),scope.src="//youtube.com/embed/"+window.url("1",scope.media);break;case"www.twitch.tv":case"twitch.tv":var b=window.url("2",scope.media),c=window.url("3",scope.media);scope.fullSrc="twitch.tv/"+b+"/"+c,scope.src="//player.twitch.tv/?video="+b+c;break;case"www.rutube.ru":case"rutube.ru":var rutubeRegExp=new RegExp(/.*rutube\.ru\/play\/embed\/([a-zA-Z0-9]+)\/?/);if(scope.media.match(rutubeRegExp)){var videoId=scope.media.replace(rutubeRegExp,"$1");scope.fullSrc="rutube.ru/video/"+videoId,scope.src="//rutube.ru/play/embed/"+videoId}else console.error("Failed to match Rutube URL pattern for:",scope.media);break;default:scope.fullSrc=scope.media,scope.isVideoFile=/\.(mp4|webm|ogg)(\?.*)?$/i.test(scope.media),scope.isVideoFile?(scope.trustedVideoSrc=scope.media,scope.src=null):scope.src=scope.media}}}function controller($scope,$sce){$scope.trustUrl=function(src){return $sce.trustAsResourceUrl(src)}}return{restrict:"A",scope:{media:"@ggMedia",params:"@ggParams"},link:link,controller:controller,transclude:!0,template:'<div class="media-content">\n                    <video ng-if="!edit && isVideoFile" ng-src="{{trustedVideoSrc}}" width="740" height="416" autoplay loop muted playsinline></video>\n                    <iframe ng-if="!edit && !isVideoFile && src" ng-src="{{trustUrl(src)}}" frameborder="0" scrolling="no" width="740px" height="416px" allowfullscreen="true"></iframe>\n                    <div ng-if="edit" class="media-edit">\n                        <div>Ссылка на медиа объект:</div>\n                        <div class="media-url" ng-transclude></div>\n                    </div>\n                 </div>'}}angular.module("GG").directive("ggMedia",ggMedia)}(angular),function(angular){function ggMixedSelector(){function link(scope,element,attr){new ParticipantsAutoComplete(element,function(nickname,el,user){user.nickname=nickname,scope.action({user:user}),setTimeout(function(){element.val(attr.value)})},!0)}return{restrict:"A",scope:{action:"&"},link:link}}angular.module("GG").directive("ggMixedSelector",ggMixedSelector)}(angular),function(angular){angular.module("GG").directive("ggModalWindow",function(){return{restrict:"E",scope:{show:"="},transclude:!0,template:'                <div ng-if="show">                    <div class="modal-window-overlay" ng-click="hideModal()"></div>                    <div class="modal-window">                      <a href class="icon icon-close2" ng-click="hideModal()"></a>                      <div class="modal-window-content" ng-transclude></div>                    </div>                </div>',link:function($scope,element){angular.element(document.body).append(element),$scope.hideModal=function(){$scope.show=!1}}}})}(angular),function(angular){angular.module("GG").directive("ggNoPreview",function(){return{restrict:"A",scope:{logo:"@ggN
6oPreview"},link:function(scope,$element){$element.on("error",function(){$element.attr("src")!=scope.logo&&$element.attr("src",scope.logo)})}}})}(angular),function(angular){angular.module("GG").directive("ggPager",function(){function link(scope,element,attrs,ctrl,transclude){transclude(scope,function(clone,scope){element.append(clone)})}function ggPager($scope){function setPage(n){$scope.currentPage=n,$scope.scrollTo&&scrollToElement($("a[name='"+$scope.scrollTo+"']"))}function scrollToElement(element,speed){var scroller=Header.getScroller();speed=void 0!==speed?speed:300,element?scroller.animate({scrollTop:scroller.scrollTop()+element.offset().top-scroller.offset().top},speed):scroller.animate({scrollTop:0},speed)}function fillPages(){var total=$scope.totalPages,current=parseInt($scope.currentPage,10),pages=[],last=0;total<=8?pages=range(1,total):(pages=range(1,1),last=1,current<total&&(last>=current-2?pages=pages.concat(range(last+1,current+1)):(pages.push(0),pages=pages.concat(range(current-1,current+1))),last=current+1),last>=total-1?pages=pages.concat(range(last,total)):(pages.push(0),total-1+1==current&&pages.push(current-1),pages=pages.concat(range(total-1+1,total)))),pages=pages.filter(function(value,index,self){return 0===value||self.indexOf(value)===index}),pager.pages=pages}function range(start,end){for(var foo=[],i=start;i<=end;i++)foo.push(i);return foo}var pager=this;pager.setPage=setPage,$scope.$watch(function(){return[$scope.currentPage,$scope.totalPages]},function(){fillPages()},!0)}return{restrict:"A",scope:{currentPage:"=",totalPages:"=",scrollTo:"@"},link:link,controller:ggPager,controllerAs:"pager",transclude:!0}})}(angular),function(angular){function Directive(PopupService){return{link:function(scope,element,attrs){function open(){popup.isOpen=!0,element.show()}function close(){popup.isOpen=!1,element.hide()}var popup;if(!attrs.id)return void console.error("popup must have an id");popup={id:attrs.id,open:open,close:close},PopupService.add(popup),scope.$on("$destroy",function(){PopupService.remove(attrs.id)})},controller:PopupController}}function PopupController($scope,PopupService){function openPopup(e){PopupService.open(_getPopupIdByEvent(e))}function closePopup(e){PopupService.close(_getPopupIdByEvent(e))}function _getPopupIdByEvent(e){return e.target.closest("gg-popup").attributes.id.value}$scope.openPopup=openPopup,$scope.closePopup=closePopup}angular.module("GG").directive("ggPopup",Directive),Directive.$inject=["PopupService"]}(angular),function(){function ggQuote(){return{restrict:"A",scope:{author:"@"},transclude:!0,link:function(scope,element){},template:'<div class="quote-block"><div class="quote-icon"><span class="icon icon-Quote-28px"></span></div><div class="quote-content" ng-transclude></div><div class="quote-author"><p class="author-edit">{{author}}</p></div></div>'}}angular.module("GG").directive("ggQuote",ggQuote)}(angular),function(angular){angular.module("GG").directive("ggRating",function(){return{scope:{rated:"=",up:"=",down:"=",type:"=",id:"=",canrate:"="},restrict:"E",template:'<span class="rate up" ng-click="rateUp()"><span class="icon" ng-class="{active:rated==1, \'icon-like\':canrate, \'icon-like-empty\':!canrate}"></span>&nbsp;<span class="count"> <span>{{ up }}</span> <span>{{ newUp }}</span> </span></span><span class="rate down" ng-click="rateDown(-1)"><span class="icon" ng-class="{active:rated==-1, \'icon-dislike\':canrate, \'icon-dislike-empty\':!canrate}"></span>&nbsp;<span class="count"> <span>{{ down }}</span> <span>{{ newDown }}</span> </span></span>',link:function(scope,element,attributes){function postVote(){if("rec"==Utils.queryParam("from")){var mark=1==scope.rated?"UP":"DOW
6N",from="p"==Utils.queryParam("b")?"PERSONAL":"CLIP";Utils.reachGoal("REC_VOTE_"+mark+"_"+from)}Utils.post("/ajax/rating/do/",{objType:scope.type,objId:scope.id,vote:scope.rated}).then(function(data){data=angular.fromJson(data),scope.newUp=parseInt(data.up)||0,scope.newDown=parseInt(data.down)||0,scope.rated=parseInt(data.vote)||0,scope.$apply(),animateRating()})}function animateRating(){if(scope.newUp!=scope.up){var elemUp=element.find(".up").find(".count");elemUp.animate({scrollTop:30},function(){scope.up=scope.newUp,scope.$apply(),elemUp.scrollTop(0)})}if(scope.newDown!=scope.down){var elemDown=element.find(".down").find(".count");elemDown.animate({scrollTop:30},function(){scope.down=scope.newDown,scope.$apply(),elemDown.scrollTop(0)})}}scope.newUp=scope.up,scope.newDown=scope.down,scope.rateUp=function(){scope.canrate&&0==scope.rated&&UserService.id&&(scope.rated=1,postVote())},scope.rateDown=function(){scope.canrate&&0==scope.rated&&UserService.id&&(scope.rated=-1,postVote())},scope.notNull=function(value){return 0==value?"":value}}}})}(angular),function(angular){if(window.Map){var debounceTimer,listeners=new Map,elements=[];angular.module("GG").directive("ggScrollSpy",function(){function link(scope,element){var scrollableElement=Header.getScroller()[0],eventListener=Utils.debounce(onScroll,500);scrollableElement.addEventListener("scroll",eventListener),scope.$on("$destroy",function(){scrollableElement.removeEventListener("scroll",eventListener)})}function controller(){return{addListener:function(elem,scope){listeners.set(elem,scope)},removeListener:function(elem){listeners.delete(elem)},debounce:debounceActions}}function onScroll(event){var scrollHeight=Header.getScroller().height();listeners.forEach(function(scope,elem){elem[0].getBoundingClientRect().top-14<scrollHeight&&scope.$emit("scrollSpy")})}function debounceActions(element,action){elements.push(element),debounceTimer&&clearTimeout(debounceTimer),debounceTimer=setTimeout(function(){action(elements),elements.length=0},500)}return{restrict:"A",link:link,controller:controller}})}}(angular),function(angular){angular.module("GG").directive("ggScrollToTop",function(){function link(scope,element){var scrollableElement=Header.getScroller(),visible=!1;window._ngZone.runOutsideAngular(function(){scrollableElement.on("scroll",function(e){!visible&&e.currentTarget.scrollTop>700?(element.hasClass("scroll-down")&&element.removeClass("scroll-down"),element.addClass("scroll-up"),visible=!0):0==e.currentTarget.scrollTop&&(element.hasClass("scroll-up")&&element.removeClass("scroll-up").addClass("scroll-down"),visible=!1)})}),$(element).click(function(){Utils.scrollToElement(null,300,!0)})}return{restrict:"A",link:link}})}(angular),function(angular){angular.module("GG").directive("ggScrollViewTrigger",function(){function link(scope,element,attrs,ggScrollSpy){var sended=!1;if(!ggScrollSpy)return!1;ggScrollSpy.addListener(element,scope),scope.$on("scrollSpy",function(){sended||(ggScrollSpy.debounce(scope.objId,function(elements){Utils.post("/ajax/news/reportViews/",{objects:elements})}),sended=!0)}),scope.$on("destroy",function(){ggScrollSpy.removeListener(element)})}return{restrict:"A",scope:{objType:"=",objId:"="},require:"?^ggScrollSpy",link:link}})}(angular),function(angular){function ggScrollable($window,$debounce){function link(scope,element){var iOS=navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform),droid=/android/i.test(navigator.userAgent);if(iOS||droid)element.css({overflow:"scroll","-webkit-overflow-scrolling":"touch"});else{element.addClass("tse-scrollable"),element.TrackpadScrollEmulator();var w=element[0],c=element.find(".tse-content")[0];scope.$watch(function(){return{h:w.clientHeight,w:w.clientWidth,ih:c.clientHeight,iw:c.clientWidth}},function(newValue,oldValue){if(0==newValue.iw&&0==newValue.ih)return!1;$debounce(function(){try{if(element.TrackpadScrollEmulator){element.TrackpadScrollEmulator("option");element.TrackpadScrollEmulator("recalculate"),newValue.h<oldValue.h&&scope.vm&&scope.vm.view&&scope.vm.view.doScroll()}}catch(e){console.error("ggScrollable",e)}},500)},!0)}}return{restrict:"A",transclude:!0,link:link,template:'<div class="tse
6-content"><ng-transclude></ng-transclude></div>'}}angular.module("GG").directive("ggScrollable",ggScrollable),ggScrollable.$inject=["$window","$debounce"]}(angular),function(angular){function ggScrollableLight($window,$debounce){function link(scope,element){new SimpleBar(element[0])}return{restrict:"A",link:link}}angular.module("GG").directive("ggScrollableLight",ggScrollableLight),ggScrollableLight.$inject=["$window","$debounce"]}(angular),function(angular){function ggSelect($timeout,$compile){function link(scope,element,attrs){function compile(){select=angular.element(element).find("select"),scope.valueText=select.find("option:selected").text(),scope.items=[],select.find("*").each(function(i,a){scope.items.push({elem:a,text:$(a).text(),value:$(a).val(),tag:!!a.getAttribute("data-del")})}),bindOnce&&(select.on("change",function(){compile()}),bindOnce=!1)}!function(){scope.onCompile&&$timeout(scope.onCompile),$timeout(compile)}();var bindOnce=!0,select=element.find("select");select.scope().$watch(function(){var elt=select[0];scope.valueText=elt&&-1!=elt.selectedIndex?elt.options[elt.selectedIndex].text:""}),angular.element(document).on("click",function(e){var target=e.target,container=angular.element(element);container.is(target)||0!==container.has(target).length||(scope.opened=!1,scope.$applyAsync())}),scope.setValue=function(item){select.val(item.value),$timeout(function(){select.change()})}}return{scope:{isblue:"=blue",disabled:"=disabled",deleteItem:"&"},restrict:"A",transclude:!0,replace:!0,link:link,template:'<div class="ui-select" ng-click="opened=!opened && !disabled" ng-class="{open:opened}"> \n                    <div style="display:none" ng-transclude></div>\n                    <div class="dropdown" ng-class="{open:opened, blue:isblue, disabled:disabled}"> \n                        <div class="dropdown-btn dropdown-toggle" type="button" id="dropdown3" data-toggle="dropdown" aria-expanded="true"> \n                        <div class="text">{{ valueText }}</div> \n                            <span class="caret"></span> \n                        </div> \n                        <ul class="dropdown-menu" role="menu" aria-labelledby="dropdown3"> \n                            <li role="presentation" ng-repeat="item in items">\n                                <a role="menuitem" tabindex="-1" href="" ng-if="item.text" ng-click="setValue(item)">{{ item.text }}</a>\n                                <span class="icon icon-trash-chat" ng-if="item.tag" ng-click="deleteItem({item: item.value})"></span>\n                            </li> \n                        </ul> \n                    </div> \n                </div>'}}angular.module("GG").directive("ggSelect",ggSelect),ggSelect.$inject=["$timeout","$compile"],angular.module("GG").directive("convertToNumber",function(){return{require:"ngModel",link:function(scope,element,attrs,ngModel){ngModel.$parsers.push(function(val){return parseInt(val,10)}),ngModel.$formatters.push(function(val){return""+val})}}})}(angular),function(angular){angular.module("GG").directive("ggSliderBlock",function(){function sliderLogic(scope,element){function goPrevPage(){rightArrow.parentNode.classList.remove("disabled"),currentPage=Math.max(currentPage-1,1),listScroll.style.transform="translateX(-"+100*(currentPage-1)+"%)",1==currentPage&&leftArrow.parentNode.classList.add("disabled"),currentPage>1&&leftArrow.parentNode.classList.remove("disabled")}function goNextPage(){last!=currentPage&&(leftArrow.parentNode.classList.remove("disabled"),currentPage+=1,last=Math.max(currentPage,last),listScroll.style.transform="translateX(-"+100*(currentPage-1)+"%)",currentPage<last&&rightArrow.parentNode.classList.remove("disabled"),currentPage==last&&rightArrow.parentNode.classList.add("disabled"))}var currentPage=1,sliderLength=document.querySelectorAll(".clip-list-scroll .clip-page"),last=sliderLength.length,listScroll=document.querySelector(".clip-slider .clip-list-scroll"),leftArrow=document.querySelector(".sections-control .icon.icon-arrow-left"),rightArrow=document.querySelector(".sections-control .icon.icon-arrow-right");leftArrow.addEventListener("click",goPrevPage),rightArrow.addEventListener("click",goNextPage)}return{restrict:"A",link:sliderLogic}})}(angular),function(){function ggSpoiler(){function link(scope,element,attrs,controller,transclude){scope.active=!1,transclude(scope,function(clone){element.find("span").replaceWith(clone[0].innerHTML)}),scope.$parent.editorCompile&&(scope.active=!0)}return{restrict:"A",scope:{title:"@ggTitle"},transclude:!0,link:link,template:'<div class="spoiler-block" ng-class="{active:active}"><div class="spoiler-head" ng-click="active=!active" data-show="показать" data-hide="скрыть">{{ title }}</div><div class="spoiler-content" ng-transclude></div></div>'}}
6angular.module("GG").directive("ggSpoiler",ggSpoiler)}(angular),function(angular){angular.module("GG").directive("ggStreamPreview",function(){return{restrict:"A",scope:{ggStreamPreview:"@",isPremium:"@",muted:"@"},link:function(scope,$element){function onMouseEnter(){scope.ggStreamPreview&&(playerHolder=angular.element('<div id="preview-player"></div>'),$element.append(playerHolder),player=new GGPlayer({container:playerHolder[0],playlist:"http://hls.goodgame.ru/dash/"+scope.ggStreamPreview+"/index.mpd",autoplay:!0,streamkey:scope.ggStreamPreview,previewmode:!0,apidata:{channel_premium:"1"==scope.isPremium},muted:scope.muted}),player.onStop(function(){onMouseLeave(!1)}))}function onMouseLeave(event){showFn.cancel(),player&&!event&&player.destroy(),playerHolder&&playerHolder.remove()}var playerHolder,player,showFn=Utils.debounce(onMouseEnter,1e3);$element.on("mouseenter",showFn),$element.on("mouseleave",onMouseLeave)}}})}(angular),function(angular){angular.module("GG").directive("ggSubscribe",function(){return{scope:{channel:"=",state:"="},restrict:"E",templateUrl:"/html/template/subscribe.html?v=2",controllerAs:"vm",controller:function($scope,$element){function changeColor(){if(!UserService.id){var color=void 0,colorsArr=["linear-gradient(180deg, #721933 0%, #1EA384 100%)","linear-gradient(180deg, #0058DC 0%, #CB0505 100%)","linear-gradient(180deg, #DC3E2C 0%, #1B2848 100%)","linear-gradient(180deg, #259E64 0%, #8E8104 100%)","linear-gradient(180deg, #7EB9B9 0%, #7E2595 100%, #7E2595 100%)","linear-gradient(180deg, #DE7321 0%, #AD5D1E 100%)"],randomIndex=function(min,max){return Math.floor(min+Math.random()*(max+1-min))}(0,colorsArr.length-1);vm._isHoverHandlerActive&&(color=colorsArr[randomIndex]),$element.find(".follow").css("background",color)}}var vm=this;vm.state="1"==$scope.state,vm._loading=!1,vm.show=0,vm._isHoverHandlerActive=!0,vm.changeColor=changeColor,vm.channelId=$scope.channel;var channelId=$scope.channel,isDetailsLoaded=!1;vm.state&&(vm._isHoverHandlerActive=!1),UserService.id||vm.changeColor(),this.showDetail
6s=function(force){vm.show=!vm.show,!force&&isDetailsLoaded||(vm._loading=!0,Utils.get("/ajax/subscription/",{obj_type:7,obj:channelId}).then(function(data){data=angular.fromJson(data),vm.get_videos=1==data.get_videos?1:0,vm.get_email=1==data.get_email?1:0,vm._loading=!1,vm.get_anons=1==data.get_anons?1:0,isDetailsLoaded=!0,vm.emptyBell=[vm.get_videos,vm.get_email,vm.get_anons].some(function(d){return!d})}))},this.subscribe=function(){if(vm._isHoverHandlerActive=!vm._isHoverHandlerActive,!UserService.id)return void window.openLogin();Utils.post(vm.state?"/ajax/unsubscribe/":"/ajax/subscribe/",{obj_type:7,obj:channelId,getEmail:1}).then(function(){vm.state||Utils.reachGoal("channel_fav"),vm.state=!vm.state,vm.state&&($element.find(".follow").css("background","rgba(68, 83, 126, 0.5)"),vm.get_email=1,$element.find(".follow").on("transitionend",function(){vm.show=1}),vm.get_anons=0,vm.showDetails(!0))}).then(function(){return $scope.$apply()})},this.saveDetails=function(){vm.show=!1,Utils.post("/ajax/subscribe/",{obj_type:7,obj:channelId,getAnons:vm.get_anons,getEmail:vm.get_email,getVideos:vm.get_videos}).then(null,function(error){vm.show=!0,Utils.reachGoal("channel_fav")}).then(function(){return $scope.$apply()})}}}})}(angular),function(angular){function ggSwitch(){function link(scope,element){function mouseEnter(){handle.animate({left:1==scope.active?hoverMove:widths[0]-hoverMove,right:1==scope.active?widths[1]-hoverMove:hoverMove},aniSpeed)}function mouseLeave(){handle.animate({left:1==scope.active?0:widths[0],right:1==scope.active?widths[1]:0},aniSpeed)}function mouseClick(event){event.preventDefault(),scope.active=1==scope.active?2:1;var link=element.find("a").eq(scope.active-1)[0];""!=link.getAttribute("href")&&PageLoader.go(link.href),mouseLeave()}var widths=[element.find("a").eq(0).outerWidth(),element.find("a").eq(1).outerWidth()],handle=element.find(".active"),hoverMove=5,aniSpeed=150;handle.css({left:1==scope.active?0:widths[0],right:1==scope.active?widths[1]:0}),element.on("mouseenter",mouseEnter),element.on("mouseleave",mouseLeave),element.on("click",mouseClick)}return{restrict:"E",scope:{active:"@"},link:link}}angular.module("GG").directive("ggSwitch",ggSwitch)}(angular),function(angular){angular.module("GG").directive("ggtextarea",function(){function link(scope,element,attrs,ctrl,transclude){transclude(scope,function(clone){element.val(clone.html())})}return{restrict:"E",transclude:!0,replace:!0,template:"<textarea></textarea>",link:link}})}(angular),function(angular){angular.module("GG").directive("ggTranslate",function(ggDateFilter){function ggTranslate(scope,element){var text=element.text();scope.$watch("ggTranslate",function(){var translation=window._translate(text,scope.ggTranslate);translation&&element.text(translation)})}return{scope:{ggTranslate:"="},restrict:"A",link:ggTranslate}})}(angular),function(angular){angular.module("GG").directive("ggUser",function(){function controller($scope,$element,UserOnlineService){$scope.userObj&&$scope.userObj.obj_key&&(UserOnlineService.watch($element,$scope.userObj),$scope.$on("$destroy",function(){return UserOnlineService.unwatch($element)}),$scope.$watch("userObj",function(){return UserOnlineService.update($element,$scope.userObj)}
6))}return{restrict:"A",scope:{userObj:"=ggUser"},controller:controller}})}(angular),function(angular){function ggUserSelector(){function link(scope,element,attr){var playerType=scope.playerType||1;scope.cupType;new ParticipantsAutoComplete(element,function(nickname,el,user){user.nickname=nickname,scope.action({user:user}),setTimeout(function(){element.val(attr.value)})},!0,playerType)}return{restrict:"A",scope:{action:"&",playerType:"@",cupType:"@"},link:link}}angular.module("GG").directive("ggUserSelector",ggUserSelector)}(angular),function(angular){angular.module("GG").directive("ggWebp",function(){function ggWebp($scope,$element,$attrs,$parse){var src=$attrs.ggWebp;supportedPromise().then(function(state){state&&(src=src.replace(".jpg",".webp").replace(".png",".webp")),$element.attr("style","background-image: url('"+src+"')")})}var supported=null,supportedPromise=function(){return new Promise(function(resolve){if(null!==supported)return resolve(supported);var setSupported=function(state){return resolve(supported=state)},img=$("<img>");img.on("load",function(){return setSupported(2===img[0].width&&1===img[0].height)}).on("error",function(){return setSupported(!1)}).attr("src","data:image/webp;base64,UklGRjIAAABXRUJQVlA4ICYAAACyAgCdASoCAAEALmk0mk0iIiIiIgBoSygABc6zbAAA/v56QAAAAA==")})};return{restrict:"A",controller:ggWebp}})}(angular),function(angular){angular.module("GG").directive("ggYoutube",function(){function controller($scope,$element,$sce){var video=this,info=angular.fromJson($scope.info);video.id=$scope.ggClip||$scope.ggYoutube,video.type=$scope.ggClip?1:0,video.title=info.title,video.img=info.thumb,video.description=info.desc,video.duration=info.time?function(duration){var match=duration.match(/PT(\d+H)?(\d+M)?(\d+S)?/),hours=parseInt(match[1])||0,minutes=parseInt(match[2])||0,seconds=parseInt(match[3])||0;
6return(hours?Utils.withZero(hours)+":":"")+Utils.withZero(minutes)+":"+Utils.withZero(seconds)}(info.time):0,video.showPlayer=!1,video.url=$sce.trustAsResourceUrl("https://www.youtube.com/embed/"+video.id+"?autoplay=1"+(info.start>0?"&start="+info.start:""))}return{restrict:"A",scope:{ggYoutube:"@",ggClip:"@",info:"@"},controller:controller,controllerAs:"video",template:'<div class="video-link-block" ng-if="!video.showPlayer">\n                    <a href="" ng-click="video.showPlayer=true" target="_blank" >\n                        <span class="img-block">\n                            <img src="" ng-src="{{ video.img }}" alt="">\n                            <span class="duration" ng-if="video.duration">{{ video.duration }}</span>\n                            <span class="icon icon-video-icon"></span>\n                        </span>\n                        <span class="ov">\n                            <span class="info-block">                                \n                                <span class="title">{{ video.title }}</span>\n                                <span class="text">{{ video.description }}</span>\n                                <span class="source" ng-if="video.type==0">youtube.com</span>\n                                <span class="source" ng-if="video.type==1">goodgame.ru</span>\n                            </span>\n                        </span>\n                    </a>\n                 </div>\n                 <div ng-if="video.showPlayer">\n                    <iframe width="560" height="315" ng-src="{{ video.url }}" ng-if="video.type==0" frameborder="0" allowfullscreen></iframe>\n                    <div ng-if="video.type==1">\n                        <gg-video-player poster="{{ video.img }}" id="{{ video.id }}"></gg-video-player>\n                    </div>\n                </div>\n                 '}})}(angular),function(){function ggGallery($scope,$element){function onClickOutside(e){Utils.checkClickOutside(e.target,$(".gallery-block-popup").add(".comments").add(".cke_editor_comments-editor_dialog"))&&closePopup()}function loadData(){Utils.get("/ajax/gallery/"+vm.galleryId).then(onLoadData).then(function(){$scope.$apply()})}function onLoadData(data){var data=angular.fromJson(data);if(vm.images=data.images,vm.title=data.title,vm.imageId){var index=getImageIndex(vm.imageId);-1!=index&&(vm.currentIndex=index)}}function getImageIndex(id){for(var i=0;i<vm.images.length;i++)if(vm.images[i].id==id)return i;return-1}function onResize(){var winHeight=window.innerHeight;vm.galleryHeight=winHeight-238+"px"}function closePopup(){$(".popup-block").remove(),window.removeEventListener("resize",debounced),window.removeEventListener("click",onClickOutside)}function showNext(){vm.currentIndex<vm.images.length-1&&vm.currentIndex++}function showPrev(){vm.currentIndex>0&&vm.currentIndex--}var debounced,vm=this;vm.currentIndex=0,vm.close=closePopup,vm.next=showNext,vm.prev=showPrev,function(){onResize(),Utils.debounce(onResize,100),window.addEventListener("resize",debounced),window.addEventListener("click",onClickOutside)}(),$scope.$watch("vm.galleryId",function(){loadData()})}angular.module("GG").controller("ggGallery",ggGallery)}(),function(angular){angular.module("GG").directive("ggGallery",function(){function ggGallery($scope){function onLoadData(_data){if(_data){var data=angular.fromJson(_data);gallery.id=data.id,gallery.images=data.images,gallery.title=data.title}$scope.$apply()}function openPopup(image){GalleryPopup.open(gallery.id,image.id)}var gallery=this;gallery.id=0,gallery.open=openPopup,function(){$scope.obj&&$scope.obj.id&&Utils.get("/ajax/gallery/",{objId:$scope.obj.id,objType:$scope.obj.type}).then(onLoadData)}()}return{restrict:"A",scope:!1,controller:ggGallery,controllerAs:"gallery",templateUrl:"/html/gallery/block.html"}})}(angular),function(angular){angular.module("GG").directive("ggGalleryEditor",function(){function ggGalleryEditor($scope){function onLoadData(_data){if(_data){var data=angular.fromJson(_data);gallery.id=data.id,gallery.images=data.images,gallery.title=data.title}$scope.$apply()}function deleteImage(image){Utils.post("/ajax/gallery/"+gallery.id+"/delete/",{image:image.id}).then(onLoadData)}function addImage(){var data=new FormData;data.append("objType",$scope.objType),data.append("objId",$scope.objId),data.append("file",gallery.$newImage),Utils.postForm("/ajax/gallery/"+gallery.id+"/add/",data).then(onLoadData)}var gallery=this;gallery.id=0,gallery.$newImage=!1,gallery.delete=deleteImage,function(){Utils.get("/ajax/gallery/",{objId:$scope.objId,objType:$scope.objType}).then(onLoadData)}(),$scope.$watch("gallery.$newImage",function(){gallery.$newImage&&addImage()})}return{restrict:"A",scope:{objId:"=",objType:"="},controller:ggGalleryEditor,controllerAs:"gallery",templateUrl:"/html/gallery/edit.html"}})}(angular),function(angular){var HelpEditorType=function(){function HelpEditorType(){_classCallCheck(this,HelpEditorType),console.log(this),this.helpTypeId=0,this.loaded=!1,this.type={id:0,title:"",order:0},window.location.href.match(/.+help\/(\d+)\/edit-type\/?/gi)&&(this.t
6ype.id=this.helpTypeId=window.location.href.replace(/.+help\/(\d+)\/edit-type\/?/gi,"$1")),this.init()}return _createClass(HelpEditorType,[{key:"init",value:function(){var _this22=this;Utils.get("/ajax/help/"+this.helpTypeId+"/type").then(function(data){return _this22.onLoadData(data)})}},{key:"onLoadData",value:function(data){this.type=data,this.type.order=parseInt(this.type.order,10)||0,this.loaded=!0}},{key:"save",value:function(){if(!this.type.title)return alert("Заполните Заголовок"),!1;var temp_order=parseInt(this.type.order,10);if(0!==temp_order&&!temp_order)return alert("Заполните правильно циферку сортировки"),!1;this.loaded=!1,PageLoader.showLoader();var form=new FormData;form.append("type",this.helpTypeId),form.append("data",angular.toJson(this.type)),Utils.postForm("/ajax/help/"+this.helpTypeId+"/save_type/",form).error(function(e){console.error(e)}).success(function(data){console.log(data),data.result?PageLoader.go("/help/"+data.result+"/"):alert("Ошибка сохранения"),this.loaded=!0})}}]),HelpEditorType}();angular.module("GG").controller("ggHelpEditorType",HelpEditorType)}(window.angular),function(){function ggHelpEditor($scope,$attrs){function defaultArticle(){return{title:"",type:1,keywords:"",text:"",status:1}}function onLoadData(data){editor.loaded=!0,data=angular.fromJson(data),editor.article=data.article||defaultArticle(),editor.types=data.types,editor.statuses={0:"Не активно",1:"Активно","-1":"Удалена"},console.log(editor),$scope.$applyAsync()}function saveHelp(){if(!editor.article.title.trim())return!1;editor.loaded=!1,PageLoader.showLoader();var form=new FormData;form.append("article",helpId),form.append("data",angular.toJson(editor.article)),
7Utils.postForm("/ajax/help/"+helpId+"/save/",form).fail(function(e){console.error(e)}).done(function(data){data.result&&PageLoader.go("/help/"+editor.article.type+"/"+data.result)})}var editor=this,helpId=0;window.location.href.match(/.+help-old\/(\d+)\/(\d+)\/edit\/?/gi)&&(helpId=window.location.href.replace(/.+help-old\/(\d+)\/(\d+)\/edit\/?/gi,"$2")),function(){Utils.get("/ajax/help/"+helpId).then(onLoadData)}(),editor.save=saveHelp}angular.module("GG").controller("ggHelpEditor",ggHelpEditor)}(),function(angular){angular.module("GG").directive("ggLiveSearch",function(){function link(scope,element,attrs){function loadResults(){PageLoader.showLoader(),$.get("/ajax/help/search/",{query:input.val()},function(data){$("#live-search-content").html(data),PageLoader.hideLoader()})}var timer,input=element.find("input");input.on("input",function(e){$(this).val().length<2||""==$(this).val()||(timer&&clearTimeout(timer),timer=setTimeout(loadResults,300))})}return{restrict:"A",link:link}})}(angular),angular.module("GG").config(function($stateProvider){$stateProvider.state("jobs.ios_android",{url:"ios_android/",templateUrl:"/html/jobs/ios_android.html",resolve:{$title:function(){return"Работа на goodgame.ru: iOS/Android разработчик"}}}).state("jobs.web",{url:"web/",templateUrl:"/html/jobs/web.html"}).state("jobs.beginning",{url:"beginning/",templateUrl:"/html/jobs/beginning.html"})}),function(){function ggMaterialEditor($scope,$attrs,$interval,$timeout){function addPlayer(user){vm.news.players[user.p_id]=user}function deletePlayer(user){delete vm.news.players[user.p_id]}function insertPlayer(user){var a=vm.news.players[user.p_id].insert;a=a.replace(new RegExp(' class="sign"',"gi"),' class="sign" contenteditable="true"'),CKEDITOR.currentInstance.insertHtml(a)}function addGame(game){vm.news.games[game.id]=game}function deleteGame(game){delete vm.news.games[game.id]}function deleteImg(logo){switch(logo){case"logo":delete vm.$logoFile,vm.news.logo="/images/channel-logo.jpg";break;case"background":delete vm.$backgroundFile,vm.news.background="/images/channel-logo.jpg";break;case"social":delete vm.$socialFile,vm.news.social="/images/channel-logo.jpg"}vm.news.crop={x:-205,y:-62.5,s:1},materialId>0&&Utils.post("/ajax/material/delete-logo/",{id:materialId,logo:logo})}function onLoadData(data){vm.loaded=!0,data=angular.fromJson(data),vm.news=data.material,vm.news.date=0==vm.news.date?new Date:new Date(1e3*vm.news.date),vm.news.url="news/"+vm.news.key,vm.news.type=""+vm.news.type,0==vm.news.games.length&&(vm.
7news.games={}),0==vm.news.players.length&&(vm.news.players={}),$scope.repostStatus=0!=vm.news.repost,materialId&&(auto=$interval(autoSave,6e4,0,!1)),$scope.$applyAsync(),$timeout(function(){$scope.$digest()},100)}function autoSave(){console.log("autosave"),saveMaterial(!0)}function saveMaterial(autosave){autosave||(autosave=!1,vm.loaded=!1,PageLoader.showLoader()),vm.news.repost=$scope.repostStatus?1:0;var form=new FormData;form.append("material",materialId),form.append("data",angular.toJson(vm.news)),form.append("autosave",autosave),vm.$logoFile&&form.append("logo",vm.$logoFile),vm.$socialFile&&form.append("social",vm.$socialFile),vm.$backgroundFile&&form.append("background",vm.$backgroundFile),Utils.postForm("/ajax/material/"+materialId+"/save/",form).fail(function(e){console.error(e),vm.loaded=!0,PageLoader.hideLoader()}).done(function(data){data.key&&!autosave&&PageLoader.go(data.key)})}function publishMaterial(){vm.news.status=2==vm.news.status?1:2}var auto,vm=this,materialId=parseInt($attrs.materialId);!function(){Utils.get("/ajax/material/"+materialId+"/edit").then(onLoadData)}(),vm.save=saveMaterial,vm.publish=publishMaterial,vm.addPlayer=addPlayer,vm.insertPlayer=insertPlayer,vm.deletePlayer=deletePlayer,vm.addGame=addGame,vm.deleteGame=deleteGame,vm.deleteImg=deleteImg,$scope.$on("$destroy",function(){return $interval.cancel(auto)})}angular.module("GG").controller("ggMaterialEditor",ggMaterialEditor)}(),function(angular){function ggPlayerEdit($scope){function onLoadedData(_data){angular.extend(vm,angular.fromJson(_data)),vm.player.country=vm.country}function save(){vm.error=!1,Utils.post("/ajax/players/save/",vm.player).then(function(id){0==parseInt(id)?vm.error=!0:PageLoader.go("/user/"+id)})}var vm=this;vm.error=!1,vm.save=save,function(){Utils.get("/ajax/players/"+("new"==window.url(2)?"0":window.url(2))+"/").then(onLoadedData)}()}angular.module("GG").controller("ggPlayerEdit",ggPlayerEdit),ggPlayerEdit.$inject=["$scope"]}(angular),function(){function ggEditOauth2($scope){function loadData(){Utils.get("/ajax/user/"+userId+"/oauth2/").then(onLoadData)}function onLoadData(data){data=angular.fromJson(data),angular.extend(vm,data),vm.loading=!1,$scope.$applyAsync()}var vm=this,userId=0;window.location.href.match(/.+user\/(\d+)\/oauth2\/?/gi)&&(userId=window.location.href.replace(/.+user\/(\d+)\/oauth2\/?/gi,"$1")),vm.loading=!0,function(){loadData()}()}angular.module("GG").controller("ggEditOauth2",ggEditOauth2)}(),function(){function ggEditProfile($scope){function setNewFile(file){vm.$imgFile=file}function onLoadData(data){data=angular.fromJson(data),angular.extend(vm,data),vm.user.country=parseInt(data.country),vm.user.city=parseInt(data.city,10),vm.rights={admin:UserService.checkAccess("SUPER_MODERATOR",data.rights)>0?1:0,moderator:UserService.checkAccess("MODERATOR",data.rights)>0?1:0,materials:UserService.checkAccess("MATERIALS",data.rights)>0?1:0,events:UserService.checkAccess("EVENTS",data.rights)>0?1:0,videos:UserService.checkAccess("FILES",data.rights)>0?1:0,streams:UserService.checkAccess("STREAMS",data.rights)>0?1:0},vm.loading=!1,$scope.$applyAsync()}function loadAvatarIconsBlock(){return Utils.get("/ajax/user/info/smiles/",{user:userId}).then(onLoadAvatarIconsBlock)}function onLoadAvatarIconsBlock(data){data=angular.fromJson(data),vm.smiles=data,vm.smilesLoaded=!0,$scope.$applyAsync()}function save(){if(0==vm.user.privacy.profile){if(!confirm("Вы уверены, что хотите удалить аккаунт?\r\nЭто действие нельзя обратить."))return!1;Utils.reachGoal("user_delete_account")}vm.loaded=!1,PageLoader.showLoader();var form=new FormData;form.append("user",userId);var userData=angular.copy(vm.user);userData.birthdayUTC&&(userData.birthdayUTC=+Utils.toUTCDate(userData.birthdayUTC)/1e3),form.append("data",angular.toJson(userData)),vm.$imgFile&&form.append("avatar",vm.$imgFile),vm.$imgFile2&&form.append("image",vm.$imgFile2),Utils.postForm("/ajax/user/"+userId+"/save/",form).fail(function(e){console.error(e)}).done(function(data){if(UserService.refreshUserObj(),data.result)PageLoader.go("/user/"+userId+"/");else{var msg="У вас проблемы с блоком "+data.msg+"\r\nПожалуйста, исправьте его";"avatar"==data.msg&&(msg="У вас проблемы с блоком Аватар\r\nПожалуйста, исправьте его. Минимальный размер изображения: 200px на 200px"),alert(msg)}})}function saveRights(){vm.loaded=!0,jQuery("#permissions-list-success").hide().stop(),setTimeout(function(){Utils.post("/ajax/user/"+userId+"/rights/",{rights:vm.rights}).then(function(data){vm.loading=!1,data=angular.fromJson(data);var selector="";selector=data.result?"#permissions-list-success":"#permissions-list-error",jQuery(selector).slideDown("slow").delay(4e3).slide
7Up("fast")})},10)}function changePassword(){return vm.admin||vm.oldPassword1?vm.newPassword1?vm.newPassword1!=vm.newPassword2?void(vm.passwordChangeError="Пароли не совпадают"):(vm.passwordChangeError="",void Utils.post("/ajax/user/"+userId+"/password/",{old:vm.oldPassword1,new:vm.newPassword1}).then(function(data){data=angular.fromJson(data),vm.passwordChangeError=data.result,$scope.$apply()})):void(vm.passwordChangeError="Введите новый пароль"):void(vm.passwordChangeError="Введите старый пароль")}function changeEmail(){return vm.admin||vm.oldPassword2?vm.newEmail?(vm.emailChangeError="",void Utils.post("/ajax/user/"+userId+"/email/",{old:vm.oldPassword2,new:vm.newEmail}).then(function(data){data=angular.fromJson(data),vm.emailChangeError=data.result,$scope.$apply()})):void(vm.emailChangeError="Введите новый email"):void(vm.emailChangeError="Введите старый пароль")}function deleteAvatar(){Utils.post("/ajax/user/"+userId+"/deleteAvatar/").then(function(data){data=angular.fromJson(data),data.result&&(vm.user.avatar=data.avatar,$scope.$apply())}).catch(function(e){console.error(e)})}function deleteImage(){Utils.post("/ajax/user/"+userId+"/deleteImage/").then(function(data){data=angular.fromJson(data),data.result&&(vm.user.image=data.image,$scope.$apply())}).catch(function(e){console.error(e)})}function changePhone(){vm.phoneError=0,Utils.post("/ajax/user/"+userId+"/phone/",{phone:vm.phone}).then(function(data){vm.phoneError=data.success?1:2}).error(function(){vm.phoneError=2})}function onClickIcon1(id,icon){vm.user.iconId=id,vm.user.icon=icon}var vm=this,userId=0;window.location.href.match(/.+user\/(\d+)\/oauth2\/?/gi)&&(userId=window.location.href.replace(/.+user\/(\d+)\/oauth2\/?/gi,"$1")),vm.loading=!0,vm.tab=5,vm.countries={},vm.phoneError=0,vm.titleAvatar="Аватар",vm.photoEditorOptions={aspectRatio:1,cropperMinWidth:200,cropperMinHeight:200,typeImg:"jpeg"},vm.smiles={},vm.smilesLoaded=!1,vm.save=save,vm.saveRights=saveRights,vm.changePassword=changePassword,vm.changeEmail=changeEmail,vm.changePhone=changePhone,vm.deleteAvatar=deleteAvatar,vm.deleteImage=deleteImage,vm.onClickIcon1=onClickIcon1,vm.setNewFile=setNewFile,function(){Utils.get("/ajax/user/"+userId+"/edit/").then(onLoadData).then(loadAvatarIconsBlock)}()}angular.module("GG").controller("ggEditProfile",ggEditProfile)}(),function(){function ggGameProfile($scope){$scope.list=$scope.vm,$scope.list.wallet=!1,$scope.list.getStage=function(stage){return"1/"+Math.ceil(Math.pow(2,stage-1))}}angular.module("GG").controller("ggGameProfile",ggGameProfile)}(),function(){function ggProfile($scope,$compile){function onLoadData(data){if(data=angular.fromJson(data),angular.extend(vm,data),vm.profiles)for(var key in vm.profiles){vm.selectedAccount=key;break}vm.singleAccount=1==Object.keys(vm.profiles).length,vm.loading=!1,$scope.$applyAsync()}function changeStatus(status){Utils.post("/ajax/user/"+userId+"/"+(status?"activate":"deactivate")+"/").then(function(){PageLoader.reload()})}function changeStatus2(status){status?vm.changeStatusOld(status):DeactivationPopup.open(userId,status,PageLoader.reload)}var vm=this,userId=0;window.location.href.match(/.+user\/(\d+)\/?/gi)&&(userId=window.location.href.replace(/.+user\/(\d+)\/?/gi,"$1")),vm.loading=!0,vm.changeStatusOld=changeStatus,vm.changeStatus=changeStatus2,vm.makeBan=function($event){return BanPopup.open(9,userId,$event.currentTarget)},function(){Utils.get("/ajax/user/"+userId+"/view/").then(onLoadData)}()}angular.module("GG").controller("ggProfile",ggProfile)}(),function(){function ggSearchPopup($scope){function loadResults(){search.loading=!0,Utils.get("/ajax/search/",{query:search.query}).then(function(data){search.results=angular.fromJson(data),search.loading=!1,$scope.$apply(),$(".search-popup").on("click","a:not(.more)",function(){PageLoader.onGo(function(){search.close()})})})}var search=this,NUMDOC_CONFIG={users:20};search.loading=!1,search.focusSearchInput=function(){function attemptFocus(){var searchElement=document.getElementById("search-results");searchElement?searchElement.focus():attemptCount<maxAttempts?(attemptCount++,setTimeout(attemptFocus,attemptInterval)):console.error("Could not focus search input: element not found after "+maxAttempts+" attempts")}var maxAttempts=5,attemptCount=0,attemptInterval=100;setTimeout(attemptFocus,0)}
7,search.close=function(event){event&&$(event.target).closest(".js-header-search").length>0||($(".js-header-search").removeClass("active"),SearchPopup.close(),$scope.$destroy())},search.clearSearch=function(){search.query="",search.focusSearchInput()},search.loadMore=function(row){row.loading=!0;var params={query:search.query,section:row.tab,offset:row.data.length},numdoc=NUMDOC_CONFIG[row.tab];numdoc&&(params.numdoc=numdoc),Utils.get("/ajax/search/",params).then(function(data){var ret=angular.fromJson(data);ret.data&&ret.data.length?row.data=row.data.concat(ret.data):row.total=row.data.length,row.loading=!1,$scope.$apply()})},$scope.$watch("search.query",function(){!search.query||search.query.length<=2||loadResults(search.query)});var params=new URLSearchParams(window.location.search),query=params.get("query");null!==query&&(search.query=query)}angular.module("GG").controller("ggSearchPopup",ggSearchPopup)}(),function(){function DateFunctions($filter){function toMysqlDate(date){return Utils.toMysqlDate(date)}function toRussianDate(date,time){var dateStr=Utils.withZero(date.getDate())+"."+Utils.withZero(date.getMonth()+1)+"."+date.getFullYear(),timeStr=Utils.withZero(date.getHours())+":"+Utils.withZero(date.getMinutes())+" ";return(time?timeStr:"")+dateStr}function formatDate(target){var current=Utils.getUserCurrentDate().getTime(),targetDate="string"==typeof target?Utils.moscowToLocalDate(Utils.parseMysqlDate(target)):target;if((targetDate=+targetDate+Utils.getUserTimezoneOffset())>current)return"number"==typeof targetDate&&(targetDate=new Date(targetDate)),targetDate.getFullYear()!=new Date(current).getFullYear()?$filter("date")(targetDate,"dd.MM.yyyy, HH:mm"):Math.round((new Date(targetDate).setHours(0,0,0)-new Date(current).setHours(0,0,0))/DAY)>1?$filter("date")(targetDate,"dd.MM, HH:mm"):targetDate-current>HOUR?(targetDate.getDay()==new Date(current).getDay()?"Сегодня в ":"Завтра в ")+targetDate.getHours()+":"+Utils.withZero(targetDate.getMinutes()):Utils.timeLeft(targetDate,current);if(current-targetDate<15e3)return"Только что";if(current-targetDate<MINUTE)return"Меньше минуты назад";if(current-targetDate<HOUR){var value=Math.round((current-targetDate)/MINUTE);return value+" "+["минуту","минуты","минут"][Utils.decl(value)]+" назад"}return new Date(targetDate).getFullYear()!=new Date(current).getFullYear()?$filter("date")(targetDate,"dd.MM.yyyy, HH:mm"):$filter("date")(targetDate,"dd.MM, HH:mm")}function getMaterialsDate(target){var diff=getDateDiff(Date.now(),target),current=Date.now(),targetDate=new Date(target),delta=Math.abs(diff.simple);if(diff.simple>0){var tomorrow=new Date;if(tomorrow.setDate(tomorrow.getDate()+1),tomorrow.setHours(23,59,59,59),delta>=HOUR&&delta<tomorrow-Date.now())return(targetDate.getDay()==(new Date).getDay()?"сегодня в ":"завтра в ")+Utils.withZero(targetDate.getHours())+":"+Utils.withZero(targetDate.getMinutes());if(delta<HOUR)return Utils.timeLeft(targetDate,current)}else{if(delta<15e3)return"Только что";if(delta<MINUTE)return"Меньше минуты назад";if(delta<HOUR){var value=Math.floor(delta/MINUTE);return value+" "+["минуту","минуты","минут"][Utils.decl(value)]+" назад"}if(delta<DAY/3){var value=Math.floor(delta/HOUR);return value+" "+["час","часа","часов"][Utils.decl(value)]+" назад"}var yesterday=new Date;if(yesterday.setDate(yesterday.getDate()-1),yesterday.setHours(0,0,0,0),delta<Date.now()-yesterday)return(targetDate.getDay()==(new Date).getDay()?"сегодня в ":"вчера в ")+Utils.withZero(targetDate.getHours())+":"+Utils.withZero(targetDate.getMinutes())}var str=[];return str.push(Utils.withZero(targetDate.getHours())+":"+Utils.withZero(targetDate.getMinutes())+","),str.push(targetDate.getDate()),str.push(MONTHES[targetDate.getMonth()]),targetDate.getFullYear()!==(new Date).getFullYear()&&str.push(targetDate.getFullYear()+"г."),str.join(" ")}function getBroadcastsDate(target){var diff=getDateDiff(Utils.getUserCurrentDate().setHours(0,0,0,0),target),targetDate=new Date(target),str=[];return diff.days<1?str.push("Сегодня,"):diff.days>=1&&diff.days<2?str.push("Завтра,"):str.push(DAY_OF_WEEK[targetDate.getDay()]+","),str.push(targetDate.getDate()),str.push(MONTHES[targetDate.getMonth()]),str.join(" ")}function getDateDiff(dateFrom,dateTo){var delta,result={};return result.simple=dateTo-dateFrom,delta=Math.abs(result.simple)/1e3,result.days=Math.floor(delta/86400),delta-=86400*result.days,result.hours=Math.floor(delta/3600)%24,delta-=3600*result.hours,result.minutes=Math.floor(delta/60)%60,delta-=60*result.minutes,result.seconds=Math.floor(delta%60),result}function getRemains(toDate){var diff=getDateDiff(Date.now(),toDate),str=[];return diff.days>0&&str.push(diff.days+" "+["день","дня","дней"][Utils.decl(diff.days)]),diff.hours>0&&str.push(diff.hours+" "+["час","часа","часов"][Utils.decl(diff.hours)]),diff.minutes>0&&str.push(diff.minutes+" "+["минута","минуты","минут"][Utils.decl(diff.minutes)]),diff.seconds>0&&str.push(diff.seconds+" "+["секунда","секунды","секунд"][Utils.decl(diff.seconds)]),str.join(" ")}var MINUTE=6e4,HOUR=60*MINUTE,DAY=24*HOUR,MONTHES=["января","февраля","марта","апреля","мая","июня","июля","августа","сентября","октября","ноября","декабря"],DAY_OF_WEEK=["Воскресенье","Понедельник","Вторник","Среда","Четверг","Пятница","Суббота"];this.formatDate=formatDate,this.toMysqlDate=toMysqlDate,this.toRussianDate=toRussianDate,this.getDateDiff=getDateDiff,this.getRemains=getRemains,this.getMaterialsDate=getMaterialsDate,this.getBroadcastsDate=getBroadcastsDate}angular.module("GG").service("DateFunctions",DateFunctions),DateFunctions.$inject=["$filter"]}(),angular.module("GG").factory("$debounce",["$rootScope","$browser","$q","$exceptionHandler",function($rootScope,$browser,$q,$exceptionHandler){function debounce(fn,delay,invokeApply){var timeoutId,cleanup,methodId,deferred=$q.defer(),promise=deferred.promise,skipApply=angular.isDefined(invokeApply)&&!invokeApply,bouncing=!1;angular.forEach(methods,function(value,key){angular.equals(methods[key].fn,fn)&&(bouncing=!0,methodId=key)}),bouncing?(deferreds[methods[methodId].timeoutId]&&deferreds[methods[methodId].timeoutId].reject("bounced"),$browser.defer.cancel(methods[methodId].timeoutId)):(methodId=uuid++,methods[methodId]={fn:fn});var debounced=function(){delete methods[methodId];try{deferred.resolve(fn())}catch(e){deferred.reject(e),$exceptionHandler(e)}skipApply||$rootScope.$apply()};return timeoutId=$browser.defer(debounced,delay),methods[methodId].timeoutId=timeoutId,cleanup=function(reason){delete deferreds[promise.$$timeoutId]},promise.$$timeoutId=timeoutId,deferreds[timeoutId]=deferred,promise.then(cleanup,cleanup),promise}var deferreds={},methods={},uuid=0;return debounce.cancel=function(promise){return!!(promise&&promise.$$timeoutId in deferreds)&&(deferreds[promise.$$timeoutId].reject("canceled"),$browser.defer.cancel(promise.$$timeoutId))},debounce}]),function(){function Service($rootScope){function add(popup){popups.push(popup)}function remove(id){close(id);var found=_findPopup(popups,{id:id});popups.splice(found.index,1)}function open(id){var found=_findPopup(popups,{id:id});found.popup.isOpen||(found.popup.open(),closeOthers(id),$rootScope.$broadcast("popup.open",id))}function close(id){var found=_findPopup(popups,{id:id});found&&found.popup.isOpen&&(found.popup.close(),$rootScope.$broadcast("popup.close",id))}function closeOthers(id){popups.forEach(function(popup){popup.id!==id&&close(popup.id)})}function _findPopup(popups,params){var result;return popups.forEach(function(popup,index){if(popup.id===params.id)return result={index:index,popup:popup},!1}),result}var popups=[],service={};return service.add=add,service.remove=remove,service.open=open,service.close=close,service.closeOthers=closeOthers,service}angular.module("GG").factory("PopupService",Service)}(),function(){angular.module("GG").factory("Reklama",function($rootScope){return $rootScope.Reklama=new Reklama})}(),function(){function UserOnlineService(){var _this25=this;this.elements=[],this.users=[];var watchTimer;this.watch=function(elem,userObj){if(-1!=this.elements.indexOf(elem))return!1;this.elements.push(elem),this.users.push(userObj),this.forceGetOnline()},this.unwatch=function(elem){var idx=this.elements.indexOf(elem);if(-1==idx)return!1;this.elements.splice(idx,1),this.users.splice(idx,1)},this.update=function(elem,userObj){var idx=this.elements.indexOf(elem);if(-1==idx)return this.watch(elem,userObj);userObj.online=this.users[idx].online,this.users[idx]=userObj,this.forceGetOnline()},this.forceGetOnline=function(){var _this23=this;watchTimer&&clearTimeout(watchTimer),watchTimer=setTimeout(function(){return _this23.getOnline()},100)},this.getOnline=function(){var _this24=this,users=[];
7this.users.forEach(function(userObj){var userId=parseInt(userObj.obj_key.split(":")[1]);-1==users.indexOf(userId)&&users.push(userId)}),users.length&&NotifyProxy.ready()&&NotifyProxy.ask("getOnline",{users:users}).then(function(data){if(data){for(var i=0;i<users.length;i++)data[i]?users[i]="9:"+users[i]:users[i]=!1;_this24.users.forEach(function(userObj){return userObj.online=-1!=users.indexOf(userObj.obj_key)})}})},this.getOnline(),setInterval(function(){return _this25.getOnline()},3e4)}angular.module("GG").service("UserOnlineService",UserOnlineService),UserOnlineService.$inject=[]}(),function(){function ggChannelAudience($scope,DateFunctions){function loadData(){setTimeout(function(){audience._loadStarted&&(audience.loading=!0,$scope.$applyAsync())},500),audience._loadStarted=!0,Utils.get("/ajax/channel/audience/",{channel:$scope.vm.channel,range:audience.range,rangeFrom:Utils.toUTCDate(Utils.toUserTimezoneDate(audience.rangeFrom)).toISOString(),rangeTo:Utils.toUTCDate(Utils.toUserTimezoneDate(audience.rangeTo)).toISOString()}).then(onLoad)}function onLoad(data){data=angular.fromJson(data),audience.data=data,audience.loading=!1,audience._loadStarted=!1,audience.rangeStr=["сегодня","неделю",data.currentMonth,data.lastMonth,"промежуток"][audience.range-1],"undefined"!=typeof d3&&createGraph(data.metrics),$scope.$applyAsync()}function formatDate(timestamp){var date=Utils.moscowTime(1e3*timestamp);return DateFunctions.formatDate(date)}function parseMetrics(data){var lines=[],i=0,lastTime=0;return data.forEach(function(d){lastTime||(lastTime=d.time-96e4),d.time-lastTime>96e4&&i++,lines[i]||(lines[i]=[]),lines[i].push(d),lastTime=d.time}),lines}function getLimits(data){var yLimits={};return data.forEach(function(d){d.time=Utils.toUserTimezoneDate(1e3*d.time),d.value=parseInt(d.viewers),yLimits.max=yLimits.max?Math.max(yLimits.max,d.value):d.value,yLimits.min=yLimits.min?Math.min(yLimits.min,d.value):d.value}),yLimits.min=.8*yLimits.min,yLimits}function buildTimeline(lines){var timeLine=[];return lines.forEach(function(line){line.forEach(function(dot){dot.point=timeLine.length,timeLine.push(dot.time)}),timeLine.push(0)}),timeLine}function createGraph(data){var vis=d3.select("#visualisation");vis.selectAll("*").remove();var yLimits=getLimits(data),lines=parseMetrics(data);d3.select(".tooltip.tip").remove();var tooltip=d3.select(".audience-graph").append("div").attr("class","tooltip tip").style("opacity",0),timeLine=buildTimeline(lines),xScale=d3.scaleLinear().range([20,WIDTH-20]).domain([0,timeLine.length-2]),yScale=d3.scaleLinear().range([HEIGHT-20,20]).domain([yLimits.min,yLimits.max]),xAxis=d3.axisBottom(xScale);vis.append("svg:g").attr("class","axis").attr("transform","translate(0,"+(HEIGHT-20)+")").call(xAxis.ticks(20).tickFormat(function(d){return timeLine[d]?d3.timeFormat("%H:%M")(timeLine[d]):""}));var lineGen=d3.line().x(function(d){return xScale(d.point)}).y(function(d){return yScale(d.value)}).curve(d3.curveCardinal.tension(.8));lines.forEach(function(line){vis.append("svg:path").attr("d",lineGen(line)).attr("stroke","#73adff").attr("stroke-width",2).attr("fill","none")}),vis.selectAll(".dot").data(data).enter().append("circle").attr("class","dot").attr("r",5).attr("stroke","#233056").attr("stroke-width",3).attr("cx",function(d){return xScale(d.point)}).attr("cy",function(d){return yScale(d.value)}).on("mouseenter",function(d){d3.select(this).transition().duration(350).ease(d3.easeBounceOut).attr("r",7).attr("stroke-width",4),tooltip.transition().duration(100).style("opacity",1);var elem=d3.event.toElement||d3.event.target,pos=$(elem).position(),parentPos=graphBlock.position();tooltip.html("").style("left",pos.left-parentPos.left+24+"px").style("top",pos.top-parentPos.top+120+"px"),tooltip.append("div").attr("class","date").html(d3.timeFormat("%H:%M")(d.time)),tooltip.append("div").attr("class","value").html(d.value)}).on("mouseleave",function(d){d3.select(this).transition().duration(350).ease(d3.easeBounceOut).attr("r",5).attr("stroke-width",3),tooltip.transition().duration(10).style("opacity",0)})}var WIDTH,HEIGHT,graphBlock=$("#visualisation"),audience=this;
7audience.loading=!0,audience.range=1,audience.rangeFrom=new Date,audience.rangeTo=new Date,audience.formatDate=formatDate,ResourceLoader.loadJs("/js/libraries/d3.v4.min.js").then(function(){WIDTH=graphBlock.width(),HEIGHT=graphBlock.height(),audience.data&&createGraph(audience.data.metrics)}),$scope.$watch("audience.range",function(){audience.range&&loadData()}),$scope.$watch("audience.rangeFrom + audience.rangeTo",function(a,b){a!=b&&(audience.range=5,loadData())})}angular.module("GG").controller("ggChannelAudience",ggChannelAudience)}(),function(){function ggChannelInfo($scope,$rootScope,StreamService,$attrs){function showPlayerMenu(){vm.playerMenu=!vm.playerMenu,vm.showBlacklist=!1,vm.showShare=!1,vm.showReport=!1}function fullSize(){var wrapper=$("#entire-wrapper");wrapper.on("mousemove",Utils.debounce(dashElementHover,500)),wrapper.hover(function(){dashElement.addClass("hover"),timer&&clearTimeout(timer),timer=setTimeout(function(){dashElement.removeClass("hover")},2e3)},function(){$(".dash-element.full-size").removeClass("hover")})}function dashElementHover(){timer&&clearTimeout(timer),dashElement.addClass("hover"),timer=setTimeout(function(){dashElement.removeClass("hover")},2e3)}function isLogged(){return UserService&&!!UserService.id}function iframePaste(){return'<iframe frameborder="0" allowfullscreen width="800" height="450"  src="https://goodgame.ru/player?'+vm.pid+'"></iframe>'}function showReportBlock(){console.log("showReportBlock",vm.showReport),vm.showReport=!vm.showReport,vm.showBlacklist=!1,vm.playerMenu=!1,vm.showShare=!1}function showShareBlock(){vm.showShare=!vm.showShare;var test=document.querySelector(".textarea.paste-block");!function(el){var range=document.createRange();range.selectNodeContents(el);var selection=window.getSelection();selection.removeAllRanges(),selection.addRange(range)}(test),vm.showReport=!1,vm.showBlacklist=!1,vm.playerMenu=!1}function showBlackListBlock(){vm.showBlacklist=!vm.showBlacklist,vm.showShare=!1,vm.playerMenu=!1,vm.showReport=!1}function addToBlacklist(){sendBlacklist(),vm.blacklist=1}function remove(){sendBlacklist("unban"),vm.blacklist=0}function hideAll(){vm.playerMenu=!1,vm.showReport=!1,vm.showShare=!1,vm.showBlacklist=!1}function sendBlacklist(action){vm.showBlacklist=!1,Utils.post("/ajax/moderation/stream-to-blacklist/",{id:vm.id,action:action})}function sendReport(){vm.showReport=!1,Utils.post("/ajax/make-claim/",{claim_msg:vm.reportText,type:vm.type,id:vm.id}).then(function(data){data=angular.fromJson(data),data&&data.msg&&alert(data.msg),vm.reportText="",$scope.$apply()})}function setGame(game){vm.gameTitle=game.title,vm.setGameId=game.id}function saveTitle(data){return vm.titleLoading=!0,vm.setGameId=data.game.gameId||vm.setGameId,window.DEV,Utils.get("/ajax/channel/get-title/",{objType:vm.type,objId:vm.id,title:data.title||vm.setTitle,gameId:data.game.gameId||vm.setGameId}).then(function(data){data=angular.fromJson(data),vm.titleLoading=!1,vm.editTitle=!1,vm.gameTitle=data.game,vm.channelTitle=data.title,vm.gameUrl=data.gameUrl,vm.backupGameTitle=vm.gameTitle,$scope.$apply()}),!1}function changeStatus(status){if(status>0||confirm("Вы уверены, что хотите забанить канал?")){var url="/ajax/moderation/"+(status>0?"publish":"unpublish")+"/";Utils.post(url,{key:vm.type+"-"+vm.id}).then(function(){PageLoader.reload()})}}function changeStatus2(status){status>0?vm.changeStatusOld(status):DeactivationChannelPopup.open(vm.type+"-"+vm.id,status,PageLoader.reload)}function resizeReset(){var left=document.querySelector(".main-inner-wrap"),right=document.querySelector(".feed-block"),chatBlock=document.querySelector(".chat .chat-container");!$rootScope.theatre&&left&&right&&chatBlock&&(left.style.right="",right.style.width="",chatBlock.style.width="",right.style.width="",right.classList.remove("closed"),right.classList.remove("close"))}function toggleTheatreMode(){StreamService.detachPlayerFromFeed(),$rootScope.theatre=!$rootScope.theatre,hideAll(),resizeReset(),Utils.reachGoal("stream_theater_mode_on")}function changeTitle(){vm.editTitle=!vm.editTitle,vm.backupGameTitle=vm.gameTitle}function cancelTitle(){vm.gameTitle=vm.backupGameTitle,vm.editTitle=!1}var vm=this;vm.init=function(){var obj=channelTopInfo;vm.blacklist="1"==obj.blacklist?1:0,vm.adult="1"==obj.adult?1:0,vm.type=7,vm.id=obj.channel.i
7d,vm.pid=obj.pid,vm.channelTitle=obj.channel.title,vm.setTitle=obj.channel.title,vm.gameTitle=obj.gameTitle,vm.setGameId=obj.gameId,vm.backupGameTitle=vm.gameTitle,vm.streamer={online:0,obj_key:"9:"+obj.streamer},vm.iframePaste=iframePaste();var keyupHandler=function(e){e.altKey&&84==e.keyCode&&(toggleTheatreMode(),$scope.$apply())};$(window).on("keyup",keyupHandler),$scope.$on("$destroy",function(){return $(window).off("keyup",keyupHandler)}),fullSize()},vm.addToBlacklist=addToBlacklist,vm.remove=remove,vm.sendReport=sendReport,vm.saveTitle=saveTitle,vm.setGame=setGame,vm.isLogged=isLogged,vm.showReportBlock=showReportBlock,vm.showShareBlock=showShareBlock,vm.showPlayerMenu=showPlayerMenu,vm.showBlackListBlock=showBlackListBlock,vm.hideAll=hideAll,vm.changeStatus=changeStatus2,vm.changeStatusOld=changeStatus,vm.toggleTheatreMode=toggleTheatreMode,vm.changeTitle=changeTitle,vm.cancelTitle=cancelTitle,$rootScope.$watch("theatre",function(newValue,oldValue){if(newValue!==oldValue){var player_size=$("#player-feed-root").width();newValue||0!==player_size||resizeReset()}});var timer=void 0,dashElement=$(".dash-element.full-size")}angular.module("GG").controller("ggChannelInfo",["$scope","$rootScope","StreamService","$attrs",ggChannelInfo])}(),function(){function ggChannelSettings($scope,$attrs,$window){function checkDirty(item,itemOld){if(item&&item.key&&!itemOld)return!0;if(!item.key&&itemOld)return!0;if(item&&itemOld){var clear=!0;for(var key in item)item.hasOwnProperty(key)&&0!=key.indexOf("$")&&item[key]!==itemOld[key]&&(clear=!1);return!clear}}function checkValid(item){var isValid=!0;for(var key in item)if(item.hasOwnProperty(key)&&0!=key.indexOf("$")){var validator=validators[key];validator&&!validator(item[key])&&(isValid=!1)}return isValid}function removePlayer(player){vm.isPlayedDisabled(player)||(vm.data.players.splice(vm.data.players.indexOf(player),1),player.id&&deletedPlayers.push(player.id))}function isPlayedDisabled(player){return!vm.data.isAdmin&&player.id&&-1!=[1,2,11].indexOf(player.server)}function reload(){vm.data=angular.copy(_data)}function save(){if(!checkFields())return!1;vm.data.deleted=deletedPlayers,vm.data.loading=!0;var form=new FormData;form.append("channel",$attrs.channel||"new"),form.append("data",angular.toJson(vm.data)),vm.$imgFile&&form.append("logo",vm.$imgFile),window.reader&&window.reader.configure(vm.data.voiceSettings),Utils.postForm("/ajax/channel/settings/",form).fail(function(e){console.error(e)}).done(onLoad)}function onLoad(raw){var data=angular.fromJson(raw);if($attrs.channel){_data=angular.copy(data),vm.data&&(vm.saved=!0),vm.data=data,-1!=["maxim","tatyana"].indexOf(vm.data.voiceSettings.voice)&&(vm.data.voiceSettings.voice="alena"),vm.data.adult_data=angular.fromJson(vm.data.adult_data);try{vm.data.adult_data.can_edit=vm.data.isAdmin||vm.data.adult_data.date<+new Date/1e3||0==vm.data.hidden}catch(exc){vm.data.adult_data.can_edit=vm.data.isAdmin||0==vm.data.hidden}vm.$imgFile=!1,vm.$imgFile2=!1,vm.data.voiceSettings.voiceMessageAmount||(vm.data.voiceSettings.voiceMessageAmount=300),!1!==vm.data.voiceSettings.teleport&&(vm.data.voiceSettings.teleport=!0),$scope.$apply()}else Utils.reachGoal("user_create_channel"),PageLoader.go("/channel/"+raw.key)}
8function generateNewKey(){var oldValue=vm.data.stream_key,playerKey=oldValue.substring(0,oldValue.indexOf("?")),newKey=Math.random().toString(36).substring(2,18);vm.showKey=!0,vm.data.stream_key=playerKey+"?pwd="+newKey,Utils.post(AJAX_PATH+"/channel/save-new-key/",{id:$attrs.channel,key:newKey})}function checkFields(){return""!=vm.data.title}function checkVoice(){var tmpConfig=window.reader.config;window.reader.configure(vm.data.voiceSettings),window.reader.say({text:"Это проверка голосового сообщения"}),window.reader.configure(tmpConfig)}function checkYoutube(){vm.errors.youtube=!1,vm.data.youtube?Utils.get("/ajax/channel/youtube/login/").then(function(callback){$window.open(callback,"youtube_connect","width=780,height=500,location=0,menubar=0,resizable=1,status=0")}):Utils.get("/ajax/channel/youtube/logout/").then(function(callback){callback=angular.fromJson(callback),callback.error&&(vm.errors.youtube=!0,angular.element("#youtube-errors").html("Что-то пошло Ð
8½Ðµ так! Попробуйт еще раз позже"))})}function deleteImg(){console.log("deleteImg"),vm.$imgFile=!1,vm.$imgFile2=!1}function setGame(game){vm.data.game_id=game.id,vm.data.game=game.title}var _data,vm=this,deletedPlayers=[],validators={title:function(val){return val&&val.length>0}};vm.removePlayer=removePlayer,vm.isPlayedDisabled=isPlayedDisabled,vm.generateNewKey=generateNewKey,vm.save=save,vm.reload=reload,vm.checkVoice=checkVoice,vm.checkYoutube=checkYoutube,vm.setGame=setGame,vm.deleteImg=deleteImg,vm.errors={youtube:!1},function(){parseInt($attrs.channel)&&Utils.get("/ajax/channel/settings/",{channel:$attrs.channel}).then(onLoad)}(),$scope.$watch("vm.data.players",function(){vm.data&&vm.data.players&&vm.data.players.length&&vm.data.players[vm.data.players.length-1].key&&vm.data.players.push({})},!0),$scope.$watch("vm.data",function(){var dirty=!1;if(vm.data&&_data){for(var key in vm.data)vm.data.hasOwnProperty(key)&&-1==["players","voiceSettings"].indexOf(key)&&vm.data[key]!=_data[key]&&(dirty=!0);if(!dirty&&vm.data.players&&_data.players&&vm.data.players.forEach(function(item,i){dirty||(dirty=checkDirty(vm.data.players[i],_data.players[i]))}),!dirty&&vm.data.voiceSettings&&_data.voiceSettings)for(var key in vm.data.voiceSettings)vm.data.voiceSettings.hasOwnProperty(key)&&vm.data.voiceSettings[key]!=_data.voiceSettings[key]&&(dirty=!0);vm.isValid=checkValid(vm.data),vm.dirty=dirty}},!0)}angular.module("GG").controller("ggChannelSettings",ggChannelSettings)}(),function(){function ggStreamControlPanel($scope,$attrs,$interval,RestreamService,RecordService,HlsService){function onMoneyEvent(data){data.events&&(control.events=data.events,control.events.forEach(function(event){return event.status=event.status||"stop"}),readEvents())}function onLoad(data){control.loaded=!0,data=angular.fromJson(data),angular.extend(control,data),control.events.length&&(_lastEvent=control.events[0].date,control.events.forEach(function(event){return event.status=event.status||"stop"})),reader=new GoogleBaba(control.voiceSettings),window.reader=reader,readEvents()}function updateVoiceSettings(settings){if(control.voiceSettings=settings,!settings.premium){var ifCurrentEvent=control.events.find(function(e){return"playing"===e.status});ifCurrentEvent&&control.stop(ifCurrentEvent)}}function saveRestreams(){return control.block=!1,RestreamService.save(control.channel,control.restream)}function startRestream(){return control.restream.enabled=!0,RestreamService.save(control.channel,control.restream)}function stopRestream(){return control.restream.enabled=!1,RestreamService.save(control.channel,control.restream)}function readEvents(){control.events.forEach(function(event){var key=event.date;key>_lastEvent&&(readEvent(event),_lastEvent=key)})}function stopEvent(event){window.reader.abort(event)}function readEvent(event,force){window.DEV;var text="";if(force=!!force,2==event.source&&(control.voiceSettings.premium||force)){var payment=0,resubs=0,qty=0,data=void 0;try{data=JSON.parse(event.data)}catch(e){return!1}data.gift?qty=data.qty:(payment=data.payment,resubs=data.resubs),0==payment&&(text=event.username+" активировал премиум на ваш канал"),1==payment&&(text=event.username+" ",text+=1==resubs?"подписался на премиум":"переподписан "+resubs+" "+["месяц","месяца","месяцев"][Utils.decl(resubs)]),2==payment&&(text=event.username+" ",text+=1==resubs?"активировал премиум":"активирует премиум "+resubs+" "+["месяц","месяца","месяцев"][Utils.decl(resubs)]),qty&&(text=(0===event.creator?"Неизвестный":event.username)+" ",text+="подарил "+qty+["примиум","примиума","примиумов"][Utils.decl(qty)])}var username="неизвестного";(event.creator||event.username)&&(username=(event.creator?"":"Некто, представившийся как ")+event.username);var amount=0;amount=event.with_commission>0?parseInt(event.amount_user,10):parseInt(event.amount,10);if(1==event.source&&(force||control.voiceSettings.donat&&amount>=control.voiceSettings.amount)){var amountText=amount+" р. ",today=new Date,year=(new Date).getFullYear();today>new Date(year+"-04-01")&&today<new Date(year+"-04-02")?(amountText=FoolsDay.convertValue(amount,!0),text=amountText+" от "+username+" sil <[500]>"):text=amount+["рубль","рубля","рублей"][Utils.decl(amount)]+" от "+username+" sil <[500]>",event.message&&(text+=event.message),event.voiceId&&(force||control.voiceSettings.voiceMessage&&amount>=control.voiceSettings.voiceMessageAmount)?(text+=" с голосовым сообщением",event.voicePlayed=!1):event.voicePlayed=!0}else 11==event.source&&(force||control.voiceSettings.teleport&&event.userCounts>3)&&(text=event.message||event.username+" успешно телепортировал к вам "+["зритель","зрителя","зрителей"][Utils.decl(event.userCounts)]+" !");event.text=text,text&&window.reader.say(event)}function startCommercial(){0!=$attrs.channelPwd&&(control.commercialInterval&&($interval.cancel(control.commercialInterval),control.commercialTimer=0,control.commercialTimerAsText="Таймер: 00:00"),window.ggplayer.startCommercial($attrs.channelKe
8y,$attrs.channelPwd),control.commercialInterval=$interval(function(){control.commercialTimer++;var mins=Math.floor(control.commercialTimer/60),secs=control.commercialTimer-60*mins;mins<10&&(mins="0"+mins),secs<10&&(secs="0"+secs),control.commercialTimerAsText="Таймер: "+mins+":"+secs},1e3))}var control=this;control.loaded=!1,control.channel=$attrs.channel,control.channelKey=$attrs.channelKey,control.block=!1,control.saveRestreams=saveRestreams,control.restreamsServices=RestreamService.services,control.startRestream=startRestream,control.stopRestream=stopRestream,control.startCommercial=startCommercial,control.commercialInterval=!1,control.commercialTimer=0,control.commercialTimerAsText="Таймер: 00:00",control.record=RecordService,RecordService.channelKey=$attrs.channelKey,RecordService.startTimer(),control.hls=HlsService,HlsService.timerStart(),control.say=function(event){return readEvent(event,!0)},control.stop=function(event){return stopEvent(event)},control.updateVoiceSettings=updateVoiceSettings;var reader,_lastEvent=0;NotifyProxy.subscribe("private:7:"+control.channel),NotifyProxy.on("object_event",onMoneyEvent),$scope.$on("$destroy",function(){RecordService.stopTimer(),NotifyProxy.unsubscribe("private:7:"+control.channel),NotifyProxy.off("object_event",onMoneyEvent),HlsService.timerStop(),reader=!1,window.reader=!1}),function(){Utils.get("/ajax/channel/control-panel/",{id:control.channel}).then(function(data){return HlsService.load(control.channelKey),data}).then(onLoad)}()}angular.module("GG").controller("ggStreamControlPanel",ggStreamControlPanel)}(),function(){function ggDescriptionEditor($scope,$attrs,$timeout,$rootScope,gg4DashboardService){function checkDirty(block,blockOld){if(block&&blockOld){var clear=!0,isValid=!0;allFields.forEach(function(p){var validator=validators[p];block[p]!==blockOld[p]&&(clear=!1),validator&&!validator(block[p])&&(isValid=!1)}),clear||(block.dirty=!0),block.isValid=isValid}}function toggleEditMode($event){if($event&&($event.preventDefault(),$event.stopPropagation(),1!=vm.tab&&(vm.tab=1,vm.editMode=0)),!vm.editMode)return vm.editMode=1,vm.loading=!0,loadDataForEditor();vm.editMode=0,reloadDescription()}function setTab(tab){vm.tab=tab}function loadDataForEditor(){return Utils.get("/ajax/channel/description/",{channel:vm.channel,editor:1}).then(function(data){data=angular.fromJson(data),vm.loading=!1,vm.blocks=data.blocks,vm.currentGame=data.currentGame||!1,vm.blocks.forEach(function(item){item.date=!!item.date&&new Date(1e3*item.date)}),$scope.$apply()})}function reloadDescription(){vm.loading=!0,Utils.get("/ajax/channel/description/",{channel:vm.channel,editor:0}).then(function(data){data=angular.fromJson(data),vm.loading=!1,vm.editMode=0,Utils.compileBlock($("#channel-description").html(data.html)),$scope.$apply()})}function deleteBlock(block){if(block.loading=!0,!block.id)return void vm.blocks.splice(vm.blocks.indexOf(block),1);Utils.post("/ajax/channel/save-description/",block).then(function(){vm.blocks.splice(vm.blocks.indexOf(block),1),$scope.$apply()})}function addBlock(date){if(!vm.editMode)return void toggleEditMode().then(function(){addBlock(date)});var block={sort:vm.blocks.length+1,date:date,status:1};vm.currentGame&&(block.game=vm.currentGame.id,block.gameTitle=vm.currentGame.title),vm.blocks.push(block),setTimeout(function(){return gg4DashboardService.addBlock$.next(date)},400)}function deleteImg(block){block.$imgFile="delete",block.image=!1,block.dirty=!0}function saveBlock(block){block.id||(block.objId=vm.channel,block.objType=7),block.loading=!0;var data=new FormData;allFields.forEach(function(v){data.append(v,block[v]||"")}),block.date&&(block.date.setSeconds&&block.date.setSeconds(0),data.append("date",+Utils.toUTCDate(block.date)/1e3)),fetch("/ajax/channel/save-description/",{method:"POST",body:data}).then(function(response){if(!response.ok)throw new Error("Network response was not ok");return response.json()}).then(function(data){block.id||(block.id=data.id),block.loading=!1,block.dirty=!1,$scope.$apply()}).catch(function(e){alert("Ошибка"),console.error(e)})}var vm=this,allFields=["id","objType","objId","sort","title","date","game","link","description","status","$imgFile"],validators={};vm.channel=$attrs.channel,vm.blocks=[],vm.editMode=0,vm.tab=$attrs.tab||1,vm.currentGame=!1,vm.user=$rootScope.User.id,$scope.$watch("vm.tab",function(newValue,oldValue){1===newValue&&vm.editMode&&$timeout(function(){$(".panel-list").length})}),vm.addBlock=addBlock,vm.saveBlock=saveBlock,vm.deleteBlock=deleteBlock,vm.deleteImg=deleteImg,vm.toggleEditMode=toggleEditMode,vm.setTab=setTab,document.addEventListener("DOMContentLoaded",function(event){if($rootScope.isMobile){var chat=(document.querySelector("body").clientHeight,document.querySelector(".tab-pane .chat-wrap"));document.querySelector(".channel-wrap .player-container").clientHeight;chat.setAttribute("data-platform",navigator.platform),console.log(chat)}}),$scope.$watch("vm.blocks",function(newValue,oldValue){window.DEV&&
8console.log("vm.blocks",newValue,oldValue),newValue&&oldValue&&(newValue.forEach(function(elem,index){checkDirty(newValue[index],oldValue[index])}),$rootScope.isMobile?vm.tab=4:vm.tab=1)},!0)}angular.module("GG").controller("ggDescriptionEditor",ggDescriptionEditor),ggDescriptionEditor.$inject=["$scope","$attrs","$timeout","$rootScope","gg4DashboardService"]}(),function(){function ggDonatPopup($scope,$attrs){vm=this,vm.$scope=$scope,vm.payments=parseInt($attrs.payments,10),vm.provider=Utils.lsGet("remember_donat_provider","0"),vm.objId=$attrs.objId,vm.objType=$attrs.objType,vm.amount=100,vm.user=$attrs.user,vm.streamer=$attrs.streamer,vm.left=parseInt($attrs.left,10),vm.next=$attrs.next,vm.step=1,vm.topDonation=$attrs.top||1e4,vm.donationError=!1,vm.animate=animateProgress,vm.handleProgressClick=handleProgressClick,vm.int=function(val){return Math.max(parseInt(val,10),0)||0},vm.check=function(){return vm.amount>0&&0!=vm.provider&&!(6==vm.provider&&vm.streamer)},vm.donate=makeDonat,vm.openPopup=openPopup,vm.close=close,vm._istest="?alfa-test"==window.location.search,vm.confirm=confirmPayment,vm.reject=rejectPayment,vm.getPaypalCommission=function(){return Math.min(Math.ceil(.06*vm.amount+2),vm.amount)},window.donatPopupCallback=externalCallback,vm.payments&&animateProgress(0,vm.payments)}function close(){$(".subscribe-popup").fadeOut(300,function(){this.remove()})}function confirmPayment(){var pid=vm.paymentId;vm.paymentId=0,$.ajax({type:"POST",url:"/payments/gg_process/",data:{pid:pid,code:vm.paymentCode},dataType:"json"}).fail(function(){externalCallback(!1)}).done(function(data){externalCallback(data.success)})}function rejectPayment(){externalCallback(!1)}function makeDonat(){vm.donationError=!1;var objId=vm.objId,objType=vm.objType,provider=vm.provider,amount=vm.amount,email=vm.email||"",comment=vm.amount>=30?vm.message:"",is_anonymous=vm.anon?1:0;if(Utils.lsSet("remember_donat_provider",provider),vm.amount<1)return void(vm.donationError=!0);8==provider&&vm._istest&&(provider=10),vm._link="/payments/save/?provider="+provider+"&objType="+objType+"&objId="+objId+"&email="+email+"&amount="+amount+"&is_anonymous="+is_anonymous+"&comment="+encodeURIComponent(comment||""),6==provider||7==provider?(vm._link+="&json=1",vm.internal=1,makePayment()):(vm.internal=0,_linkTimeout=setTimeout(function(){openPopup()},2e3)),vm.step=2}function makePayment(){vm.paymentId=0,vm.paymentCode=0;var link=vm._link;$.ajax({type:"GET",url:link,dataType:"json"}).fail(function(){externalCallback(!1)}).done(function(data){data.link&&-1!=data.link.indexOf("xsolla_continue")||(vm.paymentTitle=data.title,vm.paymentAmount=data.amount,vm.paymentCode=data.code,vm.paymentId=data.id),vm.$scope.$applyAsync()})}function openPopup(){var link=vm._link,_new=window.open(link,"_blank","width=810,height=610,toolbar=no,scrollbars=yes,resizable=yes"),pollTimer=setInterval(function(){if(!_new)return void clearInterval(pollTimer);!1!==_new.closed&&(clearInterval(pollTimer),externalCallback(!1))},200)}function externalCallback(success){if(vm._link){if(vm.step=3,vm.success=success,success)try{Utils.reachGoal("DONAT")}catch(e){}vm._link=!1,vm.$scope.$applyAsync()}}function handleProgressClick(amount){amount>=vm.payments&&(animateProgress(vm.amount,amount),vm.amount=amount-vm.payments)}function animateProgress(from,to){var _value=parseInt(from),delta=(to-_value)/50;animateInterval&&clearInterval(animateInterval),animateInterval=setInterval(function(){_value+=delta,delta>0&&_value>=to||delta<0&&_value<=to?(clearInterval(animateInterval),setProgress(parseInt(to))):setProgress(_value)},10)}function setProgress(value){value=parseInt(value),value<100?(_setStepValue(0,value),_setStepValue(1,0),_setStepValue(2,0),_setStepValue(3,0),_setStepValue(4,0)):value<300?(_setStepValue(0,100),_setStepValue(1,Math.floor(100*(value-100)/200)),_setStepValue(2,0),_setStepValue(3,0),_setStepValue(4,0)):value<500?(_setStepValue(0,100),_setStepValue(1,100),_setStepValue(2,Math.floor(100*(value-300)/200)),_setStepValue(3,0),_setStepValue(4,0)):value<3e3?(_setStepValue(0,100),_setStepValue(1,100),_setStepValue(2,100),_setStepValue(3,Math.floor(100*(value-500)/2500)),_setStepValue(4,0)):value<1e4?(_setStepValue(0,100),_setStepValue(1,100),_setStepValue(2,100),_setStepValue(3,100),_setStepValue(4,Math.floor(100*(value-3e3)/7e3))):(_setStepValue(0,100),_setStepValue(1,100),_setStepValue(2,100),_setStepValue(3,100),_setStepValue(4,100))}function _setStepValue(step,prc){var el=$(".subscribe-popup").find(".progress").eq(step);el.find(".progress-grad1").attr("offset",prc+"%"),el.find(".progress-grad2").attr("offset",prc+"%"),el.toggleClass("complete",prc>=100)}angular.module("GG").controller("ggDonatPopup",ggDonatPopup);var vm,animateInterval,_linkTimeout}(),function(){function ggChannelFinance($scope,DateFunctions){function loadData(){if(finance.rangeFrom&&finance.rangeTo){finance.loading=!0;var rangeFrom=finance.rangeFrom,rangeTo=finance.rangeTo;rangeFrom.setHours(0,0,0,0),rangeTo.setHours(23,59,59,999),Utils.get(finance.channel?"/ajax/channel/finance/":"/ajax/channel/finance-admin/",{channel:finance.channel,range:5,rangeFrom
8:rangeFrom.toISOString(),rangeTo:rangeTo.toISOString()}).then(onLoad)}}function handleDatePickerChange(_ref){var startDate=_ref.startDate,endDate=_ref.endDate,type=_ref.type;finance.range=type,finance.rangeFrom=startDate,finance.rangeTo=endDate,loadData()}function setDatePickerProps(type){finance.range=type,finance.datePickerInput={startDate:new Date,endDate:new Date,type:type}}function onLoad(data){data=angular.fromJson(data),finance.data=data,finance.loading=!1,finance.rangeStr=["день","неде лю","месяц","период"][Object.values(calendarTypes).findIndex(function(r){return r===finance.range})],parseSources(),parseLog(),data.site&&parseSite(),data.siteGG&&parseSiteGG(),data.income&&parseIncome()}function isPeriodActive(range){var isSameDate=void 0,today=new Date;if(finance.range===calendarTypes.DAY&&(isSameDate=finance.rangeFrom.getDate()===today.getDate()&&finance.rangeFrom.getMonth()===today.getMonth()&&finance.rangeFrom.getFullYear()===today.getFullYear()),finance.range===calendarTypes.WEEK){var weekStart=new Date(today.getFullYear(),today.getMonth(),today.getDate(),0,0,0,0);weekStart.setDate(weekStart.getDate()-(0===weekStart.getDay()?6:weekStart.getDay()-1));var weekEnd=new Date(weekStart);weekEnd.setDate(weekStart.getDate()+7),weekEnd.setMilliseconds(weekEnd.getMilliseconds()-1);var startDate=weekStart,endDate=new Date(weekEnd.getTime());isSameDate=finance.rangeFrom.getDate()===startDate.getDate()&&finance.rangeFrom.getMonth()===startDate.getMonth()&&finance.rangeFrom.getFullYear()===startDate.getFullYear()&&finance.rangeTo.getDate()===endDate.getDate()&&finance.rangeTo.getMonth()===endDate.getMonth()&&finance.rangeTo.getFullYear()===endDate.getFullYear()}return finance.range===calendarTypes.MONTH&&(isSameDate=finance.rangeFrom.getMonth()===today.getMonth()&&finance.rangeFrom.getFullYear()===today.getFullYear()),finance.range===range&&isSameDate}function parseSources(){finance.total=0;var values=finance.data.income;for(var i in values)values[i]&&i!=SOURCE_WALLET_PAYMENT&&(finance.total+=values[i]);finance.sources=[{value:values[4]||0,class:"adv",title:"Реклама"},{value:values[2]||0,class:"prem-personal",title:"Премиум"},{value:values[1]||0,class:"donate",title:"Поддержка"},{value:values[5]||0,class:"tourneys",title:"Турниры"},{value:values[8]||0,class:"donate",title:"Челленджи"},{value:values[10]||0,class:"deposit-to-gg",title:"ПопоКошелькаGG"},{value:values[6]||0,class:"correction",title:"Коррекция"},{value:values[13]||0,class:"correction",title:"ПлатежиКошельков"}],finance.providers={1:"Avangard",2:"WebMoney",3:"YandexMoney",4:"QIWI",5:"PayPal",6:"GG",7:"Xsolla",8:"Yandex Cards",9:"OK",12:"Альфа Банк",13:"Альфа Банк",14:"С карты на карту",17:"Intervale",18:"FREEPREM (хз что это)",19:"Moneta (должно быть пусто)",20:"CRYPTOCLOUD",21:"Зарубежная карта",22:"СБП",24:"Payture",26:"Ckassa",27:"СБП Рекурент",99:"Тестовая карта",100:"Тестовая карта",101:"Тестовая карта",102:"Тестовая карта",103:"Тестовая карта"},finance.sources.forEach(function(item){item.percent=finance.total?Math.round(100*item.value/finance.total):0})}function parseSite(){finance.site={total:0,sources:[{value:finance.data.site[SITE_ID_PREM_STREAMER]||0,class:"prem-personal",title:"Подписки стримеров"},{value:finance.data.site[SITE_ID_PREM_PLUS]||0,class:"prem-total",title:"Плюс подписка"},{value:finance.data.site[SITE_ID_DONAT]||0,class:"donate",title:"Поддержка"},{value:finance.data.site[SITE_ID_JOB]||0,class:"donate",title:"Челленджи"},{value:finance.data.site[SITE_ID_CUP]||0,class:"tourneys",title:"Турниры"},{value:finance.data.site[SITE_ID_DEPOSIT_TO_GG]||0,class:"deposit-to-gg",title:"ПопоКошелькаGG"}]},finance.data.site.forEach(function(value){finance.site.total+=value}),finance.site.sources.forEach(function(item){item.percent=finance.site.total?Math.round(100*item.value/finance.site.total):0})}function parseSiteGG(){window.DEV,finance.siteGG={total:0,sources:[{value:finance.data.siteGG[SITE_ID_PREM_STREAMER]||0,class:"prem-personal",title:"Подписки стримеров"},{value:finance.data.siteGG[SITE_ID_PREM_PLUS]||0,class:"prem-total",title:"Плюс подписка"},{value:finance.data.siteGG[SITE_ID_DONAT]||0,class:"donate",title:"Поддержка"},{value:finance.data.siteGG[SITE_ID_JOB]||0,class:"donate",title:"Челленджи"},{value:finance.data.siteGG[SITE_ID_CUP]||0,class:"tourneys",title:"Турниры"},{value:finance.data.siteGG[SITE_ID_DEPOSIT_TO_GG]||0,class:"deposit-to-gg",title:"ПопоКошелькаGG"}]},finance.data.siteGG.forEach(function(value){finance.siteGG.total+=value}
8),finance.siteGG.sources.forEach(function(item){item.percent=finance.siteGG.total?Math.round(100*item.value/finance.siteGG.total):0})}function parseIncome(){if(window.DEV,finance.data.providers){finance.income={total:0,sources:[{value:finance.data.providers[2]||0,class:"prem-total",title:"WebMoney"},{value:finance.data.providers[3]||0,class:"prem-total",title:"Yandex Money"},{value:finance.data.providers[5]||0,class:"prem-total",title:"PayPal"},{value:finance.data.providers[6]||0,class:"prem-total",title:"GG"},{value:finance.data.providers[8]||0,class:"prem-total",title:"Yandex Cards"},{value:finance.data.providers[9]||0,class:"prem-total",title:"OK"},{value:finance.data.providers[12]||0,class:"prem-total",title:"ALFA"},{value:finance.data.providers[13]||0,class:"prem-total",title:"ALFAAUTO"},{value:finance.data.providers[17]||0,class:"prem-total",title:"Intervale"},{value:finance.data.providers[22]||0,class:"prem-total",title:"Intervale SBP"},{value:finance.data.providers[4]||0,class:"prem-total",title:"Qiwi"},{value:finance.data.providers[20]||0,class:"prem-total",title:"Cryptocloud"},{value:finance.data.providers[21]||0,class:"prem-total",title:"SmartGlocal"},{value:finance.data.providers[24]||0,class:"prem-total",title:"Payture"},{value:finance.data.providers[26]||0,class:"prem-total",title:"Ckassa"}]};for(var i in finance.data.providers)finance.income.total+=parseInt(finance.data.providers[i]);finance.income.sources.forEach(function(item){item.percent=finance.income.total?Math.round(100*item.value/finance.income.total):0})}}function parseLog(){finance.log=[];for(var i=0;i<finance.data.log.length;i++){var event=finance.data.log[i];if(event.source=parseInt(event.source),event.provider=parseInt(event.provider||0),event.dest=parseInt(event.dest||0),event.class=["support","prem","prem-total","adv","tourney"][event.source-1],event.title=["Поддержка от","Премиум","Общий премиум","Реклама","Турнир"][event.source-1],0==event.source)switch(event.dest){case 32:event.title="Пополнение награды задания "+event.comment;break;case 26:event.title="Пополнение призового фонда "+event.comment;break;case 9:event.title="Поддержка "+event.comment;break;case 2:event.title="Возврат: "+event.comment;break;case 1:event.title="Коррекция администратором";break;case 0:event.title="Заявка на вывод: "+event.comment;break;default:event.title="Покупка: "+event.comment}5==event.source&&(event.title=event.comment),1!=event.source||event.username||(event.username="неизвестного"),2==event.source&&event.user&&(event.title="Премиум для"),6==event.source&&(event.title="Коррекция администратором"),event.source>=8&&(event.title=event.comment),finance.log.push(event)}}function formatDate(timestamp){var date=new Date(1e3*timestamp);return DateFunctions.formatDate(date)}var finance=this,SITE_ID_PREM_STREAMER=0,SITE_ID_PREM_PLUS=1,SITE_ID_DONAT=2,SITE_ID_JOB=3,SITE_ID_CUP=5,SITE_ID_DEPOSIT_TO_GG=6,SOURCE_WALLET_PAYMENT=13,calendarTypes={DAY:"day",WEEK:"week",MONTH:"month",PERIOD:"period"};finance.calendarTypes=calendarTypes,finance.channel=$scope.vm?$scope.vm.channel:0,finance.range=calendarTypes.DAY,finance.rangeFrom=new Date,finance.rangeTo=new Date,finance.datePickerInput={startDate:finance.rangeFrom,endDate:finance.rangeTo,type:finance.range},finance.formatDate=formatDate,finance.handleDatePickerChange=handleDatePickerChange,finance.setDatePickerProps=function(type){return setDatePickerProps(type)},finance.isPeriodActive=isPeriodActive}angular.module("GG").controller("ggChannelFinance",ggChannelFinance)}(),function(angular){var ggChannelHistoryBlock=function(){function ggChannelHistoryBlock($scope,DateFunctions){_classCallCheck(this,ggChannelHistoryBlock),this.history=[],this.DateFunctions=DateFunctions}return _createClass(ggChannelHistoryBlock,[{key:"$onInit",value:function(){var _this26=this;Utils.get("/ajax/channel/edits-history/",{channel:this.channelId}).then(function(data){_this26.history=data})}}]),ggChannelHistoryBlock}();angular.module("GG").component("ggChannelHistoryBlock",{controller:ggChannelHistoryBlock,templateUrl:"/html/stream/channel-history.html",bindings:{channelId:"@"}})}(angular),function(angular){var ggDonatSmilesEditor=function(){function ggDonatSmilesEditor($scope){var _this27=this;_classCallCheck(this,ggDonatSmilesEditor),this.channelId=0,this.levels=["","100 ₽","300 ₽","500 ₽","3000 ₽","10000 ₽","25000 ₽","50000 ₽","75000 ₽","100000 ₽","∞"],this.smiles={},this.editSmile=!1,this.$scope=$scope,$scope.$watch("$ctrl.editSmile.$imgBig",function(){return _this27.checkBigImage()}),$scope.$watch("$ctrl.editSmile.$imgGif",function(){return _this27.checkGifImage()})}return _createClass(ggDonatSmilesEditor,[{key:"$onInit",value:function(){this.loadData()}},{key:"loadData",value:function(){var _this28=this;Utils.get("/ajax/channel/donate-smiles/",{id:this.channelId}).then(function(data){return _this28.handleData(data)})}},{key:"handleData",value:function(data){var _this29=this;this.editSmile=!1,this.smiles={},data.forEach(function(smile){var url="/images/smiles/"+smile.path+smile.key;smile.big=url+"-big.png?rnd="+Date.now(),smile.gif=url+"-gif.gif?rnd="+Date.now(),_this29.smiles[smile.donat_level]=smile})}},{key:"edit",value:function(level){this.editSmile=this.smiles[level]?Object.assign({},this.smiles[level]):{donat_level:level}}},{key:"delete",value:function(){var _this30=this;if(!this.editSmile||!this.editSmile.donat_level)return void(this.editSmile=!1);var level=this.editSmile.donat_level;Utils.post("/ajax/channel/donate-smiles/delete/",{channel:this.channelId,level:level}).then(function(data){return _this30.handleData(data)})}},{key:"save",value:function(){if(!this.editSmile||!this.editSmile.donat_level)return void(this.editSmile=!1);this.check()&&this.uploadData()}},{key:"check",value:function(){return!this.errorBig&&!this.errorGif}},{key:"checkBigImage",value:function(){var _this31=this;if(this.editSmile.$imgBig){if(-1==this.editSmile.$imgBig.name.toLowerCase().indexOf(".png"))return void(this.errorBig="Неверный формат");
8this.getSizes(this.editSmile.big).then(function(sizes){36!=sizes.height||sizes.width<10||sizes.width>72?_this31.errorBig="Неверные размеры":_this31.errorBig="",_this31.$scope.$applyAsync()})}}},{key:"checkGifImage",value:function(){var _this32=this;if(this.editSmile.$imgGif){if(-1==this.editSmile.$imgGif.name.toLowerCase().indexOf(".gif"))return void(this.errorGif="Неверный формат");var bigSizes={};this.getSizes(this.editSmile.big).then(function(sizes){return bigSizes=sizes}).then(function(){return _this32.getSizes(_this32.editSmile.gif)}).then(function(sizes){sizes.height!=bigSizes.height||sizes.width!=bigSizes.width?_this32.errorGif="Размеры не совпадают":_this32.errorGif="",_this32.$scope.$applyAsync()})}}},{key:"uploadData",value:function(){var _this33=this,level=this.editSmile.donat_level,data=new FormData;data.append("level",level),data.append("channel",this.channelId),data.append("tags",this.editSmile.tags),this.editSmile.$imgBig&&data.append("big_smile",this.editSmile.$imgBig),this.editSmile.$imgGif&&data.append("gif_smile",this.editSmile.$imgGif),Utils.postForm("/ajax/channel/donate-smiles/save/",data).then(function(data){return _this33.handleData(data)})}},{key:"getSizes",value:function(url){return new Promise(function(resolve,reject){var img=new Image;img.src=url,img.onload=function(){return resolve({width:img.width,height:img.height})},img.onerror=function(){return reject()}})}}]),ggDonatSmilesEditor}();angular.module("GG").component("ggDonatSmilesEditor",{controller:ggDonatSmilesEditor,controllerAs:"$ctrl",templateUrl:"/html/stream/donat-smiles-upload.html",bindings:{channelId:"@"}})}(angular),function(angular){var ggPremiumIconEditor=function(){function ggPremiumIconEditor($scope){var _this34=this;_classCallCheck(this,ggPremiumIconEditor),this.titles=["1 месяц","3 месяца","Полгода","Год","2 года","4 года","8 лет"],this.editMode=!1,this.loading=!0,this.$scope=$scope,this.errors={},$scope.$watch("$ctrl.current.$imgFile48",function(){return _this34.checkImage(48)}),$scope.$watch("$ctrl.current.$imgFile32",function(){return _this34.checkImage(32)}),$scope.$watch("$ctrl.current.$imgFile16",function(){return _this34.checkImage(16)})}return _createClass(ggPremiumIconEditor,[{key:"$onInit",value:function(){var _this35=this;Utils.get("/ajax/channel/premium-icons/",{id:this.channelId}).then(function(data){return _this35.handleData(data)})}},{key:"handleData",value:function(data){this.icons=data;for(var key in this.icons)this.icons[key].filename48&&(this.icons[key].filename48="/files/icons/"+this.icons[key].filename48+"?rnd="+Math.random()),this.icons[key].filename32&&(this.icons[key].filename32="/files/icons/"+this.icons[key].filename32+"?rnd="+Math.random()),this.icons[key].filename16&&(this.icons[key].filename16="/files/icons/"+this.icons[key].filename16+"?rnd="+Math.random());this.loading=!1,this.editMode=!1}},{key:"edit",value:function(number){this.current=angular.copy(this.icons[number])||{type:number},this.current.title=this.titles[number-1],this.editMode=!0,this.checkFailed=!1,this.errors={}}},{key:"save",value:function(){var _this36=this;if(!this.current.delete){this.current.filename48||this.current.$imgFile48||(this.errors[48]=!0,this.errors.needAll=!0),this.current.filename32||this.current.$imgFile32||(this.errors[32]=!0,this.errors.needAll=!0),this.current.filename16||this.current.$imgFile16||(this.errors[16]=!0,this.errors.needAll=!0);for(var key in this.errors)if(this.errors[key])return!1}var form=new FormData;form.append("id",this.channelId),form.append("type",this.current.type),form.append("delete",this.current.delete?1:0),this.current.$imgFile48&&form.append("icon48",this.current.$imgFile48),this.current.$imgFile32&&form.append("icon32",this.current.$imgFile32),this.current.$imgFile16&&form.append("icon16",this.current.$imgFile16),Utils.postForm("/ajax/channel/premium-icons/save/",form).then(function(data){return _this36.handleData(data)})}},{key:"deleteCurrent",value:function(){this.current.delete=!0,this.save()}},{key:"cancel",value:function(){this.editMode=!1,this.current=!1,this.checkFailed=!1}},{key:"checkImage",value:function(size){var _this37=this;if(!this.current)return!1;console.log(size);var check=this.current.$imgFile48,url=this.current.filename48;if(32==size&&(check=this.current.$imgFile32,url=this.current.filename32),16==size&&(check=this.current.$imgFile16,url=this.current.filename16),this.current&&check&&check.name){if(-1===check.name.toLowerCase().indexOf(".png"))this.checkFailed=!0,this.errors.notPng=!0;else{var img=new Image;img.src=url,img.onload=function(){_this37.current.width=img.width,_this37.current.height=img.height,_this37.checkFailed=_this37.current.width!=size||_this37.current.height!=size,_this37.errors[size]=_this37.checkFailed,_this37.errors.wrongSize=_this37.checkFailed,_this37.$scope.$applyAsync()}}this.errors[size]=this.checkFailed,this.$scope.$applyAsync()}}}]),ggPremiumIconEditor}();angular.module("GG").component("ggPremiumIconEditor",{controller:ggPremiumIconEditor,templateUrl:"/html/stream/premium-icon-upload.html",bindings:{channelId:"@"}})}(angular),function(){var HlsService=function(){function HlsService(){_classCallCheck(this,HlsService),this.Q_BAD="bad",this.Q_MIDDLE="middle",this.Q_HIGH="good",this.hls=this,this.debug=!1,this.data=null,this.isOffline=!1,this.qual
8ity=null,
9this.errors=[],this.timer=null,this.channelId=0}return _createClass(HlsService,[{key:"load",value:function(channelId){var prom,_this38=this,self=this;return this.channelId=channelId,prom=this.debug?new Promise(function(resolve,reject){resolve(angular.fromJson('{"video":{"bitrate":"2360","codec":"H264","profile":"Main","resolution":"1280x720","cbr":true,"key_frame":"2.000"},"audio":{"bitrate":"115","codec":"AAC","sample_rate":"44100","cbr":true},"server_name":"origin-7","server_ip":"213.24.114.206"}'))}):new Promise(function(resolve,reject){Utils.get("https://hls.goodgame.ru/hls/"+channelId+".json").then(function(data){self.isOffline=!1,resolve(data)}).catch(function(e){self.isOffline=!0})}),prom.then(function(data){return _this38.data=data}).then(function(){return _this38.init()}),prom}},{key:"reload",value:function(){return this.load(this.channelId)}},{key:"setQuality",value:function(q){return this.quality=q}},{key:"getQuality",value:function(){return this.quality}},{key:"setErrors",value:function(){this.errors=[],this.setQuality(this.Q_HIGH),parseFloat(this.data.video.key_frame)>2&&(this.setQuality(this.Q_MIDDLE),this.errors.push("Установите Интервал ключевых кадров (keyframe) равный 2 секундам в настройках вашей программы для стриминга")),"Main"!==this.data.video.profile&&(this.setQuality(this.Q_MIDDLE),this.errors.push("Установите профиль Main в настройках вашей программы для стриминга"));var resolutionRatio=this.getResolutionRation();resolutionRatio?1.78===resolutionRatio||1.6===resolutionRatio||resolutionRatio>1.31&&resolutionRatio<1.35||(this.setQuality(this.Q_BAD),this.errors.push("Установите выходное разрешение с соотношением сторон 16:9, 16:10 или 4:3 в настройках вашей программы для стриминга")):this.errors.push("Cоотношение сторон не определено :("),"AAC"!==this.data.audio.codec&&(this.setQuality(this.Q_BAD),this.errors.push("Выберите аудио кодек AAC в настройках вашей программы для стриминга")),this.data.video.cbr&&1==this.data.video.cbr||(this.setQuality(this.Q_BAD),this.errors.push("Установите CBR (Constant Bit Rate) в настройках вашей программы для стриминга"))}},{key:"getErrors",value:function(){return this.errors}},{key:"getResolutionRation",value:function(){var res=this.data.video.resolution.split("x",2);if(2!==res.length)return 0;var x=parseInt(res[0],10),y=parseInt(res[1],10);try{return x>0&&y>0?parseFloat((x/y).toFixed(2)):0}catch(e){return 0}}},{key:"init",value:function(){this.setErrors()}},{key:"timerStart",value:function(){var self=this;this.timer=setInterval(function(){self.reload()},15e3)}},{key:"timerStop",value:function(){clearInterval(this.timer)}}]),HlsService}();angular.module("GG").service("HlsService",HlsService)}(),function(angular){var ggChannelInitBlock=function(){function ggChannelInitBlock(StreamService){_classCallCheck(this,ggChannelInitBlock)}return _createClass(ggChannelInitBlock,[{key:"$onInit",value:function(){var _this39=this;PageLoader.onEnter(function(){$("body").addClass("channel"),window.StreamController&&window.StreamController.showChat(_this39.channelId),ChannelPage.init(7,_this39.channelId),Utils.rootScope().isMobile&&UserService.settings.beta&&UserService.settings.beta[3]&&(Utils.rootScope().hideFeed=!0),Utils.sendEvent("stream-view",{streamId:channelCommonInfo.channelId,game:channelCommonInfo.gameTitle,gameId:channelCommonInfo.gameId,streamStarted:channelCommonInfo.streamStarted})}).onExit(function(newUrl,oldUrl){$("body").removeClass("channel"),(!newUrl||!oldUrl||newUrl.replace(/\?streamer=\d/,"")!=oldUrl.replace(/\?streamer=\d/,""))&&(window.StreamController&&window.StreamController.showChat(!1),window.ggplayer=!1)})}}]),ggChannelInitBlock}();angular.module("GG").component("ggChannelInitBlock",{controller:ggChannelInitBlock,template:"",bindings:{channelId:"@"}})}(angular),function(){function ggStreamerMoneyBlock($scope,$attrs,$window){function popup(){$window.open("/user/"+$attrs.user+"/money/","money","width=365,height=288,location=no,status=no,menubar=no,scrollbars=no")}function onData(values){if(values){for(var i in values)vm.total+=values[i];vm.sources=[{value:values[4]||0,class:"",title:"Реклама"},{value:values[2]||0,class:"prem",title:"Премиум"},{value:values[1]||0,class:"support",title:"Поддержка"},{value:values[5]||0,class:"tournaments",title:"Турниры"}],"true"==$attrs.channel&&vm.sources.splice(4,1),vm.sources.forEac
9h(function(item){item.percent=vm.total?Math.round(100*item.value/vm.total):0})}}var vm=this;vm.total=0,$attrs.values?onData(angular.fromJson($attrs.values)):$scope.$watch("control.money",function(){onData($scope.control.money)}),vm.popup=popup}angular.module("GG").controller("ggStreamerMoneyBlock",ggStreamerMoneyBlock)}(),function(angular){angular.module("GG").directive("ggPackery",function(){function ggPackery($scope,$element,$attrs,$parse){function waitAndRecalc(){i&&clearTimeout(i),setTimeout(init,500)}function init(){0!=c.clientHeight&&$element.packery&&$element.packery({itemSelector:".panel",gutter:0})}var c=$element[0],i=0;ResourceLoader.loadJs("/js/libraries/packery.pkgd.min.js").then(init),$element.find("img").off().on("load",waitAndRecalc),$scope.$watch(function(){return[c.clientHeight,c.clientWidth]},waitAndRecalc,!0),$scope.$on("$destroy",function(){$element.find("img").off()})}return{restrict:"A",controller:ggPackery}})}(angular),function(){function ggPremiumPopup($scope,$attrs){vm=this,vm.step=1,vm.type=1==$attrs.price?1:6,vm.provider=parseInt(Utils.lsGet("remember_premium_provider",-1)),vm.hideKey=1,vm.$scope=$scope,vm.types=angular.fromJson($attrs.types),vm.channel=$attrs.channel,vm.streamer=!!$attrs.streamer,vm.streamkey=$attrs.streamkey,vm.wallet=$attrs.wallet,vm.activate=1,vm.price=$attrs.price,vm.premium=$attrs.premium||0,""==vm.channel&&(vm.channel=!1),vm.check=function(){return 0!=vm.type&&(-1!=vm.provider&&(!(6==vm.provider&&vm.wallet<vm.types[vm.type].price)&&(6!=vm.provider||!vm.streamer)))},vm.comm=function(value){return value+(5==vm.provider?Math.ceil(.06*value+2):0)},vm.buy=makeBuy,vm.openPopup=openPopup,vm.close=close,vm.activateKey=activateKey,vm.confirm=confirmPayment,vm.reject=rejectPayment,vm.auth=function(){return LoginPopup.open()},vm.testPremium=testPremium,vm.copyKey=copyKey,window.buyPremiumCallback=externalCallback,_premiumKey=!1}function close(){3==vm.step&&vm.success&&1==vm.activate?activateKey():$(".subscribe-popup").fadeOut(300,function(){this.remove()})}function confirmPayment(){var pid=vm.paymentId;vm.paymentId=0,$.ajax({type:"POST",url:"/payments/gg_process/",data:{pid:pid,code:vm.paymentCode},dataType:"json"}).fail(function(){externalCallback(!1)}).done(function(data){externalCallback(data.success,data.code,vm.paymentTitle)})}function rejectPayment(){externalCallback(!1)}function makeBuy(){var provider=vm.provider,type=vm.type,email=vm.email||"";Utils.lsSet("remember_premium_provider",provider),vm._link="/payments/save/?provider="+provider+"&objType=24&objId="+type+"&email="+email,6==provider||7==provider?(vm._link+="&json=1",vm.internal=1,makePayment()):0==provider?(window.open(oplataLinks[type-1],"_blank","width=800,height=600,toolbar=no,scrollbars=yes,resizable=yes"),close()):(vm.internal=0,_linkTimeout=setTimeout(function(){openPopup()},2e3)),vm.step=2}function makePayment(){vm.paymentId=0,vm.paymentCode=0;var link=vm._link;$.ajax({type:"GET",url:link,dataType:"json"}).fail(function(){externalCallback(!1)}).done(function(data){data.link&&-1!=data.link.indexOf("xsolla_continue")||(vm.paymentTitle=data.title,vm.paymentAmount=data.amount,vm.paymentCode=data.code,vm.paymentId=data.id),vm.$scope.$apply()})}function openPopup(){var link=vm._link,_new=window.open(link,"_blank","width=800,height=600,toolbar=no,scrollbars=yes,resizable=yes"),pollTimer=setInterval(function(){if(!_new)return void clearInterval(pollTimer);!1!==_new.closed&&(clearInterval(pollTimer),externalCallback(!1))},200)}function activateKey(){window.ggplayer?window.ggplayer.checkPremiumKey(vm.manualKey,vm.streamkey,UserService.id,finalCallback):manualActivation()}function testPremium(){window.ggplayer&&(window.ggplayer.startTestPremium(),finalCallback(!1))}function copyKey(){document.querySelector('input[rel="premium-key"]').select();try{document.execCommand("copy")}catch(err){alert("Не удалось скопировать")}}function manualActivation(){Utils.post("/api/premium/xml/?all=1",{streamname:vm.streamkey||"",premium_key:vm.manualKey,uid:UserService.id}).then(function(data){var a=parseXML(data);finalCallback("OK_ALL"==a.status||"OK"==a.status)})}function parseXML(xml){for(var ret={},m=!1,params=xml.split(/<\/[^>]+>/),i=0;i<params.length;i++)(m=params[i].match(/<(.+)>(.+)/))&&(m[1].match(/activated="true"/)&&(m[1]=m[1].replace(/ activated="true"/,""),ret._activated=!0),ret[m[1]]=m[2]);return ret}function externalCallback(success,key,title){_premiumKey||(vm.step=3,vm.success=success,vm._link=!1,_premiumKey=key,vm.paymentTitle=title,vm.newKey=key,vm.manualKey=_premiumKey,vm.$scope.$apply())}function finalCallback(status){vm.$scope.$root.User.premium=status||vm.$scope.$root.User.premium,vm.$scope.$root.$applyAsync(),$(".subscribe-popup").fadeOut(300,function(){this.remove()})}angular.module("GG").controller("ggPremiumPopup",ggPremiumPopup);var vm,_linkTimeout,_premiumKey,oplataLinks=["http://www.oplata.info/asp2/p
9ay_wm.asp?id_d=1600633","http://www.oplata.info/asp2/pay_wm.asp?id_d=1303626","http://www.oplata.info/asp2/pay_wm.asp?id_d=1315650","http://www.oplata.info/asp2/pay_wm.asp?id_d=1315649","http://www.oplata.info/asp2/pay_wm.asp?id_d=1315653","http://www.oplata.info/asp2/pay_wm.asp?id_d=2022450"]}(),function(){function RecordService(){var record=this;record.start=function(){return record._loading=!0,Utils.post("/ajax/channel/record/",{channel:record.channelKey,action:"start"}).then(function(){setTimeout(function(){},5e3)})},record.stop=function(){return record._loading=!0,Utils.post("/ajax/channel/record/",{channel:record.channelKey,action:"stop"}).then(function(){})},record.toggle=function(){record.status?record.stop():record.start()};var timer;record.startTimer=function(){timer=setInterval(function(){},1e4)},record.stopTimer=function(){clearInterval(timer)}}angular.module("GG").service("RecordService",RecordService),RecordService.$inject=[]}(),function(){function RestreamService(){this.services=[{id:5,title:"Twitch"},{id:10,title:"CyberGame"},{id:9,title:"YouTube"},{id:0,title:"Другой"}],this.save=function(channelId,data){return Utils.post("/ajax/channel/restream",{id:channelId,data:JSON.stringify(data)})}}angular.module("GG").service("RestreamService",RestreamService),RestreamService.$inject=[]}(),function(){function ggSmilesBlock($scope,$attrs,$element){vm=this,vm.$scope=$scope,vm.channel=$attrs.channel,vm.$element=$element,vm.editSmile=editSmile,vm.saveSmile=saveSmile,vm.deleteSmile=deleteSmile,init(angular.fromJson($attrs.values))}function init(data){root=vm.$element,root.on("change",".upload-form input",upload).find(".upload-image").find("img").on("error",function(event){$(event.target).hide()}),load(data)}function load(data){vm.smiles=[],vm.level=parseInt(data.newlevel),vm.total=parseInt(data.total);var progressLevel=void 0!==data.rawlevel&&null!==data.rawlevel?parseInt(data.rawlevel):vm.level;vm.goal=(goals[vm.level]||vm.level+1)+" смайл",vm.expGap=levels[progressLevel]-levels[progressLevel-1],vm.expHave=Math.max(0,vm.total-levels[progressLevel-1]),vm.exppercents=parseInt(100*vm.expHave/vm.expGap,10);for(var max=6*Math.ceil((vm.level+1)/6),i=1;i<=max;i++){var sm=data.uploaded[i];sm&&(sm.src="/images/smiles/"+sm.path+sm.key+"-big.png?rnd="+Date.now(),sm.gif="/images/smiles/"+sm.path+sm.key+"-gif.gif?rnd="+Date.now()),vm.smiles.push(sm||{})}}function editSmile(smile,index){vm.editMode=!0,vm.smile=smile,vm.editIndex=index,vm.smileTags=smile.smileTags}function upload(event){var block=$(event.target).closest(".smile-upload"),isGif="upload-gif"==$(event.target).attr("id"),webUrl=window.URL||window.webkitURL;isGif?(vm.smile.gif=webUrl.createObjectURL(event.target.files[0]),_files[1]=event.target.files[0]):(vm.smile.src=webUrl.createObjectURL(event.target.files[0]),_files[0]=event.target.files[0]),block.find("img").on("load",function(){$(this).show(),doCheck(block)}),vm.$scope.$apply()}function doCheck(block){var img,sizes=!1;0!=_files[0]&&(img=block.find(".upload-image img")[0],sizes=!!img.naturalHeight&&[img.naturalHeight,img.naturalWidth],"image/png"!=_files[0].type?vm.error1="Неверный формат":sizes&&(36!=sizes[0]||sizes[1]<10||sizes[1]>72)?vm.error1="Неверные размеры":vm.error1=!1),0!=_files[1]&&(img=block.find(".upload-image img")[1],_files[0]?_files[1]&&"image/gif"!=_files[1].type?vm.error2="Неверный формат":sizes&&img.naturalHeight&&(sizes[0]!=img.naturalHeight||sizes[1]!=img.naturalWidth)?vm.error2="Размеры не совпадают":vm.error2=!1:vm.error2="Не загружен статичный смайл"),vm.$scope.$apply()}function saveSmile(){root.find(".smile-upload");if(!vm.error1&&!vm.error2){var data=new FormData;_files[0]&&data.append("big_smile",_files[0]),_files[1]&&data.append("gif_smile",_files[1]),data.append("num",vm.editIndex),data.append("channel",vm.channel),data.append("tags",vm.smile.tags),fetch("/ajax/smiles/save/",{method:"POST",body:data}).then(function(response){return response.json()}).then(function(data){load(data),_files=[!1,!1],vm.editMode=!1,vm.$scope.$apply()}).catch(function(error){console.error(error)})}}function deleteSmile(){$.post("/ajax/smiles/delete/",{num:vm.editIndex,channel:vm.channel},function(data){load(data),vm.editMode=!1,vm.$scope.$apply()},"json")}angular.module("GG").controller("ggSmilesBlock",ggSmilesBlock);for(var vm,root,_files=[!1,!1],levels=[0,0,10,25,50,100,175,275,425,625,925,1325,1825,2425,3125,3925,4725,5525,6325,7125,7925,8725,9525],n=levels.length;n<100;n++)levels.push(n*(n-1)/2*40);var goals=["первый","второй","третий","четвертый","пятый","шестой","седьмой","восьмой","девятый"]}(),function(){var ggStreamerTopDonate=function(){function ggStreamerTopDonate($scope,$attr){_classCallCheck(this,ggStreamerTopDonate),this.streamer=$attr.streamer,this.$scope=$scope,this.$attr=$attr,this.loading=!0,this.range=1,this.rangeFrom=new Date,this.rangeTo=new Date,this.start,this.count,this.total,this.payments=[];var top=this;
9this.reset(),$scope.$watch("topDonate.range",function(){top.reset(),top.range&&top.loadData()}),$scope.$watch("topDonate.rangeFrom + topDonate.rangeTo",function(a,b){top.reset(),a!=b&&(top.range=5,top.loadData())})}return _createClass(ggStreamerTopDonate,[{key:"loadData",value:function(){var _this40=this;this.loading=!0,Utils.get("/ajax/payment/"+this.streamer+"/top/",{range:this.range,rangeFrom:this.rangeFrom.toISOString(),rangeTo:this.rangeTo.toISOString(),start:this.start,count:this.count}).then(function(data){return _this40.onLoad(data)})}},{key:"onLoad",value:function(data){var key;for(key in data.payments)data.payments[key].total=Math.round(data.payments[key].total),this.payments.push(data.payments[key]);this.loading=!1,this.start=data.start,this.count=data.count,this.total=data.total,this.$scope.$applyAsync()}},{key:"loadMore",value:function(start){this.start=start,this.loadData()}},{key:"reset",value:function(){this.start=0,this.count=20,this.total=0,this.payments=[]}},{key:"getUserName",value:function(payment){return payment.creator&&payment.sign?payment.sign:payment.email?payment.email:"Неизвестный"}}]),ggStreamerTopDonate}();ggStreamerTopDonate.$inject=["$scope","$attrs"],angular.module("GG").controller("ggStreamerTopDonate",ggStreamerTopDonate)}(),function(){var ggChannelVideoList=function(){function ggChannelVideoList($scope){var _this41=this;_classCallCheck(this,ggChannelVideoList),console.log("ggChannelVideoList init"),$scope.$watch("vm.tab",function(tab){return _this41.onTabChange(tab)}),this.channel=$scope.vm.channel}return _createClass(ggChannelVideoList,[{key:"onTabChange",value:function(tab){this.tab=tab,3==this.tab&&this.loadClips(),2==this.tab&&this.loadVideos()}},{key:"loadClips",value:function(more){var _this42=this;more||(this.videos=[],this.page=1),this.loading=!0,Utils.get("/ajax/clips/",{tab:"clips.channel",channel:this.channel,page:this.page}).then(function(response){_this42.loading=!1,_this42.videos=_this42.videos.concat(response.list),_this42.more=response.total>response.list.length})}},{key:"loadVideos",value:function(){this.videos=[],this.loading=!0}},{key:"loadMore",value:function(){this.page++,3==this.tab&&this.loadClips(!0),2==this.tab&&this.loadVideos()}}]),ggChannelVideoList}();angular.module("GG").controller("ggChannelVideoList",ggChannelVideoList)}(),function(angular){function ggTeamEdit($scope){function onLoadedData(_data){angular.extend(vm,angular.fromJson(_data)),vm.team.country=vm.country}function save(){vm.error=!1,vm.ok=!1,Utils.post("/ajax/team/save/",vm.team).then(function(id){0==parseInt(id)?vm.error=!0:vm.ok=!0})}var vm=this;vm.error=!1,vm.ok=!1,vm.save=save,function(){Utils.get("/ajax/team/"+("new"==window.url(2)?"0":window.url(2))+"/").then(onLoadedData)}()}angular.module("GG").controller("ggTeamEdit",ggTeamEdit),ggTeamEdit.$inject=["$scope"]}(angular),function(angular){var ggHtml5Video=function(){function ggHtml5Video($scope,$element,$interval){var _this43=this;_classCallCheck(this,ggHtml5Video),this.$video=$element.find("video")[0],this.$video.addEventListener("canplay",function(){return _this43.canPlay()}),this.$video.addEventListener("loadstart",function(){return _this43.canPlay()}),this.$interval=$interval,this._position=0,this.fullscreen=!1,this._play=!1,this.$onInit=function(){_this43.setPosition=function(value){return _this43.$setPosition(value)}},this.$faded=$element.find(".poster-faded"),this.$scope=$scope}return _createClass(ggHtml5Video,[{key:"$onDestroy",value:function(){this.$video.pause(),this.$video.setAttribute("src",""),this.$updateInterval&&this.$interval.cancel(this.$updateInterval)}},{key:"canPlay",value:function(){this.play=this._play}},{key:"$setPosition",value:function(value){this.$video.currentTime=value,this._updatePosition()}},{key:"togglePlay",value:function(){this.play=this.$video.paused}},{key:"_updatePosition",value:function(){this._position=this.$video.currentTime}},{key:"play",get:function(){return this._play},set:function(value){var _this44=this;console.log("play",value),this._play=value,value?(this.$video.play(),this.$updateInterval=this.$interval(function(){return _this44._updatePosition()},120)):(this.$video.pause(),this.$interval.cancel(this.$updateInterval))}},{key:"volume",get:function(){return this.$video.volume},set:function(value){this.$video.volume=value,sessionStorage.setItem("clips-volume",value)}},{key:"position",get:function(){return this._position},set:function(value){}},{key:"duration",get:function(){return this.$video.duration},set:function(value){}},{key:"loaded",set:function(value){},get:function(){return this.$video.buffered.length?this.$video.buffered.end(0):0}},{key:"poster",set:function(value){this._poster&&(this.$faded.css({"background-image":"url("+this._poster+")"}),this.$faded.show(),this.$faded.fadeOut(300)),this._poster=value},get:function(){return this._poster}}]),ggHtml5Video}();angular.module("GG").component("ggHtml5Video",{template:'<div ng-click="video.togglePlay()" class="poster-faded"></div><video ng-click="video.togglePlay()" preload="{{video.preload}}" playsinline poster="{{ video.poster }}" loop ng-src="{{ video.src }}"></video>',controller:ggHtml5Video,controllerAs:"video",bindings:{src:"=",play:"=",poster:"=",volume:"=",position:"=",duration:"=",preload:"=",setPosition:"=",loaded:"="}})}(angular),function(angular){var ggPlayerPanel=function(){function ggPlayerPanel($window){_classCallCheck(this,ggPlayerPanel),this.$window=$window,this.keydownHandler=this.handleKeydown.bind(this)}return _createClass(ggPlayerPanel,[{key:"$onInit",value:function(){this.$window.addEventListener("keydown",this.keydownHandler)}},{key:"$onDestroy",value:function(){this.$window.removeEventListener("keydown",this.keydownHandler)}},{key:"handleKeydown",value:function(event){var target=event.target,tagName=target.tagName.toLowerCase(),isContentEditable=target.isContentEditable;if("input"!==tagName&&"textarea"!==tagName&&"select"!==tagName&&!isContentEditable)switch(event.key){case"ArrowRight":this.forward();break;case"ArrowLeft":this.rewind();break;case"m":case"M":case"ь":case"Ь":this.toggleMute();break;case"f":case"F":case"а":case"А":this.fullscreen=!this.fullscreen;break;case" ":event.preventDefault(),this.togglePlayPause()}}},{key:"forward",value:function(){this.position=Math.min(this.position+5,this.duration),this.updatePosition()}},{key:"rewind",value:function(){this.position=Math.max(this.position-5,0),this.updatePosition()}},{key:"updatePosition",value:function(){this.setPosition({value:this.position})}},{key:"togglePlayPause",value:function(){this.play=!this.play}},{key:"formatTime",value:function(value){if(!1===value||isNaN(value))return"--:--";var minutes=Math.floor(value/60),seconds=Math.floor(value%60);return Utils.withZero(minutes)+":"+Utils.withZero(seconds)}},{key:"getVolumeClass",value:function(){return 0==this.volume?"mute":this.volume<.75?"half":""}},{key:"toggleMute",value:function(){0==this.volume?this.volume=this.$lastVolume||.75:(this.$lastVolume=this.volume,this.volume=0)}},{key:"timelineClick",value:function(event){var elemPos=event.currentTarget.getBoundingClientRect(),pos=(event.clientX-elemPos.left)/event.currentTarget.clientWidth;this.setPosition({value:this.duration*pos})}},{key:"timelineHover",value:function(event){var elemPos=event.currentTarget.getBoundingClientRect(),pos=(event.clientX-elemPos.left)/event.currentTarget.clientWidth;this.hovered=pos*this.duration}},{key:"src",set:function(value){this._src=value},get:function(){return this._src}}]),ggPlayerPanel}();angular.module("GG").component("ggPlayerPanel",{templateUrl:"/html/videoplayer/panel.html",controller:ggPlayerPanel,controllerAs:"panel",bindings:{src:"=",play:"=",volume:"=",position:"=",duration:"=",setPosition:"&",fullscreen:"=",loaded:"="}})}(angular),function(angular){var ggVideoPlayer=function(){function ggVideoPlayer($element,$timeout){var _this45=this;_classCallCheck(this,ggVideoPlayer),this.$element=$element,this.$timeout=$timeout,this.play=!0,this.volume=sessionStorage.getItem("clips-volume")||0,this.position=0,this.duration=0,this.adult=0,this.$element=$element,this._clip=!1,this._play=!1,this._reported=!1,this.videoElement=null,this.observer=new IntersectionObserver(function(entries){entries.forEac
9h(function(entry){_this45._isVisible=entry.isIntersecting,_this45._isVisible?_this45.play=!0:_this45.play=!1})},{threshold:.7})}return _createClass(ggVideoPlayer,[{key:"$onInit",value:function(){this.adult=1==this.adult,this.play=!this.adult,this.preload=this.preload||"none",!this.src&&this.id&&this.loadData(),this.controls()}},{key:"$postLink",value:function(){var _this46=this;this.$timeout(function(){_this46.videoElement=_this46.$element.find("video")[0],_this46.videoElement&&_this46.observer.observe(_this46.videoElement)})}},{key:"$onDestroy",value:function(){this.observer&&this.observer.disconnect()}},{key:"loadData",value:function(){var _this47=this;Utils.get("/ajax/clip/"+this.id+"/").then(function(data){_this47.src=data.src,_this47.views=data.views,_this47.streamer=data.streamer,_this47.avatar=data.avatar,_this47.game=data.game,_this47.autoplay=1,_this47.play=1})}},{key:"controls",value:function(){var player=document.getElementsByClassName("video-player")[0],promise=void 0;player.addEventListener("mousemove",function(){player.classList.add("hovering"),promise&&clearTimeout(promise),promise=setTimeout(function(){player.classList.remove("hovering")},1e3)})}},{key:"reportView",value:function(){var _this48=this;this._reported||setTimeout(function(){_this48.position>0&&(_this48._reported=!0,Utils.post("/ajax/clip/"+_this48.id+"/view"))},1e3)}},{key:"play",set:function(value){this._play=value,this.adult=0,this.reportView()},get:function(){return this._play}},{key:"clip",set:function(value){this._clip=value,value&&(this.id=this._clip.id,this.src=this._clip.src,this.poster=this._clip.preview,this.views=this._clip.views,this.streamer=this._clip.streamer,this.avatar=this._clip.avatar,this.game=this._clip.game,this._reported=!1,this.play=1,this.position=0)},get:function(){return this._clip}},{key:"fullscreen",set:function(value){var elem=this.$element.find(".video-player")[0];value?elem.requestFullscreen?elem.requestFullscreen():elem.msRequestFullscreen?elem.msRequestFullscreen():elem.mozRequestFullScreen?elem.mozRequestFullScreen():elem.webkitRequestFullscreen&&elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT):document.exitFullscreen?document.exitFullscreen():document.msExitFullscreen?document.msExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()},get:function(){return!!(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement)}}]),ggVideoPlayer}();angular.module("GG").component("ggVideoPlayer",{templateUrl:"/html/videoplayer/videoplayer.html",controller:["$element","$timeout",ggVideoPlayer],controllerAs:"player",bindings:{src:"@?",views:"@?",streamer:"@?",poster:"@?",avatar:"@?",game:"@?",autoplay:"@?",preload:"@?",adult:"@?",clip:"=?",id:"@?"}})}(angular),function(angular){var ggPlayerLoading=function(){function ggPlayerLoading($scope,$element){var _this49=this;_classCallCheck(this,ggPlayerLoading),this.loading=!1,this.progress=0,this.$scope=$scope,this.$elem=$element,this.onMessageFn=function(event){return _this49.onMessage(event)},window.addEventListener("message",this.onMessageFn,!1)}return _createClass(ggPlayerLoading,[{key:"createPreview",value:function(url){var _this50=this,container=this.$elem.find(".loader").show()[0];this.video=document.createElement("video"),this.video.setAttribute("width","100%"),this.video.setAttribute("height","100%"),container.appendChild(this.video);var hls=new Hls;hls.loadSource(url),hls.attachMedia(this.video),this.video.addEventListener("canplay",function(){console.log("canplay");var width=_this50.video.clientWidth,height=_this50.video.clientHeight,canvas1=document.createElement("canvas");canvas1.classList.add("bw"),canvas1.setAttribute("width",width),canvas1.setAttribute("height",height),container.appendChild(canvas1);var canvas2=document.createElement("canvas");canvas2.setAttribute("width",width),canvas2.setAttribute("height",height),_this50.progressDiv=document.createElement("div"),_this50.progressDiv.appendChild(canvas2),_this50.progressDiv.classList.add("progress"),container.appendChild(_this50.progressDiv),canvas1.getContext("2d").drawImage(_this50.video,0,0,width,height),canvas2.getContext("2d").drawImage(_this50.video,0,0,width,height)}),hls.on(Hls.Events.MANIFEST_PARSED,function(){console.log("Hls.Events.MANIFEST_PARSED"),_this50.video.pause()})}},{key:"onProgress",value:function(value){value>99&&(value=99),this.progress=Math.round(value)+"%",this.progressDiv&&(this.progressDiv.style.width=value+"%")}},{key:"$onDestroy",value:function(){window.removeEventListener("message",this.onMessageFn)}},{key:"onMessage",value:function(event){var _this51=this;try{var data=angular.fromJson(event.data);"done"==data.type&&(this.loading=!1,this.$scope.$apply(),this.$elem.fadeOut(1e3,function(){return _this51.$elem.remove()})),"progress"==data.type&&(this.video||this.createPreview(data.video),this.loading=!0,this.onProgress(100*data.value)),this.$scope.$apply()}catch(e){}}}]),ggPlayerLoading}();angular.module("GG").component("ggPlayerLoading",{template:'<div class="loader" style="display: none"><div class="load-status">Подождите, идет обработка клипа</div></div>',controller:ggPlayerLoading,controllerAs:"loader",bindings:{loading:"="}})}(angular),function(angular){var ggPlayerVolume=function(){function ggPlayerVolume($scope,$element){var _this52=this;_classCallCheck(this,ggPlayerVolume),this.$scope=$scope;var elem=$element.find(".sound-bar-block");elem.on("mousemove",function(event){return _this52.onMove(event)}),elem.on("mousedown",function(){return _this52.$drag=!0}),window.addEventListener("mouseup",function(){return _this52.$drag=!1}),this.$elem=elem[0]}return _createClass(ggPlayerVolume,[{key:"click",value:function(event){event.target.classList.contains("handle")||(this.volume=Math.min(1,Math.max(0,event.offsetX/event.currentTarget.clientWidth)))}},{key:"onMove",value:function(event){if(this.$drag){var pos=this.$elem.getBoundingClientRect();this.volume=Math.min(1,Math.min(1,Math.max(0,event.clientX-pos.left)/this.$elem.clientWidth)),this.$scope.$applyAsync()}}}]),ggPlayerVolume}();angular.module("GG").component("ggPlayerVolume",{templateUrl:"/html/videoplayer/volume.html",controller:ggPlayerVolume,controllerAs:"volume",bindings:{volume:"="}})}(angular),function(){function ggExportEditor($scope,$attrs,$window){function onLoadData(data){data=angular.fromJson(data),vm.video=data.video,vm.youtube=data.youtube,vm.loaded=!0,vm.video.privacy=1,vm.errors={title:!1,youtube:!1,export:!1},2!=vm.video.server&&(vm.errors.export=!0),$scope.$applyAsync()}function deletePreview(){vm.video.preview=!1}function checkYoutube(){vm.errors.youtube=!1,vm.youtube?Utils.get("/ajax/channel/youtube/login/").then(function(callback){$window.open(callback,"youtube_connect","width=780,height=500,location=0,menubar=0,resizable=1,status=0")}):Utils.get("/ajax/channel/youtube/logout/").then(function(callback){callback=angular.fromJson(callback),callback.error&&(vm.errors.youtube=!0,angular.element("#youtube-errors").html("Что-то пошло Ð
9½Ðµ так! Попробуйт еще раз позже"))})}function validateData(){var errors=0,scrollTo=null;if(vm.errors={title:!1,youtube:!1},vm.youtube||(vm.errors.youtube=!0,scrollTo="youtube",errors++),vm.video.title.trim()||(vm.errors.title=!0,scrollTo="title",errors++),errors>0)return Utils.scrollToElement(angular.element("#"+scrollTo)),!1}function exportVideo(){validateData(),vm.loaded=!1,PageLoader.showLoader();var form=new FormData;form.append("video",videoId),form.append("data",angular.toJson(vm.video)),vm.$imgFile&&form.append("preview",vm.$imgFile),Utils.postForm("/ajax/video/"+videoId+"/export/",form).fail(function(e){PageLoader.hideLoader(),vm.loaded=!0,console.error(e)}).done(function(data){data.error?"no gg"==data.type&&(PageLoader.hideLoader(),vm.loaded=!0,vm.errors.export=!0):data.result&&PageLoader.goOrBack("/video/"+videoId)})}var vm=this,videoId=0;window.location.href.match(/.+video\/(\d+)\/export\/?/gi)&&(videoId=window.location.href.replace(/.+video\/(\d+)\/export\/?/gi,"$1")),function(){Utils.get("/ajax/video/"+videoId+"?m=export").then(onLoadData)}(),vm.deletePreview=deletePreview,vm.checkYoutube=checkYoutube,vm.export=exportVideo}angular.module("GG").controller("ggExportEditor",ggExportEditor)}(),function(){var ggVideo=function(){function ggVideo($scope,$attrs,$sce){_classCallCheck(this,ggVideo),this.$scope=$scope,this.$attrs=$attrs,($attrs.videoUrl.indexOf("youtube")>-1||$attrs.videoUrl.indexOf("youtu.be")>-1)&&this.makeYouTubeEmbed($sce)}return _createClass(ggVideo,[{key:"complain",value:function($event){if(!UserObj.id)return void this.$scope.$root.showLogin("Авторизуйтесь, чтобы подать жалобу.");ComplaintPopup.open(this.$attrs.objType,this.$attrs.videoId,$event.currentTarget)}},{key:"makeYouTubeEmbed",value:function(sce){var holder=document.getElementById("holder"),frame=holder.getElementsByTagName("iframe")[0];frame.style.display="block",frame.src=sce.trustAsResourceUrl(this.prepareYoutubeUrl(this.$attrs.videoUrl)),holder.appendChild(frame)}},{key:"prepareYoutubeUrl",value:function(url){return url.replace("watch","embed").replace("?v=","/")}},{key:"undelete",value:function(){Utils.post("/ajax/video/delete/",{id:this.$attrs.videoId}).then(function(){return window.location=window.location})}},{key:"delete",value:function(){Utils.post("/ajax/video/delete/",{id:this.$attrs.videoId,action:"delete"}).then(function(){return window.location=window.location})}}]),ggVideo}()
10;angular.module("GG").controller("ggVideo",ggVideo)}(),function(){function ggVideoEditor($scope,$attrs){function onLoadData(data){data=angular.fromJson(data),vm.video=data.video,vm.saved=data.saved,vm.loaded=!0,vm.errors={title:!1,video:!1},vm.video.ggFile={key:"0"};for(var i=0;i<vm.video.files.length;i++)2==vm.video.files[i].server&&(vm.video.ggFile=vm.video.files[i]);void 0===vm.saved[vm.video.ggFile.key]&&"0"!=vm.video.ggFile.key&&(vm.saved[vm.video.ggFile.key]=" ? "+vm.video.ggFile.key),bindGames(),$scope.$applyAsync()}function bindGames(){new GamesAutoComplete($("#game-name"),function(title,elem,data){vm.video.game_id=data[1]},!0,!0)}function deletePreview(){vm.video.preview=!1}function validateData(){var errors=0,scrollTo=null;if(vm.errors={title:!1,video:!1},vm.video.url.trim()||(vm.errors.video=!0,scrollTo="video",errors++),vm.video.title.trim()||(vm.errors.title=!0,scrollTo="title",errors++),errors>0)return Utils.scrollToElement(angular.element("#"+scrollTo)),!1}function saveVideo(){validateData(),vm.loaded=!1,PageLoader.showLoader();var form=new FormData;form.append("video",videoId),form.append("data",angular.toJson(vm.video)),vm.$imgFile&&form.append("preview",vm.$imgFile),Utils.postForm("/ajax/video/"+videoId+"/save/",form).fail(function(e){PageLoader.hideLoader(),vm.loaded=!0,console.error(e)}).done(function(data){data.result&&PageLoader.go("/video/"+data.result)})}var vm=this,videoId=0;window.location.href.match(/.+video\/(\d+)\/edit\/?/gi)&&(videoId=window.location.href.replace(/.+video\/(\d+)\/edit\/?/gi,"$1")),function(){Utils.get("/ajax/video/"+videoId).then(onLoadData)}(),vm.deletePreview=deletePreview,vm.save=saveVideo,$scope.$watch("vm.video.ggFile.key",function(newValue,oldValue){"0"!=newValue&&void 0!=oldValue&&(vm.video.url="http://stream.goodgame.ru"+newValue)})}angular.module("GG").controller("ggVideoEditor",ggVideoEditor)}(),function($,angular){function ggBansModerationController($scope,$element,$window){function checkAccess(type){return!0}function getTemplate(event){return!!event&&"bans-"+event+".html"}function loadData(){var data={page:vm.page,filters:vm.filters};Utils.post(getUrl(),data).then(onLoadedData)}function onLoadedData(_data){var data=angular.fromJson(_data);angular.extend(vm,data),$window.history.pushState({path:"/moderation/bans/"+vm.tab+"/"},data.title,"/moderation/bans/"+vm.tab+"/"),$window.document.title=data.title}function changeTab(tab){vm.tab=tab,vm.page=1,vm.total=1,vm.filters=[],loadData()}function getUrl(){switch(vm.tab){default:case"site":return"/ajax/moderation/get/bans-site/";case"chat":return"/ajax/moderation/get/bans-chat/";case"warning":return"/ajax/moderation/get/bans-warning/"}}function deleteBan(type,ban){var id=void 0;id=2==type?parseInt(ban.Id):ban.id,Utils.post("/ajax/moderation/delete-ban/",{id:id,type:type}).then(loadData)}function submitFilter(){$element.find("input").map(function(key,value){vm.filters[$(value).attr("name")]=$(value).get(0).value}
10),loadData()}var pageTimeout,vm=this;vm.tab="site",vm.loading=!0,vm.page=1,vm.total=1,vm.filters=[],window.url(3)&&(vm.tab=window.url(3)),changeTab(vm.tab),vm.check=checkAccess,vm.template=getTemplate,vm.change=changeTab,vm.delete=deleteBan,vm.filter=submitFilter,$scope.$watch("vm.page",function(newValue,oldValue){oldValue&&newValue&&newValue!=oldValue&&(clearTimeout(pageTimeout),pageTimeout=setTimeout(loadData,150))})}angular.module("GG").controller("ggBansModerationCtrl",ggBansModerationController),ggBansModerationController.$inject=["$scope","$element","$window"]}($,angular),function($,angular){function ggClaimsModerationController($scope,$element,$rootScope,$window){function checkAccess(type){return UserService.checkAccess(type,$rootScope.rights)>0}function getTemplate(event){return!!event&&"claims-"+event+".html"}function loadData(){var data={page:vm.page,filters:vm.filters,mode:vm.mode};Utils.post(getUrl(),data).then(onLoadedData)}function onLoadedData(_data){var data=angular.fromJson(_data);angular.extend(vm,data),$window.history.pushState({path:"/moderation/claims/"+vm.tab+"/"},data.title,"/moderation/claims/"+vm.tab+"/"),$window.document.title=data.title}function changeTab(tab){vm.tab=tab,vm.page=1,vm.total=1,loadData()}function getUrl(){switch(vm.tab){default:case"users":return"/ajax/moderation/get/claims-users/";case"streams":return"/ajax/moderation/get/claims-streams/";case"clips":return"/ajax/moderation/get/claims-clips/";case"videos":return"/ajax/moderation/get/claims-videos/"}return alert("Не пойму какая вкладка"),"/ajax/moderation/get/claims-users/"}function makeViewed(claim){Utils.post("/ajax/moderation/make-viewed/",{id:claim.id}).then(loadData)}function changeView(){vm.mode=!vm.mode,vm.page=1,loadData()}function submitFilter(){$element.find("input").map(function(key,value){vm.filters[$(value).attr("name")]=$(value).get(0).value}),loadData()}var pageTimeout,vm=this;vm.tab="users",vm.loading=!0,vm.page=1,vm.total=1,vm.filters=[],vm.mode=!1,window.url(3)&&(vm.tab=window.url(3)),changeTab(vm.tab),vm.check=checkAccess,vm.template=getTemplate,vm.change=changeTab,vm.viewed=makeViewed,vm.changeView=changeView,vm.filter=submitFilter,$scope.$watch("vm.page",function(newValue,oldValue){oldValue&&newValue&&newValue!=oldValue&&(clearTimeout(pageTimeout),pageTimeout=setTimeout(loadData,150))})}angular.module("GG").controller("ggClaimsModerationCtrl",ggClaimsModerationController),ggClaimsModerationController.$inject=["$scope","$element","$rootScope","$window"]}($,angular),function(angular){function ggMaterialModerationController($scope){function onLoadData(_data){vm.materials=angular.fromJson(_data)}function publishMaterial(material){Utils.post("/ajax/moderation/publish/",{key:"1-"+material.id}).then(function(){PageLoader.reload()})}function deleteMaterial(material){confirm("Вы точно хотите удалить материал?")&&Utils.post("/ajax/moderation/delete/",{key:"1-"+material.id}).then(function(){PageLoader.reload()})}var vm=this;vm.publish=publishMaterial,vm.delete=deleteMaterial,function(){Utils.get("/ajax/moderation/get/materials/").then(onLoadData)}()}angular.module("GG").controller("ggMaterialModerationCtrl",ggMaterialModerationController),ggMaterialModerationController.$inject=["$scope"]}(angular),function(angular){function ggModerationController($scope,$attrs){function checkAccess(type){return UserService.checkAccess(type,mod.rights)>0}function getTemplate(event){return!!event&&event+".html"}function changeTab(tab){mod.tab=tab,window.history.pushState({path:"/moderation/"+mod.tab+"/"},"Админка","/moderation/"+mod.tab+"/")}var mod=this;mod.rights=$attrs.rights,mod.tab="claims",window.url(2)&&(mod.tab=window.url(2)),mod.check=checkAccess,mod.template=getTemplate,mod.change=changeTab}angular.module("GG").controller("ggModerationCtrl",ggModerationController),ggModerationController.$inject=["$scope","$attrs"]}(angular),function($,angular){function ggOtherModerationController($scope,$element,$rootScope,$window){function checkAccess(type){return UserService.checkAccess(type,$rootScope.rights)>0}function userHasRights(type,rights){return UserService.checkAccess(type,rights)>0}function getTemplate(event){return!!event&&"other-"+event+".html"}function loadData(){var data={page:vm.page,filters:vm.filters};Utils.post(getUrl(),data).then(onLoadedData)}function onLoadedData(_data){var data=angular.fromJson(_data);
10angular.extend(vm,data),query=window.url("query")?"?"+window.url("query"):"",$window.history.pushState({path:"/moderation/other/"+vm.tab+"/"+query},data.title,"/moderation/other/"+vm.tab+"/"+query),$window.document.title=data.title}function changeTab(tab){vm.tab=tab,vm.page=1,vm.total=1,loadData()}function getUrl(){switch(vm.tab){case"smurf":return"/ajax/moderation/get/other-smurf/";case"ratings":return"/ajax/moderation/get/other-ratings/?"+window.url("query");case"comments":return vm.modPanel=!0,"/ajax/moderation/get/other-comments/";case"users":return"/ajax/moderation/get/other-users/";case"ip":return"/ajax/moderation/get/other-ip/"}}function findSmurf(){vm.filters.user=vm.smurfUser,Utils.post("/ajax/moderation/get/other-smurf/",{filters:vm.filters}).then(onLoadedData)}function deleteSmurf(){Utils.post("/ajax/moderation/del-smurfs/",{user:vm.smurfUser}).then(function(){vm.data=[]})}function changeSmurf(user){var status=user.activated?"deactivate":"activate";Utils.post("/ajax/user/"+user.id+"/"+status+"/",{reason:1,other:""}).then(function(res){if(!res.success)return void alert("Что-то сломалось");user.activated=res.activated})}function submitFilter(){$element.find("input, select").map(function(key,value){vm.filters[$(value).attr("name")]=$(value).get(0).value}),loadData()}function updateComments(){vm.data={},vm.page=1,vm.total=1,loadData()}var query,pageTimeout,vm=this;vm.tab="smurf",vm.loading=!0,vm.page=1,vm.total=1,vm.filters=[],window.url(3)&&(vm.tab=window.url(3)),angular.extend(vm.filters,window.url("?")),vm.smurfUser=vm.filters.user||"",changeTab(vm.tab),vm.check=checkAccess,vm.userHasRights=userHasRights,vm.template=getTemplate,vm.change=changeTab,vm.filter=submitFilter,vm.deleteSmurf=deleteSmurf,vm.findSmurf=findSmurf,vm.changeSmurf=changeSmurf,vm.updateComments=updateComments,$scope.$watch("vm.page",function(newValue,oldValue){oldValue&&newValue&&newValue!=oldValue&&(clearTimeout(pageTimeout),pageTimeout=setTimeout(loadData,150))})}angular.module("GG").controller("ggOtherModerationCtrl",ggOtherModerationController),ggOtherModerationController.$inject=["$scope","$element","$rootScope","$window"]}($,angular),function($,angular){function SettingsModerationController($scope,$element,$window){function getTemplate(event){return!!event&&"settings-"+event+".html"}function changeTab(tab){vm.tab=tab,vm.page=1,vm.total=1,vm.filters=[],loadData()}function loadData(){vm.loading=!0;var data={page:vm.page,filters:vm.filters};Utils.post(getUrl(),data).then(onLoadedData)}function getUrl(){switch(vm.tab){default:case"alice":return"/ajax/moderation/get/settings-alice/";case"mails":return"/ajax/moderation/get/settings-mails/";case"subscription":return"/ajax/moderation/get/settings-subscription/";case"rights":return"/ajax/moderation/get/settings-rights/"}}function onLoadedData(_data){var data=angular.fromJson(_data);angular.extend(vm,data),$window.history.pushState({path:"/moderation/settings/"+vm.tab+"/"},data.title,"/moderation/settings/"+vm.tab+"/"),$window.document.title=data.title,vm.loading=!1}function submitFilter(){$element.find("input").map(function(key,value){vm.filters[$(value).attr("name")]=$(value).get(0).value}),loadData()}function editAliceRule(rule){Utils.get("/ajax/moderation/get/chat-rule/"+rule.id+"/").then(function(_data){angular.extend(vm.alice,angular.fromJson(_data))})}function addAliceRule(){Utils.post("/ajax/moderation/add-chat-rule/",vm.alice).then(loadData)}function clearAliceRule(){vm.alice={id:0,rule:"",duration:0,units:1,action:1}}function deleteAliceRule(rule){Utils.post("/ajax/mod/delete-chat-rule/",{id:rule.id}).then(loadData)}function resetAliceRules(){Utils.get("/ajax/moderation/reload-alice/")}function deleteMail(mail){Utils.post("/ajax/moderation/delete-mail/",{id:mail.id}).then(loadData)}function addMail(){Utils.post("/ajax/moderation/add-mail/",vm.mail).then(loadData)}function saveSubscriptions(){var data={mail:{users:vm.data.users_mail,streams:vm.data.streams_mail,video:vm.data.video_mail,clips:vm.data.clips_mail},notify:{users:vm.data.users_notify,streams:vm.data.streams_notify,video:vm.data.video_notify,clips:vm.data.clips_notify}};console.log(Utils.serialize(data)),Utils.post("/ajax/moderation/subscriptionclaims/",data).then(loadData)}function chatRightsAddAny(){var data=this.rights_any;Utils.post("/ajax/mod/make-chat-grant",data).then(function(d){d.ret?alert("Success"):alert(d.msg||"Неизвестная ошибка")})}function chatRightsAddStreamer(){var data=this.rights_streamer;Utils.post("/ajax/mod/check-chat-streamer-grant",data).then(function(data){if(data.err){var error=data.msg||"Неизвестная ошибка";throw alert(error),"Error "+error}if(!data.user)throw alert("Пользователь не найден :("),"User not found";if(!data.channel)throw alert("Канала у пользователя "+data.user+" нет :("),"Channel not found";var text="Это пользователь "+data.user+" с каналом "+data.channel.substr(0,32)+" ?";if(!confirm(text))throw"Cancel";return!0}).then(function(){return Utils.post("/ajax/mod/make-chat-streamer-grant",data)}).then(function(data){alert(data.err?"Error: "+data.msg:"Success!")}
10).catch(function(e){console.log(e)})}function chatRightsDeleteChatGrant(id){Utils.post("/ajax/mod/delete-chat-grant",{id:id}).then(function(data){console.log(data),alert("Ok")})}var pageTimeout,vm=this;vm.tab="alice",vm.loading=!0,vm.page=1,vm.total=1,vm.filters=[],window.url(3)&&(vm.tab=window.url(3)),vm.alice={id:0,rule:"",duration:0,units:1,action:1},vm.mail={id:0,value:""},vm.rights_any={},vm.rights_streamer={},changeTab(vm.tab),vm.template=getTemplate,vm.change=changeTab,vm.filter=submitFilter,vm.deleteAliceRule=deleteAliceRule,vm.addAliceRule=addAliceRule,vm.clearAliceRule=clearAliceRule,vm.editAliceRule=editAliceRule,vm.resetAliceRules=resetAliceRules,vm.deleteMail=deleteMail,vm.addMail=addMail,vm.saveSubs=saveSubscriptions,vm.chatRightsAddAny=chatRightsAddAny,vm.chatRightsAddStreamer=chatRightsAddStreamer,vm.chatRightsDeleteChatGrant=chatRightsDeleteChatGrant,$scope.$watch("vm.page",function(newValue,oldValue){oldValue&&newValue&&newValue!=oldValue&&(clearTimeout(pageTimeout),pageTimeout=setTimeout(loadData,150))})}angular.module("GG").controller("ggSettingsModerationCtrl",SettingsModerationController)}($,angular),function($,angular){function ggStreamsModerationController($scope,$element,$window){function checkAccess(type){return!0}function getTemplate(event){return!!event&&"streams-all.html"}function loadData(){var data={page:vm.page};Utils.post(getUrl(),data).then(onLoadedData)}function onLoadedData(_data){var data=angular.fromJson(_data);angular.extend(vm,data),$window.history.pushState({path:"/moderation/streams/"+vm.tab+"/"},data.title,"/moderation/streams/"+vm.tab+"/"),$window.document.title=data.title}function changeTab(tab){vm.tab=tab,vm.page=1,vm.total=1,vm.filters=[],loadData()}function getUrl(){switch(vm.tab){case"hidden":return"/ajax/moderation/get/streams-all/?hidden=1";case"all":return"/ajax/moderation/get/streams-all/"}}var pageTimeout,vm=this;vm.tab="all",vm.loading=!0,vm.page=1,vm.total=1,window.url(3)&&(vm.tab=window.url(3)),changeTab(vm.tab),vm.check=checkAccess,vm.template=getTemplate,vm.change=changeTab,$scope.$watch("vm.page",function(newValue,oldValue){oldValue&&newValue&&newValue!=oldValue&&(clearTimeout(pageTimeout),pageTimeout=setTimeout(loadData,150))})}angular.module("GG").controller("ggStreamsModerationCtrl",ggStreamsModerationController),ggStreamsModerationController.$inject=["$scope","$element","$window"]}($,angular),function(angular){var ggChatDonateAmount=function(){function ggChatDonateAmount($scope){_classCallCheck(this,ggChatDonateAmount),this.amount=0}return _createClass(ggChatDonateAmount,[{key:"limit",value:function(){this.amount=Math.min(999999,Math.max(10,this.amount))}},{key:"$onInit",value:function(){}},{key:"setAmount",value:function(n){this.amount=n,Utils.reachGoal("donate_preset_select")}}]),ggChatDonateAmount}();angular.module("GG").component("ggChatDonateAmount",{bindings:{amount:"="},templateUrl:"/html/donat/amount.html",controller:ggChatDonateAmount})}(angular),function(angular){var ggChatDonatePresentation=function(){function ggChatDonatePresentation(){_classCallCheck(this,ggChatDonatePresentation),this.visible=Utils.lsGet("hide-chat-donate-presentation-2",0)?0:1}return _createClass(ggChatDonatePresentation,[{key:"close",value:function(){this.visible=0,Utils.lsSet("hide-chat-donate-presentation-2",1)}}]),ggChatDonatePresentation}();angular.module("GG").component("ggChatDonatePresentation",{template:'\n                <div class="donate-help-block" ng-if="$ctrl.visible">\n                    <div class="title-block">\n                        <div class="title">Поддержка 2.0</div>\n                        <div class="icon icon-close2 close" ng-click="$ctrl.close()"></div>\n                    </div>\n                    <ul class="benefits-list">\n                        <li>- Новый интерфейс не отвлекает от просмотра стрима</li>\n                        <li>- Поддержка в 2 клика</li>\n                        <li>- Возможность прикрепить голосовое сообщение</li>\n                    </ul>\n                </div>\n            ',controller:ggChatDonatePresentation})}(angular),function(angular){var ggChatCustomDonateCtrl=function(){function ggChatCustomDonateCtrl(){_classCallCheck(this,ggChatCustomDonateCtrl),this.channelId=0,this.currentButton=!1,this.loading=!0,this.error=!1}return _createClass(ggChatCustomDonateCtrl,[{key:"$onInit",value:function(){var _this53=this;Utils.get("/ajax/payment/2/donate/",{channelId:this.channelId}).then(function(data){_this53.data=data,_this53.loading=!1,data.cards.length<1&&(_this53.error=!0),_this53.card=data.cards[0].bindingId,console.log(data)})}},{key:"title",value:function(button){return this.getButton(button).key}},{key:"price",value:function(button){var btn=this.getButton(button);return"number"==typeof btn.value&&btn.value}},{key:"getButton",value:function(button){for(var key in button)return{key:key,value:button[key]}}},{key:"process",value:function(button){var btn=this.getButton(button);if("number"!=typeof btn.value)return void(this.currentButton=btn.value);this.payWithCard(btn.value)}},{key:"payWithCard",value:function(amount){var _this54=this;if(this.loading)return!1;this.loading=!0,Utils.post("/ajax/payment/2/card/pay/",{card:this.card,cvc:"pass",amount:amount,message:"",streamer:this.data.streamer.id}).then(function(data){_this54.loading=!1,_this54.showDonate=!1,console.log(data)}).catch(function(e){console.log(e),_this54.loading=!1})}},{key:"reset",value:function(){this.currentButton=!1}},{key:"close",value:function(){this.showDonate=!1}}]),ggChatCustomDonateCtrl}();angular.module("GG").component("ggChatCustomDonate",{bindings:{showDonate:"=",channelId:"=",buttons:"="},templateUrl:"/html/donat/custom-donate.html?v=1",controller:ggChatCustomDonateCtrl,controllerAs:"donate"})}(angular),function(angular){var ggChatDonateCtrl=function(){function ggChatDonateCtrl(){_classCallCheck(this,ggChatDonateCtrl),this.showHelp=!1,this.channelId=0,this.data=!1;var match=void 0;(match=window.location.href.match(new RegExp(/\/support\/(\d+)/)))?this.amount=parseInt(match[1]):this.amount=Utils.lsGet("chat-donat-amount",50),this.$state={component:"method",data:{},title:"Поддержка стримера"}}return _createClass(ggChatDonateCtrl,[{key:"$onInit",value:function(){var _this55=this;Utils.reachGoal("donate_showed"),Utils.get("/ajax/payment/2/donate/",{channelId:this.channelId}
10).then(function(data){_this55.data=data,_this55.$state.title="Поддержка "+data.streamer.nickname})}},{key:"close",value:function(){this.showDonate=!1}}]),ggChatDonateCtrl}();angular.module("GG").component("ggChatDonate",{bindings:{showDonate:"=",standalone:"=",channelId:"="},templateUrl:"/html/donat/donate.html",controller:ggChatDonateCtrl,controllerAs:"donate"})}(angular),function(angular){var ggChatDonateHelp=function(){function ggChatDonateHelp(){_classCallCheck(this,ggChatDonateHelp)}return _createClass(ggChatDonateHelp,[{key:"$onInit",value:function(){Utils.reachGoal("donate_rewards_click")}},{key:"hasSmile",value:function(level){return this.channel&&Global.Channel_Smiles[this.channel.id].filter(function(s){return s.donat==level}).length}}]),ggChatDonateHelp}();angular.module("GG").component("ggChatDonateHelp",{bindings:{channel:"=",level:"="},templateUrl:"/html/donat/help.html",controller:ggChatDonateHelp})}(angular),function(angular){var ggChatDonateMessage=function(){function ggChatDonateMessage(){_classCallCheck(this,ggChatDonateMessage),this.limit=280,this.disabled=!1,this.message=this.messageOld="",this.placeholder="Ты лучший стример <3",this.placeholderDisabled="При отправке голосового сообщения текст отправлен не будет"}return _createClass(ggChatDonateMessage,[{key:"$onInit",value:function(){}},{key:"isDisabled",value:function(){return this.disabled?(this.message&&(this.messageOld=this.message),this.message=""):!this.message&&this.messageOld&&(this.message=this.messageOld,this.messageOld=""),this.disabled}}]),ggChatDonateMessage}();angular.module("GG").component("ggChatDonateMessage",{bindings:{message:"=",disabled:"="},templateUrl:"/html/donat/message.html",controller:ggChatDonateMessage})}(angular),function(angular){var ggChatDonateMethod=function(){function ggChatDonateMethod(){_classCallCheck(this,ggChatDonateMethod),this.payType=0}return _createClass(ggChatDonateMethod,[{key:"$onInit",value:function(){}}]),ggChatDonateMethod}();angular.module("GG").component("ggChatDonateMethod",{bindings:{},require:{donate:"^ggChatDonate"},templateUrl:"/html/donat/method.html",controller:ggChatDonateMethod})}(angular),function(angular){var ggChatDonatePayCard=function(){function ggChatDonatePayCard($scope,$sce){var _this56=this;_classCallCheck(this,ggChatDonatePayCard),this.$scope=$scope,this.$sce=$sce,this.$popup=!1,this.card=Utils.lsGet("chat-donat-provider","0"),this.newCard=0,this.loading=!0,this.amount=0,this.message="",this.anonym=0,this.sign="",this.cvc="",this.wallet=0,this.waiting=!1,this.messageType="text",this.audioBlob=!1,this.textMessageAmount=30,this.voiceMessageAmount=300,this.voiceMessageEnabled=!1,$scope.$watch(function(){return _this56.donate.data.cards},function(a){return a&&_this56.onLoad()}),$scope.$watch(function(){return _this56.amount},function(a){return a&&_this56.onAmountChange()}),window.iframeCallback=function(result,error){return _this56.onIframeCallback(result,error)}}return _createClass(ggChatDonatePayCard,[{key:"onAmountChange",value:function(){this.amount<this.voiceMessageAmount&&(this.messageType="text")}},{key:"onLoad",value:function(){this.loading=!1,this.cards=this.parseCards(this.donate.data.cards),this.wallet=this.donate.data.ggwallet||!1,this.voiceMessageAmount=parseInt(this.donate.data.settings.voiceMessageAmount),this.voiceMessageEnabled=!!this.donate.data.settings.voiceMessage}},{key:"parseCards",value:function(cards){var mask=new RegExp(/(\d{4})(\d{2})\*{2}(\d{4})/);return cards.map(function(card){return card.maskedPan=card.maskedPan.replace(mask,"$1 $2** **** $3"),card})}},{key:"isCard",value:function(n){return!/^\d+$/.test(n)||"0"==n}},{key:"pay",value:function(){var _this57=this;return Utils.lsSet("chat-donat-amount",this.amount),Utils.lsSet("chat-donat-provider",this.card),this.isCard(this.card)?"0"==this.card||parseInt(this.cvc)?void(this.loading||(this.loading=!0,Promise.resolve().then(function(){return"voice"==_this57.messageType&&_this57.uploadVoiceMessage()}).then(function(voice){return Utils.post("/ajax/payment/2/card/pay/",{card:"0"!=_this57.card?_this57.card:0,cvc:_this57.cvc,amount:_this57.amount,message:_this57.message||"",sign:_this57.sign,anonym:_this57.anonym?1:0,streamer:_this57.donate.data.streamer.id,voice:voice||""})}).then(function(data){if(_this57.loading=!1,data.url)return _this57.newCard=1,void(_this57.iframeUrl=_this57.$sce.trustAsResourceUrl(data.url));_this57.donate.$state.component="result",_this57.donate.$state.success=!!data.success}).catch(function(e){"novoicedata"==e&&alert("Запишите сообщение"),console.log(e),_this57.waiting=!1,_this57.loading=!1}))):void alert("Введите CVC"):this.payOther()}},{key:"payOther",value:function(){var _this58=this;6!=this.card&&(this.$popup=window.open("about:blank","_blank","width=810,height=610,toolbar=no,scrollbars=yes,resizable=yes"),window.focus(),this.setPollInterval()),this.waiting||(this.waiting=!0,this.message&&Utils.reachGoal("donate_message_added"),"voice"==this.messageType&&Utils.reachGoal("donate_voice_added"),Promise.resolve().then(function(){return"voice"==_this58.messageType&&_this58.uploadVoiceMessage()}).then(function(voice){return Utils.post("/ajax/payment/2/other/pay/",{provider:_this58.card,amount:_this58.amount,message:_this58.message||"",sign:_this58.sign,anonym:_this58.anonym?1:0,streamer:_this58.donate.data.streamer.id,voice:voice||""})}).then(function(data){6==_this58.card?_this58.iframeUrl=_this58.$sce.trustAsResourceUrl(data.url):(_this58.$popup.location.href=data.url,_this58.$popup.focus())}).catch(function(e){"novoicedata"==e&&alert("Запишите сообщение"),console.log(e),_this58.waiting=!1}))}},{key:"setPollInterval",value:function(){var _this59=this,pollTimer=setInterval(function(){if(!_this59.$popup)return void clearInterval(pollTimer);!1!==_this59.$popup.closed&&(clearInterval(pollTimer),_this59.onIframeCallback(!1))},200)}},{key:"onIframeCallback",value:function(result,error){this.$popup=!1,"back"==error?(this.waiting=!1,this.iframeUrl="",this.newCard=0):(this.donate.$state.component="result",this.donate.$state.success=!!result),this.$scope.$applyAsync()}}
10,{key:"deleteCard",value:function(cardId){var _this60=this;this.loading=!0,this.cards=null,Utils.post("/ajax/payment/2/card/delete/",{id:cardId}).then(function(data){_this60.donate.data.cards=data.cards})}}]),ggChatDonatePayCard}();angular.module("GG").component("ggChatDonatePayCard",{bindings:{payType:"=",amount:"=",message:"=",state:"="},require:{donate:"^ggChatDonate"},templateUrl:"/html/donat/pay-card.html",controller:ggChatDonatePayCard})}(angular),function(angular){var ggChatDonateRecord=function(){function ggChatDonateRecord($scope){var _this61=this;_classCallCheck(this,ggChatDonateRecord),this.progress=0,this.$scope=$scope,this.recorder=null,this.meter=null,this.player=null,this.volume=.5,this.started=null,this.timeLimit=7e3,this.timeRecorded=0,this.blobUrl="",this.blob=!1,this._interval=setInterval(function(){return _this61.onProgress()},60)}return _createClass(ggChatDonateRecord,[{key:"$onDestroy",value:function(){clearInterval(this._interval)}},{key:"onProgress",value:function(){if("recording"==this.status&&(this.progress=Math.min(100,100*(Date.now()-this.started)/this.timeLimit),this.meter&&(this.volume=Math.min(1,Math.pow(Math.abs(this.meter.volume),.25))),this.$scope.$applyAsync()),"playing"==this.status){var duration=this.player.duration==1/0?this.timeRecorded:this.player.duration;this.progress=Math.min(100,100*this.player.currentTime/duration),this.$scope.$applyAsync()}}},{key:"startRecord",value:function(){var _this62=this;navigator.mediaDevices.getUserMedia({audio:!0}).then(function(stream){_this62.blobUrl="",_this62.timeRecorded=0,_this62.player=null,_this62.recorder=new MediaRecorder(stream),_this62.recorder.start(1e3),_this62.started=Date.now();var audioChunks=[];_this62.meter=new VolumeMeter(stream),_this62.recorder.ondataavailable=function(e){audioChunks.push(e.data),Date.now()-_this62.started>=_this62.timeLimit&&"recording"==_this62.recorder.state&&_this62.recorder.stop(),"inactive"!=_this62.recorder.state||_this62.blobUrl||(_this62.blob=new Blob(audioChunks,{type:"audio/x-mpeg-3"}),_this62.blobUrl=URL.createObjectURL(_this62.blob),_this62.timeRecorded=(Date.now()-_this62.started)/1e3,stream.getAudioTracks()[0].stop(),_this62.$scope.$applyAsync())}}).catch(function(e){console.log(e)})}},{key:"play",value:function(){var _this63=this;this.player=new Audio,this.player.src=this.blobUrl,this.player.play(),this.player.addEventListener("ended",function(e){_this63.progress=0,_this63.$scope.$applyAsync()})}},{key:"stop",value:function(){"recording"==this.status&&this.recorder.stop(),"playing"==this.status&&(this.player.pause(),this.player.currentTime=0),this.progress=0}},{key:"delete",value:function(){this.blobUrl="",this.progress=0,this.timeRecorded=0,this.meter.shutdown(),this.player&&(this.player.pause(),this.player=null)}},{key:"$onInit",value:function(){}},{key:"status",set:function(value){},get:function(){return this.blobUrl?this.player&&!this.player.paused?"playing":"full":this.recorder&&"recording"==this.recorder.state?"recording":"empty"}}]),ggChatDonateRecord}();angular.module("GG").component("ggChatDonateRecord",{bindings:{progress:"=",status:"=?",blob:"=?"},templateUrl:"/html/donat/record.html",controller:ggChatDonateRecord})}(angular),function(angular){var ggChatDonateResult=function(){function ggChatDonateResult(){_classCallCheck(this,ggChatDonateResult)}return _createClass(ggChatDonateResult,[{key:"$onInit",value:function(){this.donate.$state.success?Utils.reachGoal("donate_pay"):this.donate.$state.title="Ошибка операции"}},{key:"restart",value:function(){Utils.reachGoal("donate_repeat"),this.donate.$state.component="method",this.donate.$state.title="Поддержка стримера"}}]),ggChatDonateResult}();angular.module("GG").component("ggChatDonateResult",{bindings:{},require:{donate:"^ggChatDonate"},templateUrl:"/html/donat/result.html",controller:ggChatDonateResult})}(angular),function(angular){var ggChatDonateVoiceMessage=function(){function ggChatDonateVoiceMessage(){_classCallCheck(this,ggChatDonateVoiceMessage),this.progress=0,this.blob=!1}return _createClass(ggChatDonateVoiceMessage,[{key:"$onChanges",value:function(){}},{key:"uploadMessage",value:function(){if(!this.blob)return Promise.reject("novoicedata");var formData=new FormData;return formData.append("aud",this.blob,"filename"),Utils.postForm("https://storage2.goodgame.ru/audup.php",formData).then(function(data){if("ok"==data.status)return data.id;throw new Error("Voice message uploading error")})}},{key:"$onInit",value:function(){var _this64=this;this.upload=function(){return _this64.uploadMessage()}}}]),ggChatDonateVoiceMessage}();angular.module("GG").component("ggChatDonateVoiceMessage",{bindings:{upload:"="},templateUrl:"/html/donat/voice-message.html",controller:ggChatDonateVoiceMessage})}(angular);var VolumeMeter=function(){function VolumeMeter(stream,averaging){var _this65=this;_classCallCheck(this,VolumeMeter);var audioContext=new AudioContext,mediaStreamSource=audioContext.createMediaStreamSource(stream),processor=audioContext.createScriptProcessor(512);processor.onaudioprocess=function(e){return _this65.volumeAudioProcess(e)},this.volume=.1,this.averaging=averaging||.8,processor.connect(audioContext.destination),this.shutdown=function(){processor.disconnect(),processor.onaudioprocess=null,audioContext.close()},mediaStreamSource.connect(processor)}return _createClass(VolumeMeter,[{key:"volumeAudioProcess",value:function(event){for(var x,buf=event.inputBuffer.getChannelData(0),bufLength=buf.length,sum=0,i=0;i<bufLength;i++)x=buf[i],sum+=x*x;var rms=Math.sqrt(sum/bufLength);this.volume=Math.max(rms,this.volume*this.averaging)}}]),VolumeMeter}();!function(angular){angular.module("GG").directive("dialogInput",function(Sm
10ilesService,$compile,$timeout){function dialogInput(scope,element,attrs,controller){function listenSearchInputForTab(){try{var smileSearch=document.getElementById("smile-search"),eventTabHandler=function eventTabHandler(event){"Tab"===event.key&&(scope.dialogs.viewSmiles=!1,smileSearch.removeEventListener("keydown",eventTabHandler),setTimeout(function(){return input.focus()},100))};smileSearch.addEventListener("keydown",eventTabHandler)}catch(e){console.error("ERROR WHILE SETTING LISTENER TO SMILES SEARCH",e)}}function pasteSmile(smile){var range=htmlPaste.getRange();range&&$(range.startContainer).closest(input).length||htmlPaste.toEnd(),input.focus(),htmlPaste.pasteCode('<smile contenteditable="false" name="'+smile.name+'"></smile>'),htmlPaste.pasteCode("&nbsp;"),scope.dialogs.viewSmiles=!1,$compile(element.contents())(scope),SmilesService.pushToStats(smile.name)}var input=element;scope.dialogs.pasteSmile=pasteSmile,function(){input.on("keydown",function(event){33!=event.which&&34!=event.which||event.preventDefault(),8==event.which&&(input.html().length<=1||0==input.text().length&&input.find("*").length<=1)&&(input.html(""),event.preventDefault()),9==event.which&&(event.preventDefault(),scope.dialogs.viewSmiles=!scope.dialogs.viewSmiles,scope.dialogs.viewSmiles&&listenSearchInputForTab()),scope.$apply()}).on("keypress",function(event){
11if(8!=event.keyCode&&input.text().length>512&&event.preventDefault(),scope.dialogs.typingEvent(),13==event.keyCode){if(!UserService.id)return event.preventDefault(),void scope.$root.showLogin("Авторизуйтесь, чтобы была возможность вести диалог.");cleanHtml(input,!0);var tmp=angular.element("<div></div>").html(input.html());cleanHtml(tmp,!1);var re=new RegExp(String.fromCharCode(160),"g"),msg=tmp.text().replace(re," ").replace(/\s{2,}/g," ").replace(/\n/g," ");if(!msg.trim())return!1;scope.dialogs.sendMessage(msg),input.html(""),event.preventDefault()}}).on("paste",function(event){event.preventDefault();var clipboardData=event.originalEvent.clipboardData||window.clipboardData,pastedData=clipboardData.getData("text");htmlPaste.pasteCode(pastedData)})}();var htmlPaste=new HtmlPaste(input),cleanHtml=function cleanHtml(elem,leaveSmiles){elem.find("*").each(function(ind,item){if(3!=this.nodeType){var $item=$(item);if("SMILE"==$item.prop("tagName"))return void $item.replaceWith($item.find(".smile"));$item.hasClass("smile")?leaveSmiles?$item.removeAttr("style"):$item.replaceWith($item.attr("tooltip")):cleanHtml($item,leaveSmiles)}})}}return{restrict:"A",link:dialogInput}})}(angular),function(){function DialogsController($scope,SmilesService,$compile){function updateFeed(event){"dialogMessage"==event.type&&(event.defaultPrevented=!0)}function loadMoreDialogs(){Utils.get("/ajax/dialogs/get",{from:dialogs.list.length}).then(onLoadDialogs)}function loadDialogs(){Utils.get("/ajax/dialogs/get").then(onLoadDialogs)}function onLoadDialogs(data){data=angular.fromJson(data),dialogs.loaded=!0,dialogs.list=data.list,dialogs.total=data.total,UserService.dialogs=data.unread,$scope.$apply()}function loadMoreMessages(){Utils.get("/ajax/dialogs/"+dialogs.current.user.id,{from:dialogs.current.length}).then(onLoadDialog)}function loadDialog(){dialogs.loaded=!1,Utils.get("/ajax/dialogs/"+dialogs.current.user.id).then(onLoadDialog)}function onLoadDialog(_data){var data=angular.fromJson(_data);if(dialogs.loaded=!0,data.success){var list=data.messages;angular.merge(dialogs.current,data.dialog);for(var dates={},i=0;i<list.length;i++)if(list[i].text){var date=Utils.toUserTimezoneDate(1e3*list[i].ei_created);date.setHours(0,0,0,0),date=Utils.toUTCDate(date),dates[+date]||(dates[+date]={}),dates[+date][list[i].id]=list[i]}dialogs.current.length=list.length,dialogs.current.total=data.total,dialogs.current.typing=!1,dialogs.current.ignore=data.ignore,dialogs.current.banned=data.banned||!1,dialogs.current.list||(dialogs.current.list={}),angular.merge(dialogs.current.list,dates),dialogs.sendText="",UserService.dialogs=data.unread}else data.ignore?dialogs.current.ignore.ignored=!0:data.banned&&(dialogs.current.banned=!0);$scope.$apply()}function sendMessage(msg){Utils.post("/ajax/dialogs/"+dialogs.current.user.id+"/send",{text:msg}).then(onLoadDialog)}function typingEvent(){lastSend||(NotifyProxy.ask("sendEvent",["private:9:"+dialogs.current.user.id,{type:"typing",from:UserService.id}]),lastSend=setTimeout(function(){return lastSend=0},3e3))}function ignoreAction(){Utils.post("/ajax/dialogs/"+dialogs.current.user.id+"/ignore/",{action:!dialogs.current.ignore.ignore}).then(function(_data){angular.fromJson(_data).success&&(dialogs.current.ignore.ignore=!dialogs.current.ignore.ignore)})}function dialogDelete($event,d){dialogs.loaded=!1,d.deleted=!0,console.log(dialogs),Utils.post("/ajax/dialogs/delete/",{dialog:d.id}).then(function(){return dialogs.loaded=!0}),$event.preventDefault(),$event.stopPropagation()}function dialogUnDelete($event,d){dialogs.loaded=!1,d.deleted=!1,Utils.post("/ajax/dialogs/undelete/",{dialog:d.id}).then(function(){return dialogs.loaded=!0}),$event.preventDefault(),$event.stopPropagation()}function dialogDeleteMessage($event,dm){dialogs.loaded=!1,dm.deleted=!0,Utils.post("/ajax/dialogs/delete_message/",{dialog:dm.dialog,message:dm.id}).then(function(){return dialogs.loaded=!0}),$event.preventDefault(),$event.stopPropagation()}function dialogUndeleteMessage($event,dm){dialogs.loaded=!1,dm.deleted=!1,Utils.post("/ajax/dialogs/undelete_message/",{dialog:dm.dialog,message:dm.id}).then(function(){return dialogs.loaded=!0}),$event.preventDefault(),$event.stopPropagation()}var dialogs=this;dialogs.loaded=!1,dialogs.sendMessage=sendMessage,dialogs.smilesService=SmilesService,dialogs.typingEvent=typingEvent,dialogs.ignoreAction=ignoreAction,dialogs.loadMoreDialogs=loadMoreDialogs,dialogs.loadMoreMessages=loadMoreMessages,dialogs.dialogDelete=dialogDelete,dialogs.dialogUnDelete=dialogUnDelete,dialogs.dialogDeleteMessage=dialogDeleteMessage,dialogs.dialogUndeleteMessage=dialogUndeleteMessage,$scope.$watch("dialogs.current",function(){void 0===dialogs.current&&$scope.feed.currentDialog&&(dialogs.current=$scope.feed.currentDialog),dialogs.current&&dialogs.current.user?loadDialog():(dialogs.list||(dialogs.loaded=!1),loadDialogs()),$scope.feed&&($scope.feed.currentDialog=dialogs.current)}),$scope.$watch("feed.currentDialog",function(){$scope.feed.currentDialog!==dialogs.current&&(dialogs.current=$scope.feed.currentDialog)}),$scope.$on("$destroy",function(){NotifyProxy.off("update_feed",updateFeed)}),NotifyProxy.on("update_feed",updateFeed),NotifyProxy.on("object_event",function(data){"dialogMessage"==data.type&&(dialogs.current&&data.from==dialogs.current.user.id?loadDialog():loadDialogs(),UserService.dialogs=data.total),"typing"==data.type&&(dialogs.current&&data.from==dialogs.current.user.id?(clearTimeout(dialogs.current.typing),dialogs.current.typing=setTimeout(function(){return dialogs.current.typing=0},5e3)):dialogs.list.forEach(function(dialog){dialog.user.id==data.from&&(clearTimeout(dialog.typing),dialog.typing=setTimeout(function(){return dialog.typing=0},5e3))}))});var lastSend=0}angular.module("GG").controller("ggDialogsCtrl",DialogsController),DialogsController.$inject=["$scope","SmilesService","$compile"]}(),function(angular){angular.module("GG").directive("dialogMessages",function(){function dialogMessages($scope,element){function scrollDown(newValue,oldValue){if(oldValue&&content[0].scrollTop<100){var oldHeigth=content[0].scrollHeight;setTimeout(function(){var diff=content[0].scrollHeight-oldHeigth;diff&&(content[0].scrollTop=diff)},0)}else setTimeout(function(){var value=content[0].scrollHeight-content[0].clientHeight,diff=value-content[0].scrollTop;content.stop().animate({scrollTop:value},diff>300?0:330,"linear")},0)}var content=element.find(".tse-scroll-content");content.length||(content=element.find(".tse-scrollable")),$scope.$watch("dialogs.current.list",scrollDown,!0)}return{restrict:"A",link:dialogMessages}})}(angular),function(){function BroadcastsController(){function togglePremiumBroadcasts(){vm.onlyPremiumBroadcasts=!vm.onlyPremiumBroadcasts,Utils.lsSet("remember_broadcasts_tab",+vm.onlyPremiumBroadcasts)}var vm=this;vm.broadcasts=[],vm.allBroadcasts={},vm.premiumBroadcasts={},vm.onlyPremiumBroadcasts=0,vm.hasPremiums=!1,vm.togglePremiumBroadcasts=togglePremiumBroadcasts,function(){vm.broadcasts=MainPage.moduleBroadcastsInitValues?MainPage.moduleBroadcastsInitValues:[],vm.onlyPremiumBroadcasts=parseInt(Utils.lsGet("remember_broadcasts_tab",0)),vm.broadcasts.forEac
11h(function(item){var day=Utils.toUserTimezoneDate(1e3*item.date_utc);day.setHours(0,0,0,0),day=Utils.toUTCDate(day),day=day.getTime()/1e3,void 0===vm.allBroadcasts[day]&&(vm.allBroadcasts[day]=[]),vm.allBroadcasts[day].push(item),"1"==item.premium&&(void 0===vm.premiumBroadcasts[day]&&(vm.premiumBroadcasts[day]=[]),vm.premiumBroadcasts[day].push(item),vm.hasPremiums=!0)})}(),vm.onBroadcastClick=function(broadcast){console.log(broadcast),Utils.reachGoal("scheduled_block_stream_click")}}angular.module("GG").component("ggBroadcastsModule",{controller:BroadcastsController,controllerAs:"module",template:'\n           <div class="broadcasts-block">\n            <h2><a>Скоро в эфире</a></h2>\n            <div class="filter-block" ng-if="module.hasPremiums">\n                <a href="" ng-click="module.togglePremiumBroadcasts()" class="icon-star" ng-class="{active: module.onlyPremiumBroadcasts == 1}">\n                    <svg width="16px" height="16px" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n                        <g id="Page-1" stroke="none" stroke-width="1" fill-rule="evenodd">\n                            <g id="adaptive-landing-1920" transform="translate(-1533.000000, -2089.000000)" stroke-width="2" stroke="#FFF">\n                                <g id="Анонсы" transform="translate(1273.000000, 2059.000000)">\n                                    <polygon id="star-empty" points="270 45 265.297718 47.472136 266.195774 42.236068 262.391548 38.527864 267.648859 37.763932 270 33 272.351141 37.763932 277.608452 38.527864 273.804226 42.236068 274.702282 47.472136 "></polygon>\n                                </g>\n                            </g>\n                        </g>\n                    </svg>\n                    <span class="tip">Только премиум</span>\n                </a>\n            </div>\n            <div ng-repeat="(day, dayBroadcasts) in module.allBroadcasts" ng-show="module.onlyPremiumBroadcasts == 0">\n                <div class="day">\n                    <div class="day-date"><gg-local-time utc-timestamp="{{ day }}" format="3" /></div>\n                    <div class="broadcasts">\n                        <div class="broadcast" ng-repeat="broadcast in dayBroadcasts">\n                            <a title="{{ broadcast.game }}" href="{{ broadcast.link }}" ng-click="module.onBroadcastClick(broadcast)"></a>\n\n                            \x3c!-- TODO: класс live появляется в дате только если трансляция идет в данный момент ( и написано LIVE ) --\x3e\n                            <div class="date pull-left"><gg-local-time utc-timestamp="{{ broadcast.date_utc }}" format="HH:mm"/></div>\n\n                            <div class="ov">\n                                <div class="status-block">\n                                    <span class="icon icon-star" ng-show="broadcast.premium == \'1\'" />\n                                </div>\n                                <span class="streamer">{{ broadcast.streamer }}</span>\n                                <div class="game">{{ broadcast.game }}</div>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n            </div>\n            <div ng-repeat="(day, dayBroadcasts) in module.premiumBroadcasts" ng-show="module.onlyPremiumBroadcasts == 1">\n                <div class="day">\n                    <div class="day-date"><gg-local-time utc-timestamp="{{ day }}" format="3" /></div>\n                    <div class="broadcasts">\n                        <div class="broadcast" ng-repeat="broadcast in dayBroadcasts">\n                            <a title="{{ broadcast.game }}" href="{{ broadcast.link }}" ng-click="module.onBroadcastClick(broadcast)"></a>\n\n                            \x3c!-- TODO: класс live появляется в дате только если трансляция идет в данный момент ( и написано LIVE ) --\x3e\n                            <div class="date pull-left"><gg-local-time utc-timestamp="{{ broadcast.date_utc }}" format="HH:mm"/></div>\n\n                            <div class="ov">\n                                <div class="status-block">
11\n                                    <span class="icon icon-star" ng-show="broadcast.premium == \'1\'" />\n                                </div>\n                                <span class="streamer">{{ broadcast.streamer }}</span>\n                                <div class="game">{{ broadcast.game }}</div>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n            </div>\n        </div>\n            ',bindings:{}})}(),function(angular){function CupsController($scope,$window,$timeout,api,DateFunctions){function init(){if(!vm.cups||vm.cups[0]&&"object"==_typeof(vm.cups[0].start))return!1;for(var i=0;i<vm.cups.length;i++){var cup=vm.cups[i];cup.start=new Date(1e3*cup.start),cup.mine="0"!=cup.mine}vm.smallBlock=vm.cups.length>=7&&vm.cups.length<=8}function joinCup(cup){if(0==UserService.id)return void LoginPopup.open("Авторизуйтесь, чтобы принять участие в турнире");1==cup.participants_type?!1===cup.mine?api.join(cup.id).then(function(data){cup.mine=!0,setStatus(cup,"Вы участвуете в турнире")}):api.unjoin(cup.id).then(function(){cup.mine=!1,setStatus(cup,"Вы отказались от участия")}):PageLoader.go("/cup/"+cup.id+"/join/")}function setStatus(cup,text){cup.statusText=text,cup.showStatus=!0,$timeout(function(){cup.showStatus=!1},2e3)}function timeLeft(cup){cup.start.indexOf&&-1!=cup.start.indexOf("-")&&(cup.start=Utils.parseMysqlDate(cup.start));var start=cup.start,d=+start-Date.now();return cup.showJoin=d>0&&!cup.started,d<0&&!cup.closed?"Уже идет":d<0||d>216e5?DateFunctions.formatDate(start):Utils.timeLeft(d,0)}var _this66=this,vm=this;vm.cups=$window.MainPage&&$window.MainPage.Cups&&$window.MainPage.Cups.old||[],vm.Math=$window.Math,vm.join=joinCup,vm.setStatus=setStatus,vm.timeLeft=timeLeft,vm.formatDate=DateFunctions.formatDate,init(),$scope.$watch("data",function(){_this66.data&&_this66.data.length&&(vm.cups=_this66.data,init())})}angular.module("GG").component("ggCupsModule",{controller:CupsController,controllerAs:"$ctrl",template:'\n            <div class="tournaments-block">\n                <h2><a href="/cup/">Открытые турниры</a></h2>\n                <div class="tournaments-list">\n                    <div class="tournament {{ c.game || \'rnd\' }}" ng-repeat="c in $ctrl.cups">\n                        <div class="stripe-block">\n                            <a href="/cup/{{ c.id }}/"></a>\n                            <div class="icon"></div>\n                            <div class="name" title="{{ c.title }}">{{ c.title }}</div>\n                            <svg class="flag" width="30px" height="30px" viewBox="0 0 30 30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n                                <g id="Page-1" stroke="none" stroke-width="1" fill-rule="evenodd">\n                                    <g id="tournament-block" transform="translate(-378.000000, -78.000000)">\n                                        <path d="M388,93 L378,78 L398,78 L398,101 L399,102 C399,102 405.111996,104.619427 408,106 C408.009521,106.863281 408.009521,108 408.009521,108 L378,108 L388,93 Z" id="flag" sketch:type="MSShapeGroup" transform="translate(393.004761, 93.000000) scale(-1, 1) translate(-393.004761, -93.000000) "></path>\n                                    </g>\n                                </g>\n                            </svg>\n                        </div>\n                        <div class="info-block" ng-class="{status: c.showStatus}">\n\n                            <div class="text-block">\n                                <div class="date">{{ $ctrl.timeLeft(c) }}</div>\n                                <div class="prize" ng-if="c.id != 6761">{{ $ctrl.Math.floor(c.prize_fund) }} <span class="rub-sign">Р</span></div>\n                                <div class="prize" ng-if="c.id == 6761">{{ c.prize_fund }}</div>\n                            </div>\n\n                            <div class="status-block">\n                                <div class="status">{{ c.statusText }}</div>\n                            </div>\n\n                            <div class="participate-block" ng-class="{participate: c.mine}" ng-if="c.showJoin" ng-click="$ctrl.join(c)">
11\n                                <span class="participant-block">\n                                    <span class="current">{{ c.participants }}</span>\n                                    <span class="top">{{ c.participants + 1 }}</span>\n                                </span>\n                                <img class="play-hover" src="/images/svg/play-tourney-hover.svg" alt="">\n                                <svg class="play" width="28px" height="28px" viewBox="0 0 28 28" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n                                    <g id="Page-1" stroke="none" stroke-width="1" fill-rule="evenodd">\n                                        <g id="tournament-block" transform="translate(-197.000000, -80.000000)">\n                                            <path d="M206.324423,94.952678 L203.384289,97.8928113 L202.684258,97.1927796 L200.920178,98.9288583 L202.600254,100.608934 L198.652075,104.557114 L197.868039,103.773078 L197.504023,104.137094 L198.008046,104.641117 L197.560025,105.089138 L198.064048,105.59316 C197.784036,105.621162 197.67203,105.59316 197.308014,105.957177 C196.971999,106.293192 196.831992,107.217234 197.308014,107.693256 C197.784036,108.169277 198.708077,108.029271 199.044093,107.693256 C199.380108,107.35724 199.380108,107.217234 199.408109,106.937221 L199.912132,107.441244 L200.360152,106.993224 L200.836174,107.469246 L201.20019,107.105229 L200.416155,106.321194 L204.392335,102.401016 L206.072411,104.081092 L207.80849,102.345013 L207.108458,101.644981 L210.048592,98.7048481 L206.324423,94.952678 Z M197,80 L197.896041,84.6202095 L214.892811,101.61698 L214.19278,102.317012 L215.928858,104.053091 L217.608934,102.373014 L221.557114,106.321194 L220.773078,107.105229 L221.137094,107.469246 L221.613116,106.993224 L222.061136,107.441244 L222.565159,106.937221 C222.59316,107.217234 222.565159,107.329239 222.929176,107.693256 C223.265191,108.029271 224.189233,108.169277 224.665254,107.693256 C225.141276,107.217234 225.00127,106.293192 224.665254,105.957177 C224.329239,105.621162 224.189233,105.621162 223.90922,105.59316 L224.413243,105.089138 L223.993224,104.641117 L224.469246,104.165096 L224.105229,103.801079 L223.321194,104.585115 L219.401016,100.608934 L221.081092,98.9288583 L219.345013,97.1927796 L218.644981,97.8928113 L201.620209,80.8960406 L197,80 Z M215.760851,92.9645879 L224.105229,84.6202095 L225.00127,80 L220.38106,80.8960406 L212.036682,89.240419 L215.760851,92.9645879 Z" id="play-tourney" sketch:type="MSShapeGroup"></path>\n                                        </g>\n                                    </g>\n                                </svg>\n                                <svg class="cancel" width="33px" height="28px" viewBox="0 0 33 28" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n                                    <g id="Page-1" stroke="none" stroke-width="1" fill-rule="evenodd">\n                                        <g id="tournament-block" transform="translate(-254.000000, -79.000000)">\n                                            <g id="cansel-tourney" transform="translate(254.000000, 79.000000)">\n                                                <path d="M7.35595313,18.5 L6.92017776,18.9288583 L8.60025394,20.6089345 L4.65207491,24.5571135 L3.86803936,23.773078 L3.50402285,24.1370945 L4.00804571,24.6411173 L3.56002539,25.0891376 L4.06404825,25.5931605 C3.78403555,25.6211618 3.67203047,25.5931605 3.30801397,25.957177 C2.97199873,26.2931922 2.83199238,27.2172341 3.30801397,27.6932557 C3.78403555,28.1692773 4.70807745,28.029271 5.04409269,27.6932557 C5.38010792,27.3572405 5.38010792,27.2172341 5.40810919,26.9372214 L5.91213205,27.4412443 L6.36015236,26.993224 L6.83617395,27.4692456 L7.20019045,27.1052291 L6.4161549,26.3211935 L10.3923352,22.4010157 L12.0724114,24.0810919 L13.8084901,22.3450132 L13.1084584,21.6449815 L16.0485917,18.7048481 L15.8452722,18.5 L7.35595313,18.5 Z M8.27583113,9 L3.89604063,4.6202095 L3,0 L7.6202095,0.89604063 L15.7375197,9 L8.27583113,9 Z M17.7758311,18.5 L20.8928113,21.6169802 L20.1927796,22.3170119 L21.9288583,24.0530907 L23.6089345,22.3730145 L27.5571135,26.3211935 L26.773078,27.1052291 L27.1370945,27.4692456 L27.6131161,26.993224 L28.0611364,27.4412443 L28.5651592,26.9372214 C28.5931605,27.2172341 28.5651592,27.3292392 28.9291757,27.6932557 C29.265191,28.029271 30.1892329,28.1692773 30.6652544,27.6932557 C31.141276,27.2172341 31.0012697,26.2931922 30.6652544,25.957177 C30.3292392,25.6211618 30.1892329,25.6211618 29.9092202,25.5931605 L30.413243,25.0891376 L29.993224,24.6411173 L30.4692456,24.1650957 L30.1052291,23.8010792 L29.3211935,24.5851148 L25.4010157,20.6089345 L27.0810919,18.9288583 L26.6522336,18.5 L17.7758311,18.5 Z M25.7254386,9 L30.1052291,4.6202095 L31.0012697,0 L26.3810602,0.89604063 L18.2771008,9 L25.7254386,9 Z" id="Shape-Copy-10"></path>\n                                                <text id="отмена" font-family="Open Sans" font-size="8" font-weight="bold" letter-spacing="0.5">\n                                                    <tspan x="0" y="16">отмена</tspan>\n                                                </text>\n                                            </g>\n                                        </g>\n                                    </g>\n                                </svg>\n                            </div>\n                        </div>\n                    </div>\n\n                </div>\n            </div>\n            ',bindings:{data:"="}}
11),CupsController.$inject=["$scope","$window","$timeout","ggCupsApiService","DateFunctions"]}(angular),function(){function ggFavoriteGames(){function loadMoreFavorites(page){return Utils.post(AJAX_PATH+"/channels/games/",{page:page}).then(function(html){return html})}this.loadMoreFavorites=loadMoreFavorites}angular.module("GG").controller("ggFavoriteGames",ggFavoriteGames)}(),function(){function ggLoginWindow($scope){function changeLoginStep(step){wnd.step=step,Utils.lsSet("ggLastLoginTab",step)}function close(){wnd.isNoClose||$(".login-wrap-big").remove()}function loginByPassword(){if(wnd.login&&wnd.password){var gRecaptchaResponse=$('#captcha-place *[name="g-recaptcha-response"]').val(),loginResponse=void 0;return PageLoader.showLoader(),UserService.login(wnd.login,wnd.password,wnd.remember,wnd.backurl,gRecaptchaResponse).then(function(data){if(!data.result||!data.return)throw loginResponse=data,new Error;close()}).catch(function(e){if(10==loginResponse.code){var code=prompt(loginResponse.response);return Utils.post("/ajax/login-code/",{code:code}).then(function(data){data.success?(UserService.afterLogin(data),close()):alert("Неверный код!")})}alert(loginResponse.response),5==loginResponse.code&&loginResponse.login_page&&(window.location.href=loginResponse.login_page)}).then(function(){PageLoader.hideLoader()}),!1}}function loginByFB(){PageLoader.showLoader(),FB.login(function(data){"connected"==data.status&&FB.api("/me",function(response){UserService.oauth("fb",response).then(function(result){PageLoader.hideLoader(),!0===result?close():!1===result?(alert("Произошла ошибка!"),close()):(wnd.oname=response.username||response.name,wnd.regEmail=response.email,wnd.step="link-social")})})},{scope:"email"})}function loginByVK(){PageLoader.showLoader(),VK.Auth.login(function(udata){UserService.oauth("vk",udata.session.user,udata.session.sig).then(function(result){PageLoader.hideLoader(),!0===result?close():!1===result?(alert("Произошла ошибка!"),close()):(wnd.oname=udata.session.user.domain||udata.session.user.first_name+" "+udata.session.user.last_name,wnd.regEmail=!1,wnd.step="link-social")})})}function loginTwitch(){loginByRedirect("twitch")}function loginByTwitch(){}function loginByTwitter(){loginByRedirect("twitter")}function loginByBattleNet(){loginByRedirect("bnet")}function loginByRedirect(link){PageLoader.showLoader(),window.open("/oauth/"+link,"_blank","menubar=no,toolbar=no,location=no,directories=no,width=500,height=400"),window.oauthCallback=oauthCallback}function oauthCallback(data){return PageLoader.hideLoader(),"auth"==data.result?(UserService._onLogin(data.user),close()):"error"==data.result?(data.txt?alert(data.txt):alert("Произошла ошибка"),close()):(wnd.oname=data.name,void(wnd.step="link-social"))}function loginAndLink(){PageLoader.showLoader();var loginResponse=void 0;UserService.login(wnd.linkLogin,wnd.linkPassword,1).then(function(loginResponse){if(10==loginResponse.code){var code=prompt(loginResponse.response);return Utils.post("/ajax/login-code/",{code:code}).then(function(data){return data.success?data:(alert("Неверный код!"),!1)})}return loginResponse}).then(function(data){return!!data.return&&(loginResponse=data,Utils.post("/oauth/bind"))}).then(function(data){data=data?angular.fromJson(data):{},data.result?(UserService.afterLogin(loginResponse),close()):alert("Произошла ошибка")}).then(function(){PageLoader.hideLoader()})}function register(){var gRecaptchaResponse=$('#captcha-place *[name="g-recaptcha-response"]').val();PageLoader.showLoader(),UserService.register(wnd.regEmail,wnd.regLogin,wnd.regPassword,gRecaptchaResponse,wnd.regOptions).then(function(data){!0===data?wnd.step="registration-final":(wnd.regErrors=data,wnd.regError=Object.keys(data).map(function(key){return data[key]}).join("<br>"),grecaptcha.reset()),PageLoader.hideLoader()})}function registerByLink(){wnd.regPassword=!1,wnd.step="very-final"}function registerLastStep(){PageLoader.showLoader(),UserService.registerFinish(wnd.lastNickname,wnd.regEmail||wnd.lastEmail,wnd.lastPassword).then(function(response){PageLoader.hideLoader(),response.error?alert(response.error):close()})}function rememberPassword(){wnd.rememberError=!1,Utils.post("/ajax/forgotpass/",{email:wnd.rememberPass}).then(function(response){response=angular.fromJson(response),response.error?wnd.rememberError=response.error:wnd.step="remember-finish"})}function reSend(){Utils.post("/ajax/reactivate/",{nickname:wnd.regLogin})}var wnd=this;wnd.hint=$scope.hint,wnd.regPassword="",wnd.rememberPass="",wnd.remember=1,wnd.twitch=!1,wnd.step="",wnd.isNoClose=!1,wnd.showCaptcha=!1,wnd.backurl="",wnd.regOptions={},wnd.close=close,wnd.register=register,wnd.registerByLink=registerByLink,wnd.last=registerLastStep,wnd.loginByPassword=loginByPassword,wnd.vkLogin=loginByVK,wnd.twitchLogin=loginTwitch,wnd.loginByTwitch=loginByTwitch,wnd.fbLogin=loginByFB,wnd.twLogin=loginByTwitter,wnd.bnLogin=loginByBattleNet,wnd.link=loginAndLink,wnd.changeLoginStep=changeLoginStep,wnd.rememberPassword=rememberPassword,wnd.reSend=reSend,function(){window.recaptchaOnloadCallback=function(){gre
11captcha.render("captcha-place",{sitekey:"6LenFQETAAAAAO1WCIo7HQhzxbzmzt-oBHV-FPcO",theme:"dark"})},"login-step"==Utils.lsGet("ggLastLoginTab")?wnd.step="login-step opened":wnd.step="one opened"}()}angular.module("GG").controller("ggLoginWindow",ggLoginWindow)}(),function(){function ggProfileNavigation(gg4UserService){function logOut(){gg4UserService.logout(),UserService.logout()}function mouseOver(){vm.isMobile||(vm.isSubmenuOpened=!0)}function mouseLeave(){vm.isMobile||(vm.isSubmenuOpened=!1)}function togleShowMenu(){vm.isSubmenuOpened=!vm.isSubmenuOpened}function clickOutside(){vm.isSubmenuOpened=!1}function isWebmaster(){return vm.gg4UserService.isWebMaster()}var vm=this;vm.isMobile=/Mobi/i.test(window.navigator.userAgent),vm.isSubmenuOpened=!1,vm.clickOutside=clickOutside,vm.togleShowMenu=togleShowMenu,vm.mouseLeave=mouseLeave,vm.mouseOver=mouseOver,vm.logOut=logOut,vm.isWebmaster=isWebmaster,vm.gg4UserService=gg4UserService}angular.module("GG").controller("ggProfileNavigation",ggProfileNavigation,["gg4UserService","UserService"])}(),function(){function StreamsSelectorController($window,$timeout,service,$element,$scope){function animateScoll(){vm.scrolling=!0,aniTimeout&&$timeout.cancel(aniTimeout),aniTimeout=$timeout(function(){vm.scrolling=!1},500)}function fillStreams(cnt){for(var dummy={id:"",title:"",link:"",streamer:"",viewers:"",preview:"",premium:!1,streamkey:""},arr=[],i=0;i<cnt;i++)arr.push(dummy);return arr}function filterTitle(val){return $("<textarea />").html(val).text()}function goNextPage(){vm.last!=vm.currentPage&&(vm.currentPage+=1,vm.last=Math.max(vm.currentPage,vm.last),vm.pages[vm.currentPage-1]&&vm.pages[vm.currentPage-1].length==vm.onPage||(vm.pages[vm.currentPage-1]=fillStreams(vm.onPage),loadPage()),animateScoll())}function goPrevPage(){vm.currentPage=Math.max(vm.currentPage-1,1),animateScoll()}function hintHide(){Utils.lsSet("selectorHideScrollHelper2",!0),vm.hint=!1}function loadPage(){var page=vm.currentPage,tab=vm.currentTab;service.loadPage(tab,page,vm.onPage).then(function(data){if(tab==vm.currentTab){for(var i=0;i<vm.onPage;i++)data.streams[i]?vm.pages[page-1][i]=data.streams[i]:vm.pages[page-1][i]=!1;data.more&&(vm.last=Math.max(page+1,vm.last))}})}function loadTab(tab){vm.tabLoading=!0,service.loadTab(tab).then(function(data){vm.currentPage=1,vm.pages=[data.streams],vm.last=data.more?2:1,vm.currentTab=data.active,vm.tabLoading=!1})}function reset(){vm.settings=!1,service.setGames(!1).then(function(data){vm.games=data[0],vm.genres=data[1]})}function save(event){vm.settings=!1;var settingsBlock=angular.element(event.currentTarget).closest(".settings-block"),ids=[];settingsBlock.find("input").each(function(ind,e){$(e).data("gameid")&&ids.push($(e).data("gameid"))}),service.setGames(ids).then(function(data){vm.games=data[0],vm.genres=data[1]})}function setOnPage(){var ml=window.matchMedia("(max-width: 1870px)");vm.onPage=ml.matches?12:15}function toggleGamesSelector(){UserService.id?vm.settings=!vm.settings:LoginPopup.open()}var vm=this;angular.extend(vm,$window.MainPage.Selector),vm.hint=!Utils.lsGet("selectorHideScrollHelper2"),vm.showTab=loadTab,vm.goPrevPage=goPrevPage,vm.goNextPage=goNextPage,vm.save=save,vm.reset=reset,vm.hintHide=hintHide,vm.filterTitle=filterTitle,vm.toggleGamesSelector=toggleGamesSelector,vm.width=0,vm.range=function(num){return new Array(num)},vm.count=function(obj){return Object.keys(obj).length},vm.shortGameTitle=function(title){return title.split(":")[0]},function(){vm.width=window.innerWidth,window.addEventListener("resize",function(){$("#StreamSelector").length&&(1!=vm.currentPage&&vm.width!=window.innerWidth&&(vm.width=window.innerWidth,vm.currentPage=1,animateScoll()),setOnPage())}),setOnPage(),$scope.$watch(function(){return Math.round(Date.now()/12e4)},function(){return loadPage()})}();var aniTimeout}angular.module("GG").controller("ggStreamSelector",StreamsSelectorController),StreamsSelectorController.$inject=["$window","$timeout","StreamsSelectorService","$element","$scope"]}(),function(angular,$){function StreamSelector(){function link(scope,$element,attrs){function bindGames(){$($element[0]).find(".settings-wrap .form-group").each(function(ind,elem){new GamesAutoComplete($(elem).find("input"),function(title,elem,data){elem.data("gameid",data[1])},!0,!0),$(elem).on("click",".icon-close2",function(){$(elem).find("input").val("").data("gameid",0)})})}var iswheeling,wtimer;scope.$watch("selector.games",function(){$element.find(".gg-loaded").removeClass("gg-loaded"),bindGames()}),$(window).on("wheel MouseScrollEvent",function(e){if(e.originalEvent.altKey){e.preventDefault();var delta=0;"wheel"==e.type?delta=e.originalEvent.wheelDelta?e.originalEvent.wheelDelta:-1*e.originalEvent.deltaY:"MouseScrollEvent"==e.type&&(delta=-1*e.originalEvent.detail),delta&&!isNaN(delta)&&(wtimer&&clearTimeout(wtimer),iswheeling||(delta<0?scope.selector.goNextPage():scope.selector.goPrevPage()),scope.$apply(),iswheeling=!0,wtimer=setTimeout(function(){iswheeling=!1},30))}})}return{restrict:"A",link:link,templateUrl:"StreamSelector.html"}}angular.module("GG").directive("ggStreamsSelector",StreamSelector)}(angular,jQuery),function(){function StreamsSelectorService($http){function postForm(url,data){return $http({method:"POST",url:url,data:$.param(data),headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(function(res){return res.data})}this.loadPage=function(tab,page,onPage){return postForm("/ajax/streams/selector/",{tab:tab,page:page,onpage:onPage})},this.loadTab=function(tab){return postForm("/ajax/streams/selector/",{tab:tab,page:1})},this.setGames=function(ids){
12return postForm("/ajax/streams/setSelectorGames/",ids?{set:ids.join(",")}:{reset:!0})}}angular.module("GG").service("StreamsSelectorService",StreamsSelectorService),StreamsSelectorService.$inject=["$http"]}(),function(angular){var ggStreamsSelector=function(){function ggStreamsSelector(StreamsSelectorService,$scope){var _this67=this;_classCallCheck(this,ggStreamsSelector),angular.extend(this,MainPage.Selector),$scope.onStreamPreViewLoaded=this.onStreamPreViewLoaded,this.settings=!1,this.service=StreamsSelectorService,this.hint=!Utils.lsGet("selectorHideScrollHelper2"),this.videoPreview=!0,this.setTabs(),this.setOnPage(),this._onResizeHandler=function(){return _this67.onResize()},window.addEventListener("resize",this._onResizeHandler),this.cupSchedule={"2020-12-04 12:00":{streams:[746418,1001106],link:"https://goodgame.ru/multigg/FrankSG/Utan"},"2020-12-04 20:20":{streams:[100407,332555],link:"https://goodgame.ru/multigg/Sigeon2/bobbistarr"},"2020-12-04 22:40":!1,"2020-12-05 18:00":{streams:[934056,733796],link:"https://goodgame.ru/multigg/EatAlot/Olafhran"},"2020-12-05 20:20":!1},this.initCup()}return _createClass(ggStreamsSelector,[{key:"$onInit",value:function(){}},{key:"$onDestroy",value:function(){window.removeEventListener("resize",this._onResizeHandler)}}
12,{key:"setTabs",value:function(){this.tabs.forEach(function(tab){return tab.newTitle=tab.title})}},{key:"onStreamPreViewLoaded",value:function(chanel){chanel.imgLoaded=!0}},{key:"showTab",value:function(tab){var _this68=this;this.showLoading(),this.currentPage=1,this.last=!0,this.pages=[this.fillBlank(this.onPage)],this.service.loadTab(tab).then(function(data){for(var i=0;i<_this68.onPage;i++)data.streams[i]?_this68.pages[0][i]=data.streams[i]:_this68.pages[0][i]=!1;_this68.last=data.more?2:1,_this68.currentTab=data.active,_this68.hideLoading()})}},{key:"loadPage",value:function(){var _this69=this;this.showLoading();var page=this.currentPage,tab=this.currentTab;this.service.loadPage(tab,page,this.onPage).then(function(data){if(tab==_this69.currentTab){for(var i=0;i<_this69.onPage;i++)data.streams[i]?_this69.pages[page-1][i]=data.streams[i]:_this69.pages[page-1][i]=!1;data.more&&(_this69.last=Math.max(page+1,_this69.last)),_this69.hideLoading()}})}},{key:"shortGameTitle",value:function(title){return title.split(":")[0]}},{key:"toggleGamesSelector",value:function(){UserService.id?this.settings=!this.settings:window.openLogin()}},{key:"setGame",value:function(data,index){var tab=this.tabs[index];tab.newId=data.id,tab.newTitle=data.title}},{key:"save",value:function(){var _this70=this;this.showLoading();for(var ids=[],i=0;i<this.tabs.length;i++)this.tabs[i].newTitle&&ids.push(this.tabs[i].newId||this.tabs[i].id);this.service.setGames(ids).then(function(data){_this70.tabs=data,_this70.settings=!1,_this70.setTabs(),_this70.hideLoading()})}},{key:"reset",value:function(){var _this71=this;this.showLoading(),this.service.setGames(!1).then(function(data){_this71.tabs=data,_this71.settings=!1,_this71.setTabs(),_this71.hideLoading()})}},{key:"goPrevPage",value:function(){this.currentPage=Math.max(this.currentPage-1,1)}},{key:"goNextPage",value:function(){this.last!=this.currentPage&&(this.currentPage+=1,this.last=Math.max(this.currentPage,this.last),this.pages[this.currentPage-1]&&this.pages[this.currentPage-1].length==this.onPage||(this.pages[this.currentPage-1]=this.fillBlank(this.onPage),this.loadPage()))}},{key:"hintHide",value:function(){Utils.lsSet("selectorHideScrollHelper2",!0),this.hint=!1}},{key:"setOnPage",value:function(){var ml=window.matchMedia("(max-width: 1870px)");this.onPage=ml.matches?12:15}},{key:"fillBlank",value:function(count){for(var dummy={id:"",title:"",link:"",streamer:"",viewers:"",preview:"",premium:!1,streamkey:""},arr=[],i=0;i<count;i++)arr.push(dummy);return arr}},{key:"showLoading",value:function(){var _this72=this;$(".selector-container.loading").removeClass("loading"),this.loadingTimeout=setTimeout(function(){_this72.tabLoading=!0},300)}},{key:"hideLoading",value:function(){this.tabLoading=!1,clearTimeout(this.loadingTimeout)}},{key:"onResize",value:function(){var lastOnPage=this.onPage;this.setOnPage(),lastOnPage!=this.onPage&&(this.currentPage=1,1!=this.last&&this.pages[0].length<this.onPage&&this.loadPage())}},{key:"onScroll",value:function(e){var _this73=this;if(e.altKey){e.preventDefault();var delta=0;"wheel"==e.type?delta=e.wheelDelta?e.wheelDelta:-1*e.deltaY:"MouseScrollEvent"==e.type&&(delta=-1*e.detail),delta&&!isNaN(delta)&&(this.wtimer&&clearTimeout(this.wtimer),this.iswheeling||(delta<0?this.goNextPage():this.goPrevPage()),this.iswheeling=!0,this.wtimer=setTimeout(function(){return _this73.iswheeling=!1},30))}}},{key:"range",value:function(num){return new Array(num)}},{key:"initCup",value:function(){var currentTime=Utils.moscowTime(),selected=void 0;for(var key in this.cupSchedule){if(Date.parse(key)>currentTime){!0===selected&&(selected=this.cupSchedule[key],selected.upcoming=!0,selected.start=Utils.parseMysqlDate(key));break}selected=this.cupSchedule[key]}if(console.log({selected:selected}),selected&&selected.streams)for(var streams=selected.streams,i=0;i<streams.length;i++)streams[i]=this.cupData[streams[i]];this.cup=selected}}]),ggStreamsSelector}();angular.module("GG").component("ggStreamsSelector",{templateUrl:"StreamSelector.html",controller:ggStreamsSelector,controllerAs:"selector"})}(angular),function(angular){var ggDonatHistory=function(){function ggDonatHistory(DateFunctions){_classCallCheck(this,ggDonatHistory),this.formatDate=DateFunctions.formatDate,this.loading=!0,this.levels=[0,100,300,500,3e3,1e4,25e3,5e4,75e3,1e5],this.icons=["","coin","eagle","cup","diamond","crown","undead","fire","cherry","mushroom","top1"],this.classes=["","bronze","silver","gold","diamond","king","undead","fire","cherry","mushroom","top-one"],this.names=["","Бронзовый","Серебряный","Золотой","Алмазный","Царский","Бессмертный","Огненный","Черри","Грибной","Топ 1"],this.colors=["","e7820a","b4b4b4","eefc08","8781bd","30d5c8","AB4873","EC8C24","EA455C","BABABA","3BCBFF"],this.gradiendColors=new Map([["fire","#F2F932"],["cherry","#35A83F"],["mushroom","#AB4873"]]),this.logLimit=20}return _createClass(ggDonatHistory,[{key:"$onInit",value:function(){this.onLoad(this.apiData)}},{key:"onLoad",value:function(data){this.loading=!1,this.channels=data.channels,this.log=data.log,this.statuses=this.parseStatuses(data.statuses)}},{key:"parseStatuses",value:function(statuses){var _this74=this;
12return statuses.forEach(function(row){var lvl=parseInt(row.level),amount=parseInt(row.amount);row.level<_this74.levels.length-1?(lvl+=1,row.remains=_this74.levels[lvl]-amount,row.percent=100-Math.round(100*row.remains/_this74.levels[lvl])):(row.remains=0,row.percent=100),row.icon=_this74.icons[lvl],row.class=_this74.classes[lvl],row.color=_this74.colors[lvl],row.gradientColor=["fire","cherry","mushroom"].indexOf(row.class)>-1?_this74.gradiendColors.get(row.class):"",row.name=_this74.names[lvl]}),statuses}}]),ggDonatHistory}();angular.module("GG").component("ggDonatHistory",{controller:ggDonatHistory,templateUrl:"/html/profile/donat-history.html",bindings:{apiData:"<"}})}(angular),function(angular){var ggMyPremiums=function(){function ggMyPremiums(){_classCallCheck(this,ggMyPremiums),this.loading=!0,this.card=!0,this.isError=!1,this.isAdBlocked=!1,this.serverError=!1}return _createClass(ggMyPremiums,[{key:"$onInit",value:function(){this.onLoad(this.apiData)}},{key:"onLoad",value:function(data){var _this75=this;if(console.log(data),!data||data.isError)return this.isError=!0,this.isAdBlocked=data&&!!data.adBlocked,this.serverError=data&&!data.adBlocked,void(this.loading=!1);this.subs=data.subs,this.keys=data.keys,this.card=data.card,this.loading=!1,[this.subs,this.keys].forEach(function(arr){return!!arr&&arr.forEach(function(key){return key.expireText=_this75.getExpireText(key.expire)})})}},{key:"getExpireText",value:function(time){if((time-=Date.now()/1e3)<0)return"Подписка истекла";var months=Math.ceil(time/2592e3);if(months>1)return months+" "+["месяц","месяца","месяцев"][Utils.decl(months)];var days=Math.ceil(time/86400);if(days>1)return days+" "+["день","дня","дней"][Utils.decl(days)];var hours=Math.ceil(time/3600);return hours>1?hours+" "+["час","часа","часов"][Utils.decl(hours)]:time>0?"Менее часа":0}},{key:"cancel",value:function(sub){var _this76=this;this.loading=!0,Utils.post("/api/4/premium/my/disable",{id:sub.id}).then(function(data){return _this76.onLoad(data)})}},{key:"restore",value:function(sub){var _this77=this;if(!this.card)return void alert("Вы не можете возобновить подписку, так как у вас не привязана карта");("Подписка истекла"!==sub.expireText||confirm("Для возобновления с вашей карты будет списана стоимость подписки. Продолжить?"))&&(this.loading=!0,Utils.post("/api/4/premium/my/enable",{id:sub.id}).then(function(data){_this77.onLoad(data),null!==data.result&&(!0===data.result?alert("Продление прошло успешно"):!1===data.result&&alert("Продление завершилось неудачей"))}))}}]),ggMyPremiums}();angular.module("GG").component("ggMyPremiums",{controller:ggMyPremiums,templateUrl:"/html/profile/my-premiums.html",bindings:{apiData:"<"}})}(angular),function(angular){var ggMyPremiumsSidebar=function(){function ggMyPremiumsSidebar(){_classCallCheck(this,ggMyPremiumsSidebar),this.loading=!0,this.selectedStream=0,this.activateKey=""}return _createClass(ggMyPremiumsSidebar,[{key:"$onInit",value:function(){}},{key:"onLoad",value:function(){this.loading=!1}},{key:"activate",value:function(){var _this78=this;if(""==this.activateKey.trim())return void(this.activateError={empty:!0});Utils.post("/api/4/premium/activate/",{key:this.activateKey,streamId:this.selectedStream}).then(function(data){data.error&&(_this78.activateSuccess=!1,"activated"==data.error&&(_this78.activateError={already:!0}),"streamer_needed"==data.error&&(_this78.activateError={streamer:!0}),"wrong"==data.error&&(_this78.activateError={wrong:!0}),"oldKey"==data.error&&(_this78.activateError={oldKey:!0})),data.success&&(_this78.whereActivated="all"!==data.streamer?"Премиум активирован на канал"+data.streamer:"Plus активирован",_this78.activateError={},_this78.activateSuccess=!0,Utils.reachGoal("PREMIUM"))})}},{key:"streamSelected",value:function(stream){stream&&stream.id?(this.selectedStream=stream.id,this.activate()):(this.activateError={},this.activateSuccess=!1)}}]),ggMyPremiumsSidebar}();angular.module("GG").component("ggMyPremiumsSidebar",{controller:ggMyPremiumsSidebar,templateUrl:"/html/profile/my-premiums-sidebar.html"})}(angular),function(angular){var ggPremiumStreamerSelect=function(){function ggPremiumStreamerSelect($rootScope){var _this79=this;_classCallCheck(this,ggPremiumStreamerSelect),$rootScope.$watch("$root.favorites.online.length",function(){$rootScope.favorites&&$rootScope.favorites.online&&(_this79.favorites=$rootScope.favorites.online.concat($rootScope.favorites.soon,$rootScope.favorites.offline))})}return _createClass(ggPremiumStreamerSelect,[{key:"select",value:function(){this.selected&&this.onSelect({stream
12:this.selected})}},{key:"close",value:function(){this.onSelect({stream:!1})}}]),ggPremiumStreamerSelect}();angular.module("GG").component("ggPremiumStreamerSelect",{controller:ggPremiumStreamerSelect,templateUrl:"/html/profile/streamer-select.html",bindings:{onSelect:"&"}})}(angular),function(angular){var ggPremiumsHistory=function(){function ggPremiumsHistory(DateFunctions){_classCallCheck(this,ggPremiumsHistory),this.logLimit=20,this.formatDate=DateFunctions.formatDate}return _createClass(ggPremiumsHistory,[{key:"$onInit",value:function(){this.onLoad(this.apiData)}},{key:"onLoad",value:function(data){this.loading=!1,this.history=data.history,this.channels=data.channels,this.users=data.users}},{key:"getPremiumDuration",value:function(type){return type=type.toString(),["1 месяц","3 месяца","6 месяцев","12 месяцев","1 месяц"][type[2]]}},{key:"hasArrow",value:function(row){return!this.isGift(row.type)&&("0"!=row.user_id&&row.user_id!=row.creator)}},{key:"isGift",value:function(type){return 35==type}},{key:"getType",value:function(row){return this.isGift(row.type)?"Подарок":this.isSubscription(row.objId)?"Подписка":row.key}},{key:"isSubscription",value:function(type){return 1==type[0]}},{key:"getAllRecipients",value:function(usersIds){var _this80=this;return usersIds.map(function(uid){return _this80.users[uid].nickname}).join(", ")}}]),ggPremiumsHistory}();angular.module("GG").component("ggPremiumsHistory",{controller:ggPremiumsHistory,templateUrl:"/html/profile/premiums-history.html",bindings:{apiData:"<"}})}(angular),angular.module("GG").config(function($stateProvider){$stateProvider.state("userPremiumOld",{url:"/user/premium/",redirectTo:"userFinance.premiums"}).state("userFinance",{abstract:!0,url:"/user/finance/"}).state("userFinance.premiums",{url:"premium/",views:{"finance@":{component:"ggMyPremiums",bindings:{apiData:"apiData"}}},resolve:{apiData:function(){return Utils.get("/api/4/premium/my/").catch(function(error){var msg=error&&error.message?error.message.toLowerCase():"",status=error&&error.status,adBlockIndicators=["net::err_blocked_by_client","failed to fetch","networkerror when attempting to fetch resource.","load failed"];return{isError:!0,adBlocked:-1===status||0===status||adBlockIndicators.some(function(ind){return msg.includes(ind)})}})},$title:function(){return"Мои премиумы"}}}).state("userFinance.donation",{url:"donation/",views:{"finance@":{component:"ggDonatHistory",bindings:{apiData:"apiData"}}},resolve:{apiData:function(){return Utils.get("/ajax/user/donat-history/")},$title:function(){return"Статусы и поддержка"}}})}),function(){var ggFeaturedStreamCreate=function(){function ggFeaturedStreamCreate($scope,$element){var _this81=this;_classCallCheck(this,ggFeaturedStreamCreate);var date=new Date;this.date=date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(),this.price=200,this.amount=0,this.from="",this.to="",this.timeError=!1,this.limit=280,this.$scope=$scope,$scope.$watch(function(){return _this81.from+_this81.to},function(){return _this81.updateAmount()}),window.iframeCallback=function(result,error){return _this81.onIframeCallback(result,error)},this.description=localStorage.getItem("featured-description")||"",this.txtarea=$element.find("#description")[0],$scope.change=function(){this.$ctrl.txtarea.value.length<100?this.$ctrl.txtarea.classList.add("error"):this.$ctrl.txtarea.classList.remove("error")}}return _createClass(ggFeaturedStreamCreate,[{key:"updateAmount",value:function(){var fromTimeToBlock=function(time){return time.split(":").reduce(function(acc,time){return+time+60*acc})};this.amount=this.timeError?0:this.price*(fromTimeToBlock(this.to)-fromTimeToBlock(this.from))/60}},{key:"getPaymentOptions",value:function(){var _this82=this;Utils.get("/ajax/payment/2/options/").then(function(data){_this82.paymentOptions=data,_this82.card=data.cards&&data.cards[0]?data.cards[0].bindingId:0})}},{key:"pay",value:function(){var _this83=this;localStorage.setItem("featured-description",this.description);var err=[];if(this.amount||err.push("Укажите время"),this.title||err.push("Укажите Заголовок блока на главной"),this.description?this.description.length<100&&err.push("Описание блока на главной должно быть не менее 100 символов"):err.push("Укажите Описание блока на главной"),err.length>0)return alert(Utils.errorSummary(err)),!1;0!=this.card&&this.isCard(this.card)||this.openPopup(),Utils.post("/ajax/featured-stream
12s/create/",{channel:this.channel,title:this.title,description:this.description,date:this.date,from:this.from,to:this.to}).then(function(data){if(!data.success)throw new Error("Не удалось создать запись в расписании");return _this83.recordId=data.id,_this83.isCard(_this83.card)?_this83.payCard():_this83.payOther()}).catch(function(e){alert(e.message)})}},{key:"openPopup",value:function(){this.$popup=window.open("about:blank","_blank","width=810,height=610,toolbar=no,scrollbars=yes,resizable=yes"),window.focus()}},{key:"payCard",value:function(){var _this84=this;return Utils.post("/ajax/payment/2/featured-streams/card/",{card:this.card,id:this.recordId,cvc:this.cvc}).then(function(data){data.url?(_this84.$popup.resizeTo(880,547),_this84.$popup.location.href=data.url,_this84.$popup.focus()):_this84.onResult(data.success)})}},{key:"payOther",value:function(){var _this85=this;return Utils.post("/ajax/payment/2/featured-streams/other/",{provider:this.card,id:this.recordId}).then(function(data){console.log(data),_this85.$popup.location.href=data.url,_this85.$popup.focus()})}},{key:"onIframeCallback",value:function(result,error){this.$popup.close(),this.$popup=!1,this.onResult(!!result)}},{key:"onResult",value:function(success){success?alert("Вы успешно оплатили размещение"):alert("Не удалось оплатить размещение"),this.updatePicker=1,this.$scope.$applyAsync()}},{key:"isCard",value:function(n){return!/^\d+$/.test(n)||"0"==n}}]),ggFeaturedStreamCreate}();angular.module("GG").component("ggFeaturedStreamCreate",{bindings:{channel:"@",streamer:"@"},templateUrl:"/html/stream/featured-stream.html",controller:ggFeaturedStreamCreate})}(),function(){var ggFeaturedStreamTime=function(){function ggFeaturedStreamTime($scope,$element){var _this86=this;_classCallCheck(this,ggFeaturedStreamTime),this.slots={1:[],2:[],3:[]},this.times=Array(24).fill().map(function(e,i){return i>9?i:"0"+i}),this.$scope=$scope,$scope.$watch(function(){return _this86.date},function(){return _this86.onChanges()}),$scope.$watch(function(){return _this86.update},function(){return _this86.onChanges()}),this.bindResizer($element)}return _createClass(ggFeaturedStreamTime,[{key:"loadStreams",value:function(day){var _this87=this;this.loading=!0,Utils.get("/ajax/featured-streams/get/",{date:day}).then(function(data){_this87.loading=!1,_this87.slots=data.reduce(function(a,c){return a[c.slot].push(c),a},{1:[],2:[],3:[]})})}},{key:"onChanges",value:function(){if(this.loadStreams(this.date.split(" ")[0]),this.from=-1,this.selectedSlot=1,this.selectedStyle={display:"none"},this.update=0,this.date){var d=new Date;d.setTime(d.getTime()-3600*d.getHours()*1e3-60*d.getMinutes()*1e3);var timeNow=d.getTime(),timeUser=new Date(this.date).getTime();this.error=timeUser<timeNow&&"В прошлое нельзя указывать"}}},{key:"timeToBlock",value:function(time){var _time$split=time.split(":"),_time$split2=_slicedToArray(_time$split,3),hours=_time$split2[0],minutes=_time$split2[1];_time$split2[2];return parseInt(hours)+(30==minutes?.5:0)}},{key:"blockToTime",value:function(block){var isHalf=Math.floor(block)!=block;return Math.floor(block)+":"+(isHalf?"30":"00")}},{key:"getStyle",value:function(slot){var startBlock=this.timeToBlock(slot.start.split(" ")[1]);return{top:38*startBlock+5+"px",height:38*(this.timeToBlock(slot.end.split(" ")[1])-startBlock)+"px"}}},{key:"checkSlots",value:function(){var _this88=this,freeSlots=[!1];[1,2,3].forEach(function(n){freeSlots[n]=!0,freeSlots[n-1]||_this88.slots[n].forEac
12h(function(slot){if(freeSlots[n]){var startBlock=_this88.timeToBlock(slot.start.split(" ")[1]),endBlock=_this88.timeToBlock(slot.end.split(" ")[1]);_this88.to<=startBlock||_this88.from>=endBlock||(freeSlots[n]=!1)}})}),this.selectedSlot=freeSlots.indexOf(!0),this.error=-1==this.selectedSlot}},{key:"setTime",value:function(event){if(!event.target.classList.contains("event-wrapper"))return!0;var block=Math.floor(event.offsetY/19)/2;this.from=block,this.to=block+1,this.setStyle(),this.checkSlots()}},{key:"setStyle",value:function(){this.selectedStyle={top:38*this.from+5+"px",height:38*(this.to-this.from)+"px"},this.fromTime=this.blockToTime(this.from),this.toTime=this.blockToTime(this.to)}},{key:"bindResizer",value:function($element){var _this89=this,moving=!1;document.addEventListener("mouseup",function(e){moving&&(e.preventDefault(),e.stopPropagation()),moving=!1}),document.addEventListener("mousemove",function(event){if(moving){var pageOffset=$element[0].getBoundingClientRect(),coords=event.pageY-pageOffset.y,block=Math.floor(coords/19)/2;1==moving&&(_this89.from=block-.5),2==moving&&(_this89.to=block),_this89.from<0&&(_this89.from=0),_this89.from>23.5&&(_this89.from=23.5),_this89.to>24&&(_this89.to=24),_this89.to<=_this89.from&&(_this89.to=_this89.from+.5),_this89.setStyle(),_this89.checkSlots(),_this89.$scope.$applyAsync()}}),$element.find(".event-wrapper").on("mousedown",".resizer",function(e){moving=e.target.classList.contains("top")?1:2,e.preventDefault(),e.stopPropagation()})}}]),ggFeaturedStreamTime}();angular.module("GG").component("ggFeaturedStreamTime",{bindings:{date:"=",fromTime:"=",toTime:"=",channel:"=",error:"=",update:"="},templateUrl:"/html/stream/time-picker.html",controller:ggFeaturedStreamTime})}(),function(angular){var ggBindCard=function(){function ggBindCard($sce){var _this90=this;_classCallCheck(this,ggBindCard),this.$sce=$sce,this.title="Привязка карты",this.step=0,this.hideSteps=1,window.iframeCallback=function(result,error){return _this90.onIframeCallback(result,error)},this.payWithACard()}return _createClass(ggBindCard,[{key:"$onInit",value:function(){}},{key:"payWithACard",value:function(){var _this91=this;Utils.post("/ajax/payment/2/card/bind/",{}).then(function(ret){_this91.step=2,_this91.iframe=_this91.$sce.trustAsResourceUrl(ret.url),_this91.paymentId=ret.id})}},{key:"onIframeCallback",value:function(result,error){result?this.return():(this.step=3,this.error=error)}},{key:"close",value:function(){this.return()}}]),ggBindCard}();angular.module("GG").component("ggBindCard",{controller:ggBindCard,templateUrl:"/html/html-payment/premium-new.html",bindings:{return:"&"}})}(angular),function(angular){var ggBuyPremium=function(){function ggBuyPremium($sce){var _this92=this;_classCallCheck(this,ggBuyPremium),this.$sce=$sce,this.step=1,this.paymentType=1,this.subType=1,this.subPeriod=0,this.present=0,this.presentsCount=1,this.firstTimeGGPlus=0,this.activateKey=!1,this.enteredKey="",this.activateError={},this.activateSuccess=!1,this.provider=Utils.lsGet("remember_donat_provider",5),window.iframeCallback=function(result,error,key){return _this92.onIframeCallback(result,error,key)},this.loading=!0}return _createClass(ggBuyPremium,[{key:"$onInit",value:function(){var _this93=this;Utils.get("/ajax/premium/",{channel:this.channel}).then(function(data){return _this93.onLoad(data)}),1==this.ggplus?(this.subType=2,Utils.reachGoal("ggp_showed")):Utils.reachGoal("sub_showed")}},{key:"onLoad",value:function(data){if(this.channel=data.channel,this.streamer=data.streamer,this.smiles=data.smiles,this.loading=!1,this.firstTimeGGPlus=!!data.ggplusfirst,this.streamer||(this.subType=2),this.icons=[],data.icons)for(var key in data.icons)this.icons.push(data.icons[key]);this.prices=data.prices,this.price=parseInt(data.price)}},{key:"pay",value:function(){var _this94=this;if(Utils.reachGoal(1==this.subType?"sub_pay_click":"ggp_pay_click"),2==this.paymentType&&Utils.lsSet("remember_donat_provider",this.provider),1==this.subType&&3==this.subPeriod)return void(this.subPeriod=2);this.present&&0==this.presentsCount||Utils.post("/ajax/payment/2/premium/",{type:this.paymentType,provider:this.provider,subType:this.subType,subPeriod:this.subPeriod,channelId:this.channel.i
12d||"",present:this.present?this.presentsCount:0}).then(function(ret){_this94.step=2,_this94.paymentId=ret.id,ret.iframe?_this94.iframe=_this94.$sce.trustAsResourceUrl(ret.url):(_this94.popupUrl=ret.url,_this94.openPopup(ret.url))})}},{key:"openPopup",value:function(url){var _this95=this,_new=window.open(url,"_blank","width=800,height=600,toolbar=no,scrollbars=yes,resizable=yes"),pollTimer=setInterval(function(){if(!_new)return void clearInterval(pollTimer);!1!==_new.closed&&(clearInterval(pollTimer),_this95.onIframeCallback(!1))},200)}},{key:"onIframeCallback",value:function(result,error,keys){if(!(this.step>2)){if("back"==error)return Utils.reachGoal(1==this.subType?"sub_pay_cancel_click":"ggp_pay_cancel_click"),void this.again();this.keys=this.present&&keys?keys.split(","):[],this.step=3,this.error=!result,!this.present&&result&&Utils.reachGoal(1==this.subType?"sub_pay":"ggp_pay")}}},{key:"again",value:function(){this.step=1,this.iframe=!1,this.error=!1,this.paymentId=0}},{key:"copyKeys",value:function(){var textArea=document.createElement("textarea");textArea.style.position="fixed",textArea.style.top=0,textArea.style.left=0,textArea.style.width="2em",textArea.style.height="2em",textArea.style.padding=0,textArea.style.border="none",textArea.style.outline="none",textArea.style.boxShadow="none",textArea.style.background="transparent",textArea.value=this.keys.join(", "),document.body.appendChild(textArea),textArea.select();try{document.execCommand("copy");alert("Ключи скопированы в буфер обмена")}catch(err){alert("Не удалось скопировать ключи"),console.log("Oops, unable to copy",err)}document.body.removeChild(textArea)}},{key:"close",value:function(){$(".subscribe-popup").remove()}},{key:"activate",value:function(){var _this96=this;if(!this.enteredKey)return!1;Utils.post("/ajax/premium/activate/",{key:this.enteredKey,streamId:this.channel.id}).then(function(data){data.error&&(_this96.activateSuccess=!1,"activated"==data.error&&(_this96.activateError={already:!0}),"wrong"==data.error&&(_this96.activateError={wrong:!0})),data.success&&(_this96.whereActivated=data.streamer?" на канал "+data.streamer:"",_this96.activateError={},_this96.activateSuccess=!0,Utils.reachGoal("PREMIUM"))})}},{key:"showPage",value:function(n){this.subType=n,Utils.reachGoal(1==this.subType?"sub_ggp_tab":"ggp_sub_tab")}}]),ggBuyPremium}();angular.module("GG").component("ggBuyPremium",{controller:ggBuyPremium,templateUrl:"/html/html-payment/premium-new.html",bindings:{channel:"@",ggplus:"@"}})}(angular),function(angular){var ggDirectPayment=function(){function ggDirectPayment($sce){_classCallCheck(this,ggDirectPayment),this.amount=100,this.step=1,this.$sce=$sce,this.paymentId=0,this.checkTries=0,this.comment=""}return _createClass(ggDirectPayment,[{key:"$onInit",value:function(){var _this97=this;Utils.get("/ajax/premium/",{channel:this.channel}).then(function(data){return _this97.onLoad(data)})}},{key:"onLoad",value:function(data){this.channel=data.channel,this.streamer=data.streamer}},{key:"donate",value:function(){var _this98=this;if(this.amount<25)return!1;Utils.post("/ajax/payment/2/ubank/register/",{amount:this.amount,streamer:this.streamer.id,comment:this.comment}).then(function(data){data.url?(_this98.iframeUrl=_this98.$sce.trustAsResourceUrl(data.url),_this98.paymentId=data.id,_this98.step=2,_this98.handleReturn()):alert("Ошибка создания платежа")})}},{key:"close",value:function(){$(".subscribe-popup").remove()}},{key:"handleReturn",value:function(){var _this99=this;window.addEventListener("message",function(e){return _this99.onResult(e)})}},{key:"onResult",value:function(e){console.log(e);var result=e.data;"data-fail"==result&&(this.step=4,this.error="Вы ввели неверные данные"),"card-fail"==result&&(this.step=4,this.error="Не удалось осуществить перевод"),"card-success"==result&&(this.step=3,this.checkPayment(1e3))}},{key:"again",value:function(){this.step=1,this.iframeUrl=!1,this.error=!1,this.paymentId=0,this.checkTries=0}},{key:"checkPayment",value:function(timer){var _this100=this;setTimeout(function(){Utils.get("/ajax/payment/2/ubank/check/",{pid:_this100.paymentId}).then(function(ret){1==ret.status?(_this100.step=4,_this100.error=!1):_this100.checkTries<=3?
12(_this100.checkPayment(2*timer),_this100.checkTries++):(_this100.step=4,_this100.error="Не удалось осуществить перевод")})},timer)}},{key:"getStreamerAmount",value:function(){return Math.max(0,this.amount-Math.max(25,.011*this.amount))}}]),ggDirectPayment}();angular.module("GG").component("ggDirectPayment",{controller:ggDirectPayment,templateUrl:"/html/html-payment/p2p.html",bindings:{channel:"@"}})}(angular),angular.module("GG").config(function($stateProvider,$urlRouterProvider,$locationProvider,$urlMatcherFactoryProvider){$stateProvider.state("new",{url:"/cup/new/",views:{"":{templateUrl:"/html/cups/cup/main.html",controller:"ggCupController",controllerAs:"vm"},"@new":{templateUrl:"/html/cups/cup/tabs/edit.html",controller:"ggCupEditController",controllerAs:"editor"}},resolve:{cup:function(ggCupService){return ggCupService.new()}}}).state("cup",{url:"/cup/{id:int}/",abstract:!0,views:{"":{templateUrl:"/html/cups/cup/main.html",controller:"ggCupController",controllerAs:"vm"},"right-column@cup":{templateUrl:"/html/cups/cup/blocks/right-column.html"},"player-block@cup":{templateUrl:"/html/cups/cup/blocks/player-block.html",controller:"ggPlayerBlockController",controllerAs:"block"},"tabs@cup":{templateUrl:"/html/cups/cup/blocks/tabs.html?ver=3"}},resolve:{cup:function($stateParams,ggCupService){return ggCupService.init($stateParams.id)},$title:["cup",function(cup){return"Турнир "+cup.title}]}}).state("cup.about",{url:"",templateUrl:"/html/cups/cup/tabs/about.html",controller:"ggCupAboutController",controllerAs:"about"}).state("cup.edit",{url:"edit/",templateUrl:"/html/cups/cup/tabs/edit.html",controller:"ggCupEditController",controllerAs:"editor"}).state("cup.players",{url:"players/",templateUrl:"/html/cups/cup/tabs/players.html",controller:"ggCupPlayersController",controllerAs:"players",resolve:{$title:["$title",function($title){return $title+". Участники"}]}}).state("cup.grid",{url:"grid/",abstract:!0,views:{"":{controller:"ggCupGridController",controllerAs:"grid",template:"<ui-view/>"},"right-column@cup":{}},data:{fullWidth:!0},resolve:{$title:["$title",function($title){return $title+". Сетка"}]}}).state("cup.grid.single",{url:"",views:{"":{templateUrl:"/html/cups/cup/tabs/grids/single.html"},"right-column@cup":{}}}).state("cup.grid.create",{url:"create/",views:{"":{templateUrl:"/html/cups/cup/tabs/grids/create.html"},"right-column@cup":{}}}).state("cup.grid.create-event",{url:"format/",controller:"ggCupFormatController",controllerAs:"format",templateUrl:"/html/cups/cup/tabs/grids/create-event.html"}).state("cup.grid.groups",{url:"groups/",views:{"":{templateUrl:"/html/cups/cup/tabs/grids/groups.html"},"right-column@cup":{}}}).state("cup.grid.winners",{url:"winners/",views:{"":{templateUrl:"/html/cups/cup/tabs/grids/single.html"},"right-column@cup":{}}}).state("cup.grid.playoff",{url:"playoff/",views:{"":{templateUrl:"/html/cups/cup/tabs/grids/single-l.html"},"right-column@cup":{}}}).state("cup.grid.losers",{url:"losers/",views:{"":{templateUrl:"/html/cups/cup/tabs/grids/single-l.html"},"right-column@cup":{}}}).state("cup.grid.results",{url:"results/",views:{"":{templateUrl:"/html/cups/cup/tabs/results.html",controller:"ggCupResultsController",controllerAs:"results"},"right-column@cup":{templateUrl:"/html/cups/cup/blocks/right-column.html"}},data:{fullWidth:!1},resolve:{$title:["$title",function($title){return $title+". Результаты"}]}}).state("cup.grid.ffastage",{url:"ffa/{stage}/",views:{"":{controller:"ggCupFFAStageController",controllerAs:"stage",templateUrl:"/html/cups/cup/tabs/grids/ffa-stage.html"},"right-column@cup":{}}}).state("cup.grid.stage",{url:"{stage:int}/{subtype}",views:{"":{controller:"ggCupStageController",controllerAs:"stage",templateUrl:"/html/cups/cup/tabs/grids/event-stage.html"},"right-column@cup":{}}}).state("cup.donat",{url:"support/",templateUrl:"/html/cups/cup/tabs/donat.html"})}),angular.module("GG").config(function($stateProvider,$urlRouterProvider,$locationProvider,$urlMatcherFactoryProvider){$stateProvider.state("list",{url:"/cup/",abstract:!0,templateUrl:"/html/cups/list/main.html?rnd=415124",controller:"ggCupsListController",controllerAs:"list",resolve:{listView:function(ggCupsApiService){return ggCupsApiService.getCupsListView()},$title:function(){return"Турниры"}}}).state("list.main",{url:"",templateUrl:"/html/cups/list/list.html"})}),angular.module("GG").config(function($stateProvider,$urlRouterProvider,$locationProvider,$urlMatcherFactoryProvi
12der){$stateProvider.state("team",{url:"/cup/team",abstract:!0,templateUrl:"/html/cups/team/main.html"
13}).state("team.new",{url:"/new/",controller:"ggTeamEditController",controllerAs:"editor",templateUrl:"/html/cups/team/create.html",resolve:{team:function($stateParams,ggTeamService){return ggTeamService.new()},$title:function(){return"Турниры. Создать команду"}}}).state("team.id",{url:"/{id:int}/",controller:"ggTeamViewController",controllerAs:"vm",templateUrl:"/html/cups/team/view.html",resolve:{team:function($stateParams,ggTeamService){return ggTeamService.init($stateParams.id)},$title:["team",function(team){return"Турниры. Команда "+team.title}]}}).state("team.id.edit",{url:"edit/",views:{"@team":{templateUrl:"/html/cups/team/create.html",controller:"ggTeamEditController",controllerAs:"editor"}},resolve:{$title:["$title",function($title){return $title+". Редактировать"}]}})}),function(angular){var scbwReport=function(){function scbwReport($scope){var _this101=this;_classCallCheck(this,scbwReport),this.$scope=$scope,this.match=!1,this.reports=[],$scope.$watch(function(){return _this101.match.dbid},function(n,o){return n!==o&&_this101.$onChanges()})}return _createClass(scbwReport,[{key:"$onChanges",value:function(){var _this102=this;console.log("$onChanges"),this.reports.length=0,this.match.bo?(this.rounds=Array.apply(null,{length:this.match.bo}).map(Number.call,Number),this.reports.length=this.match.bo,Utils.get("/ajax/cups/"+this.match.$cup.id+"/getMatchData/",{match:this.match.dbid}).then(function(data){return _this102.onLoadData(data)})):this.rounds=[]}},{key:"deleteReplay",value:function(n){this.reports[n].file=!1}},{key:"canReport",value:function(n){return this.reports[n]&&this.reports[n].myrace&&this.reports[n].hisrace&&this.reports[n].file&&this.reports[n].winner&&!this.reports[n].reported}},{key:"report",value:function(n){var _this103=this;this.reports[n].reported=!0;var data=new FormData;data.append("match",this.match.dbid),data.append("bo",n),data.append("data",JSON.stringify(this.reports[n])),data.append("file",this.reports[n].file);var all=this.checkAllReported();console.log(all?"all, reporting win!":"not all, reloading data"),Utils.postForm("/ajax/cups/"+this.match.$cup.id+"/reportMatchData/",data).then(function(data){return all?_this103.reportWin():_this103.onLoadData(data)})}},{key:"onLoadData",value:function(data){var _this104=this;console.log("onloaddata",data),data.length&&data.forEach(function(row,idx){_this104.reports[idx]=JSON.parse(row)})}},{key:"checkAllReported",value:function(){var all=!0;return this.reports.forEach(function(report){report.reported||(all=!1)}),all}},{key:"reportWin",value:function(){var score=[0,0];this.reports.forEach(function(report){"me"==report.winner&&score[0]++,"he"==report.winner&&score[1]++});var maxScore=Math.ceil(this.match.bo/2);console.log("maxScore",maxScore),score[0]==maxScore||score[1]==maxScore||score[0]+score[1]==this.match.bo?score[0]>score[1]?this.match.loss(score[0]+":"+score[1]):console.log("Лузер, не репортим"):console.log("еще не все матчи",score)}}]),scbwReport}();angular.module("GG").component("scbwReport",{controller:scbwReport,templateUrl:"/html/cups/cup/blocks/player-blocks/scbw-report.html",bindings:{match:"="}})}(angular),function(){function ggCupAboutController(cup,$scope,gamer,api){var about=this;about.showJoin=function(){var closedCup=3==cup.status;return!(6761==cup.id&&cup.participants.length>=480)&&(0==cup.type&&gamer.userId&&!closedCup&&!cup.started&&!gamer.user&&cup.start>Date.now())},about.showUnjoin=function(){return!!gamer.userId&&(!cup.started&&(1==cup.participants_type?gamer.user:void 0))},about.join=function(){1==cup.participants_type?cup.join():api.getUserTeams().then(function(data){about.joinStep=1,about.teams=data})},about.unjoin=function(){1==cup.participants_type&&cup.unjoin()},about.lineup=function(){if(about.joinTeam)for(var i=0;i<about.teams.length;i++)about.teams[i].id==about.joinTeam&&(about.selectedTeam=about.teams[i],about._selectedPlayers={},about._selectedPlayers[about.selectedTeam.creator]=!0,about.selectPlayer())},about.selectPlayer=function(){about.selectedPlayers=[];for(var id in about._selectedPlayers)about._selectedPlayers[id]&&about.selectedPlayers.push(id);about._last=cup.team_size-about.selectedPlayers.length},about.finishJoin=function(){if(about._last)return!1;cup.joinTeam(about.selectedTeam.id,about.selectedPlayers).then(function(){about.teams=about.selectedTeam=!1})}}angular.module("GG").controller("ggCupAboutController",ggCupAboutController),ggCupAboutController.$inject=["cup","$scope","ggCupGamerService","ggCupsApiService"]}(),function(){function ggCupController(cup,gamer,$state,$scope,$compile){var vm=this;vm.cup=cup,vm.gamer=gamer,vm.$state=$state,window.GGObj="26:"+cup.id,NotifyProxy.sendPing(),NotifyProxy.subscribe("26:"+cup.id,"querytest"),NotifyProxy.on("object_event",vm.cup.onEvent),document.title=cup.title,"#toComments"===window.location.hash&&setTimeout(function(){$(window.location.hash)[0].scrollIntoView(!0)},1e3),vm.cup&&vm.cup.chat&&(window.StreamController&&window.StreamController.showChat("r"+vm.cup.chat),window.cup=cup),$scope.$on("$destroy",function(){window.StreamController&&window.StreamController.showChat(!1),NotifyProxy.unsubscribe("26:"+cup.id),window.cup=!1}),vm.donatPopup=function(){DonatPopup.open(26,vm.cup.id)};var $changeParentScope;vm.toggleGridFullscreen=function(event){if(event&&event.target)if(vm.fullscreen=!vm.fullscreen,vm.fullscreen){var gridWrap=angular.element(event.target).closest(".grid-wrap"),changeParentWrap=angular.element('<gg-change-parent new-parent="body" class="grid-wrap-fullscreen"></gg-change-parent>');gridWrap.wrap(changeParentWrap),$changeParentScope=$scope.$new(),$compile(changeParentWrap)($changeParentScope)}else $changeParentScope.$destroy()}}angular.module("GG").controller("ggCupController",ggCupController),ggCupController.$inject=["cup","ggCupGamerService","$state","$scope","$compile"]}(),function(){function ggCupEditController(cup,$scope,api,$state){function saveCup(lift){var form=new FormData,cleanCup=angular.copy(cup);
13["gamer","grid","fullGrid","participants","supporters","judges","streams","notCheckined","checkined","creator"].forEach(function(key){delete cleanCup[key]}),cleanCup.start=Utils.toUTCDate(cleanCup.start).getTime()/1e3,form.append("cup",cleanCup.id),form.append("data",angular.toJson(cleanCup)),form.append("lift",lift?1:0),editor.$imgFile&&form.append("logo",editor.$imgFile),cup.saveForm(form).then(function(){isNew?$state.go("cup.about",{id:cup.id}):$state.go("^.about")})}var editor=this,isNew=!cup.id;editor.save=saveCup,function(){api.getCupEditView(cup.id).then(function(data){data=angular.fromJson(data),editor.games=data.games,editor.currentGame=editor.games[cup.game_id]})}(),$scope.$watch("vm.cup.game_id",function(){editor.games&&(editor.currentGame=editor.games[cup.game_id])})}angular.module("GG").controller("ggCupEditController",ggCupEditController),ggCupEditController.$inject=["cup","$scope","ggCupsApiService","$state"]}(),function(){function ggCupStageController($scope,cup,$stateParams){function init(){stage.current=!!cup.fullGrid&&cup.fullGrid[parseInt($stateParams.stage)-1],stage.current&&(cup.grid=stage.current.grid),stage.losers="losers"==$stateParams.subtype}var stage=this;$scope.$watch("vm.cup.fullGrid",function(){init()}),init()}angular.module("GG").controller("ggCupStageController",ggCupStageController),ggCupStageController.$inject=["$scope","cup","$stateParams"]}(),function(){var ggCupFFAStageController=function(){function ggCupFFAStageController($scope,cup,$stateParams){var _this105=this;_classCallCheck(this,ggCupFFAStageController);var stageNum=$stateParams.stage;this.$cup=cup,this.$stage=cup.grid.stages.filter(function(stage){return stage.n==stageNum})[0],this.matches=this.$stage.matches,this.finalBO=this.matches.length-1||1,this.matches.forEach(function(match){match.oldServer=match.server,match.oldPass=match.password}),this.currentMatch=this.$stage.group?0:this.finalBO,this.$edit=!1,$scope.$watch(function(){return _this105.matches[0].scores},function(){return _this105.filterTable()})}return _createClass(ggCupFFAStageController,[{key:"save",value:function(){this.$edit=!1,this.matches.forEach(function(match){match.save(match.oldServer!=match.server),match.oldServer=match.server,match.oldPass=match.password});var grid=this.$cup.grid.getGrid(),data=this.$cup.grid.getGridData();this.$cup.saveGrid(grid,data,!0),this.$cup.grid.afterLoad()}},{key:"close",value:function(){this.$stage.matches[this.currentMatch].closed=1,this.$stage.matches.length>1&&this.$stage.matches[this.currentMatch].generateTotalScore(),this.$cup.grid.createFinal(),this.save()}},{key:"serverSaveDisabled",value:function(){return this.matches[this.currentMatch].oldServer==this.matches[this.currentMatch].server&&this.matches[this.currentMatch].oldPass==this.matches[this.currentMatch].password}},{key:"filterTable",value:function(){var _this106=this;this.matches.forEach(function(match){match.$reported=_this106.getReported(match.$scores,!0),match.$notReported=_this106.getReported(match.$scores,!1)}),this.$stage.matches.length>1&&this.$stage.matches[0].generateTotalScore()}},{key:"getReported",value:function(scores,flag){var arr=scores.filter(function(place){return flag?null!=place.score[0]:null==place.score[0]});return flag&&arr.length<3&&this.$stage.group&&(arr.length=3),arr}},{key:"getKillScore",value:function(place){return place?place.sum?place.score[1]:(new GGCupFFAMatch).getKillScore(place.score[1]):0}},{key:"getPlaceScore",value:function(place){return place?place.sum?place.score[0]:(new GGCupFFAMatch).getPlaceScore(place.score[0]):0}},{key:"getScore",value:function(place){return place?place.sum?place.score[0]+place.score[1]:(new GGCupFFAMatch).getScore(place.score[0],place.score[1]):0}}]),ggCupFFAStageController}();angular.module("GG").controller("ggCupFFAStageController",ggCupFFAStageController)}(),function(){function ggCupFormatController(cup,$scope,ggCupGridFactory,$state){var format=this;cup.fullGrid||(cup.fullGrid=[]),format.stages=cup.fullGrid,format.addGrid=function(){format.stages.push({grid_type:1})},format.addGroup=function(){format.stages.push({grid_type:5})},format.delete=function(stage){format.stages.splice(format.stages.indexOf(stage),1)},format.save=function(){cup.fullGrid||(cup.fullGrid=[]);var forSave=[];
13format.stages.forEach(function(stage,index){if(cup.fullGrid[index]=stage,!stage.grid){var grid;switch(stage.grid_type){case 1:grid=new GGCupGridSingle(cup);break;case 3:grid=new GGCupGridDouble(cup);break;case 4:grid=new GGCupGridGroups(cup),grid.hasPlayoff=!1,grid.bo=stage.bo;break;case 5:grid=new GGCupGridEventGroups(cup),grid.groupsCount=stage.groups,grid.bo=stage.bo}grid.setPlayers(parseInt(stage.participants,10)),grid.generate(),stage.grid=grid}forSave.push({name:stage.name,grid_type:stage.grid_type,grid:stage.grid.getGrid(),data:stage.grid.getGridData(),participants:parseInt(stage.participants,10),bo:stage.bo,groupsCount:stage.groupsCount})});var winners=cup.winners.map(function(user){return user.id});cup.grid_saved=!0,cup.saveGrid({stages:forSave,winners:winners}),$state.go("cup.grid.stage",{stage:1})}}angular.module("GG").controller("ggCupFormatController",ggCupFormatController),ggCupFormatController.$inject=["cup","$scope","ggCupGridFactory","$state"]}(),function(){function ggCupGridController(cup,$scope,ggCupGridFactory,$state){var gridController=this;gridController.floor=Math.floor,gridController.save=function(){if(!cup.admin)return!1;if(cup.grid_saved&&8!=cup.grid_type)return alert("Сетка уже сгенерирована"),$state.go("cup.about"),!1;var grid=cup.grid.getGrid(),data=cup.grid.getGridData();cup.saveGrid(grid,data).then(function(newData){cup.grid.load(newData)})},gridController.change=function(){cup.grid=ggCupGridFactory.create(cup,[])}}angular.module("GG").controller("ggCupGridController",ggCupGridController),ggCupGridController.$inject=["cup","$scope","ggCupGridFactory","$state"]}(),function(){function ggCupsListController(listView,$scope,api,DateFunctions,$timeout,$filter,$state){function onDataLoaded(data){if(angular.extend(list,data),["myCups","opened"].forEach(function(key){list[key].forEach(function(cup){cup.start=new Date(1e3*cup.start),cup.startInt=+cup.start,cup.mine="0"!=cup.mine})}),list.profiles)for(var key in list.profiles){list.selectedAccount=key;break}list.singleAccount=1==Object.keys(list.profiles).length,list.hot=[];for(var i=0;i<list.opened.length&&list.hot.length<6;i++)list.opened[i].prize_fund>"1"&&list.hot.push(list.opened[i]);if(list.hot.length<3)for(var i=0;list.hot.length<3;)-1==list.hot.indexOf(list.opened[i])&&list.hot.push(list.opened[i]),i++}function timeLeft(cup){var start=cup.start;if("string"==typeof start)return start;var d=+start-Date.now();return cup.showJoin=d>0&&!cup.started,d<0?"Уже идет":d>216e5?DateFunctions.formatDate(start):"Через "+Utils.timeLeft(d,0)}function getStage(stage){return"1/"+Math.ceil(Math.pow(2,stage-1))}function joinCup(cup){if(!UserObj.id)return void window.openLogin();1==cup.participants_type?!1===cup.mine?api.join(cup.id).then(function(data){cup.mine=!0,setStatus(cup,"Вы участвуете в турнире"),list.myCups.push(cup)}):api.unjoin(cup.id).then(function(data){cup.mine=!1,setStatus(cup,"Вы отказались от участия");var index=findCup(list.myCups,cup);-1!=index&&list.myCups.splice(index,1)}):$state.go("cup.about",{id:cup.id})}function findCup(where,what){for(var i=0;i<where.length;i++)if(where[i].id==what.id)return i;return-1}function setStatus(cup,text){cup.statusText=text,cup.showStatus=!0,$timeout(function(){cup.showStatus=!1},2e3)}function loadOldCups(){list.oldPage=1,list.old||(list.old=[]),list.oldLoaded=!1,list.showOldLoadMore=!0,processLoadOldCups()}function loadMoreOlds(){list.oldPage+=1,list.oldLoaded=!1,list.showOldLoadMore=!0,processLoadOldCups(list.oldSearch&&list.oldSearch.length>2?list.oldSearch:"")}function processLoadOldCups(searchString){api.getOldCupsList(list.oldPage,searchString).then(function(data){data.length<30&&(list.showOldLoadMore=!1),Array.prototype.push.apply(list.old,data),list.oldLoaded=!0,list.old.forEach(function(cup){cup.startInt||(cup.startInt=1e3*cup.start,cup.start=$filter("ggDate")(cup.startInt,"dd.MM.yyyy"))})})}function searchOldCups(){list.oldPage=1,list.old=[],list.oldLoaded=!1,list.showOldLoadMore=!0,processLoadOldCups(list.oldSearch&&list.oldSearch.length>2?list.oldSearch:"")}var list=this;list.timeLeft=timeLeft,list.getStage=getStage,list.join=joinCup,list.loadOldCups=loadOldCups,list.loadMoreOlds=loadMoreOlds,list.searchOldCups=searchOldCups,window.GGObj="26:0",NotifyProxy.sendPing(),function(){onDataLoaded(angular.copy(listView)),list.loaded=!0}()}angular.module("GG").controller("ggCupsListController",ggCupsListController),ggCupsListController.$inject=["listView","$scope","ggCupsApiService","DateFunctions","$timeout","$filter","$state"]}(),function(){function ggPlayerBlockController(cup,gamer,$scope,$sce){var block=this;!function(){block.hasChat=!(!gamer.match||!gamer.match.chat),block.chatUrl=!(!gamer.match||!gamer.match.chat)&&$sce.trustAsResourceUrl("/chat/r"+gamer.match.chat)}
13(),block.showEditAccount=!gamer.user.contact,block.editAccount=function(){block.newAccount=gamer.user.contact,block.showEditAccount=!0},block.saveAccount=function(){gamer.saveAccount(block.newAccount).then(function(data){block.showEditAccount=!gamer.user.contact})},block.canCheckin=function(){var currentUtc=Date.now(),allAccounts=!1;return gamer.team&&gamer.isCaptain?(allAccounts=!0,gamer.team&&gamer.isCaptain&&gamer.team.players.forEach(function(player){player.contact||(allAccounts=!1)})):allAccounts=!!gamer.user.contact,7102==cup.id&&(currentUtc=cup.start-18e5),gamer.user&&allAccounts&&!gamer.user.checkin&&cup.start>=currentUtc&&cup.start-36e5<=currentUtc},block.reportLoss=function(score){gamer.match&&gamer.match.loss(score||block.score)},$scope.$watch(function(){block.leftToConfirm=Utils.timeLeft(+cup.start-36e5,Date.now()),block.leftToStart=Utils.timeLeft(+cup.start,Date.now())})}angular.module("GG").controller("ggPlayerBlockController",ggPlayerBlockController),ggPlayerBlockController.$inject=["cup","ggCupGamerService","$scope","$sce"]}(),function(){function ggCupPlayersController(cup,$scope){function addJudge(user){user.p_id&&cup.addJudge(user.p_id)}function removeJudge(user){user.id&&cup.removeJudge(user.id)}function addPlayer(user){user.p_id&&cup.join(user.p_id)}var players=this;players.addJudge=addJudge,players.removeJudge=removeJudge,players.addPlayer=addPlayer}angular.module("GG").controller("ggCupPlayersController",ggCupPlayersController),ggCupPlayersController.$inject=["cup","$scope"]}(),function(){function ggCupResultsController($scope,cup){var results=this;results.prize_places=cup.prize_places,results.places=new Array(cup.prize_places),$scope.$watch("results.prize_places",function(){results.prize_places!=cup.prize_places&&(cup.prize_places=results.prize_places,cup.save({prize_places:cup.prize_places}))}),$scope.$watch("vm.cup.prize_places",function(){results.prize_places=cup.prize_places}),results.getPrize=function(place){return cup.getPrize(place)},results.setWinner=function(user,place){cup.winners[place]={id:user.p_id,name:user.nickname,avatar:user.avatar},cup.getPlayer(user.p_id)||cup.join(user.p_id),cup.saveFullGrid()}}angular.module("GG").controller("ggCupResultsController",ggCupResultsController),ggCupResultsController.$inject=["$scope","cup"]}(),function(){function ggTeamEditController(team,$scope,$state){function save(){var form=new FormData;return form.append("team",team.id),form.append("data",angular.toJson(team)),editor.$imgFile&&form.append("logo",editor.$imgFile),team.save(form)}var editor=this;editor.team=team,editor.addPlayer=function(user){Promise.resolve(!!team.id||save()).then(function(){team.addPlayer(user.p_id)})},editor.deletePlayer=function(userId){team.delPlayer(userId)},editor.save=function(){save().then(function(){$state.go("team.id",{id:team.id})})}}angular.module("GG").controller("ggTeamEditController",ggTeamEditController),ggTeamEditController.$inject=["team","$scope","$state"]}(),function(){function ggTeamViewController(team,$scope,$state){this.team=team}angular.module("GG").controller("ggTeamViewController",ggTeamViewController),ggTeamViewController.$inject=["team","$scope","$state"]}(),function(angular){function gridScroll(){function link(scope,element){var moveBegin=!1,moveCoor={};element.on("mousedown.gridScroll",function(e){e&&1===e.which&&"INPUT"!==e.target.tagName.toUpperCase()&&(moveBegin=!0,moveCoor={x:e.pageX,y:e.pageY})}),$(window).on("mousemove.gridScroll",function(e){if(moveBegin){var moveDiff={x:e.pageX-moveCoor.x,y:e.pageY-moveCoor.y};moveCoor={x:e.pageX,y:e.pageY};var scrollEl=element[0].SimpleBar.getScrollElement();scrollEl.scrollLeft-=moveDiff.x,scrollEl.scrollTop-=moveDiff.y,e.preventDefault()}}),$(window).on("mouseup.gridScroll",function(e){moveBegin=!1}),scope.$on("$destroy",function(){element.off("mousedown.gridScroll"),$(window).off(".gridScroll")});var iOS=navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform),droid=/android/i.test(navigator.userAgent);iOS||droid?element.css({overflow:"scroll","-webkit-overflow-scrolling":"touch"}):(new SimpleBar(element[0]),element.addClass("simple-bar"))}return{restrict:"A",link:link}}angular.module("GG").directive("gridScroll",gridScroll)}(angular),function(angular){function cupSortableTable(){function link(scope,element,attrs){scope.orderField=attrs.field,scope.reverse=attrs.reverse&&"false"!=attrs.reverse;var sortableHeaders=element.find("[cup-sort]"),sortableDirections=sortableHeaders.find(".icon");sortableHeaders.on("click",function(event){scope.orderField==$(this).attr("cup-sort")?scope.reverse=!scope.reverse:scope.orderField=$(this).attr("cup-sort"),scope.$apply()}),scope.$watch("[orderField, reverse]",function(){sortableHeaders.removeClass("active"),sortableDirections.removeClass("icon-angle-down icon-angle-up"),sortableHeaders.filter('[cup-sort="'+scope.orderField+'"]').addClass("active").find(".icon").addClass(scope.reverse?"icon-angle-down":"icon-angle-up")})}return{scope:!0,restrict:"A",link:link}}angular.module("GG").directive("cupSortableTable",cupSortableTable)}(angular);var GGCupFFAMatch=function(){function GGCupFFAMatch(data){_classCallCheck(this,GGCupFFAMatch),data||(data={}),this.$cup=!!data.stage&&data.stage.$cup,this.$stage=data.stage,this.n=data.n,this.$scores=[],this.scores=[],this.$players=[],data.scores&&data.scores.length&&this.fillScores(data.scores),this.opened=data.opened}return _createClass(GGCupFFAMatch,[{key:"setPlayers",value:function(players){var _this107=this;this.$players=players,this.$scores=[],this.scores=[],players.forEac
13h(function(pl){_this107.$scores.push({team:pl,score:[null,null],total:0}),_this107.scores.push([pl.id,null,null])})}},{key:"fillScores",value:function(scores){var _this108=this;this.$players.length=0,this.$scores.length=0,this.scores=scores,scores.forEach(function(line){_this108.$players.push(_this108.$cup.getPlayer(line[0])),_this108.$scores.push({team:_this108.$cup.getPlayer(line[0]),score:[line[1],line[2]]})}),this.sortScores()}},{key:"_getScore",value:function(a){return a.score[0]||a.score[1]?this.getScore(a.score[0],a.score[1]):a.team?-a.team.id:1}},{key:"getScore",value:function(place,kills){return this.getPlaceScore(place)+this.getKillScore(kills)||0}},{key:"getPlaceScore",value:function(place){return+place}},{key:"getKillScore",value:function(kills){return 9*kills||0}},{key:"sortScores",value:function(){var _this109=this;this.$scores.sort(function(a,b){return _this109._getScore(b)-_this109._getScore(a)})}},{key:"save",value:function(open){var _this110=this;this.sortScores(),open&&(this.opened=Math.round(Utils.moscowTime()/1e3)+900),this.scores=[],this.$scores.forEach(function(place){return _this110.scores.push([place.team.id,place.score[0],place.score[1]])})}},{key:"participate",value:function(player){return!this.closed&&-1!=this.$players.indexOf(player)}},{key:"getPlayerScore",value:function(player){var score=!1;return this.$scores.forEach(function(place){place.team.id==player.id&&(score=place.score)}),score}},{key:"timeLeft",value:function(){if(!this.opened)return 0;var left=Math.round(this.opened-Utils.moscowTime()/1e3);return left>0?function(secs){var minutes=Math.floor(secs/60),seconds=secs-60*minutes;return Utils.withZero(minutes)+":"+Utils.withZero(seconds)}(left):-1}},{key:"loss",value:function(score){var _this111=this;this.$cup.reportLoss(this.$stage.n+":"+this.n,score).then(function(grid){return _this111.$cup.grid.load(grid)})}},{key:"getCurrentMatch",value:function(){for(var i=0;i<this.$stage.matches.length;i++)if(!this.$stage.matches[i].closed)return this.$stage.matches[i];return this}},{key:"getSlot",value:function(player){var ret="";return this.$scores.forEach(function(place,idx){place.team.id==player.id&&(ret=idx+1)}),ret}},{key:"generateTotalScore",value:function(){var lastMatch=this.$stage.matches.length-1||1;this.$stage.matches[lastMatch]=new GGCupFFAMatch;var sum={},allClosed=!0;this.$stage.matches.forEach(function(match){match.$scores&&(match.$scores.forEach(function(place){var placeScore=(new GGCupFFAMatch).getPlaceScore(place.score[0]),killsScore=(new GGCupFFAMatch).getKillScore(place.score[1]),lastScore=sum[place.team.id]?sum[place.team.id].score:[0,0];sum[place.team.id]={sum:1,team:place.team,score:[placeScore+lastScore[0],killsScore+lastScore[1]]}}),console.log(match,match.closed),match.n&&!match.closed&&(allClosed=!1))});var sumArr=[];for(var key in sum)sumArr.push(sum[key]);sumArr.sort(function(a,b){return b.score[0]+b.score[1]-(a.score[0]+a.score[1])}),sumArr.length<3&&(sumArr.length=3),this.$stage.matches[lastMatch].$reported=sumArr,this.$stage.matches[lastMatch].closed=allClosed}}]),GGCupFFAMatch}();!function(){function ggCupGridFactory(){function create(cup,stages){if(console.log("ggCupGridFactory.create",cup.grid_type),!cup.type){var grid;switch(cup.grid_type){case 1:grid=new GGCupGridSingle(cup,stages);break;case 3:grid=new GGCupGridDouble(cup,stages);break;case 4:grid=new GGCupGridGroups(cup,stages);break;case 6:grid=new GGCupGridFFA10(cup,stages);break;case 7:grid=new GGCupGridFFAM(cup,stages);break;case 8:grid=new GGCupGridOverwatch(cup,stages);break;case 9:grid=new GGCupGridRRGroups(cup,stages)}return grid.load(),cup.grid=grid,grid}try{var fullGridDate=angular.fromJson(stages)}catch(e){return console.error(e),!1}fullGridDate.stages?(stages=fullGridDate.stages,cup.winners=fullGridDate.winners.map(function(user){return user?cup.getPlayer(user):void 0})):(stages=fullGridDate,cup.winners=[]),cup.fullGrid=[],stages.forEac
13h(function(dataArr){var grid,type=dataArr.grid_type,gridArr=dataArr.grid;switch(cup.grid_data=dataArr.data,type){case 1:grid=new GGCupGridSingle(cup,gridArr);break;case 3:grid=new GGCupGridDouble(cup,gridArr);break;case 4:grid=new GGCupGridGroups(cup,gridArr);break;case 5:grid=new GGCupGridEventGroups(cup,gridArr)}return grid&&grid.load(),dataArr.grid=grid,cup.fullGrid.push(dataArr),cup.fullGrid})}return{create:create}}angular.module("GG").factory("ggCupGridFactory",ggCupGridFactory)}(),GGCupMatch.prototype.getClass=function(){return this.$cup.grid.getMatchClass(this)},GGCupMatch.prototype.close=function(save){return this.closed?this.winner:(this.dbid&&save?this.save(!0):this.players[1]||(this.winner=this.players[0],this.closed=!0,this.$stage&&this.$cup&&this._showTargetPlace()),this.winner)},GGCupMatch.prototype.changeScore=function(plus,index,force){if(!(force=force||!1)&&this.closed)return!1;this.score.length||(this.score=[0,0]);var targetValue=Math.max(parseInt(plus)+parseInt(this.score[index]),0);if(this.bo){var flawless=Math.ceil(this.bo/2);targetValue=Math.min(targetValue,flawless),targetValue=Math.min(targetValue,this.bo-this.score[index?0:1]),this.score[index]=targetValue}else this.score[index]=targetValue;return this._canClose(),this.canclose?(this.winner=this.score[0]>this.score[1]?this.players[0]:this.players[1],this.loser=this.winner==this.players[0]?this.players[1]:this.players[0]):(this.winner=!1,this.loser=!1),this._showTargetPlace(),this.changed=!0,!0},GGCupMatch.prototype.changeScoreHard=function(plus,index){return this.changeScore(plus,index,!0)},GGCupMatch.prototype._showTargetPlace=function(){this.$cup.grid.showTargetPlace(this)},GGCupMatch.prototype._canClose=function(){if(this.bo){var flawless=Math.ceil(this.bo/2);this.canclose=this.score[0]==flawless||this.score[1]==flawless}else this.canclose=!0},GGCupMatch.prototype.cancelEdit=function(){this.score=angular.copy(this._score),this.changed=!1,this.editMode=!1,this.winner=!1,this.loser=!1,this._canClose(),this._showTargetPlace()},GGCupMatch.prototype.save=function(close){var self=this;self._loading=!0,this.$cup&&this.dbid?this.$cup.saveMatch(this.getData(),close).then(function(grid){self.$cup.grid.load(grid),self.changed=!1,self._loading=!1}):this.$cup&&this.$cup.type?(self.closed=self.canclose,self.$cup.saveFullGrid()):alert("Ошибка сохранения матча")},GGCupMatch.prototype.getData=function(){return{dbid:this.dbid,first:this.first,third:this.third,closed:this.closed,score:this.score,seeded:this.seeded,players:!!this.players&&[!!this.players[0]&&this.players[0].id,!!this.players[1]&&this.players[1].id]}},GGCupMatch.prototype.cancel=function(save){if(this.$cup.closed)return!1;if(!save||confirm("Вы уверены, что хотите отменить результаты этого матча?")){if(save?GGCupMatch.bulkArray=[]:GGCupMatch.bulkArray.push(this),!this.closed)return!1;this.closed=!1,this.score=[],this.third&&(this.$cup.winners[2]&&(this.$cup.winners[2]=!1),this.$cup.winners[3]&&(this.$cup.winners[3]=!1)),this.first&&(this.$cup.winners[0]=!1,this.$cup.winners[1]&&(this.$cup.winners[1]=!1));var stages=this.$cup.grid.getStages(),currentStage=stages.indexOf(this.$stage),s=[this.winner.id,this.loser.id];if(1==this.$stage.group)for(var currentMatch=this.$stage.matches.indexOf(this),y=currentMatch+1;y<this.$stage.matches.length;y++){var m=this.$stage.matches[y];-1!=s.indexOf(m.players[0].id)&&(m.players[0]={},m.score=[],m.seeded=0,m.cancel(!1)),-1!=s.indexOf(m.players[1].id)&&(m.players[1]={},m.score=[],m.seeded=0,m.cancel(!1))}if(-1!=currentStage)for(var x=currentStage+1;x<stages.length;x++)for(var y=0;y<stages[x].matches.length;y++){var m=stages[x].matches[y];-1!=s.indexOf(m.players[0].id)&&(m.players[0]={},m.score=[],m.seeded=0,m.cancel(!1)),-1!=s.indexOf(m.players[1].id)&&(m.players[1]={},m.score=[],m.seeded=0,m.cancel(!1))}this.winner=!1,this.loser=!1,save&&(this.$cup.grid._closeFreeMatches(),GGCupMatch.bulkArray.push(this),this.bulkSave())}},GGCupMatch.prototype.bulkSave=function(){for(var self=this,data=[],i=0;i<GGCupMatch.bulkArray.length;i++)data.push(GGCupMatch.bulkArray[i].getData());this.$cup.saveMatches(data).then(function(grid){self.$cup.grid.load(grid),self.changed=!1})},GGCupMatch.prototype.loss=function(_score){var self=this;if(1==this.bo&&(_score="1:0"),2!=this.bo){var score=_score.split(":"),maxScore=Math.ceil(this.bo/2);if(score[0]=parseInt(score[0]),score[1]=parseInt(score[1]),score[0]!=maxScore&&score[1]!=maxScore||score[0]+score[1]>this.bo)return void alert("Введен неправильный счет для Bo"+this.bo)}this.$cup.reportLoss(this.dbid,_score).then(function(grid){self.$cup.grid.load(grid),self.changed=!1})},GGCupMatch.prototype.getSword=function(pos){return(parseInt(this.dbid)+parseInt(pos?this.players[1].id:this.players[0].id))%11},GGCupMatch.prototype.addPlayer=function(user,place){user&&user.avatar&&"/"!=user.avatar[0]&&(user.avatar="/"+user.avatar),console.log(this.players),this.players[place]={id:user.p_id,name:user.nickname,avatar:user.avatar},this.$cup.join(user.p_id),this.$cup.type?this.$cup.saveFullGrid():this.save()},GGCupMatch.prototype.scrollTo=function(){var _this112=this,mBlock=$("#m"+this.dbid),wH=$(window).height()/2,wW=$(".grid-wrap").width()/2;if(!wW)return this.$cup.showPage("cup.grid.single"),void setTimeout(function(){return _this112.scrollTo()},100);Header.getScroller().animate({scrollTop:mBlock.offset().top-wH+"px"},"fast");var container=$(".simplebar-content"),wH2=$("[grid-scroll]").height()/2;$(".simplebar-scroll-content").animate({scrollTop:mBlock.offset().top-container.offset().top-wH2+"px",scrollLeft:mBlock.offset().left-container.offset().left-wW+"px"},"fast"),mBlock.addClass("highlight"),setTimeout(function(){mBlock.removeClass("highlight")},2e3)},GGCupMatch.prototype.participate=function(player){return this.players[0].id==player.id||this.players[1].id==player.id},GGCupMatch.prototype.timeElapsed=function(){if(!this.opened)return!1;return function(secs,showAll){void 0===showAll&&(showAll=!0);var sec_num=Math.floor(secs/1e3),hours=Math.floor(sec_num/3600),minutes=Math.floor((sec_num-3600*hours)/60),seconds=sec_num-3600*hours-60*minutes;if(hours<0)return"";if(showAll)var time=Utils.withZero(hours)+":"+Utils.withZero(minutes)+":"+Utils.withZero(seconds);else var time=(hours?Utils.withZero(hours)+":":"")+Utils.withZero(minutes)+":"+Utils.withZero(seconds);return time}(Date.now()-this.opened,!1)},GGCupStage.prototype.getName=function(){if(this.$cup.grid.ffa)return this.getFFAQualiName();if(this.group)return this.getGroupStageName();if(1.3==this.n)return"Матч за третье место";if(-1==this.n)return"Суперфинал";var r=Math.ceil(Math.pow(2,this.n-1));
13return{1:"Финал",2:"Полуфинал"}[r]||"1/"+r},GGCupStage.prototype.getFFAQualiName=function(){if(!this.group)return"Финал";if(6==this.$cup.grid_type)return"Квалификация Q"+this.n;var QH=Math.floor(this.n/10)+1;return"Квалификация Q"+QH+"-"+(this.n-10*(QH-1))},GGCupStage.prototype.getGroupStageName=function(){return"Группа "+String.fromCharCode(65+this.n)},GGCupStage.prototype.setPlayer=function(user,place){user&&user.avatar&&"/"!=user.avatar[0]&&(user.avatar="/"+user.avatar),this.scores[place].user={id:user.p_id,name:user.nickname,avatar:user.avatar},this.$cup.grid.fillMatches(this),1==this.$cup.participants_type?this.$cup.join(user.p_id):this.$cup.joinTeam(user.p_id,!0),this.$cup.saveFullGrid()},GGCupGroupStage.prototype=Object.create(GGCupStage.prototype),
14GGCupGroupStage.prototype.constructor=GGCupStage,GGCupGroupStage.prototype.getRows=function(){if(this.matches._rows)return this.matches._rows;var rows=this.matches.slice(),teamsMatches={};rows.forEach(function(match){teamsMatches[match.players[0].id]||(teamsMatches[match.players[0].id]={player:match.players[0],matches:[]}),teamsMatches[match.players[1].id]||(teamsMatches[match.players[1].id]={player:match.players[1],matches:[]}),teamsMatches[match.players[0].id].matches.push(match)});var ret=[];for(var t in teamsMatches)ret.push(teamsMatches[t]);return this.matches._rows=ret.sort(function(a,b){return a.matches.length-b.matches.length}),this.matches._rows},GGCupGroupStage.prototype.getTeamsRow=function(){return this.matches._rows||this.getRows(),this.matches._rows.map(function(a){return a.player})},function(){function ggCupsApiService($http,$httpParamSerializer,$timeout){function showLoader(){loaderTimeout=$timeout(function(){started=!0,PageLoader.showLoader()},250)}function hideLoader(){$timeout.cancel(loaderTimeout),started&&(PageLoader.hideLoader(),started=!1)}var api=function(){return{get:function(url,params){return showLoader(),$http.get("/ajax/cups/"+url+(params?"/?"+$httpParamSerializer(params):"")).then(function(response){return hideLoader(),response.data})},post:function(url,params){return params||(params={}),showLoader(),$http({method:"POST",url:"/ajax/cups/"+url+"/",data:$.param(params),headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(function(response){return hideLoader(),response.data})},postForm:function(url,form){return showLoader(),$http({method:"POST",url:"/ajax/cups/"+url+"/",data:form,transformRequest:angular.identity,headers:{"Content-Type":void 0}}).then(function(response){return hideLoader(),response.data})}}}(),_gridCache={};this.getCupsListView=function(){return api.get("list/view")},this.getOldCupsList=function(page,search){return page=page||1,api.get("list/oldcups",{page:page,search:search})},this.getCup=function(cupid){return api.get(cupid)},this.getCupView=function(cupid){return _gridCache={},api.get(cupid+"/view")},this.getCupEditView=function(cupid){return api.get(cupid+"/edit")},this.join=function(cupid,userId,lineup){return api.post(cupid+"/join",{user:userId,lineup:lineup})},this.unjoin=function(cupid,userId){return api.post(cupid+"/unjoin",{user:userId})},this.checkin=function(cupid,teamId){return api.post(cupid+"/checkin",{team:teamId})},this.addStreamer=function(cupid){return api.post(cupid+"/streamer",{join:1})},this.removeStreamer=function(cupid){return api.post(cupid+"/streamer",{join:0})},this.addJudge=function(cupid,userid){return api.post(cupid+"/judge",{join:1,user:userid})},this.removeJudge=function(cupid,userid){return api.post(cupid+"/judge",{join:0,user:userid})},this.getGrid=function(cupid){return _gridCache[cupid]?Promise.resolve(angular.copy(_gridCache[cupid])):api.get(cupid+"/grid").then(function(data){return angular.copy(_gridCache[cupid]=data)})},this.saveGrid=function(cupid,grid_type,grid,data){return api.post(cupid+"/saveGrid",{grid:grid,grid_type:grid_type,grid_data:data}).then(function(data){return angular.copy(_gridCache[cupid]=data.grid)})},this.saveMatch=function(cupid,matchData,close){return api.post(cupid+"/saveMatch",{data:matchData,close:close}).then(function(data){return angular.copy(_gridCache[cupid]=data.grid)})},this.saveMatches=function(cupid,matchesData){return api.post(cupid+"/saveMatches",{data:matchesData}).then(function(data){return angular.copy(_gridCache[cupid]=data.grid)})},this.reportLoss=function(cupid,matchid,score){return api.post(cupid+"/reportLoss",{match:matchid,score:score}).then(function(data){return angular.copy(_gridCache[cupid]=data.grid)})},this.close=function(cupid){return api.post(cupid+"/close")},this.save=function(cupId,form){return api.postForm(cupId+"/save",form)},this.saveValues=function(cupId,values){return values.values=1,api.post(cupId+"/save",values)},this.delete=function(cupId,action){return api.post(cupId+"/delete",{action:action})},this.publish=function(cupId){return api.post(cupId+"/publish",{action:"publish"})},this.attachAccount=function(cupId,account){return api.post(cupId+"/userAccount",{account:account})},this.getUserTeams=function(){return api.get("team/user/")},this.getTeam=function(teamId){return api.get("team/"+teamId+"/")},this.addTeamPlayer=function(teamId,userId){return api.post("team/"+teamId+"/join",{user:userId})},this.delTeamPlayer=function(teamId,userId){return api.post("team/"+teamId+"/leave",{user:userId})},this.saveTeam=function(teamId,form){return api.postForm("team/"+teamId+"/save",form)},this.teamProcessInvite=function(teamId,action){return api.post("team/"+teamId+"/invite",{action:action})},this.deleteTeam=function(teamId,action){return api.post("team/"+teamId+"/delete",{action:action?1:0})};var loaderTimeout,started}angular.module("GG").service("ggCupsApiService",ggCupsApiService)}(),function(){function ggCupService(api,gamer,ggCupGridFactory,$rootScope,$state){function init(cupId){return api.getCupView(cupId).then(function(data){return onDataLoad(data.cup,data.grid),cup.admin=data.admin,cup})}function newCup(){return cup.id=0,cup.title="",cup.game_id=0,cup.logo=!1,cup.description="",cup.start=new Date,cup.participants_type=1,cup.finalbo=3,cup.status=1,cup.admin=1,cup.grid=!1,cup.fullGrid=!1,0==window.location.search.indexOf("?type=1")&&(cup.type=1,cup.prizes=[]),cup}function onDataLoad(cupData,gridData){return cup.id!=cupData.id&&newCup(),cup.fullGrid=!1,angular.extend(cup,parseCup(cupData)),gridData&&ggCupGridFactory.create(cup,gridData),cup.gamer.init(cup),cup}function joinPlayer(userId){return console.log("join player"),api.join(cup.id,userId).then(function(data){return onDataLoad(data)})}function joinTeam(teamId,lineup){return console.log("join team"),api.join(cup.id,teamId,lineup).then(function(data){return onDataLoad(data)})}function unjoinPlayer(userId){return api.unjoin(cup.id,userId).then(function(data){return onDataLoad(data)})}function checkinPlayer(teamId){return api.checkin(cup.id,teamId).then(function(data){return"too_many_players"==data.error?(alert("На турнире установлено ограничение в 120 команд. К сожалению, вы не успели подтвердить участие."),!1):data.error?(alert("Вы можете подтвердить участие за час до турнира."),!1):onDataLoad(data)})}function addStreamer(){return api.addStreamer(cup.id).then(function(data){return onDataLoad(data)})}function removeStreamer(){return api.removeStreamer(cup.id).then(function(data){return onDataLoad(data)})}function addJudge(userId){return api.addJudge(cup.id,userId).then(function(data){return onDataLoad(data)})}function removeJudge(userId){return api.removeJudge(cup.id,userId).then(function(data){return onDataLoad(data)})}function save(form){return api.save(cup.id,form).then(function(data){return onDataLoad(data)})}function saveValues(values){return api.saveValues(cup.id,values).then(function(data){return onDataLoad(data)})}function publish(){return api.publish(cup.id).then(function(data){return onDataLoad(data)})}function getGrid(){return api.getGrid(cup.id)}function saveGrid(grid,data,noInit){return api.saveGrid(cup.id,cup.grid_type,angular.toJson(grid),angular.toJson(data)).then(function(data){return noInit||init(cup.id),data})}function saveFullGrid(){var forSave=[];if(!this.fullGrid)throw console.log("fullGrid not exist"),"fullGrid not exist";
14this.fullGrid.forEach(function(stage){forSave.push({name:stage.name,grid_type:stage.grid_type,grid:stage.grid.getGrid(),data:stage.grid.getGridData(),participants:stage.participants,bo:stage.bo,groupsCount:stage.groupsCount})});var winners=[],key=null;for(key in this.winners)this.winners[key]&&winners.push(this.winners[key]);console.log(forSave),this.saveGrid({stages:forSave,winners:winners})}function saveMatch(matchData,close){return api.saveMatch(cup.id,angular.toJson(matchData),close)}function saveMatches(matchesData){return api.saveMatches(cup.id,angular.toJson(matchesData))}function reportLoss(matchId,score){return api.reportLoss(cup.id,matchId,score)}function deleteCup(action){return api.delete(cup.id,action?1:0).then(function(data){return onDataLoad(data)})}function closeCup(){return api.close(cup.id).then(function(data){return onDataLoad(data)})}function getTeamPlayer(playerId){for(var players=this.players,i=0;i<players.length;i++)if(players[i].id==playerId)return players[i];return!1}function getPlayer(playerId){for(var players=this.participants,i=0;i<players.length;i++)if(players[i].id==playerId)return players[i];return!1}function getTeam(teamId){for(var i=0;i<this.participants.length;i++)if(this.participants[i].id==teamId)return this.participants[i];return!1}function getJudge(userId){for(var i=0;i<cup.judges.length;i++)if(this.judges[i].id==userId)return this.judges[i];return!1}function attachPlayerAccount(account){return api.attachAccount(cup.id,account).then(function(data){return onDataLoad(data)})}function parseCup(cup){cup.start=new Date(1e3*cup.start),cup.startInt=+cup.start,cup.isStreamer=_isStreamer(cup.streams,UserObj.id),cup.deleted=-1==cup.status,cup.winners=[];try{var maps=angular.fromJson(cup.maps);cup.maps={},maps&&maps.forEach(function(a){cup.maps[a]=1})}catch(e){cup.maps={}}return cup.type&&cup.prizes.length&&(cup.prize_places=cup.prizes.length),parsePlayers(cup),cup}function parsePlayers(cup){if(1==cup.participants_type)cup.participants=cup.participants.sort(function(a,b){return a.rating==b.rating?parseInt(a.id)>parseInt(b.id)?1:-1:a.rating<b.rating?1:-1});else{cup.players=cup.participants,cup.participants=cup.teams;for(var i=0;i<cup.teams.length;i++){var team=cup.teams[i];cup.teams[i].players=cup.players.filter(function(player){return player.id==team.creator&&(team.captain=player),player.team==team.id}),team.avatar=team.logo,team.name=team.title,team.checkin=!!team.captain&&team.captain.checkin}}cup.checkined=[],cup.notCheckined=[];for(var i=0;i<cup.participants.length;i++)cup.participants[i].checkin?cup.checkined.push(cup.participants[i]):cup.notCheckined.push(cup.participants[i])}function _isStreamer(streams,userId){if(!streams)return!1;for(var i=0;i<streams.length;i++)if(streams[i].user_id==userId)return!0;return!1}function onEvent(eventObj){switch(eventObj.event){case"cupEvent":onDataLoad(angular.fromJson(eventObj.data));break;case"streamsEvent":cup.streams=angular.fromJson(eventObj.data);break;case"moneyEvent":var d=angular.fromJson(eventObj.data);cup.prize_fund=d.prize_fund,cup.supporters=d.supporters;break;case"participantsEvent":cup.participants=angular.fromJson(eventObj.data[0]),cup.teams=angular.fromJson(eventObj.data[1]),parsePlayers(cup),cup.gamer.init(cup);break;case"gridEvent":var gridData=angular.fromJson(eventObj.data);console.log(cup.grid_type,eventObj.gtype,cup.grid_type!=eventObj.gtype),cup.grid_type!=eventObj.gtype?(cup.grid_type=+eventObj.gtype,cup.grid=ggCupGridFactory.create(cup,gridData)):cup.grid.load(gridData),cup.grid_saved=!0,cup.gamer.init(cup)}$rootScope.$applyAsync()}function addChatData(user){user.cup=this.getPlayer(user.id)}function getPrize(place){if(cup.type||6761==cup.id)return cup.prizes&&cup.prizes[place-1]?cup.prizes[place-1]:0;if(!cup.prize_places||place>cup.prize_places)return 0;var deviations=[[1],[.7,.3],[.5,.3,.2],[.5,.25,.15,.1],[],[],[],[.46,.2,.14,.08,.03,.03,.03,.03]],sums=[],total=0,fund=Math.floor(cup.prize_fund);return deviations[cup.prize_places-1].map(function(v,i){var t=Math.floor(fund*v);sums[i]=t,total+=t}),total!=fund&&(sums[0]+=fund-total),sums[place-1]}var cup=this;cup.gamer=gamer,cup.fromStage=0,cup.new=newCup,cup.init=init,cup.join=joinPlayer,cup.joinTeam=joinTeam,cup.unjoin=unjoinPlayer,cup.checkin=checkinPlayer,cup.joinStreamer=addStreamer,cup.unjoinStreamer=removeStreamer,cup.addJudge=addJudge,cup.removeJudge=removeJudge,cup.getPlayer=getPlayer,cup.getTeamPlayer=getTeamPlayer,cup.getTeam=getTeam,cup.getJudge=getJudge,cup.isSC2Game=function(){return-1!=[21912,38383].indexOf(parseInt(cup.game_id))},cup.isBnetGame=function(){return!1}
14,cup.isWc3aGame=function(){return-1!=[12908].indexOf(parseInt(cup.game_id))},cup.isOtherGame=function(){return!cup.isBnetGame()&&!cup.isWc3aGame()},cup.attachPlayerAccount=attachPlayerAccount,cup.saveForm=save,cup.save=saveValues,cup.publish=publish,cup.getGrid=getGrid,cup.saveFullGrid=saveFullGrid,cup.saveGrid=saveGrid,cup.saveMatch=saveMatch,cup.saveMatches=saveMatches,cup.getPrize=getPrize,cup.reportLoss=reportLoss,cup.delete=deleteCup,cup.close=closeCup,cup.onEvent=onEvent,cup.showPage=$state.go,cup.addChatData=addChatData}angular.module("GG").service("ggCupService",ggCupService),ggCupService.$inject=["ggCupsApiService","ggCupGamerService","ggCupGridFactory","$rootScope","$state"]}(),function(){function ggCupGamerService(api){function init(_cup){cup=_cup,gamer.userId=UserObj.id,gamer.user=!1,gamer.userId&&(2==cup.participants_type?(gamer.user=cup.getTeamPlayer(gamer.userId),gamer.team=cup.getPlayer(gamer.user.team),gamer.isCaptain=gamer.team.captain==gamer.user):gamer.user=cup.getPlayer(gamer.userId)),gamer.user&&(getCurrentMatch(),initWinners())}function initWinners(){gamer.winner=cup.winners.indexOf(gamer.team||gamer.user)}function getCurrentMatch(){gamer.match=!1;var stages=cup.grid.getStages(),player=gamer.team||gamer.user;if(!stages)return!1;for(var x=stages.length-1;x>=0;x--){for(var sorted=stages[x].matches.slice().sort(function(a,b){return a.data>b.data?-1:a.data==b.data?0:1}),y=sorted.length-1;y>=0;y--){var match=sorted[y];if(match.participate(player)&&!match.closed){gamer.match=match,cup.grid.ffa&&(gamer.match=match.getCurrentMatch(),gamer.score=gamer.match.getPlayerScore(player),gamer.matchSlot=match.getSlot(player));break}}if(gamer.match)break}if(gamer.match.closed&&3==cup.grid_type){var first=cup.grid.$first;first.players[0]!=player&&first.players[1]!=player||(gamer.match=first)}}function saveAccount(account){return cup.attachPlayerAccount(account)}var gamer=this,cup=!1;gamer.init=init,gamer.saveAccount=saveAccount,gamer.initWinners=initWinners}angular.module("GG").service("ggCupGamerService",ggCupGamerService),ggCupGamerService.$inject=["ggCupsApiService"]}(),function(){function ggTeamService(api){function init(teamId){return api.getTeam(teamId).then(function(data){return onDataLoad(data),team})}function newTeam(){return team.id=0,team.title="",team.logo=!1,team.participants=[],team}function onDataLoad(data){return team.id!=data.id&&newTeam(),angular.extend(team,parseTeam(data)),team}function addPlayer(userId){return api.addTeamPlayer(team.id,userId).then(function(data){return onDataLoad(data),team})}function delPlayer(userId){return api.delTeamPlayer(team.id,userId).then(function(data){return onDataLoad(data),team})}function saveForm(form){return api.saveTeam(team.id,form).then(function(data){return onDataLoad(data),team})}function processInvite(action){return api.teamProcessInvite(team.id,action).then(function(data){return onDataLoad(data),team})}function deleteTeam(action){return api.deleteTeam(team.id,action).then(function(data){return onDataLoad(data),team})}function parseTeam(team){return parsePlayers(team),team}function parsePlayers(team){team.confirmed=[];for(var i=0;i<team.participants.length;i++)team.participants[i].status&&team.confirmed.push(team.participants[i]);if(team.invite=!1,UserService.id&&team.participants.length)for(var i=0;i<team.participants.length;i++)team.participants[i].id==UserObj.id&&0==team.participants[i].status&&(team.invite=!0)}console.log("ggTeamService");var team=this;team.new=newTeam,team.init=init,team.addPlayer=addPlayer,team.delPlayer=delPlayer,team.save=saveForm,team.processInvite=processInvite,team.delete=deleteTeam}angular.module("GG").service("ggTeamService",ggTeamService),ggTeamService.$inject=["ggCupsApiService"]}(),GGCupGridSingle.prototype.find=function(userId){for(var last=!1,stages=this.stages,s=0;s<stages.length;s++){var stage=stages[s];for(var m in stage.matches){var match=stage.matches[m];match.players&&(match.players[0]&&match.players[0].id==userId||match.players[1]&&match.players[1].id==userId)&&(last=match)}}last?last.scrollTo():alert("Пользователь не найден в сетке")},GGCupGridSingle.prototype.afterLoad=function(){this.$cup.gamer&&this.$cup.gamer.init(this.$cup)},GGCupGridSingle.prototype.setPlayers=function(number){this.$cup.checkined=new Array(number)},GGCupGridSingle.prototype.load=function(_data,reset){var cup=this.$cup,data=_data||this._data;if(!data||0==data.length)return!1;this.stages||(this.stages=[]),reset&&(this.stages.length=0);for(var i=0;i<data.length;i++){var stage=this.stages[i]||new GGCupStage({cup:cup,bo:data[i].bo,n:data.length-i});this.stages[i]||(this.stages[i]=stage);for(var hidden=!0,m=0;m<data[i].matches.length;m++){var t=data[i].matches[m],mdata={};t.players&&!t._players&&(t._players=[t.players[0]?t.players[0].id:0,t.players[1]?t.players[1].id:0],t.players=!1);for(var key in t)t.hasOwnProperty(key)&&(mdata[key]=t[key]);mdata.stage=stage,mdata.n=m+1,stage.matches[m]=new GGCupMatch(mdata),mdata.closed||(hidden=!1)}hidden&&i+1}return this._closeFreeMatches(),this.updateWinners(),this.afterLoad(),!0},GGCupGridSingle.prototype._getSeed=function(all,totalCells){for(var seeded=[],others=[],i=0;i<all.length;i++)i<totalCells?(all[i]&&(all[i].seeded=1),seeded.push(all[i])):others.push(all[i]);return[seeded,others]},GGCupGridSingle.prototype.generate=function(){var cup=this.$cup,stage=new GGCupStage({cup:cup});this.stages?this.stages.length=0:this.stages=[],this.stages.push(stage);var all=cup.checkined,totalCells=Math.round(Math.pow(2,Math.ceil(Math.log2(all.length))))/4,freeSlots=4*totalCells-all.length,seed=this._getSeed(all,totalCells),seeded=seed[0],others=seed[1],cells=this._seed(seeded);others=this._shuffle(others);for(var sfree=freeSlots/(2*totalCells),last=0,merged=[],i=0;i<2*totalCells;i++){var t=Math.round((i+1)*sfree);merged.push(i%2?others.shift():cells.shift()),merged.push(last==t&&others.shift()),last=t}others.length&&alert("Алгоритм фрислотов накосячил :(");for(var m=1;merged.length;)stage.matches.push(new GGCupMatch({stage:stage,players:[merged.shift(),merged.shift()],n:m++}));this._emptyMatches(stage,cup),this._closeFreeMatches();var totalStages=this.stages.length-1;0==totalStages?this.stages[0].matches[0].first=!0:cup.prize_places>2&&this._thirdPlaceMatch(this.stages[totalStages-1].bo,this.stages[totalStages])},GGCupGridSingle.prototype._closeFreeMatches=function(){if(!this.$cup.type)for(var matches=this.stages[0].matches,i=0;i<matches.length;i++)matches[i].players[1]&&matches[i].players[1].id||matches[i].close(!1)},GGCupGridSingle.prototype._shuffle=function(o){for(var j,x,i=o.length;i;j=Math.floor(Math.random()*i),x=o[--i],o[i]=o[j],o[j]=x);return o},GGCupGridSingle.prototype._seed=function(players){for(var cells=[],i=0;i<players.length;i++)cells[i>1?this._getNextCell(cells):(players.length-1)*i]=players[i];return cells},GGCupGridSingle.prototype._getNextCell=function(arr){for(var lst=0,cnt=0,ind=0,i=arr.length-1;i>=0;i--)arr[i]?(cnt>lst&&(lst=cnt,ind=i),cnt=0):cnt++;return Math.ceil(ind+lst/2)},GGCupGridSingle.prototype._emptyMatches=function(stage,cup){var totalStages=Math.ceil(Math.log2(stage.matches.length)),cnt=stage.matches.length/2;stage.bo=Math.max(1,cup.finalbo-2*totalStages),stage.n=totalStages+1;for(var i=1;i<=totalStages;i++){var st=this.stages[i]=new GGCupStage({cup:cup});
14st.bo=Math.max(1,cup.finalbo-2*(totalStages-i)),st.n=totalStages-i+1;for(var n=0;n<cnt;n++)st.matches[n]=new GGCupMatch(1==cnt?{stage:st,first:!0,n:n}:{stage:st,n:n});cnt/=2}},GGCupGridSingle.prototype._thirdPlaceMatch=function(bo,stage){stage.matches.push(new GGCupMatch({third:!0,bo:bo,stage:stage}))},GGCupGridSingle.prototype.getGrid=function(){return this._clone(this.getStages())},GGCupGridSingle.prototype.getGridData=function(){return this.data||""},GGCupGridSingle.prototype.getStages=function(){return this.stages},GGCupGridSingle.prototype._clone=function(obj){if(null==obj||"object"!=(void 0===obj?"undefined":_typeof(obj)))return obj;var temp=obj.constructor===Array?[]:{};for(var key in obj)obj.hasOwnProperty(key)&&0!==key.indexOf("$")&&(temp[key]=this._clone(obj[key]));return temp},GGCupGridSingle.prototype.showTargetPlace=function(match){if(match.first||match.third)return void this.updateWinners();var currentMatch=match.$stage.matches.indexOf(match),currentStage=this.stages.indexOf(match.$stage),targetStage=1+currentStage,targetMatch=Math.floor(currentMatch/2);this.stages[targetStage].matches[targetMatch].players[currentMatch%2?1:0]=match.winner},GGCupGridSingle.prototype.updateWinners=function(){var cup=this.$cup;this.$first&&this.$first.closed&&(cup.winners[0]=this.$first.winner,cup.prize_places>1&&(cup.winners[1]=this.$first.loser)),this.$third&&this.$third.closed&&(cup.prize_places>2&&(cup.winners[2]=this.$third.winner),cup.prize_places>3&&(cup.winners[3]=this.$third.loser))},GGCupGridSingle.prototype.getMatchClass=function(match){var ret="";return match.third&&(ret+="third-place "),match.closed||match.canclose?1==match.$stage.n?ret:(ret+=match.n%2?"top-win":"bot-win",ret+=" ",ret+=!match.players[1]||match.score[0]>match.score[1]?"one":"two"):ret},GGCupGridDouble.prototype=Object.create(GGCupGridSingle.prototype),GGCupGridDouble.prototype.constructor=GGCupGridSingle,GGCupGridDouble.prototype._emptyMatches=function(stage,cup){var totalStages=Math.ceil(Math.log2(stage.matches.length)),cnt=stage.matches.length;stage.bo=Math.max(1,cup.finalbo-2*totalStages),stage.n=totalStages+1,cnt/=2;for(var i=1;i<=totalStages;i++){var st=this.stages[i]=new GGCupStage({cup:cup});
14st.bo=Math.max(1,cup.finalbo-2*(totalStages-i)),st.n=totalStages-i+1;for(var n=0;n<cnt;n++)st.matches[n]=new GGCupMatch({stage:st});cnt/=2}this.stages2=[];for(var lg=Math.log2(stage.matches.length),cnt=stage.matches.length/2,i=0;i<lg;i++){for(var x=0;x<=1;x++){for(var st=new GGCupStage({cup:cup,bo:this.stages[i].bo,losers:1}),n=0;n<cnt;n++)st.matches[n]=new GGCupMatch({stage:st});this.stages2.push(st)}cnt/=2}this.stages2[this.stages2.length-1].matches[0].third=1;var st=new GGCupStage({cup:cup,bo:this.stages[this.stages.length-1].bo,n:-1});st.matches.push(new GGCupMatch({stage:st,first:!0})),this.stages.push(st),this.data.stages={stages1:this.stages.length,stages2:this.stages2.length}},GGCupGridDouble.prototype._thirdPlaceMatch=function(bo,stage){},GGCupGridDouble.prototype.getStages=function(stage){return!!this.stages&&(void 0!==stage?-1!=this.stages.indexOf(stage)?this.stages:this.stages2:this.stages.concat(this.stages2))},GGCupGridDouble.prototype.updateWinners=function(){var cup=this.$cup;if(this.$first&&this.$first.closed&&(cup.winners[0]=this.$first.winner,cup.prize_places>1&&(cup.winners[1]=this.$first.loser)),this.$third&&this.$third.closed&&cup.prize_places>2&&(cup.winners[2]=this.$third.loser),cup.prize_places>3){var fourthPlaceMatch=cup.grid.stages2[cup.grid.stages2.length-2].matches[0];fourthPlaceMatch.closed&&(cup.winners[3]=fourthPlaceMatch.loser)}},GGCupGridDouble.prototype.getMatchClass=function(match){var ret="";return-1==match.$stage.n?ret:(match.players[0]||match.players[1])&&(match.closed||match.canclose)?(match.losers&&match.$stage.n%2?ret="straight-loser":1==match.$stage.n?ret="straight-winner":ret+=match.n%2?"top-win":"bot-win",ret+=" ",ret+=!match.players[1]||match.score[0]>match.score[1]?"one":"two"):ret},GGCupGridDouble.prototype.load=function(_data,reset){console.log("double grid load");var cup=this.$cup,data=_data||this._data;if(!data||0==data.length)return!1;if(this.stages||(this.stages=[]),0==data.length)return!1;this.stages2||(this.stages=[],this.stages2=[]),reset&&(this.stages.length=0,this.stages2.length=0);for(var i=0;i<data.length;i++){var stage=(data[i].losers?this.stages2[i-this.stages.length]:this.stages[i])||new GGCupStage({cup:cup,bo:data[i].bo,losers:data[i].losers});data[i].losers?this.stages2[i-this.stages.length]=stage:this.stages[i]=stage;for(var hidden=!0,m=0;m<data[i].matches.length;m++){var t=data[i].matches[m],mdata={stage:stage,n:m+1,losers:stage.losers};for(var key in t)if(t.hasOwnProperty(key)){if("n"==key||"losers"==key)continue;mdata[key]=t[key]}stage.matches[m]&&stage.matches[m].changed&&!stage.matches[m]._loading||(stage.matches[m]=new GGCupMatch(mdata),mdata.first&&mdata.closed&&(cup.winners[0]=mdata.winner,cup.prize_places>1&&(cup.winners[1]=mdata.loser)),mdata.third&&mdata.closed&&cup.prize_places>2&&(cup.winners[2]=mdata.loser)),mdata.closed||(hidden=!1)}hidden&&i+1}for(var i=0;i<this.stages.length;i++)this.stages[i].n=this.stages.length-i-1||-1;for(var i=0;i<this.stages2.length;i++)this.stages2[i].n=this.stages2.length-i-1;return this._closeFreeMatches(),this.updateWinners(),cup.grid_saved=!0,cup._loading=!1,this.afterLoad(),!0},GGCupGridDouble.prototype.find2=function(userId){for(var last=!1,stages=this.stages2,s=0;s<stages.length;s++){var stage=stages[s];for(var m in stage.matches){var match=stage.matches[m];match.players&&(match.players[0]&&match.players[0].id==userId||match.players[1]&&match.players[1].id==userId)&&(last=match)}}last?last.scrollTo():alert("Пользователь не найден в сетке")},GGCupGridGroups.prototype=Object.create(GGCupGridSingle.prototype),GGCupGridGroups.prototype.constructor=GGCupGridSingle,GGCupGridGroups.prototype.load=function(_data,reset){console.log("groups grid load");var cup=this.$cup,data=_data||this._data;if(!data||0==data.length)return!1;if(this.stages||(this.stages=[]),0==data.length)return!1;this.playoff&&!reset||(this.groups=[],this.playoff={stages:[]}),2==this.data.playoff.type&&(this.playoff.stages2=[]);for(var stage,i=0;i<data.length;i++){stage=data[i].group?this.groups[i]:data[i].losers?this.playoff.stages2[i-this.groups.length-this.playoff.stages.length]:this.playoff.stages[i-this.groups.length],stage||(stage=new GGCupStage({cup:cup,bo:data[i].bo,losers:data[i].losers,group:data[i].group,n:i}),data[i].group?this.groups[i]=stage:data[i].losers?this.playoff.stages2[i-this.groups.length-this.playoff.stages.length]=stage:(this.playoff.stages[i-this.groups.length]=stage,stage.n=this.data.stages.playoff1-i+this.groups.length)),stage.scores={};for(var hidden=!0,m=0;m<data[i].matches.length;m++){var t=data[i].matches[m],mdata={stage:stage,n:m-1};for(var key in t)t.hasOwnProperty(key)&&(mdata[key]=t[key]);stage.matches[m]&&stage.matches[m].changed&&!stage.matches[m]._loading||(stage.matches[m]=new GGCupMatch(mdata),mdata.first&&mdata.closed&&(cup.winners[0]=mdata.winner,cup.prize_places>
141&&(cup.winners[1]=mdata.loser)),mdata.third&&mdata.closed&&cup.prize_places>2&&(cup.winners[2]=mdata.loser)),stage.group&&this._addPlayersToStage(stage.matches[m]),mdata.closed||(hidden=!1)}hidden&&(stage.closed=1,i+1)}return this._addFreeScores(),this.updateWinners(),cup.grid_saved=!0,cup._loading=!1,cup.grid.stages=cup.grid.playoff.stages,this.afterLoad(),!0},GGCupGridGroups.prototype._addFreeScores=function(){for(var i=0;i<this.groups.length;i++){var stage=this.groups[i];stage.scores||(stage.scores={});var cnt=Object.keys(stage.scores).length;if(cnt<4)for(var x=1;x<=4-cnt;x++)stage.scores[-x]={}}},GGCupGridGroups.prototype._addPlayersToStage=function(match){var stage=match.$stage;stage.scores||(stage.scores={}),match.players[0]&&match.players[0].id&&!stage.scores[match.players[0].id]&&(stage.scores[match.players[0].id]={user:match.players[0],w1:0,l1:0,w2:0,l2:0}),match.players[1]&&match.players[1].id&&!stage.scores[match.players[1].id]&&(stage.scores[match.players[1].id]={user:match.players[1],w1:0,l1:0,w2:0,l2:0}),match.closed&&match.players[0]&&match.players[1]&&(stage.scores[match.players[0].id].w2+=match.score[0],stage.scores[match.players[1].id].w2+=match.score[1],stage.scores[match.players[0].id].l2+=match.score[1],stage.scores[match.players[1].id].l2+=match.score[0],match.winner==match.players[0]?(stage.scores[match.players[0].id].w1+=1,stage.scores[match.players[1].id].l1+=1):(stage.scores[match.players[1].id].w1+=1,stage.scores[match.players[0].id].l1+=1),stage.scores[match.players[0].id].sort=10*(stage.scores[match.players[0].id].l1-stage.scores[match.players[0].id].w1)+stage.scores[match.players[0].id].l2-stage.scores[match.players[0].id].w2,stage.scores[match.players[1].id].sort=10*(stage.scores[match.players[1].id].l1-stage.scores[match.players[1].id].w1)+stage.scores[match.players[1].id].l2-stage.scores[match.players[1].id].w2)},GGCupGridGroups.prototype.generate=function(){var cup=this.$cup;this.groups?this.groups.length=0:this.groups=[],this.playoff={stages:[]},this.data&&this.data.playoff||(this.data={playoff:{type:1}});var all=cup.checkined,totalCells=Math.round(Math.pow(2,Math.ceil(Math.log2(all.length))))/4,freeSlots=4*totalCells-all.length,seed=this._getSeed(all,totalCells),seeded=seed[0],others=seed[1],cells=this._seed(seeded);others=this._shuffle(others);for(var sfree=freeSlots/(2*totalCells),last=0,merged=[],i=0;i<2*totalCells;i++){var t=Math.round((i+1)*sfree);merged.push(i%2?others.shift():cells.shift()),merged.push(last==t&&others.shift()),last=t}others.length&&alert("Алгоритм фрислотов накосячил :(");for(var i=0;i<totalCells;i++){var stage=new GGCupStage({cup:cup,group:1,n:i,bo:this.bo});stage.matches.push(new GGCupMatch({stage:stage,players:[merged.shift(),merged.shift()]})),stage.matches.push(new GGCupMatch({stage:stage,players:[merged.shift(),merged.shift()]})),stage.matches.push(new GGCupMatch({stage:stage,players:[0,0]})),stage.matches.push(new GGCupMatch({stage:stage,players:[0,0]})),stage.matches.push(new GGCupMatch({stage:stage,players:[0,0]})),this.groups.push(stage),this._addPlayersToStage(stage.matches[0]),this._addPlayersToStage(stage.matches[1])}this._emptyMatches(),this.createPlayoff(),this.hasPlayoff&&this._closeFreeMatches()},GGCupGridGroups.prototype.createPlayoff=function(){this.hasPlayoff&&(this.playoff.stages=[],1==this.data.playoff.type&&this.createSinglePlayoff()),this.data.stages={group:this.groups.length,playoff1:this.playoff.stages.length,playoff2:this.playoff.stages2?this.playoff.stages2.length:0},this.stages=this.playoff.stages},GGCupGridGroups.prototype.createSinglePlayoff=function(){for(var groups=this.getGroupStages(1).length,totalStages=Math.ceil(Math.log2(groups)),cnt=groups,cup=this.$cup,i=0;i<=totalStages;i++){var st=this.playoff.stages[i]=new GGCupStage({cup:cup,group:0});st.bo=Math.max(1,cup.finalbo-2*(totalStages-i));for(var n=0;n<cnt;n++)st.matches[n]=new GGCupMatch(1==cnt?{stage:st,first:!0}:{stage:st});cnt/=2}cup.prize_places>2&&this._thirdPlaceMatch(this.playoff.stages[totalStages-1].bo,this.playoff.stages[totalStages])},GGCupGridGroups.prototype._emptyMatches=function(){},GGCupGridGroups.prototype.getGroupStages=function(){return this.groups},GGCupGridGroups.prototype._closeFreeMatches=function(){for(var i=0;i<this.groups.length;i++){var stage=this.groups[i];stage.matches[0].players[1]&&stage.matches[0].players[1].id||stage.matches[0].close(!1),stage.matches[1].players[1]&&stage.matches[1].players[1].id||stage.matches[1].close(!1);for(var x=2;x<=4;x++)(!1===stage.matches[x].players[0]&&0!==stage.matches[x].players[1]||!1===stage.matches[x].players[1]&&0!==stage.matches[x].players[0])&&stage.matches[x].close(!1)}}
14,GGCupGridGroups.prototype.showTargetPlace=function(match){if(match.first||match.third)return void this.updateWinners();if(match.$stage.group){var matchNum=match.$stage.matches.indexOf(match);matchNum<2&&(match.$stage.matches[3].players[1==matchNum?0:1]=match.winner,match.$stage.matches[2].players[1==matchNum?0:1]=match.loser),2!=matchNum&&3!=matchNum||(match.$stage.matches[4].players[2==matchNum?0:1]=2==matchNum?match.winner:match.loser)}else if(!match.$stage.losers){var currentStage=this.playoff.stages.indexOf(match.$stage),targetStage=1+currentStage,currentMatch=match.$stage.matches.indexOf(match),targetMatch=Math.floor(currentMatch/2),m=this.playoff.stages[targetStage].matches[targetMatch];m.players[currentMatch%2?1:0]=match.winner}},GGCupGridGroups.prototype.getStages=function(stage){
15return!!this.groups&&(void 0!==stage?this._getStages(stage):this.groups.concat(1==this.data.playoff.type?this.playoff.stages:this.playoff.stages.concat(this.playoff.stages2)))},GGCupGridGroups.prototype._getStages=function(stage){return stage.group?this.groups:1==this.data.playoff.type?this.playoff.stages:-1!=this.playoff.stages.indexOf(stage)?this.playoff.stages:this.playoff.stages2},GGCupGridGroups.prototype.fillMatches=function(stage){var players=Object.keys(stage.scores);for(var key in players){var player=stage.scores[players[key]].user,match=Math.floor(key/2),place=key%2;stage.matches[match].players[place]=player}},GGCupGridEventGroups.prototype=Object.create(GGCupGridSingle.prototype),GGCupGridEventGroups.prototype.constructor=GGCupGridSingle,GGCupGridEventGroups.prototype.load=function(_data,reset){console.log("event groups grid load");var cup=this.$cup,data=_data||this._data;this.stages||(this.stages=[]),this.groups&&!reset||(this.groups=[]);for(var stage,i=0;i<data.length;i++){stage=this.groups[i],stage||(stage=new GGCupStage({cup:cup,bo:data[i].bo,group:data[i].group,n:i}),this.groups[i]=stage,stage.scores={});for(var m=0;m<data[i].matches.length;m++){var t=data[i].matches[m],mdata={stage:stage,n:m-1};if(t.players&&!t._players)try{t._players=[!!t.players[0]&&t.players[0].id,!!t.players[1]&&t.players[1].id],t.players=!1}catch(e){console.log(e,t.players)}for(var key in t)t.hasOwnProperty(key)&&(mdata[key]=t[key]);stage.matches[m]&&stage.matches[m].changed&&!stage.matches[m]._loading||(stage.matches[m]=new GGCupMatch(mdata)),this._addPlayersToStage(stage.matches[m])}var playersInGroup=(1+Math.sqrt(1+8*data[i].matches.length))/2,currentPlayers=Object.keys(stage.scores).length;if(currentPlayers<playersInGroup)for(var p=0;p<playersInGroup-currentPlayers;p++)stage.scores["d"+p]={user:{},sort:0}}},GGCupGridEventGroups.prototype.generate=function(){var cup=this.$cup;this.groups?this.groups.length=0:this.groups=[];for(var totalCells=this.groupsCount,playersInGroup=Math.ceil(cup.checkined.length/totalCells),matchesInGroup=playersInGroup*(playersInGroup-1)/2,i=0;i<totalCells;i++){var stage=new GGCupStage({cup:cup,group:1,n:i,bo:this.bo});stage.scores={};for(var p=0;p<playersInGroup;p++)stage.scores[p]={};for(var m=0;m<matchesInGroup;m++)stage.matches.push(new GGCupMatch({stage:stage,players:[0,0]}));this.groups.push(stage)}},GGCupGridEventGroups.prototype.getGroupStages=function(){return this.groups},GGCupGridEventGroups.prototype.showTargetPlace=function(match){},GGCupGridEventGroups.prototype.getStages=function(stage){return!!this.groups&&this.groups},GGCupGridEventGroups.prototype.fillMatches=function(stage){var currentMatch=0;for(var key1 in stage.scores){var player1=stage.scores[key1].user;for(var key2 in stage.scores)key2>key1&&(console.log("set match ",currentMatch),stage.matches[currentMatch].players[0]=player1,stage.matches[currentMatch].players[1]=stage.scores[key2].user,currentMatch++)}},GGCupGridEventGroups.prototype._addPlayersToStage=function(match){var stage=match.$stage;stage.scores||(stage.scores={}),match.players[0]&&match.players[0].id&&!stage.scores[match.players[0].id]&&(stage.scores[match.players[0].id]={user:match.players[0],w1:0,l1:0,w2:0,l2:0}),match.players[1]&&match.players[1].id&&!stage.scores[match.players[1].id]&&(stage.scores[match.players[1].id]={user:match.players[1],w1:0,l1:0,w2:0,l2:0}),match.closed&&match.players[0]&&match.players[1]&&(stage.scores[match.players[0].id].w2+=match.score[0],stage.scores[match.players[1].id].w2+=match.score[1],stage.scores[match.players[0].id].l2+=match.score[1],stage.scores[match.players[1].id].l2+=match.score[0],match.winner==match.players[0]?(stage.scores[match.players[0].id].w1+=1,stage.scores[match.players[1].id].l1+=1):(stage.scores[match.players[1].id].w1+=1,stage.scores[match.players[0].id].l1+=1),stage.scores[match.players[0].id].sort=10*(stage.scores[match.players[0].id].l1-stage.scores[match.players[0].id].w1)+stage.scores[match.players[0].id].l2-stage.scores[match.players[0].id].w2,stage.scores[match.players[1].id].sort=10*(stage.scores[match.players[1].id].l1-stage.scores[match.players[1].id].w1)+stage.scores[match.players[1].id].l2-stage.scores[match.players[1].id].w2)},GGCupGridFFA10.prototype=Object.create(GGCupGridSingle.prototype),GGCupGridFFA10.prototype.constructor=GGCupGridSingle,GGCupGridFFA10.prototype.load=function(_data,reset){var _this113=this;console.log("ffa grid load",_data,reset);var cup=this.$cup;return _data&&_data.length&&(this.data=_data),this.stages||(this.stages=[]),reset&&(this.stages.length=0),!!this.data.length&&(this.data.forEach(function(stageData,idx){var stage=_this113.stages[idx]||new GGCupStage({cup:cup,group:stageData.group,n:stageData.n});
15stageData.matches.forEach(function(matchData,idx){var match=stage.matches[idx]||new GGCupFFAMatch({stage:stage,n:idx});match.opened=matchData.opened,match.closed=matchData.closed,match.server=matchData.server,match.password=matchData.password,match.fillScores(matchData.scores),stage.matches[idx]||(stage.matches[idx]=match)}),_this113.stages[idx]||(_this113.stages[idx]=stage)}),this.afterLoad(),!0)},GGCupGridFFA10.prototype.getInvitedTeams=function(){var _this114=this,teamIds=[11436,13773,11177,13825,11134,13670,5940,13688,13684,11413,11120,11039,13790,13796,13729,13149,13739,11982,13656,11291,13673],teams=teamIds.map(function(id){return _this114.$cup.getPlayer(id)});return console.log(teams),teams},GGCupGridFFA10.prototype.createFinal=function(){var _this115=this;if(6==this.stages.length)for(var fi=0;fi<3;fi++)!function(fi){var f=new GGCupStage({cup:cup,group:0,n:_this115.stages.length+1});_this115.stages.push(f),f.matches=[new GGCupFFAMatch({stage:f,n:1}),new GGCupFFAMatch({stage:f,n:2}),new GGCupFFAMatch({stage:f,n:3}),new GGCupFFAMatch({stage:f,n:4}),new GGCupFFAMatch({stage:f,n:5}),new GGCupFFAMatch({stage:f,n:6}),new GGCupFFAMatch({stage:f,n:7})];var players=[],top1=_this115.stages[2*fi].matches[0].$scores.slice(0,10),top2=_this115.stages[2*fi+1].matches[0].$scores.slice(0,10);top1.forEach(function(place){return players.push(place.team)}),top2.forEach(function(place){return players.push(place.team)}),f.matches.forEach(function(match){return match.setPlayers(players)})}(fi);if(9==this.stages.length){var f=new GGCupStage({cup:cup,group:0,n:this.stages.length+1});this.stages.push(f),f.matches=[new GGCupFFAMatch({stage:f,n:1}),new GGCupFFAMatch({stage:f,n:2}),new GGCupFFAMatch({stage:f,n:3}),new GGCupFFAMatch({stage:f,n:4}),new GGCupFFAMatch({stage:f,n:5}),new GGCupFFAMatch({stage:f,n:6}),new GGCupFFAMatch({stage:f,n:7})];var _players=this.getInvitedTeams();console.log("createFinal players",_players.length),f.matches.forEach(function(match){return match.setPlayers(_players)}),console.log(this.stages)}},GGCupGridFFA10.prototype.generate=function(){var cup=this.$cup;console.log("generate"),this.stages||(this.stages=[]),this.stages.length=0;for(var invited=this.getInvitedTeams(),all=this._shuffle(cup.checkined).filter(function(team){return-1===invited.indexOf(team)}),perQuali=Math.round(all.length/this.qualies),i=0;i<this.qualies;i++){var stage=new GGCupStage({cup:cup,group:1,n:i+1}),match=new GGCupFFAMatch({stage:stage});i==this.qualies-1?match.setPlayers(all.slice(i*perQuali)):match.setPlayers(all.slice(i*perQuali,(i+1)*perQuali)),stage.matches.push(match),this.stages.push(stage)}},GGCupGridFFA10.prototype.getGrid=function(){return{}},GGCupGridFFA10.prototype.getGridData=function(){return this._clone(this.getStages())},GGCupGridFFA10.prototype._emptyMatches=function(){},GGCupGridFFA10.prototype.showTargetPlace=function(match){},GGCupGridFFAM.prototype=Object.create(GGCupGridSingle.prototype),GGCupGridFFAM.prototype.constructor=GGCupGridSingle,GGCupGridFFAM.prototype.load=function(_data,reset){var _this116=this;console.log("ffa grid load",_data,reset);var cup=this.$cup;return _data&&_data.length&&(this.data=_data),this.stages||(this.stages=[]),reset&&(this.stages.length=0),!!this.data.length&&(this.data.forEach(function(stageData,idx){var stage=_this116.stages[idx]||new GGCupStage({cup:cup,group:stageData.group,n:stageData.n});stageData.matches.forEach(function(matchData,idx){var match=stage.matches[idx]||new GGCupFFAMatch({stage:stage,n:idx});match.opened=matchData.opened,match.closed=matchData.closed,match.server=matchData.server,match.password=matchData.password,match.fillScores(matchData.scores),stage.matches[idx]||(stage.matches[idx]=match)}),_this116.stages[idx]||(_this116.stages[idx]=stage)}),this.afterLoad(),!0)},GGCupGridFFAM.prototype.getQStages=function(n){return this.stages.filter(function(stage){return stage.n<10*n&&stage.n>=10*(n-1)})},GGCupGridFFAM.prototype.getInvitedTeams=function(){return[]},GGCupGridFFAM.prototype.createFinal=function(){console.log("createFinal");var Q1Stages=this.getQStages(1),Q2Created=this.stages[6].matches[0].$players.length>0;if(0==Q1Stages.filter(function(stage){return!stage.matches[0].closed}).length&&!Q2Created){console.log("Fill Q2");var Q1Winners=this._shuffle(Q1Stages.map(function(stage){return stage.matches[0].$scores.slice(0,9)}).flat().map(function(score){return score.team}));console.log(Q1Winners,Q1Winners.length),this.getQStages(2).forEach(function(stage,i){var stagePlayers=Q1Winners.splice(0,13+i%2);
15console.log(i,13+i%2,stagePlayers.length),stage.matches.forEach(function(match){return match.setPlayers(stagePlayers)})})}var Q2Stages=this.getQStages(2),Q3Created=this.stages[10].matches[0].$players.length>0;if(0==Q2Stages.filter(function(stage){return!stage.matches[0].closed}).length&&!Q3Created){console.log("Fill Q3");var Q2Winners=this._shuffle(Q2Stages.map(function(stage){return stage.matches[0].$scores.slice(0,stage.matches[0].$scores.length-6)}).flat().map(function(score){return score.team}));this.getQStages(3).forEach(function(stage){var stagePlayers=Q2Winners.splice(0,15);stage.matches.forEach(function(match){return match.setPlayers(stagePlayers)})})}var Q3Stages=this.getQStages(3),FCreated=this.stages[12].matches[0].$players.length>0,Q3Closed=0==Q3Stages.filter(function(stage){return!stage.matches[2].closed}).length;if(console.log(Q3Stages,Q3Closed,FCreated),Q3Closed&&!FCreated){console.log("Fill F");var Q3Winners=this._shuffle(Q3Stages.map(function(stage){return stage.matches[0].generateTotalScore(),stage.matches[2].$reported.slice(0,stage.matches[0].$scores.length-8)}).flat().map(function(score){return score.team}));console.log(Q3Winners);this.getQStages(4).forEach(function(stage){var stagePlayers=Q3Winners.splice(0,14);stage.matches.forEach(function(match){return match.setPlayers(stagePlayers)})})}},GGCupGridFFAM.prototype.generate=function(){var cup=this.$cup;console.log("generate"),this.stages||(this.stages=[]),this.stages.length=0;for(var invited=this.getInvitedTeams(),all=this._shuffle(cup.checkined).filter(function(team){return-1===invited.indexOf(team)}),perQuali=Math.round(all.length/this.qualies),i=0;i<6;i++){var stage=new GGCupStage({cup:cup,group:1,n:i+1}),match=new GGCupFFAMatch({stage:stage});i==this.qualies-1?match.setPlayers(all.slice(i*perQuali)):match.setPlayers(all.slice(i*perQuali,(i+1)*perQuali)),stage.matches.push(match),this.stages.push(stage)}for(var i=0;i<4;i++){var stage=new GGCupStage({cup:cup,group:1,n:10+i+1}),match=new GGCupFFAMatch({stage:stage});stage.matches.push(match),this.stages.push(stage)}for(var i=0;i<2;i++){var stage=new GGCupStage({cup:cup,group:1,n:20+i+1});stage.matches=[new GGCupFFAMatch({stage:stage}),new GGCupFFAMatch({stage:stage}),new GGCupFFAMatch({stage:stage})],this.stages.push(stage)}var lastStage=new GGCupStage({cup:cup,group:0,n:31});this.stages.push(lastStage),lastStage.matches=[new GGCupFFAMatch({stage:lastStage,n:1}),new GGCupFFAMatch({stage:lastStage,n:2}),new GGCupFFAMatch({stage:lastStage,n:3}),new GGCupFFAMatch({stage:lastStage,n:4})]},GGCupGridFFAM.prototype.getGrid=function(){return{}},GGCupGridFFAM.prototype.getGridData=function(){return this._clone(this.getStages())},GGCupGridFFAM.prototype._emptyMatches=function(){},GGCupGridFFAM.prototype.showTargetPlace=function(match){},GGCupGridOverwatch.prototype=Object.create(GGCupGridSingle.prototype),GGCupGridOverwatch.prototype.constructor=GGCupGridSingle,GGCupGridOverwatch.prototype.load=function(_data,reset){console.log("ruov grid load",this._data);var cup=this.$cup,data=_data||this._data;if(!data||0==data.length)return!1;this.groups&&this.stages2&&!reset||(this.groups=[],this.stages2=[]);for(var stage,i=0;i<data.length;i++){stage=data[i].group?this.groups[i]:this.stages2[i-this.groups.length],stage||(stage=new GGCupGroupStage({cup:cup,bo:data[i].bo,losers:data[i].losers,group:data[i].group,n:i}),data[i].group?this.groups[i]=stage:(this.stages2[i-this.groups.length]=stage,stage.n=i-this.groups.length)),stage.scores={};for(var m=0;m<data[i].matches.length;m++){var t=data[i].matches[m],mdata={stage:stage,n:m};for(var key in t)t.hasOwnProperty(key)&&(mdata[key]=t[key]);stage.matches[m]&&stage.matches[m].changed&&!stage.matches[m]._loading||(stage.matches[m]=new GGCupMatch(mdata))}stage.group&&this._addPlayersToStage(stage.matches[0])}return this.afterLoad(),!0},GGCupGridOverwatch.prototype.generate=function(){var cup=this.$cup;this.groups?this.groups.length=0:this.groups=[];for(var all=this._shuffle(cup.checkined.slice()),totalGroups=all.length>=10?2:1,playersPerGroup=Math.ceil(all.length/totalGroups),i=0;i<totalGroups;i++){for(var stage=new GGCupGroupStage({cup:cup,group:1,n:i,bo:2}),groupPlayers=all.splice(0,playersPerGroup),x=0;x<playersPerGroup;x++)!function(x){var team=groupPlayers.pop();
15groupPlayers.forEach(function(opp){var match=new GGCupMatch({stage:stage,players:[team,opp]});stage.matches.push(match)})}();this.groups.push(stage),this._addPlayersToStage(stage.matches[0])}this.generatePlayoff()},GGCupGridOverwatch.prototype.generatePlayoff=function(match){var playoffStages=0;if(cup.checkined.length<=8&&(playoffStages=2),9==cup.checkined.length&&(playoffStages=3),0==playoffStages)return!1;this.stages2=[];for(var i=0;i<playoffStages;i++){var stage=new GGCupGroupStage({cup:cup,group:0,losers:1,n:playoffStages-i,bo:1});stage.matches.push(new GGCupMatch({stage:stage})),stage.matches.push(new GGCupMatch({stage:stage})),this.stages2.push(stage)}console.log(this.stages2)},GGCupGridOverwatch.prototype._closeFreeMatches=function(){},GGCupGridOverwatch.prototype.showTargetPlace=function(match){match.first||match.third;var currentStage=this.stages2.indexOf(match.$stage),targetStage=1+currentStage;this.stages2[targetStage].matches[0].players[1]=match.winner},GGCupGridOverwatch.prototype.getStages=function(stage){return!!this.groups&&(void 0!==stage?this.stages2:this.groups.concat(this.stages2))},GGCupGridOverwatch.prototype._addPlayersToStage=function(match){var stage=match.$stage;stage.scores=[],stage.matches._rows=null;var scores={},win={},draw={},loss={};stage.matches.forEach(function(currentMatch){var player1=currentMatch.players[0].id,player2=currentMatch.players[1].id;scores[player1]=(scores[player1]||0)+(currentMatch.score[0]||0),scores[player2]=(scores[player2]||0)+(currentMatch.score[1]||0),currentMatch.score[0]>currentMatch.score[1]&&(win[player1]=(win[player1]||0)+1,loss[player2]=(loss[player2]||0)+1,scores[player1]+=1),currentMatch.score[0]<currentMatch.score[1]&&(win[player2]=(win[player2]||0)+1,loss[player1]=(loss[player1]||0)+1,scores[player2]+=1),currentMatch.score[0]&&currentMatch.score[0]===currentMatch.score[1]&&(draw[player2]=(draw[player2]||0)+1,draw[player1]=(draw[player1]||0)+1)}),stage.scores=[];for(var teamId in scores)stage.scores.push({player:this.$cup.getPlayer(teamId),points:scores[teamId],wins:win[teamId],loss:loss[teamId],draws:draw[teamId]});stage.scores.sort(function(a,b){return b.points-a.points})},GGCupGridOverwatch.prototype._closeMatches=function(){this.groups.forEach(function(group){group.matches.forEach(function(match){(match.score[0]||match.score[1])&&(match.closed=1)})})},GGCupGridOverwatch.prototype.getGrid=function(){return this._closeMatches(),this._clone(this.getStages())},GGCupGridRRGroups.prototype=Object.create(GGCupGridSingle.prototype),GGCupGridRRGroups.prototype.constructor=GGCupGridSingle,GGCupGridRRGroups.prototype.load=function(_data,reset){console.log("ruov grid load",this._data);var cup=this.$cup,data=_data||this._data;if(!data||0==data.length)return!1;this.groups&&this.stages&&!reset||(this.groups=[],this.stages=[]);for(var stage,i=0;i<data.length;i++){stage=data[i].group?this.groups[i]:this.stages[i-this.groups.length],stage||(stage=new GGCupGroupStage({cup:cup,bo:data[i].bo,losers:data[i].losers,group:data[i].group,n:i}),data[i].group?this.groups[i]=stage:(this.stages[i-this.groups.length]=stage,stage.n=i-this.groups.length)),stage.scores={};for(var m=0;m<data[i].matches.length;m++){var t=data[i].matches[m],mdata={stage:stage,n:m+1};for(var key in t)t.hasOwnProperty(key)&&(mdata[key]=t[key]);stage.matches[m]&&stage.matches[m].changed&&!stage.matches[m]._loading||(stage.matches[m]=new GGCupMatch(mdata))}stage.group&&this._addPlayersToStage(stage.matches[0])}return this.afterLoad(),!0},GGCupGridRRGroups.prototype.generate=function(){var cup=this.$cup;this.groups?this.groups.length=0:this.groups=[];for(var all=this._shuffle(cup.checkined.slice()),playersPerGroup=Math.ceil(all.length/2),i=0;i<2;i++){for(var stage=new GGCupGroupStage({cup:cup,group:1,n:i,bo:2}),groupPlayers=all.splice(0,playersPerGroup),x=0;x<playersPerGroup;x++)!function(x){var team=groupPlayers.pop();groupPlayers.forEach(function(opp){var match=new GGCupMatch({stage:stage,players:[team,opp]});stage.matches.push(match)})}();this.groups.push(stage),this._addPlayersToStage(stage.matches[0])}this.generatePlayoff(),console.log(this.groups,this.stages)},GGCupGridRRGroups.prototype.generatePlayoff=function(){var cup=this.$cup,stage=(Math.round(Math.pow(2,Math.ceil(Math.log2(8)))),new GGCupStage({cup:cup}));this.stages=[stage];for(var i=1;i<=4;i++)stage.matches.push(new GGCupMatch({stage:stage,n:i}));console.log(stage),this._emptyMatches(stage,cup);this.stages.length},GGCupGridRRGroups.prototype.getStages=function(stage){return!!this.groups&&(void 0!==stage?this.stages:this.groups.concat(this.stages))},GGCupGridRRGroups.prototype._addPlayersToStage=function(match){var stage=match.$stage;stage.scores=[],stage.matches._rows=null;var scores={},win={},draw={},loss={};
15stage.matches.forEach(function(currentMatch){var player1=currentMatch.players[0].id,player2=currentMatch.players[1].id;scores[player1]=(scores[player1]||0)+(currentMatch.score[0]||0),scores[player2]=(scores[player2]||0)+(currentMatch.score[1]||0),currentMatch.score[0]>currentMatch.score[1]&&(win[player1]=(win[player1]||0)+1,loss[player2]=(loss[player2]||0)+1,scores[player1]+=1),currentMatch.score[0]<currentMatch.score[1]&&(win[player2]=(win[player2]||0)+1,loss[player1]=(loss[player1]||0)+1,scores[player2]+=1),currentMatch.score[0]&&currentMatch.score[0]===currentMatch.score[1]&&(draw[player2]=(draw[player2]||0)+1,draw[player1]=(draw[player1]||0)+1)}),stage.scores=[];for(var teamId in scores)stage.scores.push({player:this.$cup.getPlayer(teamId),points:scores[teamId],wins:win[teamId],loss:loss[teamId],draws:draw[teamId]});stage.scores.sort(function(a,b){return b.points-a.points})},GGCupGridRRGroups.prototype._closeMatches=function(){this.groups.forEach(function(group){group.matches.forEach(function(match){(match.score[0]||match.score[1])&&(match.closed=1)})})},GGCupGridRRGroups.prototype.getGrid=function(){return this._closeMatches(),this._clone(this.getStages())};
16"use strict";function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function extend(Child,Parent){var F=function(){};F.prototype=Parent.prototype,Child.prototype=new F,Child.prototype.constructor=Child,Child.superclass=Parent.prototype}function AutoCompleteWrapper(input){this.input=$(input),this.options=angular.extend({},defaultAutoCompleteOptions),this.url=""}function AutoCompleteActionWrapper(input,show_result,init_func){AutoCompleteActionWrapper.superclass.constructor.call(this,input),this.options.resultsClass="hidden",this.options.showResult=function(value,data){return show_result(value),""},this.options.processData=function(data){return init_func(),data},this.onItemSelectFuncs.customFunc.call(this,nullFunc)}function TagsAutoComplete2(input,func,select_first,disallow_submit){TagsAutoComplete2.superclass.constructor.call(this,input),this.options.selectFirst=!!select_first,this.url="/tags/suggestions2/",this.options.showResult=function(value,data){return'<span class="suggest">'+data.show+'</span><span class="type">'+data.lang+"</span>"},this.onItemSelectFuncs.customFunc.call(this,func),this.init(disallow_submit)}function PlayersAutoComplete2(input,func,select_first,disallow_submit){PlayersAutoComplete2.superclass.constructor.call(this,input),this.options.selectFirst=!!select_first,this.url="/players/suggestions2/",this.options.showResult=function(value,data){return'<span class="suggest">'+data.show+'</span><span class="type">'+data.lang+"</span>"},this.onItemSelectFuncs.customFunc.call(this,func),this.init(disallow_submit)}function ObjAutoComplete(input,func,select_first,disallow_submit){ObjAutoComplete.superclass.constructor.call(this,input),this.options.selectFirst=!!select_first,this.url="/search_obj/",this.remoteDataType="html",this.options.showResult=function(value,data){return'<span class="suggest">'+data.show+'</span><span class="type">'+data.lang+"</span>"},this.onItemSelectFuncs.customFunc.call(this,func),this.init(disallow_submit)}function ParticipantsAutoComplete(input,func){var clear=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],type=arguments[3];EventsAutoComplete.superclass.constructor.call(this,input),this.url="/search_participant/",this.formatItemFuncs.showSign2.call(this),this.onItemSelectFuncs.customFunc.call(this,func,clear),type&&(this.options.extraParams.type=type),this.init()}function UsersAutoComplete(input,func){var clear=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];EventsAutoComplete.superclass.constructor.call(this,input),this.url="/users/suggestions/",this.formatItemFuncs.showSign.call(this),this.onItemSelectFuncs.customFunc.call(this,func,clear),this.init()}function GamesAutoComplete(input,func,all,genres){GamesAutoComplete.superclass.constructor.call(this,input),this.url=all?"/games/all/":"/games/",this.options.maxItemsToShow=35,this.options.extraParams.genres=genres?1:0,this.options.showResult=function(value,data){return'<span class="suggest'+(-1!=data[1].indexOf("genre")?" genre":"")+'">'+(null!=data[0]?data[0]:"")+" "+value+"</span>"},this.onItemSelectFuncs.customFunc.call(this,func),this.init()}function GamesAdminAutoComplete(input,show_result,init_func){GamesAutoComplete.superclass.constructor.call(this,input),this.url="/games/admin/",this.options.resultsClass="hidden",this.options.maxItemsToShow=35,this.options.showResult=function(value,data){return show_result(value),""},this.options.processData=function(data){return init_func(),data},this.onItemSelectFuncs.customFunc.call(this,function(){}),this.init()}function EventsAutoComplete(input,func){EventsAutoComplete.superclass.constructor.call(this,input),this.url="/events/suggestions/",this.formatItemFuncs.showEvent.call(this),this.onItemSelectFuncs.customFunc.call(this,func,!0),this.init()}function ChannelsAutoComplete(input,func){ChannelsAutoComplete.superclass.constructor.call(this,input),this.url="/channel/suggestions/",this.formatItemFuncs.showEvent.call(this),this.onItemSelectFuncs.customFunc.call(this,func,!0),this.init()}var _get=function get(object,property,receiver){null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0===desc){var parent=Object.getPrototypeOf(object);return null===parent?void 0:get(parent,property,receiver)}if("value"in desc)return desc.value;var getter=desc.get;if(void 0!==getter)return getter.call(receiver)},_slicedToArray=function(){function sliceIterator(arr,i){var _arr=[],_n=!0,_d=!1,_e=void 0;try{for(var _s,_i=arr[Symbol.iterator]();!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{!_n&&_i.return&&_i.return()}finally{if(_d)throw _e}}return _arr}return function(arr,i){if(Array.isArray(arr))return arr;if(Symbol.iterator in Object(arr))return sliceIterator(arr,i);
16throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),GoodgamePage=function(){function GoodgamePage(){var _this=this;_classCallCheck(this,GoodgamePage),this.root=$(document),$(function(){return _this.bind()})}return _createClass(GoodgamePage,[{key:"bind",value:function(){}}]),GoodgamePage}(),GGEventEmitter=function(){function GGEventEmitter(){_classCallCheck(this,GGEventEmitter),this._events={}}return _createClass(GGEventEmitter,[{key:"on",value:function(event,fn,def){return fn.default=def||!1,this._events[event]=this._events[event]||[],this._events[event].push(fn),this}},{key:"off",value:function(event,fn){if(event in this._events!=!1)return this._events[event].splice(this._events[event].indexOf(fn),1),this}},{key:"emit",value:function(event,eventData){if(event in this._events!=!1){for(var args=Array.prototype.slice.call(arguments,1),i=0;i<this._events[event].length;i++){var fn=this._events[event][i];fn&&!fn.default&&this._events[event][i].apply(this,1==args.length?[eventData]:args)}if(eventData&&eventData.defaultPrevented)return this;for(var _i=0;_i<this._events[event].length;_i++){var _fn=this._events[event][_i];_fn&&_fn.default&&this._events[event][_i].apply(this,1==args.length?[eventData]:args)}return this}}}]),GGEventEmitter}(),UserService=function(){function onLogin(user){user?(angular.extend(self,user),angular.extend(UserObj,user),Utils.reachGoal("login_success"),iosLogin(user),androidLogin(user)):(self.id=0,self.jwt="",UserObj.id=0,UserObj.jwt=""),Utils.ecid(),self.emit("loginChange",user)}function iosLogin(user){try{webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify(user))}catch(err){}}function androidLogin(user){try{window.AndroidInterface&&window.AndroidInterface.onLogin(JSON.stringify(user))}catch(err){}}var self=new(function(_GGEventEmitter){function UserServiceClass(){return _classCallCheck(this,UserServiceClass),_possibleConstructorReturn(this,(UserServiceClass.__proto__||Object.getPrototypeOf(UserServiceClass)).call(this))}return _inherits(UserServiceClass,_GGEventEmitter),_createClass(UserServiceClass,[{key:"register",value:function(email,login,password,captcha){var options=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};return Utils.post("/ajax/user/register/email/",{email:email,login:login,password:password,"g-recaptcha-response":captcha,options:options}).then(function(response){return angular.fromJson(response)}).then(function(data){return data.result||data.errors})}},{key:"registerFinish",value:function(username,email,password){return Utils.post("/ajax/user/register/finish/",{username:username,email:email,password:password}).then(function(response){return angular.fromJson(response)}).then(function(data){return data.result&&data.return&&onLogin(data.return),data})}},{key:"activate",value:function(code,username){return Utils.post("/ajax/user/register/activate/",{code:code,username:username}).then(function(response){return angular.fromJson(response)}).then(function(data){return data.result&&data.return&&onLogin(data.return),data})}},{key:"login",value:function(username,password,remember,backurl,captcha){return remember=void 0===remember?1:!!remember,Utils.post("/ajax/login/",{login:username,password:password,remember:remember?1:0,return:"user",backurl:backurl||"","g-recaptcha-response":captcha}).then(function(data){return angular.fromJson(data)}).then(function(data){return data.result&&data.redirect?void(window.location.href=data.redirect):(data.result&&data.return&&onLogin(data.return),data)})}},{key:"afterLogin",value:function(data){onLogin(data.return)}},{key:"logout",value:function(){return Utils.post(AJAX_PATH+"/exit/").then(function(){return onLogin(!1)})}},{key:"oauth",value:function(site,data,token){return Utils.post("/oauth/auth/",{site:site,data:data,token:token}).then(function(data){return angular.fromJson(data)}).then(function(data){return"auth"==data.result?data.redirect?void(window.location.href=data.redirect):(onLogin(data.user),!0):"notfound"==data.result&&data})}},{key:"refreshUserObj",value:function(){return Utils.post("/ajax/userobj/").then(function(data){return angular.fromJson(data)}).then(function(data){return onLogin(data)})}},{key:"_onLogin",value:function(user){return onLogin(user)}},{key:"logged",value:function(){return!!this.id}},{key:"onLoginChange",value:function(fn){this.on("loginChange",fn)}},{key:"hasAccess",value:function(type){return this.checkAccess(type,this.rights)}},{key:"checkAccess",value:function(type){var rights=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return!type||rights&rigths[type]}},{key:"isPremium",value:function(){return this.id&&this.premium}}]),UserServiceClass}(GGEventEmitter)),rigths={SUPER_MODERATOR:1,MATERIALS:2,EVENTS:4,FILES:8,MODERATOR:32,SELLER:64,STREAMS:128,SUPPORT:256,TESTER:512,ANY_MODERATOR:33};return function(){angular.extend(self,UserObj),UserObj.id&&androidLogin(UserObj),function chatFn(){if(!window.Chat)return void setTimeout(chatFn,350);
16window.Chat.on("updateUserInfo",function(data){try{self.refreshUserObj().then(function(){return angular.element(document.body).scope().$apply()})}catch(e){console.error(e)}}),window.Chat.on("updateStreamerInRoom",function(data){try{data.data.id==UserObj.id&&self.refreshUserObj().then(function(){return angular.element(document.body).scope().$apply()})}catch(e){console.error(e)}})}()}(),self}(),defaultAutoCompleteOptions={maxItemsToShow:35,minChars:2,remoteDataType:"json",sortResults:!1,useCache:!1,filterResults:!1,extraParams:{}};AutoCompleteWrapper.prototype.init=function(){var _this3=this,allow_submit=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.options.url=AJAX_PATH+this.url,this.options.extraParams.limit=this.options.maxItemsToShow,ResourceLoader.loadJs("/js/libraries/jquery.autocomplete.js?rnd=11").then(function(){return _this3.input.autocomplete(_this3.options)}),allow_submit&&(this.input.keypress(function(e){13==e.which&&e.preventDefault()}),this.input.parent("form").length&&this.input.parent().submit(function(){return!1}))},AutoCompleteWrapper.prototype.makeRow=function(left,right){return'<span class="suggest">'+left+'</span><span class="type">'+right+"</span>"},AutoCompleteWrapper.prototype.formatItemFuncs={},AutoCompleteWrapper.prototype.formatItemFuncs.showSign=function(){this.options.showResult=function(value,data){return'<span class="suggest">'+data.sign+'</span><span class="type">'+data.id+"</span>"}},AutoCompleteWrapper.prototype.formatItemFuncs.showSign2=function(){this.options.showResult=function(value,data){return'<span class="suggest">'+data.show+'</span><span class="type">'+data.lang+"</span>"}},AutoCompleteWrapper.prototype.formatItemFuncs.showEvent=function(){var that=this;this.options.showResult=function(value,data){return that.makeRow(value,data.id)}},AutoCompleteWrapper.prototype.formatItemFuncs.withLeftReversed=function(){this.options.showResult=function(value,data){return'<span class="suggest">'+data[1]+'</span><span class="type">'+data[0]+"</span>"}},AutoCompleteWrapper.prototype.formatItemFuncs.withLeft=function(){this.options.showResult=function(value,data){return'<span class="suggest">'+value+'</span><span class="type">'+data[0]+"</span>"}},AutoCompleteWrapper.prototype.onItemSelectFuncs={},AutoCompleteWrapper.prototype.onItemSelectFuncs.customFunc=function(func,clear){this.options.onItemSelect=function(li,options){void 0!=(void 0===clear?"undefined":_typeof(clear))&&clear&&$(options.dom.$elem).val(""),func(li.value,options.dom.$elem,li.data)}},AutoCompleteWrapper.prototype.onItemSelectFuncs.appendFirst=function(elem){this.options.onItemSelect=function(li){return $(elem).html(li.data[0])}},extend(AutoCompleteActionWrapper,AutoCompleteWrapper),extend(TagsAutoComplete2,AutoCompleteWrapper),extend(PlayersAutoComplete2,AutoCompleteWrapper),extend(ObjAutoComplete,AutoCompleteWrapper),extend(ParticipantsAutoComplete,AutoCompleteWrapper),extend(UsersAutoComplete,AutoCompleteWrapper),extend(GamesAutoComplete,AutoCompleteWrapper),extend(GamesAdminAutoComplete,AutoCompleteWrapper),extend(EventsAutoComplete,AutoCompleteWrapper),extend(ChannelsAutoComplete,AutoCompleteWrapper);var ChannelPage=new function(){function loadPlayer(event){var pid=$(event.target).val();if(oldPlayer==pid)return!1;oldPlayer=pid,Utils.post("/ajax/player/get/",{key:"p"+pid}).then(function(data){return angular.fromJson(data)}).then(function(data){var el=$(".channel-wrap").find(".player-tab .player-inner");el.html(data.content),Utils.compileBlock(el)})}function restrictTabOnTheatre(e){Utils.rootScope().theatre&&9==e.keyCode&&e.preventDefault()}function resizeFunc(){var isResizing=!1,lastDownX=0,container=document.querySelector(".outer-wrap"),left=document.querySelector(".main-inner-wrap"),right=document.querySelector(".feed-block"),resizer=document.querySelector(".resizer"),opener=document.querySelector(".opener"),sizeMin=!0;resizer.addEventListener("mousedown",function(e){isResizing=!0,lastDownX=e.clientX,right.classList.add("resizing")}),opener.addEventListener("click",function(e){var chatBlock=document.querySelector(".chat .chat-container");left.style.right="350px",right.style.width="350px",chatBlock.style.width="",right.classList.remove("closed"),right.classList.remove("close")}),document.addEventListener("mousemove",function(e){if(isResizing){var offsetRight=container.offsetWidth-(e.clientX-container.offsetLeft);right.style.width=offsetRight+"px",offsetRight>=250&&(right.classList.remove("close"),sizeMin=!0),offsetRight<250&&sizeMin&&(right.classList.add("close"),sizeMin=!1),offsetRight<=315&&right.classList.add("task-small"),offsetRight>315&&right.classList.remove("task-small"),offsetRight>=600&&right.classList.add("big"),offsetRight<600&&right.classList.remove("big")}}),document.addEventListener("mouseup",function(e){var chatBlock=document.querySelector(".chat .chat-container");isResizing=!1,right.classList.contains("close")&&(right.style.width=0,chatBlock.style.width=0,left.style.right=0,right.classList.add("closed")),right&&(left.style.right=right.style.width,chatBlock&&(chatBlock.style.width=right.style.width),right.classList.remove("resizing"))})}var rootElem,oldPlayer;return new(function(_GoodgamePage){function _class(){return _classCallCheck(this,_class),_possibleConstructorReturn(this,(_class.__proto__||Object.getPrototypeOf(_class)).apply(this,arguments))}return _inherits(_class,_GoodgamePage),_createClass(_class,[{key:"bind",value:function(){rootElem=this.root,rootElem.on("change",".channel-wrap [data-action=player-selector]",loadPlayer)}},{key:"init",value:function(_objType,_ObjId){objType=_objType,channelId=_ObjId,oldPlayer=$("[data-action=player-selector]").find("select").val(),resizeFunc(),$(".main-inner-wrap").on("keydown",restrictTabOnTheatre)}}]),_class}(GoodgamePage));var objType,channelId},ChannelsRatings=new function(){function loadMore(){var count=$(selectorElements).length/20,nextPage=Math.round(count)+1;Utils.get("/ajax/channels/rating/",{page:nextPage}).then(function(data){$(selectorBlock).append(data),count>nextPage-1?$(".mine:eq(0)").remove():$(".mine:eq(1)").remove()})}function search(e){var str=$(e.currentTarget).val();if(""==str)return $(selectorElements).remove(),loadMore();Utils.get("/ajax/channels/rating/search",{query:str}).then(function(data){$(selectorElements).remove(),$(selectorBlock).append(data)})}var rootElem,selectorBlock="#channels-ratings .table-streamer-rating tbody",selectorElements=selectorBlock+" tr";return new(function(_GoodgamePage2){function _class2(){return _classCallCheck(this,_class2),_possibleConstructorReturn(this,(_class2.__proto__||Object.getPrototypeOf(_class2)).apply(this,arguments))}return _inherits(_class2,_GoodgamePage2),_createClass(_class2,[{key:"bind",value:function(){rootElem=this.root,rootElem.on("click","#channels-ratings [data-action=loadMore]",loadMore).on("keyup","#channels-ratings [data-action=search]",Utils.debounce(search,100))}}]),_class2}(GoodgamePage))},DraggablePanels=function(){function DraggablePanels(root,$scope,save){_classCallCheck(this,DraggablePanels),this._root=root,this._scope=$scope,this._save=save,this._placeholder=!1,this._init()}return _createClass(DraggablePanels,[{key:"_init",value:function(){var _this6=this;this._root.on("mousedown",".panel.draggable",function(event){if(!_this6._dragging&&!_this6._placeholder&&"DIV"==event.target.tagName){event.preventDefault(),event.stopPropagation(),_this6._dragging=!0,_this6._elem=$(event.currentTarget);var pos=_this6._elem.position();_this6._elem.css({position:"absolute","z-index":100,top:pos.top+"px",left:pos.left+"px"}),_this6._placeholder=$("<div></div>"),_this6._placeholder.insertAfter(_this6._elem).attr("class",_this6._elem.attr("class")).addClass("placeholder").css({width:_this6._elem.outerWidth(),height:_this6._elem.outerHeight()}),_this6._clickPos={x:event.pageX,y:event.pageY},_this6._sourcePos=pos}}),$(window).on("mouseup",function(){if(_this6._dragging){_this6._dragging=!1;var pos=_this6._placeholder.position();_this6._elem.animate({top:pos.top+"px",left:pos.left+"px"},300,function(){_this6._reorder(),_this6._elem.removeAttr("style"),_this6._placeholder.remove(),_this6._placeholder=!1})}}).on("mousemove",function(event){_this6._dragging&&(_this6._elem.css({top:_this6._sourcePos.top+(event.pageY-_this6._clickPos.y)+"px",left:_this6._sourcePos.left+(event.pageX-_this6._clickPos.x)+"px"}),_this6._checkHover(event.pageX,event.pageY))})}},{key:"_checkHover",value:function(x,y){this._elem.hide();var hovered=$(document.elementFromPoint(x,y)).closest(".panel");!hovered.length||hovered.hasClass("placeholder")||hovered.hasClass("add")||(hovered.index()<this._placeholder.index()?this._placeholder.insertBefore(hovered):this._placeholder.insertAfter(hovered)),this._elem.show()}},{key:"_reorder",value:function(){var all=this._root.find(".panel:not(.add)"),count=all.length-1,eScope=angular.element(this._elem).scope(),ret={};all.each(function(i,elem){var scope=angular.element(elem).scope();if(!scope.block||scope.block.id!=eScope.block.id){scope.block||(scope=eScope);var newSort=count-i;scope.block.id&&scope.block.sort!=newSort&&(ret[scope.block.id]=newSort),scope.block.sort=newSort}}),this._scope.$apply(),this._save(ret)}}]),DraggablePanels}(),FoolsDay=function(){function FoolsDay(){_classCallCheck(this,FoolsD
16ay)}return _createClass(FoolsDay,null,[{key:"currencies",value:function(){return[{title:["рулон туалетной бумаги 🧻","рулона туалетной бумаги 🧻","рулонов туалетной бумаги 🧻","рулона туалетной бумаги 🧻"],rate:10},{title:["килограмм гречки","килограмма гречки","килограмм гречки","килограмма гречки"],rate:80},{title:["головку чеснока","головки чеснока","головок чеснока","головки чеснока"],rate:15},{title:["казахстанский тенге","казахстанских тенге","казахстанских тенге","казахстанского тенге"],rate:.2},{title:["трёшку на Тверской","трёшки на Тверской","трёшек на Тверской","трёшки на Тверской"],rate:4e7},{title:["пекоин","пекоина","пекоинов","пекоина"],titleSound:["пе коин","пе коина","пе коинов","пе коина"],rate:1.3},{title:["кусочек льда для попы","кусочков льда для попы","кусочков льда для попы","кусочков льда для попы"],rate:10}]}},{key:"convertValue",value:function(value){var sound=arguments.length>1&&void 0!==arguments[1]&&arguments[1],currencies=FoolsDay.currencies(),currency=currencies[Math.floor(Math.random()*currencies.length)],newValue=value/currency.rate;newValue=newValue>100?Math.round(newValue):newValue>.01?Math.floor(100*newValue)/100:newValue.toString().replace(new RegExp("(0.0+..).+"),"$1");var delc=newValue%1==0?Utils.decl(newValue):3,titles=sound&&currency.titleSound?currency.titleSound:currency.title,title=titles[delc];return newValue<.001&&(newValue*=100,title="процента "+title),newValue.toString().replace(".",",")+" "+title}}]),FoolsDay}(),GoogleBaba=function(){function GoogleBaba(options){_classCallCheck(this,GoogleBaba),this.isSpeaking=!1,this.queue=[],this.audio=!1,this.configure(options)}return _createClass(GoogleBaba,[{key:"configure",value:function(options){var defaults={voice:"alena",emotion:"good",donat:0,amount:30,premium:0,yandex:{token:UserService.token,url:"/ajax/voice/yandex"},ivona:{url:"http://chat.goodgame.ru:8012/read_text/"},polly:{url:"/ajax/voice/polly/"}};this.config=angular.extend({},defaults,options)}},{key:"say",value:function(event){event.status="waiting",this.queue.push(event),this._processQueue()}},{key:"abort",value:function(event){var index=this.queue.indexOf(event);-1!=index&&this.queue.splice(index,1),event.status="stop",this.audio&&this.audio.event&&this.audio.event===event&&(this.audio.pause(),this.audio.event.voicePlayed=!0,this._onEnd())}},{key:"_processQueue",value:function(){this.isSpeaking||this._sayNext()}},{key:"_sayNext",value:function(){var _this7=this,event=this.queue.shift();if(event){event.status="playing";var text=this._trimUrls(event.text),url=this._getUrl(text);this.isSpeaking=setTimeout(function(){return _this7._onEnd()},3e4),this.playUrl(url),this.audio.event=event}}},{key:"_trimUrls",value:function(text){return!!text&&text.replace(/https?:[^\s]+/,"{ссылка}")}},{key:"playUrl",value:function(url){var _this8=this;return console.log("Voice URL: "+url),this.audio=new Audio(url),this.audio.play(),this.audio.addEventListener("ended",function(){return _this8._onEnd()}),this.audio.addEventListener("error",function(){return _this8._onEnd()}),this.audio.addEventListener("abort",function(){return _this8._onEnd()}),this.audio}},{key:"_onEnd",value:function(){if(this.audio.event&&this.audio.event.voiceId&&!this.audio.event.voicePlayed){var event=this.audio.event;return event.voicePlayed=!0,this.playUrl("https://storage2.goodgame.ru/auds/"+this.audio.event.voiceId+".aac"),void(this.audio.event=event)}this.audio.event.status="stop",clearTimeout(this.isSpeaking),this.isSpeaking=!1,this.audio&&this.audio.pause(),this._sayNext()}},{key:"_getUrl",value:function(text){var urlParams;return-1==["maxim","tatyana"].indexOf(this.config.voice)?(urlParams={text:text,speaker:this.config.voice,emotion:this.config.emotion,token:this.config.yandex.token},this.config.yandex.url+"?"+this._buildParams(urlParams)):(urlParams={text:text,voice:this.config.voice,codec:"OGG",token:UserService.token},this.config.polly.url+"?"+this._buildParams(urlParams))}},{key:"_buildParams",value:function(data){return Object.keys(data).map(function(key){return[key,data[key]].map(e
16ncodeURIComponent).join("=")}).join("&")}}]),GoogleBaba}(),Header=new function($){var rootElem={};return new(function(_GoodgamePage3){function _class3(){return _classCallCheck(this,_class3),_possibleConstructorReturn(this,(_class3.__proto__||Object.getPrototypeOf(_class3)).apply(this,arguments))}return _inherits(_class3,_GoodgamePage3),_createClass(_class3,[{key:"bind",value:function(){rootElem=this.root,rootElem.on("click","[data-action=showLogin]",this.showLogin).on("click","[data-action=logout]",this.logout),this.headShorten()}},{key:"showLogin",value:function(){window.openLogin()}},{key:"logout",value:function(){PageLoader.showLoader(),UserService.logout().then(function(){return PageLoader.hideLoader()})}},{key:"getScroller",value:function(){var block=$("#entire"),tse=block.closest(".simplebar-scroll-content");return tse.length||(tse=block.closest(".simplebar-content-wrapper")),tse.length?tse:block.closest(".tse-scrollable")}},{key:"headShorten",value:function(){var _this10=this,resizeHandler=function(){var wrapper=document.querySelector(".outer-wrap");if(!wrapper)return!1;var wrap=wrapper.offsetWidth,head_menu=document.querySelector("header .menu-links"),menu_links_wrap=document.querySelector("header .menu-links-wrap");wrap<=(document.querySelector(".feed-block.wide")?1176:980)?(menu_links_wrap.classList.add("more"),head_menu.classList.add("remove"),_this10.countDotsMenu()):(menu_links_wrap.classList.remove("more"),head_menu.classList.remove("remove"))};resizeHandler(),window.addEventListener("resize",Utils.debounce(resizeHandler,50))}},{key:"countDotsMenu",value:function(){var _this11=this,dots_available=document.querySelectorAll(".dots-menu-links > li"),menu_visible=document.querySelectorAll(".main-menu-links > li"),visible=0;menu_visible.forEach(function(item){_this11.isElementVisible(item)&&visible++}),dots_available.forEach(function(item,index){item.style.display=index>=visible?"block":"none"})}},{key:"isElementVisible",value:function(element){var rect=element.getBoundingClientRect(),centerX=rect.left+rect.width/2,centerY=rect.top+rect.height/2,topElement=document.elementFromPoint(centerX,centerY);return!(!element.contains(topElement)&&topElement!==element)}}]),_class3}(GoodgamePage))}(jQuery),HelpPage=new function(){function doDelete(event){var id=$(event.currentTarget).data("id");Utils.post("/ajax/help/delete",{id:id}).then(function(){$(".help-inner").hide(),$(".undelete").show()})}function doUndelete(event){var id=$(event.currentTarget).data("id");Utils.post("/ajax/help/undelete",{id:id}).then(function(){$(".help-inner").show(),$(".undelete").hide()})}function doDeleteType(event){if(confirm("Точно удалить раздел?")){var id=$(event.currentTarget).data("id");Utils.post("/ajax/help/delete-type",{id:id}).then(function(){$(".help-block-expand").hide("slow"),$(".help-block-expand-restore").show("slow")})}}var rootElem;return new(function(_GoodgamePage4){function _class4(){return _classCallCheck(this,_class4),_possibleConstructorReturn(this,(_class4.__proto__||Object.getPrototypeOf(_class4)).apply(this,arguments))}return _inherits(_class4,_GoodgamePage4),_createClass(_class4,[{key:"bind",value:function(){rootElem=this.root,rootElem.on("click",".help-block-expand [data-action=delete]",doDelete).on("click",".help-block-expand [data-action=undelete]",doUndelete).on("click",'.help-block-expand [data-action="delete_type"]',doDeleteType)}}]),_class4}(GoodgamePage))},HtmlPaste=function(){function HtmlPaste(input){_classCallCheck(this,HtmlPaste),this._input=input[0]}return _createClass(HtmlPaste,[{key:"getRange",value:function(){if(window.getSelection){var sel=window.getSelection();if(sel.getRangeAt&&sel.rangeCount)return sel.getRangeAt(0)}else if(document.selection&&document.selection.createRange)return document.selection.createRange();return null}},{key:"setRange",value:function(range){if(window.getSelection){var sel=window.getSelection();sel.removeAllRanges(),sel.addRange(range)}else document.selection&&range.select&&range.select()}},{key:"pasteCode",value:function(code){var el,img=code,editable=this._input,sel=!!window.getSelection&&window.getSelection();if(sel&&sel.rangeCount){var r=sel.getRangeAt(0);el=r.commonAncestorContainer?r.commonAncestorContainer:r.parentElement?r.parentElement():r.item(0)}else el=!1;for(;el&&el!=editable;)el=el.parentNode;var edLast=editable.lastChild||{};"BR"!=edLast.tagName||edLast.previousSibling||this._re(editable.lastChild),el||this._editableFocus(editable,!1,!0),this.insertHTML(img)}},{key:"deleteLastParsedWord",value:function(html){var sel=void 0,range=void 0;if(window.getSelection){if(sel=window.getSelection(),sel.getRangeAt&&sel.rangeCount){range=sel.getRangeAt(0),range=range.cloneRange();var textContent=range.startContainer.textContent,words=textContent.split(" ");words.pop();var newTextContent=words.join(" "),newNode=document.createTextNode(newTextContent);range.endContainer.parentNode.replaceChild(newNode,range.endContainer),range.setStartAfter(newNode),range.collapse(!1),sel.removeAllRanges(),sel.addRange(range),words.length||this.insertHTML("&nbsp;")}this.insertHTML("&nbsp;"),this.insertHTML(html)}}},{key:"_re",value:function(el){var $el=$(el instanceof HTMLElement?el:"#"+el);return $el&&$el.parentNode&&$el.parentNode.removeChild($el),$el}},{key:"insertHTML",value:function(html){var sel,range;if(window.getSelection){if(sel=window.getSelection(),sel.getRangeAt&&sel.rangeCount){range=sel.getRangeAt(0),range.deleteContents();var el=document.createElement("div");el.innerHTML=html;for(var node,lastNode,frag=document.createDocumentFragment();node=el.firstChild;)lastNode=frag.appendChild(node);
16range.insertNode(frag),lastNode&&(range=range.cloneRange(),range.setStartAfter(lastNode),range.collapse(!0),sel.removeAllRanges(),sel.addRange(range))}}else document.selection&&"Control"!=document.selection.type&&document.selection.createRange().pasteHTML(html)}},{key:"_editableFocus",value:function(editable,obj,after){if(!editable)return!1;if(editable.focus(),editable.phonfocus&&editable.phonfocus(),void 0!==window.getSelection&&void 0!==document.createRange){var sel=window.getSelection();if(after){var range=document.createRange();obj?range.selectNode(obj):range.selectNodeContents(editable),range.collapse(!after);var sel=window.getSelection();sel.removeAllRanges(),sel.addRange(range)}else sel.collapse(obj||editable,0)}else if(void 0!==document.body.createTextRange){var textRange=document.body.createTextRange();textRange.moveToElementText(obj||editable),textRange.collapse(!after),textRange.select()}}},{key:"toEnd",value:function(){var range=document.createRange(),sel=window.getSelection();range.setStart(this._input,this._input.childNodes.length),range.collapse(!0),sel.removeAllRanges(),sel.addRange(range)}}]),HtmlPaste}(),InfinityScroll=function(){function InfinityScroll(rootElem){_
16classCallCheck(this,InfinityScroll),this._rootElem=rootElem,this._loading=!1,this._nextPageCb=!1,this._init()}return _createClass(InfinityScroll,[{key:"_init",value:function(){var _this13=this;this._rootElem.on("scroll",function(){
17!_this13._loading&&_this13._rootElem.scrollTop()>_this13._rootElem.find(".tse-content:first").height()-$(window).height()-300&&(_this13._loading=!0,_this13._nextPageCb&&_this13._nextPageCb())})}},{key:"nextPage",value:function(cb){this._nextPageCb=cb}},{key:"done",value:function(){this._loading=!1}},{key:"disable",value:function(){this._loading=!0}},{key:"destroy",value:function(){this._rootElem.off("scroll")}}]),InfinityScroll}(),MainPage=new function(){var rootElem={},showFavouriteBroadcasts=function(e){e.preventDefault();var bBlock=rootElem.find(".broadcasts-block");bBlock.find(".icon-heart").toggleClass("active");var current=bBlock.find(".icon-heart").hasClass("active");bBlock.find(".broadcasts-all").toggle(!current),bBlock.find(".broadcasts-favs").toggle(current),bBlock.find(".broadcasts-premium").toggle(!1)},hideTopicPreview=function(event){var block=$(event.currentTarget).find(".theme-preview");block.data("timeout")&&clearTimeout(block.data("timeout")),rootElem.find(".theme-preview").removeClass("active")},showTopicPreview=function(event){var block=$(event.currentTarget).find(".theme-preview");block.data("timeout")&&clearTimeout(block.data("timeout"));var timeout=setTimeout(function(){Utils.get(AJAX_PATH+"/topic/"+$(block).data("id")+"/preview/").then(function(data){return angular.fromJson(data)}).then(function(data){block.find(".forum-text").html(data.text),block.addClass("active")})},300);block.data("timeout",timeout)},loadGallery=function(event){var _this14=this;event.preventDefault(),$(this).toggleClass("active").closest(".gallery-wrap").addClass("loading"),Utils.post(AJAX_PATH+"/index/loadgallery/",{type:$(this).hasClass("active")?3:9}).then(function(data){return $(_this14).closest(".gallery-wrap").replaceWith(data)})};return new(function(_GoodgamePage5){function _class5(){return _classCallCheck(this,_class5),_possibleConstructorReturn(this,(_class5.__proto__||Object.getPrototypeOf(_class5)).apply(this,arguments))}return _inherits(_class5,_GoodgamePage5),_createClass(_class5,[{key:"bind",value:function(){rootElem=this.root,rootElem.on("click",".main-inner-wrap [data-action=showFavouriteBroadcasts]",showFavouriteBroadcasts).on("mouseenter",".forum-wrap .theme",showTopicPreview).on("mouseleave",".forum-wrap .theme",hideTopicPreview).on("click",".main-inner-wrap .gallery-wrap .switch-block",loadGallery)}}]),_class5}(GoodgamePage))},Materials=new function(){function switchTheme(){var tip=wrapper.querySelector(".tip"),icon=wrapper.querySelector(".icon-block").querySelector(".icon");wrapper.classList.toggle("light"),isLight=!isLight,isLight?(icon.classList.remove("icon-Sun-18px"),icon.classList.add("icon-Moon-18px"),tip.textContent="Темная тема"):(icon.classList.add("icon-Sun-18px"),icon.classList.remove("icon-Moon-18px"),tip.textContent="Светлая тема"),Utils.lsSet("gg-light",isLight?1:0)}function publish(){Utils.post("/ajax/moderation/publish/",{key:$objType+"-"+$objId}).then(afterLoading)}function unpublish(){Utils.post("/ajax/moderation/unpublish/",{key:$objType+"-"+$objId}).then(afterLoading)}function deleteMaterial(){confirm("Вы действительно хотите удалить этот материал?")&&Utils.post("/ajax/moderation/delete/",{key:$objType+"-"+$objId}).then(function(data){data&&PageLoader.go("/")})}function afterLoading(data){data&&PageLoader.reload()}var $rootElem,$objId,$objType,isLight,wrapper;return new(function(_GoodgamePage6){function _class6(){return _classCallCheck(this,_class6),_possibleConstructorReturn(this,(_class6.__proto__||Object.getPrototypeOf(_class6)).apply(this,arguments))}return _inherits(_class6,_GoodgamePage6),_createClass(_class6,[{key:"init",value:function(type,id){$objType=type,$objId=id,$rootElem=$(".news-block"),wrapper=$rootElem.closest(".
17news-wrapper")[0],$rootElem.on("click","[data-action=publish]",publish).on("click","[data-action=unpublish]",unpublish).on("click","[data-action=delete]",deleteMaterial).on("click",".icon-Moon-18px",switchTheme).on("click",".icon-Sun-18px",switchTheme),isLight=1==Utils.lsGet("gg-light",0),isLight&&wrapper.classList.add("light"),wrapper.style.display="block",Utils.reachGoal("news_view")}}]),_class6}(GoodgamePage))},ModerationPage=new function(){var $rootElem;return new(function(_GoodgamePage7){function _class7(){return _classCallCheck(this,_class7),_possibleConstructorReturn(this,(_class7.__proto__||Object.getPrototypeOf(_class7)).apply(this,arguments))}return _inherits(_class7,_GoodgamePage7),_createClass(_class7,[{key:"bind",value:function(){$rootElem=this.root}},{key:"changeStatus",value:function(data){var tr=$("tr[data-id="+data+"]");tr.addClass("deactivated"),tr.find(".icon").removeClass("icon-blocked").addClass("icon-checkmark")}}]),_class7}(GoodgamePage))},NotifyProxy=function(){function asap(fn){return isSocketReady()&&canSubscribe?fn():(window.DEV_FEED&&console.log("FEED","Call notify before connect. Try to postpone"),new Promise(function(resolve){return postponedCalls.push([fn,resolve])}))}function connect(){if(pingTimeout&&clearTimeout(pingTimeout),UserService.id)try{reconnecting=!1,websocket=new WebSocket(config.host),websocket.onmessage=onSocketMessage,websocket.onclose=onSocketClose}catch(e){}}function auth(){socketAsk("auth",{user_id:UserService.id,token:UserService.token,object:GGObj,active:TabsManager.isTopWindow()}).then(function(data){"ok"===data.answer?onAuthSuccess(data.data):(window.DEV_FEED&&console.error("FEED","Auth Error"),console.error("Auth Error"))})}function deferSubscribe(key){return objectsToSubscribe.push(key)}function _unsubscribe(key){key&&canSubscribe&&socketAsk("unsubscribeObject",{id:key});var idx=objectsToSubscribe.findIndex(function(obj){return obj.id==key});-1!==idx&&objectsToSubscribe.splice(idx,1)}function _subscribe(){var key=arguments.length>0&&void 0!==arguments[0]&&arguments[0],query=arguments[1],obj={id:key,query:query};if(!canSubscribe&&!key)return!1;if(!canSubscribe)return deferSubscribe(obj);if(key)return socketAsk("subscribeObject",obj),deferSubscribe(obj);for(var object,i=0;object=objectsToSubscribe[i];i++)socketAsk("subscribeObject",object);for(var postponed,_i2=0;postponed=postponedCalls[_i2];_i2++)try{var _postponed=postponed,_postponed2=_slicedToArray(_postponed,2),funcName=_postponed2[0],promise=_postponed2[1];funcName().then(promise)}catch(e){}postponedCalls=[]}function ping(){return!waitingPong&&(isSocketReady()?(waitingPong=!0,socketAsk("ping",{active:TabsManager.isTopWindow(),object:GGObj}
17).then(function(){waitingPong=!1,clearTimeout(pingTimeout),pingTimeout=setTimeout(ping,3e4)}),void setTimeout(function(){waitingPong&&(waitingPong=!1,console.warn("No pong in 5 seconds. Closing."),close(),onSocketClose())},5e3)):(close(),void onSocketClose()))}function close(){websocket&&(websocket.onclose=function(){},websocket.close(),websocket=null)}function onAuthSuccess(data){canSubscribe=!0,_subscribe(),clearTimeout(pingTimeout),pingTimeout=setTimeout(ping,3e4),ping(),window.DEV_FEED&&console.log("FEED","onAuthSuccess",data),data&&(self.userData=data),self.emit("connected")}function onSocketMessage(message){var msg=void 0;try{msg=angular.fromJson(message.data)}catch(err){return void console.log(err)}if(window.DEV_FEED&&console.log("FEED","<-",msg),answersCallbacks[msg.type])return void answersCallbacks[msg.type](msg.data);switch(msg.type){case"welcome":return reconnecting=!1,auth()}self.emit(msg.type,msg.data)}function onSocketClose(){if(reconnecting)return!1;reconnecting=!0,console.warn("Notify connection closed. Reconnect after 5 second"),canSubscribe=!1,waitingPong=!1,setTimeout(connect,5e3),close()}function socketAsk(type){var data=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise(function(resolve){return answersCallbacks[type+"_answer"]=resolve,socketSend(type,data)})}function socketSend(type,data){if(!isSocketReady())return void console.log("Cant send "+type+". Not ready");window.DEV_FEED&&console.log("FEED","->",{type:type,data:data});try{websocket.send(JSON.stringify({type:type,data:data}))}catch(e){}}function isSocketReady(){return websocket&&1===websocket.readyState}var config={host:(window.WS_SCHEMA||"wss")+"://"+CHAT+"/feed2/"},self=new(function(_GGEventEmitter2){function NotifyProxyClass(){_classCallCheck(this,NotifyProxyClass);var _this18=_possibleConstructorReturn(this,(NotifyProxyClass.__proto__||Object.getPrototypeOf(NotifyProxyClass)).call(this));return _this18.userData={},_this18}return _inherits(NotifyProxyClass,_GGEventEmitter2),_createClass(NotifyProxyClass,[{key:"subscribe",value:function(object,query){return _subscribe(object,query),this}},{key:"unsubscribe",value:function(object){return _unsubscribe(object),this}},{key:"loadFavorites",value:function(){return this.ask("getFavorites",{subscribe:!0})}},{key:"loadFeed",value:function(){return this.ask("getFeed")}},{key:"feedSetRead",value:function(eventId){return this.ask("feedSetRead",{id:eventId})}},{key:"feedDelete",value:function(eventId){return this.ask("feedDelete",{id:eventId})}},{key:"ask",value:function(type,data){return asap(function(){return socketAsk(type,data)})}},{key:"onConnect",value:function(fn){canSubscribe&&fn(),this.on("connected",fn)}},{key:"sendPing",value:function(){return waitingPong=!1,ping(),this}},{key:"ready",value:function(){return isSocketReady()}}]),NotifyProxyClass}(GGEventEmitter)),websocket=void 0,pingTimeout=void 0,reconnecting=!1,waitingPong=!1,
17canSubscribe=!1,postponedCalls=[],answersCallbacks=[],objectsToSubscribe=[];return function(){UserService.id&&connect(),UserService.onLoginChange(function(user){close(),user&&user.id&&connect()})}(),self}(),PageLoader=function($,angular,window,console){function init(){window.history.replaceState({path:window.location.href},window.document.title),createLoader(),bind(),afterLoaded(),lastLink=window.location.href}function createLoader(){bodyBlock=$("#entire"),loaderFrame=document.createElement("iframe"),loaderFrame.id="frameLoader",document.body.appendChild(loaderFrame)}function updateLoader(url){loaderFrame&&(loaderFrame.remove?loaderFrame.remove():loaderFrame.parentNode.removeChild(loaderFrame)),createLoader(),loaderFrame.src=url}function bind(){$("body").on("click","a",linkClick),window.addEventListener("popstate",function(e){if(e.state&&e.state.path)isGoingBack=!0,loadPage(e.state.path);else{document.querySelector("[ui-view]")||(isGoingBack=!0,loadPage(window.location.href))}},!1)}function linkClick(event){if(event.currentTarget.hasAttribute&&event.currentTarget.hasAttribute("no-scroll"))return!0;var link=event.currentTarget.href.replace("http://gg.test",window.location.origin).replace("https://goodgame.ru",window.location.origin).replace("https://stage.goodgame.ru",window.location.origin).replace("http://test.goodgame.ru",window.location.origin).replace("https://beta.goodgame.ru",window.location.origin),href=event.currentTarget.getAttribute("href")||"";return!!href&&(href&&"#"===href[0]?("c"!==href[1]&&Utils.scrollToElement($("a[name='"+event.currentTarget.getAttribute("href").slice(1)+"']")),event.preventDefault(),!1):!!event.currentTarget.hasAttribute("target")||(!!(event.originalEvent&&event.originalEvent.defaultPrevented||event.metaKey||event.ctrlKey)||(0!==link.indexOf(window.location.origin)||(Utils.rootScope().isMobile&&"/"===href&&(link+="mobile"),preserveScroll="preserve"==$(event.currentTarget).data("scroll"),event.preventDefault(),console.log("loadPage"),isGoingBack=!1,void loadPage(link)))))}function inIframe(){try{return window.self!==window.top}catch(e){return!0}}function reload(){loadPage(window.location.href)}function loadPage(link,cb){if(console.log("Loading page",link),inIframe())return void(window.location.href=link);setProgressBar("loading"),currentLink=link,goCb=cb||goCb,updateLoader("/content/?q="+link.replace(window.location.origin,""))}function loadPageOrBack(link,cb){window.history.length>1?window.history.back():loadPage(link,cb)}function onLoaded(data,xhrid){if(window.DEV&&console.log("Loading complete",currentLink),Utils.rootScope().isMobile){var sb=document.querySelector(".simplebar-scroll-content");sb&&sb.scrollTo(0,0)}setProgressBar("loaded"),beforeLoaded(),isGoingBack||(console.log("Pushing state:",currentLink),window.history.pushState({path:currentLink},data.title||currentLink,currentLink)),window.document.title=data.title||currentLink,data.object&&(window.GGObj=data.object,NotifyProxy.sendPing()),setBodyAndCompile(data.html),afterLoaded(),addRequestToProfiler(xhrid)}function beforeLoaded(){fnOnExit&&(fnOnExit(currentLink,lastLink),fnOnExit=!1),preserveScroll||Utils.scrollToElement(!1,0),$("div.popup-block").length>0&&PopupBlock.outerClose(),window.pageScope.$destroy()}function afterLoaded(){setTimeout(function(){return $(window).trigger("resize")},10),trackCounter(),fnOnEnter&&(fnOnEnter(),fnOnEnter=!1),goCb&&(goCb(),goCb=!1),window.location.hash&&setTimeout(function(){window.location.hash.match(/#comment-(\d+)?/gi)?Utils.scrollToElement2($('*[gg-ancor="#toComments"]'),300):Utils.scrollToElement($('*[gg-ancor="'+window.location.hash+'"]'),300)},500),lastLink=currentLink}function trackBranding(){var reklama=Utils.rootScope().Reklama;reklama&&reklama.reloadBrand()}function trackCounter(){if(lastTrack!==window.location.href){lastTrack=window.location.href;try{trackBranding()}catch(e){console.log(e)}Utils.reachYandexHit(lastLink);try{void 0!==UserService&&_gaq.push(["_setCustomVar",1,"User Type",UserService&&"0"!=UserService.id?"Registered":"Guest"]),_gaq.push(["_trackPageview"])}catch(e){}try{_tmr.push({id:"3749895",type:"pageView",start:(new Date).getTime()})}catch(e){}}}function addRequestToProfiler(xhrid){"undefined"!=typeof phpdebugbar&&xhrid&&phpdebugbar.loadDataSet(xhrid,"(page)")}function setProgressBar(state){var wrapper=$(".outer-wrap");switch(state){case"loaded":wrapper.removeClass("loading").addClass("loaded"),setTimeout(function(){return wrapper.removeClass("loaded")},1500);break;case"loading":wrapper.removeClass("loaded").addClass("loading")}}function setBodyAndCompile(html){try{bodyBlock.html("");var divHtml=bodyBlock[0].outerHTML;$("#entire-wrapper").html(divHtml),bodyBlock=$("#entire"),bodyBlock.html(html),Utils.compileBlock(bodyBlock)}catch(e){console.log(e)}}function onExit(fn){return fnOnExit=fn,this}function onEnter(fn){return fnOnEnter=fn,this}$(function(){return Utils.delayExec(function(){return init()})});return{cb:onLoaded,go:loadPage,onGo:function(cb){goCb=cb},goOrBack:loadPageOrBack,reload:reload,onExit:onExit,onEnter:onEnter,showLoader:function(){return setProgressBar("loading")},hideLoader:function(){return setProgressBar("loaded")},afterLoad:function(){trackCounter(),lastLink=window.location.href}};var currentLink,lastLink,lastTrack,bodyBlock,loaderFrame,fnOnExit,fnOnEnter,goCb,preserveScroll,isGoingBack}(jQuery,angular,window,console),_plcb=PageLoader.cb,PopupBlock=function(){function PopupBlock(){_classCallCheck(this,PopupBlock)}return _createClass(PopupBlock,[{key:"open",value:function(){var _this19=this;$("div.popup-block").length>0&&this.close();var newElement,elem=$('<div class="popup-block"></div>');return $("body").append(elem),fetch(this._getLink(),{method:"GET",credentials:"same-origin"}).then(function(response){return response.text()}).then(function(html){angular.element(document).injector().invoke(function($rootScope,$compile){newElement=$compile(html)($rootScope),elem.replaceWith(newElement),_this19._onScope(newElement.scope())}),_this19._onLoad(newElement)}).catch(function(data){console.error(data)})}},{key:"close",value:function(){$("div.popup-block").remove()}},{key:"_getLink",value:function(){}},{key:"_onScope",value:function(){}},{key:"_onLoad",value:function(elem){}}],[{key:"outerClose",value:function(){$("div.popup-block").remove()}}]),PopupBlock}(),BanPopup=new function(){return new(function(_PopupBlock){function _class8(){return _classCallCheck(this,_class8),_possibleConstructorReturn(this,(_class8.__proto__||Object.getPrototypeOf(_class8)).apply(this,arguments))}return _inherits(_class8,_PopupBlock),_createClass(_class8,[{key:"open",value:function(_objType,_objId,_parent){var _callback=arguments.length>3&&void 0!==arguments[3]&&arguments[3],_args=arguments.length>4&&void 0!==arguments[4]&&arguments[4];objType=parseInt(_objType),objId=parseInt(_objId),callback=_callback,args=_args,parent=$(_parent),_get(_class8.prototype.__proto__||Object.getPrototypeOf(_class8.prototype),"open",this).call(this)}},{key:"_getLink",value:function(){return"/html/template/moderation/ban.html"}},{key:"_onLoad",value:function(elem){var elemTop=parent.offset().top+20,windowHeight=$(window).height();elemTop+332>windowHeight&&(elemTop=windowHeight-332),elem.css({top:elemTop+20+"px",left:parent.offset().left-55+"px"})}},{key:"_onScope",value:function(scope){scope.vm.objType=objType,scope.vm.objId=objId,scope.vm.callback=callback,scope.vm.args=args,scope.vm.init(
17)}}]),_class8}(PopupBlock));var objType,objId,parent,callback,args},ComplaintPopup=new function(){return new(function(_PopupBlock2){function _class9(){return _classCallCheck(this,_class9),_possibleConstructorReturn(this,(_class9.__proto__||Object.getPrototypeOf(_class9)).apply(this,arguments))}return _inherits(_class9,_PopupBlock2),_createClass(_class9,[{key:"open",value:function(_objType,_objId,_parent){var _adult=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;objType=parseInt(_objType),objId=parseInt(_objId),adult=parseInt(_adult),parent=$(_parent),_get(_class9.prototype.__proto__||Object.getPrototypeOf(_class9.prototype),"open",this).call(this)}},{key:"_getLink",value:function(){return"/html/template/moderation/complaint.html"}},{key:"_onLoad",value:function(elem){var elemTop=parent.offset().top+27,windowHeight=$(window).height();elemTop+208>windowHeight&&(elemTop=windowHeight-208);var _left=parent.offset().left-445;_left<0&&(_left=0),elem.css({top:elemTop+"px",left:_left+"px"})}},{key:"_onScope",value:function(scope){scope.vm.objType=objType,scope.vm.objId=objId,scope.vm.adult=adult,scope.vm.loading=!1}}]),_class9}(PopupBlock));var objType,objId,adult,parent},PopupPage=function(){function PopupPage(){_classCallCheck(this,PopupPage)}return _createClass(PopupPage,[{key:"open",value:function(){var _this22=this,elem=$('<div class="subscribe-popup loading"></div>');return this._getParent().append(elem),elem.fadeIn(200),this._getContent().then(function(html){return angular.element(document).injector().invoke(function($rootScope,$compile){var newElement=$compile(html)($rootScope);elem.replaceWith(newElement),_this22._onScope(newElement.scope())}),_this22._onLoad(),$(".subscribe-popup").removeClass("loading").show()}).catch(function(data){console.error(data)})}},{key:"close",value:function(){$(".subscribe-popup").remove()}},{key:"_getContent",value:function(){return fetch(this._getLink(),{method:"GET",credentials:"same-origin"}).then(function(response){return response.text()})}},{key:"_onScope",value:function(){}},{key:"_onLoad",value:function(){}},{key:"_getLink",value:function(){}},{key:"_getParent",value:function(){return $("body")}}]),PopupPage}(),DonatPopup=new function(){return new(function(_PopupPage){function _class10(){return _classCallCheck(this,_class10),_possibleConstructorReturn(this,(_class10.__proto__||Object.getPrototypeOf(_class10)).apply(this,arguments))}return _inherits(_class10,_PopupPage),_createClass(_class10,[{key:"open",value:function(_objType,_objId){objType=_objType,objId=_objId,type=1,_get(_class10.prototype.__proto__||Object.getPrototypeOf(_class10.prototype),"open",this).call(this)}},{key:"openP2P",value:function(_objId){type=2,objId=_objId,_get(_class10.prototype.__proto__||Object.getPrototypeOf(_class10.prototype),"open",this).call(this)}},{key:"_getContent",value:function(){return 1==type?_get(_class10.prototype.__proto__||Object.getPrototypeOf(_class10.prototype),"_getContent",this).call(this):Promise.resolve('<div class="subscribe-popup" style="display: block"><gg-direct-payment channel="'+objId+'"></gg-direct-payment></div>')}},{key:"_getLink",value:function(){return"/ajax/payment/donatpopup/?objId="+objId+"&objType="+objType}}]),_class10}(PopupPage));var objId,objType,type},PremiumPopup=new function(){return new(function(_PopupPage2){function _class11(){return _classCallCheck(this,_class11),_possibleConstructorReturn(this,(_class11.__proto__||Object.getPrototypeOf(_class11)).apply(this,arguments))}return _inherits(_class11,_PopupPage2),_createClass(_class11,[{key:"open",value:function(_channelName,_ggplus){return UserService.id?(channelName=_channelName,ggplus=_ggplus||0,_get(_class11.prototype.__proto__||Object.getPrototypeOf(_class11.prototype),"open",this).call(this)):window.openLogin()}},{key:"_getContent",value:function(){return Promise.resolve('<div class="subscribe-popup auto"><gg-buy-premium channel="'+(channelName||"")+'" ggplus="'+ggplus+'"></gg-buy-premium></div>')}},{key:"_getLink",value:function(){return"/ajax/payment/buypremium/"+(channelName?"?channel="+channelName:"")}}]),_class11}(PopupPage));var channelName,ggplus},LoginPopup=new function(){return new(function(_PopupPage3){function _class12(){return _classCallCheck(this,_class12),_possibleConstructorReturn(this,(_class12.__proto__||Object.getPrototypeOf(_class12)).apply(this,arguments))}return _inherits(_class12,_PopupPage3),_createClass(_class12,[{key:"open",value:function(_hint){hint=_hint,_get(_class12.prototype.__proto__||Object.getPrototypeOf(_class12.prototype),"open",this).call(this),page=!1}},{key:"register",value:function(options){this.open(),regOptions=options,page="registration-step opened"}},{key:"remember",value:function(step){this.open(),page=step}},{key:"noClose",value:function(){isNoClose=!0}},{key:"setBackurl",value:function(url){backurl=url}},{key:"showCaptcha",value:function(){_showCaptcha=!0}},{key:"_getLink",value:function(){return"/html/login/login.html"}},{key:"_onScope",value:function(scope,e){scope.window.hint=hint,page&&(scope.window.step=page),isNoClose&&(scope.window.isNoClose=isNoClose),_showCaptcha&&(scope.window.showCaptcha=_showCaptcha),backurl&&(scope.window.backurl=backurl),regOptions&&(scope.window.regOptions=regOptions)}}]),_class12}(PopupPage));var hint,page,isNoClose,_showCaptcha,backurl,regOptions},GalleryPopup=new function(){return new(function(_PopupPage4){function _class13(){return _classCallCheck(this,_class13),_possibleConstructorReturn(this,(_class13.__proto__||Object.getPrototypeOf(_class13)).apply(this,arguments))}return _inherits(_class13,_PopupPage4),_createClass(_class13,[{key:"open",value:function(_galleryId,_imageId){galleryId=_galleryId,imageId=_imageId||0,_get(_class13.prototype.__proto__||Object.getPrototypeOf(_class13.prototype),"open",this).call(this)}},{key:"_getLink",value:function(){return"/html/gallery/gallery.html"}},{key:"_onScope",value:function(scope){scope.vm.galleryId=galleryId,scope.vm.imageId=imageId}}]),_class13}(PopupPage));var galleryId,imageId},SearchPopup=new function(){return new(function(_PopupPage5){function _class14(){_classCallCheck(this,_class14);var _this27=_possibleConstructorReturn(this,(_class14.__proto__||Object.getPrototypeOf(_class14)).call(this));return _this27.lastQuery="",_this27}return _inherits(_class14,_PopupPage5),_createClass(_class14,[{key:"showResults",value:function(_query){query=_query,opened?(scope.search.query=_query,scope.$apply()):this.open()}},{key:"open",value:function(){opened=!0,_get(_class14.prototype.__proto__||Object.getPrototypeOf(_class14.prototype),"open",this).call(this)}},{key:"close",value:function(){scope&&scope.search&&(this.lastQuery=scope.search.query||""),opened=!1,_get(_class14.prototype.__proto__||Object.getPrototypeOf(_class14.prototype),"close",this).call(this)}},{key:"_getLink",value:function(){return"/html/search/index.html"}},{key:"_onScope",value:function(_scope){scope=_scope,scope.search.query=query||this.lastQuery}}]),_class14}(PopupPage));var opened,query,scope},DeactivationPopup=new function(){return new(function(_PopupPage6){function _class15(){return _classCallCheck(this,_class15),_possibleConstructorReturn(this,(_class15.__proto__||Object.getPrototypeOf(_class15)).apply(this,arguments))}return _inherits(_class15,_PopupPage6),_createClass(_class15,[{key:"open",value:function(_id,_status){var _callback=arguments.length>2&&void 0!==arguments[2]&&arguments[2];id=_id,status=_status,callback=_callback,_get(_class15.prototype.__proto__||Object.getPrototypeOf(_class15.prototype),"open",this).call(this)}},{key:"_onScope",value:function(scope){scope.vm.id=id,scope.vm.status=status,scope.vm.callback=callback}},{key:"_getLink",value:function(){return"/html/template/moderation/deactivation.html"}}]),_class15}(PopupPage));var id,status,callback},DeactivationChannelPopup=new function(){return new(function(_PopupPage7){function _class16(){return _classCallCheck(this,_class16),_possibleConstructorReturn(this,(_class16.__proto__||Object.getPrototypeOf(_class16)).apply(this,arguments))}return _inherits(_class16,_PopupPage7),_createClass(_class16,[{key:"open",value:function(_id,_status){var _callback=arguments.length>2&&void 0!==arguments[2]&&arguments[2];id=_id,status=_status,callback=_callback,_get(_class16.prototype.__proto__||Object.getPrototypeOf(_class16.prototype),"open",this).call(this)}},{key:"_onScope",value:function(scope){scope.vm.id=id,scope.vm.status=status,scope.vm.callback=callback}},{key:"_getLink",value:function(){return"/html/template/moderation/deactivation_channel.html"}}]),_class16}(PopupPage));var id,status,callback},Reklama=function(_GGEventEmitter3){function Reklama(){_classCallCheck(this,Reklama);var _this30=_possibleConstructorReturn(this,(Reklama.__proto__||Object.getPrototypeOf(Reklama)).call(this));return _this30.loaded=!1,_this30.noBrand=!0,_this30.data=!1,_this30.reloadBrand=Utils.debounce(function(){return _this30._reloadBrand()},1e3),_this30.zoneIdParams={26:{pp:"g",ps:"diew",p2:"gorv"}}
17,_this30.containerId="adfox_155180713667936946",_this30.on("loaded",function(){return _this30.setBrand()}),_this30.hasAdvert()&&_this30.loadData(),_this30}return _inherits(Reklama,_GGEventEmitter3),_createClass(Reklama,[{key:"loadData",value:function(){var _this31=this;try{window.Ya.adfoxCode.create({ownerId:310915,containerId:this.containerId,params:{pp:"sqn",ps:"diew",p2:"gkuv"},onLoad:function(data){_this31.data=data,_this31.emit("loaded")},onRender:function(){},onError:function(error){console.log("onError",error)},onStub:function(){console.log("onStub")}})}catch(e){console.log("Error loading adfox")}}},{key:"loadBanner",value:function(zoneId){if(!this.hasAdvert())return!1;var params=this.zoneIdParams[zoneId];return params?new Promise(function(resolve,reject){try{window.Ya.adfoxCode.create({ownerId:310915,containerId:"adzone_"+zoneId,params:params,onLoad:function(data){console.log("onLoad",data,zoneId),resolve(data)},onError:function(error){console.log("onError",error,zoneId),reject(data)},onStub:function(){console.log("onStub",zoneId),resolve(!1)}})}catch(e){console.log("Error loading adfox, zone "+zoneId,e)}}):Promise.reject()}},{key:"setBrand",value:function(){try{this.data&&!UserService.isPremium()&&($(".banner-block").find('a:not([rel="remove-banner"])').attr("href",this.data.bundleParams.reference),$(".aside-link").attr("href",this.data.bundleParams.reference),$("#branging-bg").css("background-image","url("+this.data.bundleParams.imageUrl+")"),this.loaded=!0,this.noBrand=!1,$("body").removeClass("no-ads"),$("#"+this.containerId).show())}catch(e){}}},{key:"getZoneData",value:function(){return!1}},{key:"_reloadBrand",value:function(){if(performance.now()<1e4)return!1;try{window.Ya.adfoxCode.reload(this.containerId)}catch(e){}}},{key:"isNewUser",value:function(){return!1}},{key:"hasAdvert",value:function(){return!UserService.isPremium()}}]),Reklama}(GGEventEmitter),ResourceLoader=function(jQuery){function loadJs(filename){function onLoad(resolve){done.push(filename),pending[filename].forEach(function(res){return res()}),resolve()}return-1!==done.indexOf(filename)?Promise.resolve():pending[filename]?new Promise(function(resolve){return pending[filename].push(resolve)}):(pending[filename]=[],new Promise(function(resolve){var script=document.createElement("script");script.src=filename,script.onload=function(){return onLoad(resolve)},document.head.appendChild(script)}))}function loadCss(filename){jQuery("head").append(jQuery('<link rel="stylesheet" type="text/css" />').attr("href",filename))}var done=[],pending={};return function(){jQuery.cachedScript=function(url,options){return options=jQuery.extend(options||{},{dataType:"script",cache:!0,url:url}),jQuery.ajax(options)}}(),{loadJs:loadJs,loadCss:loadCss}}(jQuery),StreamsListPage=new function(){function setActive(){$("#favorite-games-wrap").find(".selected").removeClass("selected"),$(this).addClass("selected"),$(".stream-list").addClass("loading")}function genreSwitcher(event){$(event.currentTarget).find("span").toggleClass("active")}function loadMoreStreams(event){event.preventDefault();var block=rootElem.find(".stream-list"),link=$(event.currentTarget).addClass("loading"),currentPage=Math.ceil(block.find(".stream-block").length/40);Utils.post(AJAX_PATH+"/channels/",{slider:!1,page:currentPage+1}).then(function(data){return JSON.parse(data)}).then(function(data){block.append(data.html),Utils.compileBlock(block),link&&link.hide()});var infScroll=new InfinityScroll(Header.getScroller());infScroll.nextPage(function(){var currentPage=Math.ceil(block.find(".stream-block").length/40);PageLoader.showLoader(),Utils.post(AJAX_PATH+"/channels/",{slider:!1,page:currentPage+1}).then(function(data){return JSON.parse(data)}).then(function(data){block.append(data.html),Utils.compileBlock(block),40==$(data.html).find(".preview-inner").length&&infScroll.done(),PageLoader.hideLoader()})})}var rootElem;return new(function(_GoodgamePage8){function _class17(){return _classCallCheck(this,_class17),_possibleConstructorReturn(this,(_class17.__proto__||Object.getPrototypeOf(_class17)).apply(this,arguments))}return _inherits(_class17,_GoodgamePage8),_createClass(_class17,[{key:"bind",value:function(){rootElem=this.root,rootElem.on("click","#channels-tab [data-action=loadMoreStreams]",loadMoreStreams).on("click","#favorite-games-wrap [data-action=switch]",genreSwitcher).on("click","#favorite-games-wrap .favorite-game",setActive)}}]),_class17}(GoodgamePage))},TabsManager=new function(){function count(){return!1}function isTopWindow(){return!document.hidden}return{isTopWindow:isTopWindow,count:count}},TopSearch=function(){var rootElem={},showResults=function(e){e.preventDefault(),$(".js-header-search").hasClass("active")?($
17(".js-header-search").removeClass("active"),SearchPopup.close()):($(".js-header-search").addClass("active"),SearchPopup.showResults(SearchPopup.lastQuery))};return new(function(_GoodgamePage9){function _class18(){return _classCallCheck(this,_class18),_possibleConstructorReturn(this,(_class18.__proto__||Object.getPrototypeOf(_class18)).apply(this,arguments))}return _inherits(_class18,_GoodgamePage9),_createClass(_class18,[{key:"bind",value:function(){rootElem=this.root,rootElem.on("click","header .icon-search",showResults)}}]),_class18}(GoodgamePage))}(),Utils=function(){function Utils(){_classCallCheck(this,Utils)}return _createClass(Utils,null,[{key:"post",value:function(url,data){return fetch(url,{method:"POST",headers:{"Content-type":"application/x-www-form-urlencoded; charset=UTF-8","X-Requested-With":"XMLHttpRequest"},credentials:"same-origin",body:Utils.serialize(data)}).then(function(response){return 0===response.headers.get("Content-Type").indexOf("application/json")?response.json():response.text()}).then(function(response){return Utils.rootScope().$applyAsync(),response})}},{key:"postForm",value:function(url,form){return $.ajax({url:url,type:"POST",data:form,dataType:"json",processData:!1,contentType:!1})}},{key:"get",value:function(url,data){function _throw(m){throw m}var headers={};try{var urlHostname=Utils.parseUrl(url).hostname
18;window.location.hostname===urlHostname&&(headers["X-Requested-With"]="XMLHttpRequest")}catch(e){console.log(e)}return fetch(url+(data?"?"+Utils.serialize(data):""),{method:"GET",credentials:"same-origin",headers:headers}).then(function(response){return response.ok?response:_throw(response.statusCode+": "+response.statusText)()}).then(function(response){return 0===response.headers.get("Content-Type").indexOf("application/json")?response.json():response.text()}).then(function(response){return Utils.rootScope().$applyAsync(),response})}},{key:"serialize",value:function(obj){var str=[];for(var p in obj)if(obj.hasOwnProperty(p))if("object"===_typeof(obj[p]))for(var pp in obj[p])obj[p].hasOwnProperty(pp)&&str.push(encodeURIComponent(p+"["+pp+"]")+"="+encodeURIComponent(obj[p][pp]));else str.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));return str.join("&")}},{key:"debounce",value:function(func,wait,immediate){var timeout=void 0,debouncedFn=function(){var context=this,args=arguments,later=function(){timeout=null,immediate||func.apply(context,args)},callNow=immediate&&!timeout;clearTimeout(timeout),timeout=setTimeout(later,wait),callNow&&func.apply(context,args)};return debouncedFn.cancel=function(){clearTimeout(timeout)},debouncedFn}},{key:"throttle",value:function(func,wait){function wrapper(){if(isThrottled)return savedArgs=arguments,void(savedThis=this);func.apply(this,arguments),isThrottled=!0,setTimeout(function(){isThrottled=!1,savedArgs&&(wrapper.apply(savedThis,savedArgs),savedArgs=savedThis=null)},wait)}var savedArgs,savedThis,isThrottled=!1;return wrapper}},{key:"checkClickOutside",value:function(target,container){return!container.is(target)&&0===container.has(target).length}},{key:"parseMysqlDate",value:function(mysqlDate){var parts=mysqlDate.split(" "),date=parts[0].split("-");if(2==parts.length){var time=parts[1].split(":");return new Date(date[0],date[1]-1,date[2],time[0],time[1],time[2]||0)}return new Date(date[0],date[1]-1,date[2])}},{key:"parseRussianDate",value:function(rusDate,withTime){var date=void 0,time=void 0;try{if(withTime){var parts=rusDate.split(" ");date=parts[1].split("."),time=parts[0].split(":")}else date=rusDate.split("."),time=["0","00"]}catch(e){return!1}return Utils.validDate(date[2],date[1],date[0],time[0],time[1])}},{key:"validDate",value:function(y,m,d,h,min){if(4!=y.length||2!=m.length||2!=d.length||2!=min.length)return!1;y=parseInt(y,10),m=parseInt(m,10),d=parseInt(d,10),h=parseInt(h,10),min=parseInt(min,10);var date=new Date(y,m-1,d,h,min);return y>1910&&y<2030&&date.getFullYear()==y&&date.getMonth()+1==m&&date.getDate()==d&&date.getHours()==h&&date.getMinutes()==min&&date}},{key:"moscowTime",value:function(d){d=void 0===d?new Date(Date.now()-window.timeLag):new Date(+d-window.timeLag);var _userOffset=6e4*d.getTimezoneOffset();return d.getTime()+108e5+_userOffset}},{key:"moscowToLocalDate",value:function(moscowDate){var _userOffset=6e4*(new Date).getTimezoneOffset();return new Date(+moscowDate-108e5-_userOffset)}},{key:"timeLeft",value:function(to,current){var secs=to-current,sec_num=Math.floor(secs/1e3),last=sec_num,hours=Math.floor(last/3600);last-=3600*hours;var minutes=Math.floor(last/60),seconds=last-60*minutes;return hours<0?"":(hours<10&&(hours="0"+hours),minutes<10&&(minutes="0"+minutes),seconds<10&&(seconds="0"+seconds),(+hours?hours+":":"")+minutes+":"+seconds)}},{key:"getTimezoneOffset",value:function(){return 60*(new Date).getTimezoneOffset()*1e3}},{key:"getUserTimezoneOffset",value:function(){var userTimezoneOffset=60*(UserService.id&&null!=UserService.timezone?parseInt(UserService.timezone):0)*60*1e3;return UserService.id&&null!=UserService.timezone?Utils.getTimezoneOffset()+userTimezoneOffset:0}},{key:"toUserTimezoneDate",value:function(date){return new Date(+date+Utils.getUserTimezoneOffset())}},{key:"toUTCDate",value:function(userDate){return new Date(+userDate-Utils.getUserTimezoneOffset())}},{key:"getUserCurrentDate",value:function(){return Utils.toUserTimezoneDate(Date.now())}},{key:"decl",value:function(number){var cases=[2,0,1,1,1,2];return number%100>4&&number%100<20?2:cases[number%10<5?number%10:5]}},{key:"rootScope",value:function(){return angular.element(document).scope().$root}},{key:"compileBlock",value:function(bodyBlock,_scope){!bodyBlock||bodyBlock.getAttribute&&bodyBlock.getAttribute("data-compiled")||Utils.isAngularComponent(bodyBlock)||(bodyBlock.setAttribute&&bodyBlock.setAttribute("data-compiled","true"),angular.element(document).injector().invoke(function($compile){var scope=_scope||angular.element(bodyBlock).scope();$compile(bodyBlock)(scope),scope.$digest()}))}},{key:"compileBlockSaveDigest",value:function(bodyBlock,_scope){!bodyBlock||bodyBlock.getAttribute&&bodyBlock.getAttribute("data-compiled")||Utils.isAngularComponent(bodyBlock)||(bodyBlock.setAttribute&&bodyBlock.setAttribute("data-compiled","true"),angular.element(document).injector().invoke(function($compile){var scope=_scope||angular.element(bodyBlock).scope();scope&&($compile(bodyBlock)(scope),scope.$applyAsync())}))}},{key:"scrollToElement",value:function(element,speed,force){var scroller=Header.getScroller();speed=void 0!==speed?speed:300,element&&element.length?scroller.animate({scrollTop:element.position().top+window.innerHeight-scroller.offset().top},speed):!force&&window.location.hash||scroller.animate({scrollTop:0},speed)}},{key:"scrollToElement2",value:function(element){var scroller=Header.getScroller();if(element&&element.length){scroller.scrollTop(0),element.css("border","1p
18x solid red");var rect=element.get(0).getBoundingClientRect();return scroller.scrollTop(rect.bottom-scroller.offset().top-rect.height-10),!0}return scroller.scrollTop(0),!1}},{key:"withZero",value:function(num){return num<10?"0"+num:num}},{key:"toMysqlDate",value:function(date){return"string"==typeof date?date:date.getFullYear()+"-"+Utils.withZero(date.getMonth()+1)+"-"+Utils.withZero(date.getDate())+" "+Utils.withZero(date.getHours())+":"+Utils.withZero(date.getMinutes())+":00"}},{key:"clearObject",value:function(object){return Object.keys(object).forEach(function(key){delete object[key]}),object}},{key:"lsSet",value:function(name,value){try{localStorage.setItem(name,value)}catch(e){console.log(e)}}},{key:"lsGet",value:function(name){var def=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;try{var value=localStorage.getItem(name);return null===value?def:value}catch(e){console.log(e)}return def}},{key:"lsGetJSON",value:function(name){var def=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,value=Utils.lsGet(name,null);if(!value)return def;try{return JSON.parse(value)}catch(e){}return def}},{key:"ecid",value:function(){UserService.id&&ResourceLoader.loadJs("/js/libraries/evercookie.js?rnd=10").then(function(){var ec=new evercookie({tests:1});ec.get("ecid",function(ecUser){void 0===ecUser?ec.set("ecid",UserService.id):ecUser!=UserService.id&&(ec.set("ecid",UserService.id),Utils.post("/ajax/ecid/",{ecid:ecUser,user:UserService.id}))})})}},{key:"reachGoal",value:function(goal){if(goal){try{window.ym&&ym(11385799,"reachGoal",goal)}catch(e){console.log(e)}
18try{window._gaq.push(["_trackEvent","YaGoal","Reach",goal])}catch(e){}try{_tmr.push({id:"3749895",type:"reachGoal",goal:goal})}catch(e){}}}},{key:"reachYandexHit",value:function(lastLink){try{ym(11385799,"hit",window.location.href,{title:document.title,referer:lastLink||""})}catch(e){console.log(e)}}},{key:"htmlDecode",value:function(text){return $("<p>"+text+"</p>").text()}},{key:"queryParam",value:function(param,empty){return function(a){if(""==a)return{};for(var b={},i=0;i<a.length;++i){var p=a[i].split("=",2);1==p.length?b[p[0]]=empty||"":b[p[0]]=decodeURIComponent(p[1].replace(/\+/g," "))}return b}(window.location.search.substr(1).split("&"))[param]||null}},{key:"parseUrl",value:function(href){var location=document.createElement("a");return location.href=href,""==location.host&&(location.href=location.href),location}},{key:"escapeRegExp",value:function(str){return str.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&")}},{key:"errorSummary",value:function(arr,separator){return separator=separator||",\r\n",arr.join(separator)}},{key:"delayExec",value:function(callback){var fn=setTimeout;window.requestIdleCallback&&(fn=window.requestIdleCallback),fn(function(){return callback()})}},{key:"sendEvent",value:function(name,details){return window.DEV_EVENTS&&console.log("Utils sendEvent",name,details,window.UserEvents),window.UserEvents.submit(name,details)}},{key:"isAngularComponent",value:function(el){return!(!el||!el.attributes)&&!(!el.getAttribute||!el.getAttribute("data-ignore-compile"))}}]),Utils}(),VideosListPage=new function(){function loadMoreVideos(event){event.preventDefault();var block=rootElem.find(".stream-list"),link=$(event.currentTarget).addClass("loading"),currentPage=Math.ceil((block.find(".stream-block").length-1)/40);Utils.post(AJAX_PATH+document.location.pathname,{page:currentPage+1}).then(function(data){return angular.fromJson(data)}).then(function(data){block.append(data.html),Utils.compileBlock(block),link&&link.hide(),$(data.html).find(".preview-inner").length<40&&link.hide()});var infScroll=new InfinityScroll(Header.getScroller());infScroll.nextPage(function(){var currentPage=Math.ceil(block.find(".stream-block").length/40);PageLoader.showLoader(),Utils.post(AJAX_PATH+document.location.pathname,{page:currentPage+1}).then(function(data){return angular.fromJson(data)}).then(function(data){block.append(data.html),Utils.compileBlock(block),40==$(data.html).find(".preview-inner").length&&infScroll.done(),PageLoader.hideLoader()})})}function doDelete(event){var id=$(event.currentTarget).data("id");Utils.post("/ajax/video/delete",{id:id,action:1}).then(function(){$(".video-page-wrap").hide(),$(".video-deleted").show()})}function doUndelete(event){var id=$(event.currentTarget).data("id");Utils.post("/ajax/video/delete",{id:id,action:0}).then(function(){$(".video-page-wrap").show(),$(".video-deleted").hide()})}var rootElem;return new(function(_GoodgamePage10){function _class19(){return _classCallCheck(this,_class19),_possibleConstructorReturn(this,(_class19.__proto__||Object.getPrototypeOf(_class19)).apply(this,arguments))}return _inherits(_class19,_GoodgamePage10),_createClass(_class19,[{key:"bind",value:function(){rootElem=this.root;var rootHtmlElem=rootElem.get(0);rootHtmlElem.querySelector("#videos-box [data-action=loadMoreVideos]")&&(rootHtmlElem.querySelector("#videos-box [data-action=loadMoreVideos]").onclick=loadMoreVideos),rootElem.on("click","#videos-box [data-action=loadMoreVideos]",loadMoreVideos).on("click",".video-page-wrap [data-action=delete]",doDelete).on("click",".video-deleted [data-action=undelete]",doUndelete)}}]),_class19}(GoodgamePage))},Gfycat=function(){function Gfycat(){_classCallCheck(this,Gfycat)}return _createClass(Gfycat,[{key:"textToGif",value:function(text){var _this35=this;return this.resolveToken().then(function(data){return _this35.makeRequest({method:"GET",headers:_this35.getAuthHeader(),url:"https://api.gfycat.com/v1/reactions/populated?tagName="+text})}).then(function(data){if(data.gfycats&&data.gfycats.length){var items=data.gfycats;return items[Math.floor(Math.random()*items.length)].miniUrl.replace("https://thumbs.gfycat.com/","")}})}},{key:"getAuthHeader",value:function(){return{Authorization:"Bearer "+Gfycat.accessToken}}},{key:"resolveToken",value:function(){return Gfycat.accessToken?Promise.resolve(Gfycat.accessToken):this.requestToken().then(function(data){return Gfycat.accessToken=data.access_token,Gfycat.accessToken})}}
18,{key:"requestToken",value:function(){return this.makeRequest({method:"POST",url:"https://api.gfycat.com/v1/oauth/token",payload:{grant_type:"client_credentials",client_id:"2_U8PSJb",client_secret:"cWnLNKXSHMrdfTlbmjEJNmSYCOkS17zYKac0zTkZ8fEYW4HF2TyQijVZbcC4SpCp"}})}},{key:"makeRequest",value:function(request){return new Promise(function(resolve,reject){function handleError(err){err=err||new Error("API request failed"),reject(err)}function handleResponse(res){if(xhr.status>=400)return reject(xhr.status);var body=xhr.response;try{body=JSON.parse(body),resolve(body)}catch(e){reject(e)}}var xhr=new XMLHttpRequest;xhr.addEventListener("error",handleError),xhr.addEventListener("abort",handleError),xhr.addEventListener("load",handleResponse),xhr.open(request.method,request.url,!0);var headers=request.headers||null;headers&&Object.keys(headers).forEach(function(header){xhr.setRequestHeader(header,headers[header])});var data=JSON.stringify(request.payload)||null;data?(xhr.setRequestHeader("Content-Type","application/json"),xhr.send(data)):xhr.send()})}}]),Gfycat}(),Chat3=function(ChatSettings){var defaultSettings={debug:0,server:(window.WS_SCHEMA||"wss")+"://"+CHAT+"/chat2/",popupUrl:"",userId:UserObj.id||0,userToken:UserObj.token||"",channelId:0,userData:"{}"};return new(function(_GGEventEmitter4){function _class20(){_classCallCheck(this,_class20);var _this36=_possibleConstructorReturn(this,(_class20.__proto__||Object.getPrototypeOf(_class20)).call(this));return _this36.settings=angular.extend({},defaultSettings,ChatSettings),_this36.rooms=new ChatRoomService(_this36.settings,{onUpdateUserInfo:function(data){return _this36.emit("updateUserInfo",data)},onUpdateUserInfoInRoom:function(data){return _this36.emit("updateUserInfoInRoom",data)},onUpdateStreamerInRoom:function(data){return _this36.emit("updateStreamerInRoom",data)}}),_this36.rooms.onUpdate(function(data){return window.DEV_CHAT&&console.log("Chat3 onUpdate",data),_this36.emit("update",data)}),_this36.rooms.onUpdateChannelJobs(function(room,jobs){return window.DEV_CHAT&&console.log("Chat3 onUpdateChannelJobs",room,jobs),_this36.emit("updateChannelJobs",room,jobs)}),_this36.rooms.listenForHelpers(_this36.emitHelpers.bind(_this36)),UserService.onLoginChange(function(user){_this36.settings.userId=user.id,_this36.settings.userToken=user.token,_this36.rooms.auth()}),_this36}return _inherits(_class20,_GGEventEmitter4),_createClass(_class20,[{key:"emitHelpers",value:function(helpers){this.emit("helpers",helpers)}},{key:"room",value:function(id){return id?this.rooms.getRoom(id):this.rooms.currentRoom()}},{key:"openRoom",value:function(id){this.rooms.openRoom(id)}},{key:"closeRoom",value:function(id){this.rooms.closeRoom(id)}},{key:"sendPrivateMessage",value:function(nickname,message){this.rooms.sendPrivateMessage(nickname,message)}},{key:"rejoin",value:function(){this.rooms.rejoin()}}]),_class20}(GGEventEmitter))},ChatApi=function(_GGEventEmitter5){function ChatApi(settings){_classCallCheck(this,ChatApi);var _this37=_possibleConstructorReturn(this,(ChatApi.__proto__||Object.getPrototypeOf(ChatApi)).call(this));return _this37.sock=new ChatTransport({server:settings.server}),_this37.settings=settings,_this37.bind(),_this37._callbacks={},_this37}return _inherits(ChatApi,_GGEventEmitter5),_createClass(ChatApi,[{key:"bind",value:function(){function processCallback(data,type){return self._processCallback(type,data)}function emitNext(data,type){return self.emit(type,data)}var _this38=this;this.sock.on("welcome",function(){return _this38.auth()}),this.sock.on("success_auth",function(){return _this38.emit("connected")}),this.sock.on("success_join",function(data){return _this38.emit("joined",data)}),this.sock.on("reconnecting",emitNext),this.sock.on("update_rights",emitNext),this.sock.on("reconnected",emitNext),this.sock.on("channel_history",function(data){return _this38.emit("history",data)}),this.sock.on("channel_counters",emitNext),this.sock.on("user_ban",emitNext),this.sock.on("user_warn",emitNext),this.sock.on("payment",emitNext),this.sock.on("premium",emitNext),this.sock.on("remove_message",emitNext),this.sock.on("message",emitNext),this.sock.on("private_message",function(data,type){return _this38.emit("message",data)}),this.sock.on("error",emitNext),this.sock.on("new_poll",emitNext),this.sock.on("setting",emitNext),this.sock.on("set_smile_only_mode",emitNext),this.sock.on("random_result",emitNext),this.sock.on("update_user_info",emitNext),this.sock.on("update_user_info_
18in_room",emitNext),this.sock.on("update_streamer_in_room",emitNext),this.sock.on("new_job",emitNext),this.sock.on("gifted_premiums",emitNext),this.sock.on("update_job",emitNext),this.sock.on("job_prize_increased",emitNext),this.sock.on("update_channel_info_jobs",emitNext),this.sock.on("teleport_user",emitNext),this.sock.on("teleport_aim",emitNext),this.sock.on("user_payment_failed",emitNext),this.sock.on("default",processCallback);var self=this}},{key:"connect",value:function(){this.sock.connected()||this.sock.connect()}},{key:"disconnect",value:function(){this.sock.connected()&&this.sock.disconnect()}},{key:"join",value:function(roomId){var reload=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.sock.send("join",{channel_id:roomId,hidden:UserObj.id&&null!=UserObj.settings.chat?UserObj.settings.chat.hide:0,reload:reload})}},{key:"unjoin",value:function(roomId){return this._sendWithCallback("unjoin",{channel_id:roomId},"unjoin")}},{key:"rejoin",value:function(roomId){var _this39=this;this.unjoin(roomId).then(function(){return _this39.join(roomId,!0)})}},{key:"getHistory",value:function(roomId,from){this.sock.send("get_channel_history",{channel_id:roomId,from:from||0})}},{key:"auth",value:function(){var _this40=this;if(!this.sock.connected())return!1;this.sock.send("auth",{user_id:this.settings.userId,token:this.settings.userToken}),setTimeout(function(){_this40.sock.send("get_user_rooms",{user_id:_this40.settings.userId})},3e3)}},{key:"sendMessage",value:function(roomId,text,user){this.sock.send("send_message",{channel_id:roomId,text:text,color:user.color,icon:user.icon,role:user.role,mobile:user.mobile})}},{key:"deleteMessage",value:function(roomId,messageId,adminName){this.sock.send("remove_message",{channel_id:roomId,message_id:messageId,adminName:adminName})}},{key:"getUsersList",value:function(roomId){return this._sendWithCallback("get_users_list2",{channel_id:roomId},"users_list")}},{key:"getIgnoreList",value:function(){return this._sendWithCallback("get_ignore_list",{},"ignore_list")}},{key:"deleteFromIgnoreList",value:function(userId){return this._sendWithIgnoreListEmit("del_from_ignore_list",{user_id:userId},"ignore_list")}},{key:"addToIgnoreList",value:function(userId){return this._sendWithIgnoreListEmit("add_to_ignore_list",{user_id:userId},"ignore_list")}},{key:"getStreamModers",value:function(roomId){return this._sendWithCallback("get_stream_moders_list",{channel_id:roomId},"stream_moders_list")}},{key:"getPoll",value:function(roomId){return this._sendWithCallback("get_poll",{channel_id:roomId},"poll_results")}},{key:"makeVote",value:function(roomId,answerId){return this.getVote(roomId,answerId)}},{key:"getVote",value:function(roomId,answerId){return this._sendWithCallback("vote",{channel_id:roomId,answer_id:answerId},"poll_results")}},{key:"createPoll",value:function(roomId,pollData){return pollData.channel_id=roomId,this.sock.send("new_poll",pollData)}},{key:"setRoomSettings",value:function(roomId,settings){return this.sock.send("setting",{channel_id:roomId,settings:settings})}},{key:"addStreamModer",value:function(roomId,userId){var _this41=this;return this._sendWithCallback("make_moderator",{channel_id:roomId,user_id:userId},"moder_rights").then(function(data){return _this41.emit("error",{errorMsg:data.retMsg})}).then(function(data){return _this41.getStreamModers(roomId)})}},{key:"deleteStreamModer",value:function(roomId,userId){var _this42=this;return this._sendWithCallback("clean_moderator",{channel_id:roomId,user_id:userId},"moder_rights").then(function(data){return _this42.getStreamModers(roomId)})}},{key:"banUser",value:function(roomId,data){return data.roomId=roomId,this.sock.send("ban2",data)}},{key:"unbanUser",value:function(roomId,userId){var data={roomId:roomId,userId:userId};return this.sock.send("unban",data)}},{key:"warnUser",value:function(roomId,userId){return this.sock.send("warn",{channel_id:roomId,user_id:userId,reason:""})}},{key:"_sendWithCallback",value:function(cmd,data,callback){var _this43=this;return new Promise(function(resolve){_this43._callbacks[callback]=resolve,_this43.sock.send(cmd,data)})}},{key:"_sendWithIgnoreListEmit",value:function(cmd,data,callback){var _this44=this;return new Promise(function(resolve){_this44._callbacks[callback]=resolve,_this44.sock.send(cmd,data),_this44.getIgnoreList(
18).then(function(ignoreList){delete _this44._callbacks[callback],resolve(ignoreList)})})}},{key:"_processCallback",value:function(event,data){this._callbacks[event]&&(this._callbacks[event](data),delete this._callbacks[event])}},{key:"startCommercial",value:function(key,pwd){return this.sock.send("commercial",{action:"show",key:key,pwd:pwd})}},{key:"getRandomUser",value:function(roomId,data){return data.channel_id=roomId,this.sock.send("get_random",data)}},{key:"setSmileOnlyMode",value:function(roomId,enabled){return this.sock.send("set_smile_only_mode",{channel_id:roomId,enabled:enabled})}}]),ChatApi}(GGEventEmitter),ChatMessage=function(){function ChatMessage(data,room){var _this45=this,fromHistory=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(_classCallCheck(this,ChatMessage),["color","icon","isStatus","message_id","mobile","payments","premium","premiums","private","text","mine","timestamp","user_id","user_name","user_rights","gift","html","system","is_commission_covered","donateValue","voice","anonymous","invites","inviteLevels"].forEach(function(field){return _this45[field]=data[field]}),this.id=data.message_id,this.user=new ChatUser(data,room),this.time=this._getTime(this.timestamp),room.user&&room.user.nickname&&!this.mine){var userNicknameStr=Utils.escapeRegExp(room.user.nickname);this.mine=new RegExp("(^|\\s)"+userNicknameStr+",").test(this.text)}this.mine&&!fromHistory&&room.emit("private_message",this),data.private&&(this.mine=data.user&&data.user.id==room.user.id,data.to&&data.to.id!=room.user.id&&(this.user=new ChatUser({private:1,user:data.to},room)),this.hide=data.banned&&room.id==data.channel),this.color=this.user.nickname?"":this.color,this.room=room}return _createClass(ChatMessage,[{key:"_getTime",value:function(timestamp){if(!timestamp)return"";var time,date=Utils.toUserTimezoneDate(1e3*this.timestamp),oneDayAgoTime=Utils.getUserCurrentDate().getTime()-864e5;return time=[date.getHours(),":",Utils.withZero(date.getMinutes()),":",Utils.withZero(date.getSeconds())].join(""),date.getTime()<=oneDayAgoTime&&(time=[Utils.withZero(date.getDate()),".",Utils.withZero(date.getMonth()+1)," "].join("")+time),time}},{key:"remove",value:function(){this.room.deleteMessage(this)}}]),ChatMessage}(),ChatRoomService=function(settings){function openRoom(id){rooms.get(id)||rooms.set(id,new ChatRoom(id,this)),watchConnect()}function closeRoom(id){_currentRoom&&_currentRoom.id===id&&(_currentRoom=!1),rooms.delete(id),watchConnect()}function rejoin(){_currentRoom&&_currentRoom.id&&api.rejoin(_currentRoom.id)}function sendMessage(text,user,_room){var room=_room||_currentRoom;api.sendMessage(room.id,text,user)}function deleteMessage(message,_room){var room=_room||_currentRoom;api.deleteMessage(room.id,message.id,room.user.nickname)}function watchConnect(){rooms.size?api.connect():api.disconnect()}function onConnected(){rooms.forEach(function(room){room.joined?api.unjoin(room.id).then(function(){setTimeout(function(){return api.join(room.id)},150)}):setTimeout(function(){return api.join(room.id)},150)}),loadIgnoreList()}function onUpdateRights(){_currentRoom.getHelpers()}function onReconnected(){reconnectionCounter=0;var msg={color:"system moderator",user_rights:30,text:"Соединение восстановлено"};_currentRoom&&_currentRoom.message(msg),_onUpdate()}function onMessageQuestLog(data){var task=JSON.stringify(data.job).replace("'","&#39;"),room=!!data.channel_id&&rooms.get(data.channel_id),msg={html:1,color:"system king",text:"<gg-quest-task user='"+room.streamer.id+"' task-as-str='"+task+"'></gg-quest-task>"};room.message(msg),_onUpdate()}function onGiftedPremium(data){var info=JSON.stringify(data).replace("'","&#39;"),room=!!data.channel_id&&rooms.get(data.channel_id),msg={html:1,color:"system",text:"<gg-chat-gift data='"+info+"'></gg-chat-gift>"};room.emit("premium",Object.assign({},data,{userIds:data.users.map(function(user){return user.id})})),room.message(msg),_onUpdate()}function _onInviteMessage(data){var room=!!data.channel_id&&rooms.get(data.channel_id),messageData={};messageData.userId=currentUser.id,messageData.streamKey=_currentRoom.streamer.username,messageData.channel_id=data.channel_id;var info=JSON.stringify(messageData).replace("'","&#39;"),msg={html:1,color:"system",text:"<gg4-friend-invite data='"+info+"'></gg4-friend-invite>"};room.message(msg),_onUpdate()}function onUpdateJob(data){var room=!!data.channel_id&&rooms.get(data.channel_id),newStatus=data.job.status,statuses={2:"принято",3:"отклонено",4:"успешно выполнено",5:"провалено",6:"оспаривается"},statusTxt=statuses[newStatus];if(statusTxt){var msg={color:"system king",text:'Задание "'+data.job.title+'" '+statusTxt};room.message(msg),_onUpdate()}}function onPrizeIncreased(data){var room=!!data.channel_id&&rooms.get(data.channel_id),amount=parseInt(data.amount),total=parseInt(data.job.amount),msg={color:"system king",text:data.user.nickname+' пополнил задание "'+data.job.title+'" на '+amount+" р, увеличив награду до "+total+" р"};room.message(msg),_onUpdate()}function onPayment(data){var amount=data.amount+(data.total?" р":""),today=new Date;today>new Date("2024-04-01")&&today<new Date("2024-04-02")&&(amount=FoolsDay.convertValue(data.amount,!1));var msg=void 0;if(data.gift){var giftNumber=Math.floor(3*Math.random())+1;msg={html:1,color:"top-one",icon:"none",user_rights:0,payments:6,nickname:data.userName,text:data.message+' <img class="smile" src="/images/promo/gifts/gift-'+giftNumber+'.gif">',gift:1}}else data.anonymous=!data.userId,data.payment=!0,data.user_id=data.userId,data.user_name=data.userName,data.icon="none",msg={color:"simple",user_rights:0,text:data.total?data.userName+" перевел "+amount:createDonateMessageString(data),with_commission:data.with_commission,donateValue:!data.total&&formatNumber(amount)+" руб."},data.total&&(msg.text+=", увеличив призовой фонд турнира "+data.title+" "+data.link+" до "+data.total+" р"),msg.is_commission_covered=data.is_commission_covered||!1;_currentRoom.message(Object.assign(data,msg)),_onUpdate()}function formatNumber(number){return number.toString().split(".")[0].replace(/\B(?=(\d{3})+(?!\d))/g," ")}function createDonateMessageString(data){return data.voice?data.anonymous?data.userName+"<голосовое сообщение>":"<голосовое сообщение>":data.anonymous?data.userName+(data.message?":":"")+" "+data.message:data.message}function onPremium(data){var msg={color:"system premium",user_rights:30,text:data.userName+" активировал премиум на канал"};1==data.payment&&(msg.text=data.userName+" ",1==data.resub?msg.text+="подписался на премиум":msg.text+="переподписан "+data.resub+" "+["месяц","месяца","месяцев"][Utils.decl(data.resub)]),2==data.payment&&(msg.text=data.userName+" ",1==data.resub?msg.text+="активировал премиум":msg.text+="активирует премиум "+data.resub+" "+["месяц","месяца","месяцев"][Utils.decl(data.resub)],data.subType&&"FreeStreamerPremium"==data.subType&&(msg.text+=" с помощью плюса"));try{_currentRoom.emit("premium",Object.assign({},data,{userIds:[data.userId]}))}catch(e){console.error(e)}_currentRoom.message(msg),_onUpdate()}function onReconnecting(){reconnectionCounter++;var text=["Подключаюсь к серверу чата (",reconnectionCounter,")..."].join(""),msg={color:"system moderator",user_rights:30,text:text};_currentRoom&&_currentRoom.message(msg),_onUpdate()}
18function loadIgnoreList(){api.getIgnoreList().then(_onIgnoreList)}function _onIgnoreList(data){return Utils.clearObject(ignoreList),data.users.forEach(function(usr){return ignoreList[usr.id]=new ChatUser(usr)}),ignoreList}function onJoin(data){if(!(_currentRoom=!!data.channel_id&&rooms.get(data.channel_id)))return console.error("room not found"),!1;_currentRoom.on("helpers",function(helpers){onHelpersCallback(helpers)}),_currentRoom.on("premium",function(data){if(window.DEV,Array.isArray(data.userIds)&&data.userIds.findIndex(function(id){return id==_currentRoom.user.id})>-1){data.userIds.find(function(u){return u.id==_currentRoom.user.id}),_currentRoom.user}}),_currentRoom.getHelpers(),_currentRoom.update(data),_currentRoom.emit("joined"),0==_currentRoom.messages.length&&api.getHistory(data.channel_id),currentUser={id:data.user_id,nickname:data.name},_updateBanInfo(_currentRoom,data.ban),_onUpdate()}function onHistory(data){var messages=data.messages.filter(function(msg){return!ignoreList[msg.user_id]}),room=rooms.get(data.channel_id);room.history(messages),room.smilesOnlyMod&&showSmilesOnlyModeMessage(room),_onUpdate()}function showSmilesOnlyModeMessage(room){var msg={color:"system moderator",user_rights:30,text:'В чате включен режим "Только смайлы"'};room.message(msg)}function onMessage(data){if(!ignoreList[data.user_id]){(data.channel_id?rooms.get(data.channel_id):_currentRoom).message(data),_onUpdate()}}function onMessageUnderBan(data){var room=data.channel_id?rooms.get(data.channel_id):_currentRoom,baninfo=room.baninfo,text="Вы забанены на канале";if(baninfo){var TextFormat=angular.element(document).injector().get("TextFormat");if(1==baninfo.type&&(text+=" до конца стрима"),2==baninfo.type&&(text="Вы навсегда забанены на этом канале"),0==baninfo.type){var tillBanDrop=1e3*baninfo.till-Date.now();if(tillBanDrop>0){text+=". Бан закончится через "+TextFormat.getBanTimeFormatted(tillBanDrop/1e3/60)}}baninfo.reason&&(text+='. Причина бана: "'+baninfo.reason+'"')}var msg={color:"system moderator",user_rights:30,text:text};room.message(msg),_onUpdate()}function onRemoveMessage(data){var message=rooms.get(data.channel_id).getMessage(data.message_id);message&&(message.deleted=!0,message.adminName=data.adminName)}function onError(data){if(-1!==data.errorMsg.indexOf("You are banned"))return void onMessageUnderBan(data);var room=data.channel_id?rooms.get(data.channel_id):_currentRoom,msg={color:"system moderator",user_rights:30,text:data.errorMsg};room.message(msg),_onUpdate()}function onSystemMessage(data){var room=data.channel_id?rooms.get(data.channel_id):_currentRoom,msg={color:"system moderator",user_rights:30,text:data.systemMsg};room.message(msg),_onUpdate()}function getUsersList(room){return api.getUsersList(room.id)}function deleteFromIgnoreList(userId){return api.deleteFromIgnoreList(userId).then(_onIgnoreList)}function addToIgnoreList(userId,currentChatUser){return+userId==+currentChatUser?(alert("Нельзя игнорировать самого себя!"),!1):api.addToIgnoreList(userId).then(_onIgnoreList)}function getStreamModers(roomId){return api.getStreamModers(roomId)}function getPoll(roomId){return api.getPoll(roomId)}function makeVote(roomId,vote){return api.makeVote(roomId,vote)}function createPoll(roomId,pollData){return api.createPoll(roomId,pollData)}function setMotd(roomId,motdText){return api.setRoomSettings(roomId,{motd:motdText})}function addStreamModer(roomId,userId){return api.addStreamModer(roomId,userId)}function deleteStreamModer(roomId,userId){return api.deleteStreamModer(roomId,userId)}function showWhenStarted(roomId){var DateFunctions=angular.element(document).injector().get("DateFunctions"),TextFormat=angular.element(document).injector().get("TextFormat"),room=roomId?rooms.get(roomId):_currentRoom,dateDiff=DateFunctions.getDateDiff(1e3*room.started,Date.now()),text="Стрим идет ";dateDiff.hours>0&&(text+=dateDiff.hours+[" час "," часа "," часов "][TextFormat.decl(dateDiff.hours)]),dateDiff.minutes>0&&(text+=dateDiff.minutes+[" минуту"," минуты"," минут"][TextFormat.decl(dateDiff.minutes)]),room.message({color:"system streamer",user_rights:30,text:text}),_onUpdate()}function onNewPoll(data){var room=!!data.channel_id&&rooms.get(data.channel_id);room&&room._onPoll(data)}function onSettings(data){
19var room=!!data.channel_id&&rooms.get(data.channel_id);"motd"==data.name&&room&&room.updateMotd(data.value),_onUpdate()}function onUserBan(data){var room=data.channel_id?rooms.get(data.channel_id):_currentRoom,TextFormat=angular.element(document).injector().get("TextFormat");
19if(data.show||currentUser.id==data.user_id){var text="";if(1==data.type&&(text=data.moder_name+" забанил "+data.user_name+" до конца стрима"),2==data.type&&(text=data.moder_name+" забанил "+data.user_name+" бессрочно"),0==data.type)if(0==data.duration)text=data.moder_name+" разбанил "+data.user_name;else{text=data.moder_name+" забанил "+data.user_name;var duration=TextFormat.getBanTimeFormatted(data.duration/60);text+=" на "+duration,data.reason&&(text+=' по причине: "'+data.reason+'"')}var msg={color:"system moderator",user_rights:30,text:text};room.message(msg),_onUpdate()}}function onUserWarn(data){var room=data.channel_id?rooms.get(data.channel_id):_currentRoom,text=data.moder_name+" вынес предупреждение "+data.user_name,msg={color:"system moderator",user_rights:30,text:text};room.message(msg),_onUpdate()}function onChannelCountersUpdate(data){var room=!!data.channel_id&&rooms.get(data.channel_id);void 0==room&&(room=rooms.get(parseInt(data.channel_id))||!1),room&&room.updateCounters(data)}function _updateBanInfo(room,data){window.DEV&&console.log("_updateBanInfo",room,data),room.baninfo=data?{banned:!!data,till:data.till,type:data.type,reason:data.reason}:{banned:!!data}}
19function sendResubNotify(roomId,action){return webapi.sendResubNotify(roomId,action).catch(function(error){return onError({errorMsg:error.message})})}function sendPrivateMessage(nickname,message){return webapi.sendPrivateMessage(nickname,message).then(function(response){return onMessage({private:!0,text:response.message,user:response.from,to:response.to})}).catch(function(error){return onError({errorMsg:error.message})})}function getBannedList(){return webapi.getBannedList(_currentRoom.id).then(function(data){return data.map(function(usr){return new ChatUser(usr,_currentRoom.id)})}).catch(function(error){return onError({errorMsg:error.message})})}function onRandomResults(res){if(!res.success)return void alert("Нет ни одного пользователя, удовлетворяющего условиям");var room=!!res.channel_id&&rooms.get(res.channel_id),user=room.saveRandomizerUser(new ChatUser(res.data,room)),me=room.user&&user.id==room.user.id,msg={color:"system streamer",mine:me,user_rights:30,text:"В чате случайным образом был выбран "+user.nickname};me&&Utils.post("/api/4/achievements/report",{id:"WinRandom"}),room.message(msg),_onUpdate()}function onUpdateUserInfo(data){window.DEV_CHAT&&console.log("onUpdateUserInfo",_currentRoom,data);var chatUser=_currentRoom.user;for(var k in data)chatUser[k]=data[k];_cb("onUpdateUserInfo",{room:_currentRoom,data:data})}function onUpdateUserInfoInRoom(data){if(window.DEV_CHAT&&console.log("CHAT","onUpdateUserInfoInRoom",_currentRoom,data),_currentRoom.streamer&&_currentRoom.streamer.id==data.id)for(var k in data)_currentRoom.streamer[k]=data[k];_cb("onUpdateUserInfoInRoom",{room:_currentRoom,data:data})}function onUpdateStreamerInRoom(data){if(window.DEV_CHAT&&console.log("CHAT","onUpdateStreamerInRoom",_currentRoom,data),_currentRoom.streamer&&_currentRoom.streamer.id==data.id)for(var k in data)_currentRoom.streamer[k]=data[k];_cb("onUpdateStreamerInRoom",{room:_currentRoom,data:data})}function onUpdateChannelInfoJobs(data){self=this,window.DEV_CHAT&&console.log("onUpdateChannelInfoJobs",data);var room=rooms.get(data.channel_id);room.updateJobs(data.jobs.enabled),_onUpdateChannelJobs.map(function(f){return f(room,data.jobs)})}function onTeleportUser(data){if(_currentRoom.id==data.channelSrc){Utils.reachGoal("teleport_user");var msg={html:1,color:"system",text:'<gg4-teleport-confirm style="color:#35A83F">Телепорт на канал '+data.name+" начнётся через 10 секунд!</gg4-teleport-confirm>"};_currentRoom.message(msg),_onUpdate(),document.dispatchEvent(new CustomEvent("chatTeleportRedirectCommand",{detail:{command:"teleport",name:data.name}}))}}function onTeleportAim(data){window.DEV_CHAT,Utils.reachGoal("teleport_aim");var room=_currentRoom,msg={html:1,color:"system",text:"<gg4-teleport-streamer-welcome data='"+JSON.stringify(data)+"'></gg4-teleport-streamer-welcome>"};room.message(msg),_onUpdate(),currentUser.id==data.streamerIdDest&&Utils.post("/api/4/teleport/end")}function onTeleportError(data){var room=data.channel_id?rooms.get(data.channel_id):_currentRoom;if(room){Utils.reachGoal("teleport_error");var msg={color:"system moderator",user_rights:30,text:data.message};room.message(msg),_onUpdate()}}function onSmileOnlyMode(data){var room=data.channel_id?rooms.get(data.channel_id):_currentRoom;if(room){room.smilesOnlyMod=data.enabled;var msg={color:"system moderator",user_rights:30,text:data.enabled?'Включен режим "Только смайлы"':'Режим "Только смайлы" отключен'};room.message(msg),_onUpdate()}}function onUserPaymentFailed(data){if(window.DEV_CHAT,data.user_id==currentUser.id){var msg={color:"system moderator",user_rights:30,text:"Платеж отклонен. Вы можете попробовать ещё раз или обратиться в поддержку."};_currentRoom.message(msg),_onUpdate()}}var callbacks=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},rooms=new RoomsMap,api=new ChatApi(settings),webapi=new WebApi(rooms),_currentRoom=void 0,_onUpdate=void 0,_onUpdateChannelJobs=[],ignoreList={},currentUser=void 0,reconnectionCounter=0,onHelpersCallback=function(){};!function(){api.on("connected",onConnected),api.on("payment",onPayment),api.on("premium",onPremium),api.on("update_rights",onUpdateRights),api.on("set_smile_only_mode",onSmileOnlyMode),api.on("reconnecting",onReconnecting),api.on("reconnected",onReconnected),api.on("joined",onJoin),api.on("history",onHistory),api.on("message",onMessage),api.on("remove_message",onRemoveMessage),api.on("user_ban",onUserBan),api.on("user_warn",onUserWarn),api.on("error",onError),api.on("system_message",onSystemMessage),api.on("teleport_user",onTeleportUser),api.on("teleport_aim",onTeleportAim),api.on("new_poll",onNewPoll),api.on("setting",onSettings),api.on("channel_c
19ounters",onChannelCountersUpdate),api.on("random_result",onRandomResults),api.on("new_job",onMessageQuestLog),api.on("gifted_premiums",onGiftedPremium),api.on("job_prize_increased",onPrizeIncreased),api.on("update_job",onUpdateJob),api.on("update_user_info",onUpdateUserInfo),api.on("update_user_info_in_room",onUpdateUserInfoInRoom),api.on("update_streamer_in_room",onUpdateStreamerInRoom),api.on("update_channel_info_jobs",onUpdateChannelInfoJobs),api.on("user_payment_failed",onUserPaymentFailed)}();var _cb=function(key,data){if(callbacks&&callbacks[key])try{callbacks[key](data)}catch(e){console.error(e),window.ggLog&&window.ggLog(e)}};return{ignoreList:ignoreList,openRoom:openRoom,closeRoom:closeRoom,rejoin:rejoin,getPoll:getPoll,makeVote:makeVote,createPoll:createPoll,setMotd:setMotd,sendMessage:sendMessage,deleteMessage:deleteMessage,getUsersList:getUsersList,getBannedList:getBannedList,addToIgnoreList:addToIgnoreList,deleteFromIgnoreList:deleteFromIgnoreList,getStreamModers:getStreamModers,addStreamModer:addStreamModer,deleteStreamModer:deleteStreamModer,sendPrivateMessage:sendPrivateMessage,sendResubNotify:sendResubNotify,banUser:function(roomId,data){return api.banUser(roomId,data)},banUserTillStreamEnd:function(roomId,data){return api.banUserTillStreamEnd(roomId,data)},unbanUser:function(roomId,data){return api.unbanUser(roomId,data)},showWhenStarted:showWhenStarted,warnUser:function(roomId,data){return api.warnUser(roomId,data)},startCommercial:function(key,pwd){return api.startCommercial(key,pwd)},auth:function(){return api.auth()},currentRoom:function(){return _currentRoom},getRoom:function(id){return rooms.get(id)},onUpdate:function(fn){return _onUpdate=fn},onUpdateChannelJobs:function(fn){return _onUpdateChannelJobs.push(fn)},getRandomUser:function(roomId,data){return api.getRandomUser(roomId,data)},onInviteMessage:function(data){return _onInviteMessage(data)},listenForHelpers:function(fn){return onHelpersCallback=fn},onTeleportError:onTeleportError,setSmileOnlyMode:function(roomId,enabled){return api.setSmileOnlyMode(roomId,enabled)}}},ChatRoom=function(_GGEventEmitter6){function ChatRoom(id,service){_classCallCheck(this,ChatRoom);var _this46=_possibleConstructorReturn(this,(ChatRoom.__proto__||Object.getPrototypeOf(ChatRoom)).call(this));return _this46.id=id,_this46.type="",_this46.messages=[],_this46.user=!1,_this46.joined=!1,_this46._service=service,_this46.users=[],_this46.helpers=[],_this46.poll={},_this46.premiumOnly=!1,_this46.randomizerUsers=[],_this46.jobs=0,_this46.isNotifyDisabled=!1,_this46.smilesOnlyMod=!1,_this46}return _inherits(ChatRoom,_GGEventEmitter6),_createClass(ChatRoom,[{key:"isStream",value:function(){return this.id&&"stream"==this.type}},{key:"update",value:function(data){window.DEV_CHAT&&console.log("CHAT","ChatRoom update before",data,this),this.joined=!0,this.streamer=data.channel_streamer,this.streamKey=data.channel_key||data.channel_id||data.name||!1,this.motd=data.motd,this.smilesOnlyMod=data.smile_only_mode||!1,this.started=data.started,this.premiumOnly=!!data.premium_only,this.room_premium=data.room_premium,this.notify=data.notifies?data.notifies[this.id]:0;try{this.freeprem=data.notifies[0]&&data.room_premium}catch(exc){this.freeprem=!1}this.user=!!data.user_id&&new ChatUser(data,this);try{this.donateButtons=JSON.parse(data.donate_buttons)}catch(e){this.donateButtons=""}return this.jobs=data.jobs?1:0,this.type=data.room_type,window.DEV_CHAT&&console.log("CHAT","ChatRoom update after",this),this.updateCounters(data),this}},{key:"updateCounters",value:function(data){this.usersCnt=data.users_in_channel}},{key:"updateMotd",value:function(text){this.motd=text}},{key:"updateJobs",value:function(enabled){this.jobs=enabled}},{key:"history",value:function(messages){var _this47=this;window.DEV_CHAT&&console.log("CHAT","history",messages,this),this.messages.loaded=!0,messages.forEach(function(msg){return _this47.messages.push(new ChatMessage(msg,_this47,!0))})}},{key:"message",value:function(msg){this.messages.push(new ChatMessage(msg,this)),this.emit("message")}},{key:"getMessage",value:function(id){for(var i=0;i<this.messages.length;i++)if(this.messages[i].id==id)return this.messages[i];return!1}},{key:"clearMessage",value:function(){return this.messages.length=0,!1}},{key:"sendMessage",value:function(text,settings){Utils.reachGoal("stream_message_send"),this._service.sendMessage(text,settings,this)}},{key:"deleteMessage",value:function(message){this._service.deleteMessage(message,this)}},{key:"getUsersListPromise",value:function(){var _this48=this;return this._service.getUsersList(this).then(function(ret){var users=[];
19return ret.users.forEach(function(usr){return users.push(new ChatUser(usr,_this48))}),users})}},{key:"getUsersList",value:function(){var _this49=this;return this.getUsersListPromise().then(function(users){_this49.users.length=0,angular.extend(_this49.users,users)}),this.users}},{key:"getBannedList",value:function(){var _this50=this;return this._service.getBannedList(this).then(function(users){return users.map(function(usr){return new ChatUser(usr,_this50)})})}},{key:"getHelpers",value:function(){var _this51=this;return this._service.getStreamModers(this.id).then(function(data){return _this51._onHelperList(data)}),this.helpers}},{key:"addHelper",value:function(userId){var _this52=this;return this._service.addStreamModer(this.id,userId).then(function(data){return _this52._onHelperList(data)})}},{key:"sendNotify",value:function(){var _this53=this;return this.isNotifyDisabled=!0,this._service.sendResubNotify(this.id,1).then(function(data){return _this53.isNotifyDisabled=!1,_this53.notify=0,data}).catch(function(err){_this53.isNotifyDisabled=!1})}},{key:"discardNotify",value:function(){var _this54=this;return this._service.sendResubNotify(this.id,0).then(function(data){return _this54.notify=0,data})}},{key:"deleteHelper",value:function(userId){var _this55=this;return this._service.deleteStreamModer(this.id,userId).then(function(data){return _this55._onHelperList(data)})}},{key:"getPoll",value:function(){var _this56=this;return this._service.getPoll(this.id).then(function(data){return _this56._onPoll(data)}),this.poll}},{key:"makeVote",value:function(vote){var _this57=this;this._service.makeVote(this.id,vote).then(function(data){return _this57._onPoll(data)})}},{key:"createPoll",value:function(pollData){this._service.createPoll(this.id,pollData)}},{key:"setMotd",value:function(text){this._service.setMotd(this.id,text)}},{key:"banUser",value:function(data,message){this._service.banUser(this.id,data),data.deleteMessage&&this.deleteMessage(message)}},{key:"unBanUser",value:function(userId){this._service.unbanUser(this.id,userId)}},{key:"warnUser",value:function(userId){this._service.warnUser(this.id,userId)}},{key:"_onPoll",value:function(data){var oldMine=this.poll.mine;Utils.clearObject(this.poll),angular.extend(this.poll,data),data.moder_id?this.poll.mine=this.user&&data.moder_id==this.user.id?1:0:this.poll.mine=oldMine}},{key:"_onHelperList",value:function(data){var users=[];data.moders.forEach(function(usr){return users.push(new ChatUser(usr))}),this.helpers.length=0,angular.extend(this.helpers,users),this.emit("helpers",Array.isArray(users)?users.map(function(u){return u.id}):[])}},{key:"startCommercial",value:function(key,pwd){this._service.startCommercial(key,pwd)}},{key:"getRandomUser",value:function(data){this._service.getRandomUser(this.id,data)}},{key:"saveRandomizerUser",value:function(user){return this.randomizerUsers.push(user),user}},{key:"cleanRandomizerUsers",value:function(){this.randomizerUsers=[]}},{key:"setSmileOnlyMode",value:function(enabled){this._service.setSmileOnlyMode(this.id,enabled)}}]),ChatRoom}(GGEventEmitter),RoomsMap=function(){function RoomsMap(){_classCallCheck(this,RoomsMap),this.list={},this.size=0}return _createClass(RoomsMap,[{key:"set",value:function(id,value){this.list[id]=value,this.size=Object.keys(this.list).length}},{key:"get",value:function(id){return this.list[id]||null}},{key:"delete",value:function(id){delete this.list[id],this.size=Object.keys(this.list).length}},{key:"forEach",value:function(callback){for(var key in this.list)callback(this.list[key]);return!0}}]),RoomsMap}(),TextFormatFactory=new function(){var units=[["минуту","минуты","минут"],["час","часа","часов"],["день","дня","дней"]];return new(function(){function _class21(){_classCallCheck(this,_class21)}return _createClass(_class21,[{key:"decl",value:function(number){var cases=[2,0,1,1,1,2];return number%100>4&&number%100<20?2:cases[number%10<5?number%10:5]}},{key:"roundBanTime",value:function(value){return value>=1440?1440*Math.ceil(value/1440):value>=60?60*Math.ceil(value/60):Math.ceil(value)}},{key:"getBanTimeFormatted",value:function(value){var uvalue;
19return value=this.roundBanTime(value),value>=1440?" "+(uvalue=Math.ceil(value/1440))+" "+units[2][decl(uvalue)]:value>=60?" "+(uvalue=Math.ceil(value/60))+" "+units[1][decl(uvalue)]:" "+(uvalue=Math.ceil(value)||0)+" "+units[0][decl(uvalue)]}},{key:"convertTimeFormat",value:function(value,units){return value+" "+units[units][decl(value)]}}]),_class21}())},ChatTransport=function(_GGEventEmitter7){function ChatTransport(options){_classCallCheck(this,ChatTransport);var _this58=_possibleConstructorReturn(this,(ChatTransport.__proto__||Object.getPrototypeOf(ChatTransport)).call(this));return _this58.maxSilentReconnectAttempts=5,_this58._reconnectAttempts=0,_this58.forced=!1,_this58.sockjsUrl=options.server,_this58._pingInterval=!1,_this58._waitingPong=!1,_this58}return _inherits(ChatTransport,_GGEventEmitter7),_createClass(ChatTransport,[{key:"connected",value:function(){return this.socket&&1===this.socket.readyState}},{key:"connect",value:function(){if(this.disconnect(),this.socket=new WebSocket(this.sockjsUrl)||null,!this.socket)throw new Error("Can't create sockjs-client.");this.resetPingInterval(),this._bindings()}},{key:"resetPingInterval",value:function(){clearInterval(this._pingInterval),this._pingInterval=setInterval(this._ping.bind(this),1e4)}},{key:"disconnect",value:function(){this.socket&&(this.socket.onclose=function(){},this.socket.close())}},{key:"_bindings",value:function(){var _this59=this;this.socket.onopen=function(){return _this59._onOpen()},this.socket.onclose=function(){return _this59._onClose()},this.socket.onmessage=function(event){return _this59._onMessage(event)},this.socket.onerror=function(e){return console.error(e)},this.on("pong",this._onPong)}},{key:"_onPong",value:function(){this._waitingPong=!1}},{key:"_ping",value:function(){this.connected()&&(this._waitingPong=!0,this.send("ping",{}),setTimeout(function(){this._waitingPong&&(console.warn("No pong in 6 seconds. Closing."),this._onClose())}.bind(this),6e3))}},{key:"_onOpen",value:function(){console.warn("opened"),(this.forced||this._reconnectAttempts>this.maxSilentReconnectAttempts)&&this.emit("reconnected",{},"reconnected"),this._reconnectAttempts=0,this.forced=!1}},{key:"_onClose",value:function(){this._tryReconnect(this.forced)}},{key:"_onMessage",value:function(event){this.resetPingInterval();try{var msg=angular.fromJson(event.data);window.DEV_CHAT&&console.log("<-",msg,msg.type,msg.data),this.emit(msg.type,msg.data,msg.type),this.emit("default",msg.data,msg.type)}catch(err){console.log(err.toString())}}},{key:"_tryReconnect",value:function(forced){var _this60=this;this.reconnected=!0,this.forced=!!forced,this._reconnectAttempts++,(this.debug||forced||this._reconnectAttempts>this.maxSilentReconnectAttempts)&&this.emit("reconnecting",{},"reconnecting"),setTimeout(function(){return _this60.connect()},2e3)}},{key:"send",value:function(type,data){if(!this.connected())return void console.log("not connected",type,data);try{window.DEV_CHAT&&console.log("->",type,data),this.socket.send(JSON.stringify({type:type,data:data}))}catch(e){console.log("err",e)}}}]),ChatTransport}(GGEventEmitter),ChatUser=function(){function ChatUser(data,_room){_classCallCheck(this,ChatUser);var room=_room||{};data.private&&data.user?(this.id=data.user.id,this.nickname=data.user.nickname,this.private=1):(this.id=data.user_id||data.id,this.nickname=data.user_name||data.nickname||data.name,this.rights=data.user_rights||data.access_rights||room.accessRights||data.rights||0,this.roomid=data.channel_id||room.id,data.paymentsAll?(this.paymentsAll=data.paymentsAll,this.payments=data.paymentsAll[this.roomid]||0):(this.payments=parseInt(data.payments,10)||0,this.paymentsAll=_defineProperty({},this.roomid,+this.payments)),this.premium=!!data.premium,this.mobile=data.mobile,this.hidden=data.hidden,this.banned=data.banned,this.baninfo=data.baninfo,this.regtime=data.regtime,this.premiums=data.premiums,this.ggPlusTier=data.gg_plus_tier||data.ggPlusTier||0,this.resub=room.id&&data.resubs&&data.resubs[room.id]?data.resubs[room.id]:0,this.ggresub=data.resubs&&data.resubs[0]?data.resubs[0]:0,this.premiums?(this.roomPremium=this.roomid&&-1!=this.premiums.indexOf(this.roomid),this.commonPremium=0==this.premiums.indexOf("0")):(this.commonPremium=this.premium,this.roomPremium=!1),this.canwrite=!data.premium_only||this.premium||this.payments,this.color=data.color,this.icon=data.icon,this.invites=data.invites,this.inviteLevels=data.inviteLevels,this.role=data.role,this.staff="1"==data.staff,this.lawyer="2"==data.staff)}return _createClass(ChatUser,[{key:"getRoomPremium",value:function(){var _this61=this;if(!this.roomid)throw new Error("Logic error, need roomId");return!!this.premiums&&this.premiums.filter(function(p){return p==_this61.roomid}).length>0}}]),ChatUser}(),WebApi=function(_GGEventEmitter8){function WebApi(rooms){_classCallCheck(this,WebApi);var _this62=_possibleConstructorReturn(this,(WebApi.__proto__||Object.getPrototypeOf(WebApi)).call(this));return _this62._rooms=rooms,_this62.bind(),_this62}return _inherits(WebApi,_GGEventEmitter8),_createClass(WebApi,[{key:"bind",value:function(){var _this63=this;NotifyProxy.on("update_feed",function(event){"dialogMessage"==event.type&&_this63._rooms.size&&(event.defaultPrevented=!0)})}},{key:"sendPrivateMessage",value:function(nickname,text){return Utils.post("/ajax/dialogs/send/",{nickname:nickname,text:text}).then(function(data){var response=angular.fromJson(data);if(!response.success)throw new Error;return response})}}
19,{key:"sendResubNotify",value:function(channelId,action){return Utils.post("/ajax/premium/notify/",{channelId:channelId,action:action}).then(function(response){if(!response.success)throw new Error;return response})}},{key:"getBannedList",value:function(channel_id){return Utils.get("/ajax/chat/banned/",{channel_id:channel_id}).then(function(data){var response=angular.fromJson(data);if(!response.success)throw new Error;return response.data})}}]),WebApi}(GGEventEmitter);!function(){function normalizeName(name){if("string"!=typeof name&&(name=String(name)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name))throw new TypeError("Invalid character in header field name");return name.toLowerCase()}function normalizeValue(value){return"string"!=typeof value&&(value=String(value)),value}function Headers(headers){this.map={},headers instanceof Headers?headers.forEach(function(value,name){this.append(name,value)},this):headers&&Object.getOwnPropertyNames(headers).forEach(function(name){this.append(name,headers[name])},this)}function consumed(body){if(body.bodyUsed)return Promise.reject(new TypeError("Already read"));body.bodyUsed=!0}function fileReaderReady(reader){return new Promise(function(resolve,reject){reader.onload=function(){resolve(reader.result)},reader.onerror=function(){reject(reader.error)}})}function readBlobAsArrayBuffer(blob){var reader=new FileReader;return reader.readAsArrayBuffer(blob),fileReaderReady(reader)}function readBlobAsText(blob){var reader=new FileReader;return reader.readAsText(blob),fileReaderReady(reader)}function Body(){return this.bodyUsed=!1,this._initBody=function(body){if(this._bodyInit=body,"string"==typeof body)this._bodyText=body;else if(support.blob&&Blob.prototype.isPrototypeOf(body))this._bodyBlob=body;else if(support.formData&&FormData.prototype.isPrototypeOf(body))this._bodyFormData=body;else if(body){if(!support.arrayBuffer||!ArrayBuffer.prototype.isPrototypeOf(body))throw new Error("unsupported BodyInit type")}else this._bodyText=""},support.blob?(this.blob=function(){var rejected=consumed(this);if(rejected)return rejected;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this.blob().then(readBlobAsArrayBuffer)},this.text=function(){var rejected=consumed(this);if(rejected)return rejected;if(this._bodyBlob)return readBlobAsText(this._bodyBlob);if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)}):this.text=function(){var rejected=consumed(this);return rejected||Promise.resolve(this._bodyText)},support.formData&&(this.formData=function(){return this.text().then(decode)}),this.json=function(){return this.text().then(JSON.parse)},this}function normalizeMethod(method){var upcased=method.toUpperCase();return methods.indexOf(upcased)>-1?upcased:method}
19function Request(input,options){options=options||{};var body=options.body;if(Request.prototype.isPrototypeOf(input)){if(input.bodyUsed)throw new TypeError("Already read");this.url=input.url,this.credentials=input.credentials,options.headers||(this.headers=new Headers(input.headers)),this.method=input.method,this.mode=input.mode,body||(body=input._bodyInit,input.bodyUsed=!0)}else this.url=input;if(this.credentials=options.credentials||this.credentials||"omit",!options.headers&&this.headers||(this.headers=new Headers(options.headers)),this.method=normalizeMethod(options.method||this.method||"GET"),this.mode=options.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&body)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(body)}function decode(body){var form=new FormData;return body.trim().split("&").forEach(function(bytes){if(bytes){var split=bytes.split("="),name=split.shift().replace(/\+/g," "),value=split.join("=").replace(/\+/g," ");form.append(decodeURIComponent(name),decodeURIComponent(value))}}),form}function headers(xhr){var head=new Headers;return xhr.getAllResponseHeaders().trim().split("\n").forEach(function(header){var split=header.trim().split(":"),key=split.shift().trim(),value=split.join(":").trim();head.append(key,value)}),head}function Response(bodyInit,options){options||(options={}),this._initBody(bodyInit),this.type="default",this.status=options.status,this.ok=this.status>=200&&this.status<300,this.statusText=options.statusText,this.headers=options.headers instanceof Headers?options.headers:new Headers(options.headers),this.url=options.url||""}if(!self.fetch){Headers.prototype.append=function(name,value){name=normalizeName(name),value=normalizeValue(value);var list=this.map[name];list||(list=[],this.map[name]=list),list.push(value)},Headers.prototype.delete=function(name){delete this.map[normalizeName(name)]},Headers.prototype.get=function(name){var values=this.map[normalizeName(name)];return values?values[0]:null},Headers.prototype.getAll=function(name){return this.map[normalizeName(name)]||[]},Headers.prototype.has=function(name){return this.map.hasOwnProperty(normalizeName(name))},Headers.prototype.set=function(name,value){this.map[normalizeName(name)]=[normalizeValue(value)]},Headers.prototype.forEach=function(callback,thisArg){Object.getOwnPropertyNames(this.map).forEach(function(name){this.map[name].forEach(function(value){callback.call(thisArg,value,name,this)},this)},this)};var support={blob:"FileReader"in self&&"Blob"in self&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in self,arrayBuffer:"ArrayBuffer"in self},methods=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];Request.prototype.clone=function(){return new Request(this)},Body.call(Request.prototype),Body.call(Response.prototype),Response.prototype.clone=function(){return new Response(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Headers(this.headers),url:this.url})},Response.error=function(){var response=new Response(null,{status:0,statusText:""});return response.type="error",response};var redirectStatuses=[301,302,303,307,308];Response.redirect=function(url,status){if(-1===redirectStatuses.indexOf(status))throw new RangeError("Invalid status code");return new Response(null,{status:status,headers:{location:url}})},self.Headers=Headers,self.Request=Request,self.Response=Response,self.fetch=function(input,init){return new Promise(function(resolve,reject){function responseURL(){return"responseURL"in xhr?xhr.responseURL:/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())?xhr.getResponseHeader("X-Request-URL"):void 0}var request;request=Request.prototype.isPrototypeOf(input)&&!init?input:new Request(input,init);var xhr=new XMLHttpRequest;xhr.onload=function(){var status=1223===xhr.status?204:xhr.status;if(status<100||status>599)return void reject(new TypeError("Network request failed"));var options={status:status,statusText:xhr.statusText,headers:headers(xhr),url:responseURL()},body="response"in xhr?xhr.response:xhr.responseText;resolve(new Response(body,options))},xhr.onerror=function(){reject(new TypeError("Network request failed"))},xhr.open(request.method,request.url,!0),"include"===request.credentials&&(xhr.withCredentials=!0),"responseType"in xhr&&support.blob&&(xhr.responseType="blob"),request.headers.forEac
19h(function(value,name){xhr.setRequestHeader(name,value)}),xhr.send(void 0===request._bodyInit?null:request._bodyInit)})},self.fetch.polyfill=!0}}(),function(e){e.matches||(e.matches=e.matchesSelector||function(selector){var matches=document.querySelectorAll(selector),th=this;return Array.prototype.some.call(matches,function(e){return e===th})})}(Element.prototype),function(e){e.closest=e.closest||function(css){for(var node=this;node;){if(node.matches(css))return node;node=node.parentElement}return null}}(Element.prototype),function(){function lib$es6$promise$utils$$objectOrFunction(x){return"function"==typeof x||"object"===(void 0===x?"undefined":_typeof(x))&&null!==x}function lib$es6$promise$utils$$isFunction(x){return"function"==typeof x}function lib$es6$promise$utils$$isMaybeThenable(x){return"object"===(void 0===x?"undefined":_typeof(x))&&null!==x}function lib$es6$promise$asap$$setScheduler(scheduleFn){lib$es6$promise$asap$$customSchedulerFn=scheduleFn}function lib$es6$promise$asap$$setAsap(asapFn){lib$es6$promise$asap$$asap=asapFn}function lib$es6$promise$asap$$useVertxTimer(){return function(){lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useSetTimeout(){return function(){setTimeout(lib$es6$promise$asap$$flush,1)}}function lib$es6$promise$asap$$flush(){for(var i=0;i<lib$es6$promise$asap$$len;i+=2){(0,lib$es6$promise$asap$$queue[i])(lib$es6$promise$asap$$queue[i+1]),lib$es6$promise$asap$$queue[i]=void 0,lib$es6$promise$asap$$queue[i+1]=void 0}lib$es6$promise$asap$$len=0}function lib$es6$promise$$internal$$noop(){}function lib$es6$promise$$internal$$selfFulfillment(){return new TypeError("You cannot resolve a promise with itself")}function lib$es6$promise$$internal$$cannotReturnOwn(){return new TypeError("A promises callback cannot return that same promise.")}function lib$es6$promise$$internal$$getThen(promise){try{return promise.then}catch(error){return lib$es6$promise$$internal$$GET_THEN_ERROR.error=error,lib$es6$promise$$internal$$GET_THEN_ERROR}}function lib$es6$promise$$internal$$tryThen(then,value,fulfillmentHandler,rejectionHandler){try{then.call(value,fulfillmentHandler,rejectionHandler)}catch(e){return e}}function lib$es6$promise$$internal$$handleForeignThenable(promise,thenable,then){lib$es6$promise$asap$$asap(function(promise){var sealed=!1,error=lib$es6$promise$$internal$$tryThen(then,thenable,function(value){sealed||(sealed=!0,thenable!==value?lib$es6$promise$$internal$$resolve(promise,value):lib$es6$promise$$internal$$fulfill(promise,value))},function(reason){sealed||(sealed=!0,lib$es6$promise$$internal$$reject(promise,reason))},"Settle: "+(promise._label||" unknown promise"));!sealed&&error&&(sealed=!0,lib$es6$promise$$internal$$reject(promise,error))},promise)}function lib$es6$promise$$internal$$handleOwnThenable(promise,thenable){thenable._state===lib$es6$promise$$internal$$FULFILLED?lib$es6$promise$$internal$$fulfill(promise,thenable._result):thenable._state===lib$es6$promise$$internal$$REJECTED?lib$es6$promise$$internal$$reject(promise,thenable._result):lib$es6$promise$$internal$$subscribe(thenable,void 0,function(value){lib$es6$promise$$internal$$resolve(promise,value)},function(reason){lib$es6$promise$$internal$$reject(promise,reason)})}function lib$es6$promise$$internal$$handleMaybeThenable(promise,maybeThenable){if(maybeThenable.constructor===promise.constructor)lib$es6$promise$$internal$$handleOwnThenable(promise,maybeThenable);else{var then=lib$es6$promise$$internal$$getThen(maybeThenable);then===lib$es6$promise$$internal$$GET_THEN_ERROR?lib$es6$promise$$internal$$reject(promise,lib$es6$promise$$internal$$GET_THEN_ERROR.error):void 0===then?lib$es6$promise$$internal$$fulfill(promise,maybeThenable):lib$es6$promise$utils$$isFunction(then)?lib$es6$promise$$internal$$handleForeignThenable(promise,maybeThenable,then):lib$es6$promise$$internal$$fulfill(promise,maybeThenable)}}function lib$es6$promise$$internal$$resolve(promise,value){promise===value?lib$es6$promise$$internal$$reject(promise,lib$es6$promise$$internal$$selfFulfillment()):lib$es6$promise$utils$$objectOrFunction(value)?lib$es6$promise$$internal$$handleMaybeThenable(promise,value):lib$es6$promise$$internal$$fulfill(promise,value)}
20function lib$es6$promise$$internal$$publishRejection(promise){promise._onerror&&promise._onerror
20(promise._result),lib$es6$promise$$internal$$publish(promise)}function lib$es6$promise$$internal$$fulfill(promise,value){promise._state===lib$es6$promise$$internal$$PENDING&&(promise._result=value,promise._state=lib$es6$promise$$internal$$FULFILLED,0!==promise._subscribers.length&&lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish,promise))}function lib$es6$promise$$internal$$reject(promise,reason){promise._state===lib$es6$promise$$internal$$PENDING&&(promise._state=lib$es6$promise$$internal$$REJECTED,promise._result=reason,lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection,promise))}function lib$es6$promise$$internal$$subscribe(parent,child,onFulfillment,onRejection){var subscribers=parent._subscribers,length=subscribers.length;parent._onerror=null,subscribers[length]=child,subscribers[length+lib$es6$promise$$internal$$FULFILLED]=onFulfillment,subscribers[length+lib$es6$promise$$internal$$REJECTED]=onRejection,0===length&&parent._state&&lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish,parent)}function lib$es6$promise$$internal$$publish(promise){var subscribers=promise._subscribers,settled=promise._state;if(0!==subscribers.length){for(var child,callback,detail=promise._result,i=0;i<subscribers.length;i+=3)child=subscribers[i],callback=subscribers[i+settled],child?lib$es6$promise$$internal$$invokeCallback(settled,child,callback,detail):callback(detail);promise._subscribers.length=0}}function lib$es6$promise$$internal$$ErrorObject(){this.error=null}function lib$es6$promise$$internal$$tryCatch(callback,detail){try{return callback(detail)}catch(e){return lib$es6$promise$$internal$$TRY_CATCH_ERROR.error=e,lib$es6$promise$$internal$$TRY_CATCH_ERROR}}function lib$es6$promise$$internal$$invokeCallback(settled,promise,callback,detail){var value,error,succeeded,failed,hasCallback=lib$es6$promise$utils$$isFunction(callback);if(hasCallback){if(value=lib$es6$promise$$internal$$tryCatch(callback,detail),value===lib$es6$promise$$internal$$TRY_CATCH_ERROR?(failed=!0,error=value.error,value=null):succeeded=!0,promise===value)return void lib$es6$promise$$internal$$reject(promise,lib$es6$promise$$internal$$cannotReturnOwn())}else value=detail,succeeded=!0;promise._state!==lib$es6$promise$$internal$$PENDING||(hasCallback&&succeeded?lib$es6$promise$$internal$$resolve(promise,value):failed?lib$es6$promise$$internal$$reject(promise,error):settled===lib$es6$promise$$internal$$FULFILLED?lib$es6$promise$$internal$$fulfill(promise,value):settled===lib$es6$promise$$internal$$REJECTED&&lib$es6$promise$$internal$$reject(promise,value))}function lib$es6$promise$$internal$$initializePromise(promise,resolver){try{resolver(function(value){lib$es6$promise$$internal$$resolve(promise,value)},function(reason){lib$es6$promise$$internal$$reject(promise,reason)})}catch(e){lib$es6$promise$$internal$$reject(promise,e)}}function lib$es6$promise$enumerator$$Enumerator(Constructor,input){var enumerator=this;enumerator._instanceConstructor=Constructor,enumerator.promise=new Constructor(lib$es6$promise$$internal$$noop),enumerator._validateInput(input)?(enumerator._input=input,enumerator.length=input.length,enumerator._remaining=input.length,enumerator._init(),0===enumerator.length?lib$es6$promise$$internal$$fulfill(enumerator.promise,enumerator._result):(enumerator.length=enumerator.length||0,enumerator._enumerate(),0===enumerator._remaining&&lib$es6$promise$$internal$$fulfill(enumerator.promise,enumerator._result))):lib$es6$promise$$internal$$reject(enumerator.promise,enumerator._validationError())}function lib$es6$promise$promise$all$$all(entries){return new lib$es6$promise$enumerator$$default(this,entries).promise}function lib$es6$promise$promise$race$$race(entries){function onFulfillment(value){lib$es6$promise$$internal$$resolve(promise,value)}function onRejection(reason){lib$es6$promise$$internal$$reject(promise,reason)}var Constructor=this,promise=new Constructor(lib$es6$promise$$internal$$noop);if(!lib$es6$promise$utils$$isArray(entries))return lib$es6$promise$$internal$$reject(promise,new TypeError("You must pass an array to race.")),promise;for(var length=entries.length,i=0;promise._state===lib$es6$promise$$internal$$PENDING&&i<length;i++)lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]),void 0,onFulfillment,onRejection);return promise}function lib$es6$promise$promise$resolve$$resolve(object){var Constructor=this;if(object&&"object"===(void 0===object?"undefined":_typeof(object))&&object.constructor===Constructor)return object;var promise=new Constructor(lib$es6$promise$$internal$$noop);return lib$es6$promise$$internal$$resolve(promise,object),promise}function lib$es6$promise$promise$reject$$reject(reason){var Constructor=this,promise=new Constructor(lib$es6$promise$$internal$$noop);return lib$es6$promise$$internal$$reject(promise,reason),promise}function lib$es6$promise$promise$$needsResolver(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function lib$es6$promise$promise$$needsNew(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object c
20onstructor cannot be called as a function.")}function lib$es6$promise$promise$$Promise(resolver){this._id=lib$es6$promise$promise$$counter++,this._state=void 0,this._result=void 0,this._subscribers=[],lib$es6$promise$$internal$$noop!==resolver&&(lib$es6$promise$utils$$isFunction(resolver)||lib$es6$promise$promise$$needsResolver(),this instanceof lib$es6$promise$promise$$Promise||lib$es6$promise$promise$$needsNew(),lib$es6$promise$$internal$$initializePromise(this,resolver))}function lib$es6$promise$polyfill$$polyfill(){var local;if("undefined"!=typeof global)local=global;else if("undefined"!=typeof self)local=self;else try{local=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var P=local.Promise;P&&"[object Promise]"===Object.prototype.toString.call(P.resolve())&&!P.cast||(local.Promise=lib$es6$promise$promise$$default)}var lib$es6$promise$utils$$_isArray;lib$es6$promise$utils$$_isArray=Array.isArray?Array.isArray:function(x){return"[object Array]"===Object.prototype.toString.call(x)};var lib$es6$promise$asap$$vertxNext,lib$es6$promise$asap$$customSchedulerFn,lib$es6$promise$asap$$scheduleFlush,lib$es6$promise$utils$$isArray=lib$es6$promise$utils$$_isArray,lib$es6$promise$asap$$len=0,lib$es6$promise$asap$$asap=function(callback,arg){lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len]=callback,lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len+1]=arg,2===(lib$es6$promise$asap$$len+=2)&&(lib$es6$promise$asap$$customSchedulerFn?lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush):lib$es6$promise$asap$$scheduleFlush())},lib$es6$promise$asap$$browserWindow="undefined"!=typeof window?window:void 0,lib$es6$promise$asap$$browserGlobal=lib$es6$promise$asap$$browserWindow||{},lib$es6$promise$asap$$BrowserMutationObserver=lib$es6$promise$asap$$browserGlobal.MutationObserver||lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver,lib$es6$promise$asap$$isNode="undefined"!=typeof process&&"[object process]"==={}.toString.call(process),lib$es6$promise$asap$$isWorker="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,lib$es6$promise$asap$$queue=new Array(1e3);lib$es6$promise$asap$$scheduleFlush=lib$es6$promise$asap$$isNode?function(){return function(){process.nextTick(lib$es6$promise$asap$$flush)}}():lib$es6$promise$asap$$BrowserMutationObserver?function(){var iterations=0,observer=new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush),node=document.createTextNode("");return observer.observe(node,{characterData:!0}),function(){node.data=iterations=++iterations%2}}():lib$es6$promise$asap$$isWorker?function(){var channel=new MessageChannel;return channel.port1.onmessage=lib$es6$promise$asap$$flush,function(){channel.port2.postMessage(0)}}():void 0===lib$es6$promise$asap$$browserWindow&&"function"==typeof require?function(){try{var r=require,vertx=r("vertx");return lib$es6$promise$asap$$vertxNext=vertx.runOnLoop||vertx.runOnContext,lib$es6$promise$asap$$useVertxTimer()}catch(e){return lib$es6$promise$asap$$useSetTimeout()}}():lib$es6$promise$asap$$useSetTimeout();var lib$es6$promise$$internal$$PENDING=void 0,lib$es6$promise$$internal$$FULFILLED=1,lib$es6$promise$$internal$$REJECTED=2,lib$es6$promise$$internal$$GET_THEN_ERROR=new lib$es6$promise$$internal$$ErrorObject,lib$es6$promise$$internal$$TRY_CATCH_ERROR=new lib$es6$promise$$internal$$ErrorObject;lib$es6$promise$enumerator$$Enumerator.prototype._validateInput=function(input){return lib$es6$promise$utils$$isArray(input)},lib$es6$promise$enumerator$$Enumerator.prototype._validationError=function(){return new Error("Array Methods must be provided an Array")},lib$es6$promise$enumerator$$Enumerator.prototype._init=function(){this._result=new Array(this.length)};var lib$es6$promise$enumerator$$default=lib$es6$promise$enumerator$$Enumerator;lib$es6$promise$enumerator$$Enumerator.prototype._enumerate=function(){for(var enumerator=this,length=enumerator.length,promise=enumerator.promise,input=enumerator._input,i=0;promise._state===lib$es6$promise$$internal$$PENDING&&i<length;i++)enumerator._eachEntry(input[i],i)},lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry=function(entry,i){var enumerator=this,c=enumerator._instanceConstructor;lib$es6$promise$utils$$isMaybeThenable(entry)?entry.constructor===c&&entry._state!==lib$es6$promise$$internal$$PENDING?(entry._onerror=null,enumerator._settledAt(entry._state,i,entry._result)):enumerator._willSettleAt(c.resolve(entry),i):(enumerator._remaining--,enumerator._result[i]=entry)},lib$es6$promise$enumerator$$Enumerator.prototype._settledAt=function(state,i,value){var enumerator=this,promise=enumerator.promise;promise._state===lib$es6$promise$$internal$$PENDING&&(enumerator._remaining--,state===lib$es6$promise$$internal$$REJECTED?lib$es6$promise$$internal$$reject(promise,value):enumerator._result[i]=value),0===enumerator._remaining&&lib$es6$promise$$internal$$fulfill(promise,enumerator._result)},lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt=function(promise,i){var enumerator=this;lib$es6$promise$$internal$$subscribe(promise,void 0,function(value){enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED,i,value)},function(reason){enumerator._settledAt(lib$es6$promise$$internal$$REJECTED,i,reason)})};var lib$es6$promise$promise$all$$default=lib$es6$promise$promise$all$$all,lib$es6$promise$promise$race$$default=lib$es6$promise$promise$race$$race,lib$es6$promise$promise$resolve$$default=lib$es6$promise$promise$resolve$$resolve,lib$es6$promise$promise$reject$$default=lib$es6$promise$promise$reject$$reject,lib$es6$promise$promise$$counter=0,lib$es6$promise$promise$$default=lib$es6$promise$promise$$Promise;lib$es6$promise$promise$$Promise.all=lib$es6$promise$promise$all$$default,lib$es6$promise$promise$$Promise.race=lib$es6$promise$promise$race$$default,lib$es6$promise$promise$$Promise.resolve=lib$es6$promise$promise$resolve$$default,lib$es6$promise$promise$$Promise.reject=lib$es6$promise$promise$reject$$default,lib$es6$promise$promise$$Promise._setScheduler
20=lib$es6$promise$asap$$setScheduler,lib$es6$promise$promise$$Promise._setAsap=lib$es6$promise$asap$$setAsap,lib$es6$promise$promise$$Promise._asap=lib$es6$promise$asap$$asap,lib$es6$promise$promise$$Promise.prototype={constructor:lib$es6$promise$promise$$Promise,then:function(onFulfillment,onRejection){var parent=this,state=parent._state;if(state===lib$es6$promise$$internal$$FULFILLED&&!onFulfillment||state===lib$es6$promise$$internal$$REJECTED&&!onRejection)return this;var child=new this.constructor(lib$es6$promise$$internal$$noop),result=parent._result;if(state){var callback=arguments[state-1];lib$es6$promise$asap$$asap(function(){lib$es6$promise$$internal$$invokeCallback(state,child,callback,result)})}else lib$es6$promise$$internal$$subscribe(parent,child,onFulfillment,onRejection);return child},catch:function(onRejection){return this.then(null,onRejection)}};var lib$es6$promise$polyfill$$default=lib$es6$promise$polyfill$$polyfill,lib$es6$promise$umd$$ES6Promise={Promise:lib$es6$promise$promise$$default,polyfill:lib$es6$promise$polyfill$$default};"function"==typeof define&&define.amd?define(function(){return lib$es6$promise$umd$$ES6Promise}):"undefined"!=typeof module&&module.exports?module.exports=lib$es6$promise$umd$$ES6Promise:void 0!==this&&(this.ES6Promise=lib$es6$promise$umd$$ES6Promise),lib$es6$promise$polyfill$$default()}.call(void 0);
21"use strict";function _await(value,then,direct){return direct?then?then(value):value:(value&&value.then||(value=Promise.resolve(value)),then?value.then(then):value)}function _async(f){return function(){for(var args=[],i=0;i<arguments.length;i++)args[i]=arguments[i];try{return Promise.resolve(f.apply(this,args))}catch(e){return Promise.reject(e)}}}function _catch(body,recover){try{var result=body()}catch(e){return recover(e)}return result&&result.then?result.then(void 0,recover):result}function _continue(value,then){return value&&value.then?value.then(then):then(value)}function _empty(){}function _invokeIgnored(body){var result=body();if(result&&result.then)return result.then(_empty)}function _invoke(body,then){var result=body();return result&&result.then?result.then(then):then(result)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _call(body,then,direct){if(direct)return then?then(body()):body();try{var result=Promise.resolve(body());return then?result.then(then):result}catch(e){return Promise.reject(e)}}function _async(f){return function(){for(var args=[],i=0;i<arguments.length;i++)args[i]=arguments[i];try{return Promise.resolve(f.apply(this,args))}catch(e){return Promise.reject(e)}}}function _catch(body,recover){try{var result=body()}catch(e){return recover(e)}return result&&result.then?result.then(void 0,recover):result}function _continue(value,then){return value&&value.then?value.then(then):then(value)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var GGPlayer=function GGPlayer(initData){var playback,websocket,_onStop,_onStart,_ifRemInt,eventBus=GGPlayer.models.EventBus.getInstance(!0),rootScope=GGPlayer.models.RootScope.getInstance(!0),config=new GGPlayer.modules.Config,view=new GGPlayer.modules.View,apiRes=new GGPlayer.modules.ApiResolver,intervalClean=void 0,play=function(){playback&&playback.play(),intervalClean&&clearInterval(intervalClean),intervalClean=setInterval(function(){return clean()},1e3*(window.DEV?20:240))},loadScript=function(script){try{return new Promise(function(resolve,reject){function loadLoop(){var scriptUrl=scripts.shift();if(!scriptUrl)return resolve();try{var scriptTag=document.createElement("script");scriptTag.src=scriptUrl,scriptTag.onload=function(){return loadLoop()},scriptTag.onerror=reject,document.body.appendChild(scriptTag)}catch(e){console.error("player loadScript",e)}}var scripts=Array.isArray(script)?script.slice():[script];loadLoop()})}catch(e){console.error("player loadScript",e)}},stop=function(){playback&&playback.stop(),intervalClean&&clearInterval(intervalClean)},clean=function(){return!(!playback||!playback.clean||(playback.clean(),0))},init=_async(function(initData){return window.DEV_HLS,config.load(initData),rootScope.config=config,rootScope.self=ret,config.get("container")._ggplayer=rootScope,window.DEV&&
21console.log("Player","INIT",rootScope),new GGPlayer.modules.Reyden,view.render(config.get("container"),_async(function(element){new GGPlayer.modules.DebugConsole.getInstance(!0),"undefined"==typeof UserService&&(window.UserService={});var adminLL=!1;try{adminLL=window.UserService&&window.UserService.AdminFeature&&window.UserService.AdminFeature.player_ll}catch(e){}UserService.settings||(UserService.settings={beta:{}});var isBeta=config.get("beta")||!1;try{isBeta=UserService.settings.beta[4]}catch(e){console.log(e)}return _invoke(function(){if(!adminLL)return _invokeIgnored(function(){if(!isBeta||!GGPlayer.protocols.hlsjs.isAvailable())return _invokeIgnored(function(){if(GGPlayer.protocols.hlsjs.isAvailable()){log("candy. Подключаю скрипты СТАРТ");var candySrc01="https://candy.systems/candyLib/[email protected]?v=0.6&channel="+config.get("streamkey");return log("candy. Подключаю скрипты "+candySrc01),_continue(_catch(function(){return _await(loadScript([candySrc01]),function(){log("candy. Подключаю скрипты КОНЕЦ: "+(window.Candy?" УСПЕХ":"ОШИБКА"))})},function(e){console.error("player loadScript",e),log("candy. player loadScript ERROR КОНЕЦ: "+(window.Candy?" УСПЕХ":"ОШИБКА"))}),function(){log("Использую hlsjs "+Hls.version),playback=new GGPlayer.protocols.hlsjs})}GGPlayer.protocols.iOS.isAvailable()?(log("Использую iOS HLS"),playback=new GGPlayer.protocols.iOS):(log("Использую Flash HLS"),playback=new GGPlayer.protocols.HLS)});log("Использую beta ggws"),playback=new GGPlayer.protocols.GGWs});log("Использую hlsjs ll ADMIN"),playback=new GGPlayer.protocols.hlsjsll},function(){playback?(log("Бобро пожаловать! v0.0.17 build 2026-09-23T10:33:50.383Z"),playback.setupVideo(element),playback.setPlaylist(config.get("playlist"),config.get("streamkey"),config.get2("apidata","sources")),rootScope.playback=playback):view.showNotAvailable(),window.DEV_PLAYER&&console.log("PLAYER","previewmode",!rootScope.config.get("previewmode")),rootScope.config.get("previewmode")||((new GGPlayer.modules.Advert).init(config.get("streamkey")),(new GGPlayer.modules.ClipsNew).init(config.get("streamkey")),websocket=new GGPlayer.modules.Websocket,websocket.init(),websocket.setStreamKey(config.get("streamkey"))),apiRes.getData(config.get("streamkey")),_ifRemInt=setInterval(checkIfRemoved,1e3)})})),_await()}),checkPremiumKey=function(premiumKey,streamKey,id,callback){view.premiumChecker(premiumKey,streamKey,id,callback)},startTestPremium=function(){view.startTestPremium()},startCommercial=function(key,pwd){websocket.startCommercial(key,pwd)},onLogin=function(){apiRes.getData(config.get("streamkey"),!0)},onViewers=function(fn){eventBus.addEventListener(GGPlayer.modules.Websocket.events.VIEWERS,fn)},destroy=function(){console.log("PLAYER DESTROY",{playback:playback,view:view}),!0!==_onStop&&(playback&&(playback.stop&&playback.stop(),playback.destroy&&playback.destroy()),view.destroy(),websocket&&websocket.destroy(),_onStop&&(_onStop(),_onStop=!0),_ifRemInt&&clearInterval(_ifRemInt),intervalClean&&clearInterval(intervalClean))},checkIfRemoved=function(){document.contains&&!document.contains(config.get("container"))&&(_onStop=!1,destroy())},detach=function(){rootScope._detaching=!0};!function(){"hidden"in document?(document.addEventListener("visibilitychange",function(e){rootScope.windowIsActive=!document.hidden,rootScope._startLater&&(rootScope._startLater=!1,eventBus.dispatchEvent(GGPlayer.modules.View.events.PLAY))}),rootScope.windowIsActive=!document.hidden):rootScope.windowIsActive=!0}();var ret={};return ret.init=init,ret.appendUserData=function(user){apiRes.appendUserData(user)},ret.appendClipsStatus=function(status){apiRes.appendClipsStatus(status)},ret.play=play,ret.stop=stop,ret.destroy=destroy,ret.detach=detach,ret.isPlaying=function(){return rootScope.isPlaying},ret.onStart=function(cb){_onStart=cb},ret.onStop=function(cb){_onStop=cb},ret.onLogin=onLogin,ret.onViewers=onViewers,ret.checkPremiumKey=checkPremiumKey,ret.startTestPremium=startTestPremium,ret.startCommercial=startCommercial,ret.clean=clean,rootScope.self=ret,initData&&init(initData),ret};GGPlayer.prototype={constructor:GGPlayer},GGPlayer.protocols={},GGPlayer.modules={},GGPlayer.models={},GGPlayer.events={ERROR:"error",LOG:"log"};var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();GGPlayer.modules.HideAdultWarning=function(){function _class(){_classCallCheck(this,_class)}return _createClass(_class,[{key:"get",value:function(streamkey){return localStorage.getItem("hide_adult_warning_"+streamkey)}},{key:"set",value:function(streamkey,value){localStorage.setItem("hide_adult_warning_"+streamkey,value)}}]),_class}(),GGPlayer.modules.Advert=function(){var adsMod,eventBus=GGPlayer.models.EventBus.getInstance(),rootScope=GGPlayer.models.RootScope.getInstance(),swf=!1,channel=13214,once=!1,disableAdvert=!1,_adblock=!1,loadTries=0,streamer="",channelKe
21y="",hidden=!1,loadModule=function(ch){_detectAdblock(),channel=ch,window.testAdvEvent=function(){eventBus.dispatchEvent(GGPlayer.modules.Advert.events.SHOW),console.log("DISPATCH ADV EVENT")},eventBus.addEventListener(GGPlayer.modules.Playback.events.PLAYING,onPlaybackStarted),eventBus.addEventListener(GGPlayer.modules.Advert.events.SHOW,show),eventBus.addEventListener(GGPlayer.modules.Advert.events.SHOW_FORCE,showForce),eventBus.addEventListener(GGPlayer.modules.Advert.events.RELOAD,reload),eventBus.addEventListener(GGPlayer.modules.ApiResolver.events.DATA,onApiData),eventBus.addEventListener(GGPlayer.modules.ApiResolver.events.USER_DATA,onApiUpdateUser)},reload=function(){try{swf.remove(),_createFlashElement()}catch(e){}},_detectAdblock=function(){var js=document.createElement("script");js.type="text/javascript",js.src="/js/advert.js?time="+Date.now(),js.onload=function(){},js.onerror=function(){log("Замечено использование adblock. Ай-яй-яй!")},document.body.appendChild(js)},onFlashLoaded=function(data){swf=data.ref,swf.style.position="absolute",swf.style.zIndex="2200000000",swf.style.top="0",_showHideSwf(0)},onInitComplete=function(){var data={};data.streamName=channel,window.advModule.setInfo(data)},onPlaybackStarted=function onPlaybackStarted(){if(!(loadTries>=5))return adsMod||swf&&swf.show?void(!adsMod&&!swf.show||once||(setTimeout(show,25e3),hidden&&setInterval(show,9e5),once=!0)):(loadTries++,setTimeout(onPlaybackStarted,5e3))},onApiUpdateUser=function(user){console.log("ON API DATA USER UPDATE",{user:user}),user&&user.premium&&(log("Премиум - отключаем рекламу"),disableAdvert=!0,console.log("DISABLED ADV AFTER USER UPDATE",{user:user}))},onApiData=function(data){data.user&&data.user.premium_key&&rootScope.premiumSecondsLeft(data.user.expire)&&(log("Премиум - отключаем рекламу"),disableAdvert=!0),-1!=window.location.href.indexOf("utm_source")&&(log("Utm_source - отключаем рекламу"),disableAdvert=!0),-1!=["127418","127419","145623","171046","171047","175200","175553","175853","175596","175643"].indexOf(data.channel_id)&&(log("Канал из стоплиста - отключаем рекламу"),disableAdvert=!0),streamer=data.streamer_name,channelKey=data.channel_key,hidden=!!data.hidden,disableAdvert||loadHtmlModule(),"undefined"!=typeof Reklama&&(new Reklama).isNewUser()&&(disableAdvert=!0),disableAdvert||trackLoaded(),console.log("ON API DATA DISABLE ADV RESULT",disableAdvert)},trackLoaded=function(){trackEvent("loaded")},trackShown=function(campaign){trackEvent("shown",campaign)},trackEvent=function(event){var opt=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;
21try{window._gaq.push(["_trackEvent","PlayerAdvert",event,opt])}catch(e){}},show=function(){try{rootScope&&rootScope.apiData&&rootScope.apiData.user&&rootScope.apiData.user.premium&&(disableAdvert=!0)}catch(e){}if(log("Показываем рекламу:",disableAdvert,rootScope.isPlaying),console.log("START ADV SHOW"),disableAdvert=!0)return!1;if(!rootScope.isPlaying)return!1;if(!_checkAdvertTimeout())return!1;_adblock="passed"!=window._ggAdblockDetect,showForce();try{Utils.reachGoal("VIDEO_ADS"),Utils.reachGoal("stream_ad_start")}catch(e){}try{localStorage.setItem("ggplayer_lastadvtime",Date.now())}catch(e){}return!0},showForce=function(){if(adsMod)return console.log("SHOW ADV START"),adsMod.showAd();try{var r=swf.show();try{0==_getVolume()?window.advModule.mute():window.advModule.unmute()}catch(e){}return r}catch(e){return console.error(e),!1}},_getVolume=function(){return rootScope.config.get("muted")?0:rootScope.config.get("volume")},_showHideSwf=function(show){swf&&(swf.style.visibility=show?"visible":"hidden"),adsMod&&(adsMod.elem.style.visibility=show?"visible":"hidden"),show?rootScope.config.get("muted")||eventBus.dispatchEvent(GGPlayer.modules.View.events.VOLUME,0):eventBus.dispatchEvent(GGPlayer.modules.View.events.VOLUME,_getVolume())},_createFlashElement=function(){if("undefined"==typeof swfobject)return!1;var elem=document.createElement("div");elem.setAttribute("id","advFlashContent"),rootScope.config.get("container").appendChild(elem);var flashvars={},params={};params.quality="high",params.wmode="opaque",params.allowscriptaccess="always",params.allowfullscreen="true";var attributes={};attributes.id="AdvModule",attributes.name="AdvModule",attributes.align="middle",swfobject.embedSWF("/files/AdvModule.swf?time="+Date.now().toString(36)+"&src="+channel,"advFlashContent","100%","100%","0.0.0","",flashvars,params,attributes,onFlashLoaded)},loadHtmlModule=function loadHtmlModule(){"undefined"==typeof require?setTimeout(loadHtmlModule,100):_loadHtmlModule()},_removeAdCallback=function(){try{PremiumPopup.open(channelKey)}catch(e){console.log(e)}},_loadHtmlModule=function(){var elem=document.createElement("div");elem.setAttribute("id","addBlock"),elem.setAttribute("style","display:block!important;position:absolute;visibility:hidden;top:0;left:0;right:0;bottom:0;"),rootScope.config.get("container").appendChild(elem);var AdsMod=require("goodgame.adsmod");adsMod=new AdsMod,adsMod.setConfig({channelId:channel,channelName:streamer,container:elem,volume:_getVolume(),preset:"ok",hidden:hidden,adOffCallback:_removeAdCallback,source:document.location.href}),adsMod.elem=elem,adsMod.on("started",function(event){adsMod.setVolume(_getVolume()),trackShown(event.agency),_showHideSwf(1)}),adsMod.on("ended",function(event){_showHideSwf(0)})},_checkAdvertTimeout=function(){var lastAdvertShowTime=parseInt(localStorage.getItem("ggplayer_lastadvtime"));return!(lastAdvertShowTime&&lastAdvertShowTime+12e4>=Date.now())||(log("Реклама не чаще раз в 2мин."),!1)};return function(){var obj={};obj.setInfo=function(info){log("setInfo",info),swf.setInfo(info)},obj.show=function(){swf.show()},obj.mute=function(){swf.mute()},obj.unmute=function(){swf.unmute()},obj.initialized=function(ver){log("ad ver: "+ver),onInitComplete()},obj.started=function(){log("ad started"),_showHideSwf(1)},obj.ended=function(){log("ad ended"),_showHideSwf(0)},obj.log=function(level,adname,message){"name"==level&&log("Advert:",adname.substr(0,3),message)},window.advModule=obj}(),{init:loadModule}},GGPlayer.modules.Advert.events={SHOW:"advert_show",SHOW_FORCE:"advert_show_force",RELOAD:"advert_reload"},GGPlayer.modules.ApiResolver=function(){var eventBus=GGPlayer.models.EventBus.getInstance(),rootScope=GGPlayer.models.RootScope.getInstance(),_loaded=!1,_loadCache=[],_src=!1,getData=function(src,force){if(_src=src,void 0===force&&(force=!1),window.DEV_HLS,rootScope.config.get("apidata")&&!force)rootScope.apiData=rootScope.config.get("apidata"),1==rootScope.config.get("candy")&&(rootScope.apiData.p2p=1),eventBus.dispatchEvent(GGPlayer.modules.ApiResolver.events.DATA,rootScope.apiData,force),_loaded=!0,_loadCache&&Object.assign(rootScope.apiData.user,_loadCache),_loadCache=null,window.DEV_PLAYER&&console.log("PLAYER","apiResolver::getData",rootScope.apiData.user),eventBus.dispatchEvent(GGPlayer.modules.ApiResolver.events.USER_DATA,rootScope.apiData.user);else{var xhr=new XMLHttpRequest;xhr.open("GET","/api/player?src="+src,!0),xhr.withCredentials=!0,xhr.responseType="text",x
21hr.send(),xhr.onreadystatechange=function(){4==xhr.readyState&&xhr.response&&(rootScope.apiData=JSON.parse(xhr.response),1==rootScope.config.get("candy")&&(rootScope.apiData.p2p=1),window.DEV_PLAYER&&console.log("apiResolver::getData apiData",rootScope.apiData),eventBus.dispatchEvent(GGPlayer.modules.ApiResolver.events.DATA,rootScope.apiData,force),_loaded=!0,_loadCache&&Object.assign(rootScope.apiData.user,_loadCache),_loadCache=null,window.DEV_PLAYER&&console.log("apiResolver::getData user",rootScope.apiData.user),eventBus.dispatchEvent(GGPlayer.modules.ApiResolver.events.USER_DATA,rootScope.apiData.user))},xhr.addEventListener("error",function(e){eventBus.dispatchEvent(GGPlayer.modules.ApiResolver.events.ERROR)},!1)}},appendUserData=function appendUserData(user){if(window.DEV&&console.log("apiResolver::appendUserData",_loaded,user,rootScope.apiData),!_loaded)return void Object.assign(_loadCache,user);rootScope.apiData&&rootScope.apiData.user?(Object.assign(rootScope.apiData.user,user),eventBus.dispatchEvent(GGPlayer.modules.ApiResolver.events.USER_DATA,rootScope.apiData.user)):setTimeout(function(){return appendUserData(user)},50)},appendClipsStatus=function(status){status?eventBus.dispatchEvent(GGPlayer.modules.Clips.events.DISABLED,!0):eventBus.dispatchEvent(GGPlayer.modules.Clips.events.AVAILABLE,!0)},addToFavorites=function(state,anons,start){var xhr=new XMLHttpRequest;xhr.withCredentials=!0,xhr.responseType="text";var formData=new FormData;formData.append("obj_type",7),formData.append("obj",rootScope.apiData.channel_id),state?(formData.append("getEmail",start),formData.append("getAnons",anons),xhr.open("POST","/ajax/subscribe/",!0),xhr.send(formData)):(xhr.open("POST","/ajax/unsubscribe/",!0),xhr.send(formData)),xhr.onreadystatechange=function(){4==xhr.readyState&&getData(_src,!0)}};return function(){eventBus.addEventListener(GGPlayer.modules.ApiResolver.events.FAV,addToFavorites)}(),{getData:getData,appendUserData:appendUserData,appendClipsStatus:appendClipsStatus}},GGPlayer.modules.ApiResolver.events={ERROR:"api_error",DATA:"api_on_data",USER_DATA:"api_on_user_data",FAV:"api_fav_stream"},GGPlayer.modules.ClipsNew=function(){var streamKey,eventBus=GGPlayer.models.EventBus.getInstance(),rootScope=GGPlayer.models.RootScope.getInstance(),loadModule=function(_streamKey){streamKey=_streamKey,eventBus.addEventListener(GGPlayer.modules.ApiResolver.events.DATA,onApiData),eventBus.addEventListener(GGPlayer.modules.ApiResolver.events.USER_DATA,onApiData)},onApiData=function(){rootScope.apiData.user&&rootScope.apiData.user.user_id&&(eventBus.addEventListenerUniq(GGPlayer.modules.View.events.CREATE_CLIP,onCreateClip),eventBus.dispatchEvent(GGPlayer.modules.Clips.events.AVAILABLE,!0)),(rootScope.apiData.hidden||rootScope.apiData.watchTogether||!rootScope.apiData.user&&!rootScope.apiData.user.user_id)&&eventBus.dispatchEvent(GGPlayer.modules.Clips.events.DISABLED,!0)},onCreateClip=function(e){return window.open("/clip/creating?src="+streamKey),!0};return{init:loadModule}},GGPlayer.modules.Clips={},GGPlayer.modules.Clips.events={DISABLED:"clips_disabled",AVAILABLE:"clips_available",SAVE:"clips_save"},GGPlayer.modules.Config=function(){var forsave=["volume","muted","muted_preview","quality","premiumkey","PLAY_SEGMENTS","USE_FLASH","candy_view"],options={},preview_mode=!1,defaults={autoplay:!1,container:!1,adult:!1,playlist:"",quality:"auto",poster:"https://goodgame.ru/images/channel-logo.jpg",volume:.5,muted:0,muted_preview:1,candy_view:!1},_extend=function(){for(var i=1;i<arguments.length;i++)for(var key in arguments[i])arguments[i].hasOwnProperty(key)&&(arguments[0][key]=arguments[i][key]);return arguments[0]},load=function(initOptions){preview_mode=initOptions.previewmode||!1,options=_extend(defaults,initOptions,saved()),window.DEV_PLAYER&&console.log("PLAYER","load options",options)},saved=function(){var ret={},s=localStorage.getItem(getkey());if(!s)return ret;try{ret=JSON.parse(s)}catch(e){log(e.toString())}return ret},save=function(){var saved={};for(var name in options)options.hasOwnProperty(name)&&-1!=forsave.indexOf(name)&&(saved[name]=options[name]);try{localStorage.setItem(getkey(),JSON.stringify(saved))}catch(e){}return!0},getkey=function(){return"ggplayer_settings"},setFunc=function(name,value){preview_mode&&"muted"==name&&(name="muted_preview"),options[name]=value,save()};return{load:load,get:function(name){return options[preview_mode&&"muted"==name?"muted_preview":name]},get2:function(name,subname){var def=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;return options[name]?options[name][subname]||def:def},set:setFunc}},GGPlayer.modules.DebugConsole=function(){var eventBus=GGPlayer.models.EventBus.getInstance(),rootScope=GGPlayer.models.RootScope.getInstance(),elem,input,logElem,video,fps,_frames,temp,isVisible=!1,extLog="",last={},init=function(){createElement(),bindButtons(),bindCounters()},qos=function(value){return void 0===value?rootScope.config.get("PLAY_SEGMENTS"):(rootScope.config.set("PLAY_SEGMENTS",value),eventBus.dispatchEvent(GGPlayer.modules.View.events.STOP),eventBus.dispatchEvent(GGPlayer.modules.View.events.PLAY),eventBus.dispatchEvent(GGPlayer.modules.View.events.STATUS,"set qos = "+value),value)},proxy=function(value){return rootScope.proxy=value,eventBus.dispatchEvent(GGPlayer.modules.View.events.QUALITY,""),eventBus.dispatchEvent(GGPlayer.modules.View.events.STOP),eventBus.dispatchEvent(GGPlayer.modules.View.events.PLAY),eventBus.dispatchEvent(GGPlayer.modules.View.events.STATUS,"set proxy = "+value),value},flash=function(value){return void 0===value?rootScope.config.get("USE_FLASH"):(rootScope.config.set("USE_FLASH",value),eventBus.dispatchEvent(GGPlayer.modules.View.events.STATUS,"set flash = "+value),value)}
21,createElement=function(){elem=document.createElement("div"),elem.setAttribute("id","debugConsole"),elem.innerHTML='<div class="log"></div><div class="fps"></div><div class="input"><input style="color:#fff"></div>',input=elem.querySelector("input"),logElem=elem.querySelector(".log"),fps=elem.querySelector(".fps"),window.DEV&&console.log("GGPlayer","Console",rootScope.config.get("container"),rootScope.config.get("dev")),rootScope.config.get("container").appendChild(elem),1==rootScope.config.get("dev")&&toggle()},clear=function(){return logElem.innerHTML="","Консоль очищена"},cleanup=function(){var lines=logElem.innerHTML.split("\n");logElem.innerHTML=lines.slice(-100).join("\n")},bindButtons=function bindButtons(){rootScope.config.get("container").addEventListener("keydown",function(e){192!=e.which&&221!=e.which||(e.stopImmediatePropagation(),e.stopPropagation(),e.preventDefault(),toggle())}),document.addEventListener("keydown",function(e){!isVisible||192!=e.which&&221!=e.which?"Backquote"==e.code&&e.shiftKey&&e.ctrlKey&&(e.stopImmediatePropagation(),e.stopPropagation(),e.preventDefault(),toggle()):(e.stopImmediatePropagation(),e.stopPropagation(),e.preventDefault(),toggle())}),input.addEventListener("keydown",function(e){if(e.stopImmediatePropagation(),e.stopPropagation(),192!=e.which&&221!=e.which||(toggle(),e.preventDefault(),this.value=""),13==e.which){if(""!=this.value.trim()){log("> "+this.value);try{if(route[this.value.split(" ")[0]]){var pars=this.value.split(" "),name=pars.shift();temp=route[name].apply(this,pars)}else temp=eval(this.value);log(temp),console.dir(temp)}catch(e){log(e.toString())}}this.value=""}})},toggle=function(){isVisible?(elem.style.display="none",isVisible=!1,rootScope.config.get("container").querySelector(".player-block").focus()):(elem.style.display="block",isVisible=!0,input.focus())},bindCounters=function(){!(video=rootScope.config.get("container").querySelector("video"))||void 0===video.webkitDecodedFrameCount&&void 0===video.mozDecodedFrames||setInterval(countFPS,1e3)},addExtLog=function(l){extLog=l},countFPS=function(){var df=video.webkitDecodedFrameCount||video.mozDecodedFrames,drop=video.webkitDroppedFrameCount||"-",buffer=video.buffered.length?video.buffered.end(video.buffered.length-1)-video.currentTime:0;fps.innerHTML="FPS: "+(df-_frames),fps.innerHTML+="\nDropped: "+drop,fps.innerHTML+="\nBuffer: "+buffer.toFixed(2)+" queue: "+(rootScope._queue||0),fps.innerHTML+="\nServer ip: "+(rootScope.cdnServer?rootScope.cdnServer.ip:"?"),fps.innerHTML+="\nName: "+(rootScope.cdnServer?rootScope.cdnServer.name:"?"),fps.innerHTML+="\nСкорость: "+(rootScope._speed||0)+"M",rootScope.speeds&&(fps.innerHTML+="\nBalancer: "+rootScope.speeds[0]+" : "+rootScope.speeds[1]),_frames=df;var logCandy=!1;if(window.CANDY_FORCE?("on"==window.CANDY_FORCE&&(logCandy=!0),logCandy="off"!=window.CANDY_FORCE&&window.Candy&&window.Candy.getStat):logCandy=window.Candy&&window.Candy.getStat,logCandy){try{var stat=window.Candy.getStat();if(stat){var cdn=parseFloat((stat.cdnBytes/1048576).toFixed(2)),p2p=parseFloat((stat.p2pBytes/1048576).toFixed(2)),rate=(100*p2p/(cdn+p2p)).toFixed(2)||0;fps.innerHTML+="\n Rate: "+p2p+"/"+cdn+" "+rate+"%",fps.innerHTML+="\n CandyMyId: "+(stat.myid||"");var CandyPeersAll=stat.peersObj||{};fps.innerHTML+="\n CandyPeersAllLength: "+Object.keys(CandyPeersAll).length;var CandyPeersConnected=stat.peers||[];fps.innerHTML+="\n CandyPeersConnectedLength: "+CandyPeersConnected.length}}catch(e){var _log="?";_log=e.stack?e.stack:e.message?e.message:e.toString?e.toString():e,fps.innerHTML+="\nCandy is down: "+_log,window.ggLog&&window.ggLog(_log)}fps.innerHTML+=extLog}},append=function(e){video||bindCounters();try{for(var str="",i=0;i<e.length;i++)"string"==typeof e[i]?str+=e[i]+" ":str+=JSON.stringify(e[i])+" ";"undefined"==str&&console.trace(),logElem.innerHTML+=str+"\n",logElem.scrollTop=1e4,cleanup()}catch(error){console.log(e)}},route={};return route.test=function(){return":peka:"},route.qos=qos,route.proxy=proxy,route.flash=flash,route.clear=function(){logElem.innerHTML=""},route.help=route.man=function(){var txt="\n";return txt+="candy off - Disable candy in current page\n",txt+="candy on - Enable candy in current page\n",txt+="candy auto - Auto mode\n",txt+="==========================================\n",txt+="advert - Show advert\n",txt+="adv - Show advert\n"},route.candy=function(v){return"auto"!=v&&"off"!=v&&"on"!=v?"Need parameter: on / off / auto":(window.CANDY_FORCE=v,eventBus.dispatchEvent(GGPlayer.modules.View.events.STOP),eventBus.dispatchEvent(GGPlayer.modules.View.events.PLAY),"go-go-go")},route.advert=route.adv=function(){return eventBus.dispatchEvent(GGPlayer.modules.Advert.events.SHOW_FORCE,{}),"start adv"},init(),{append:append,addExtLog:addExtLog}},GGPlayer.modules.DebugConsole.getInstance=function(createNew){return!createNew&&GGPlayer.modules.DebugConsole._singletonInstance||(GGPlayer.modules.DebugConsole._singletonInstance=new GGPlayer.modules.DebugConsole),GGPlayer.modules.DebugConsole._singletonInstance},GGPlayer.modules.DebugConsole.events={};var log=function(){GGPlayer.modules.DebugConsole.getInstance().append(Array.prototype.slice.call(arguments)),window._log&&window._log.apply(window,arguments)},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),qualityKeys={"":4,720:3,480:2,240:1,audio:1}
21,GGPlayerModulesHlsPlayerQuality2Hls=function(){function GGPlayerModulesHlsPlayerQuality2Hls(hls){_classCallCheck(this,GGPlayerModulesHlsPlayerQuality2Hls),this.hls=hls,this.timeout=null}return _createClass(GGPlayerModulesHlsPlayerQuality2Hls,[{key:"changeLevel",value:function(quality,timer){var _this=this;if(this.hls){if(0===this.hls.levels.length)return this.timeout&&clearTimeout(this.timeout),timer||(this.timeout=setTimeout(function(){return _this.changeLevel(quality,!0)},2e3)),!1;if(1===this.hls.levels.length)return this.hls.currentLevel;if("auto"==quality)return this.hls.currentLevel=-1,!0;try{if(qualityKeys[quality]&&this.hls.levels.length>=qualityKeys[quality]-1)return this.hls.currentLevel=qualityKeys[quality]-1}catch(e){window.DEV&&console.error(e)}for(var hlsIndex=null,i=0;i<this.hls.levels.length;++i)if(this.hls.levels[i].height==quality){hlsIndex=i;break}return hls.loadLevel=null!==hlsIndex?hlsIndex:-1,!0}}},{key:"getQuality",value:function(){return this.hls.levels.length<=1?"":qualityKeys[this.hls.currentLevel]||""}}]),GGPlayerModulesHlsPlayerQuality2Hls}();GGPlayer.modules.HlsTranscodingDetector=function(){function hasTranscoding(smil){return!!smil&&(smil.match(/#EXT-X-STREAM-INF/g)||[]).length>1}function destroy(){_interval&&clearInterval(_interval)}var getSmil=_async(function(){sources||(sources=rootScope.config.get2("apidata","sources"));var playlistMaster=sources.master||sources.source||"https://hls.goodgame.ru/manifest/"+streamKey+"_master.m3u8";return window.DEV_PLAYER&&console.log("HlsTranscodingDetector",playlistMaster),fetch(playlistMaster).then(function(response){var allHeaders={};return response.headers&&response.headers.forEach(function(value,key){allHeaders[key]=value}),monitor.saveLastHeaders(allHeaders),response.text()}).catch(function(e){monitor.postAfterStatusCheck(function(){return monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_MANIFEST_LOAD_ERROR,{status:e.status,error:e.message,streamKey:streamKey})})(),eventBus.dispatchEvent(GGPlayer.modules.HlsTranscodingDetector.events.TRANSCODING_MASTER_PLAYLIST_FAILED,e)})}),checkTranscoding=_async(function(){var _exit=!1;return _continue(_catch(function(){return _call(getSmil,function(_getSmil){_masterPlaylistData=_getSmil})},function(e){return window.DEV_PLAYER&&console.log(e),_exit=!0,!1}),function(_result){return _exit?_result:hasTranscoding(_masterPlaylistData)})}),detectTranscoding=_async(function(){return sources=rootScope.config.get2("apidata","sources"),_call(checkTranscoding,function(hasTr){hasTr||setTimeout(function(){return detectTranscoding},500),eventBus.dispatchEvent(GGPlayer.modules.HlsTranscodingDetector.events.TRANSCODING_STATE,hasTr),eventBus.dispatchEvent(GGPlayer.modules.HlsTranscodingDetector.events.TRANSCODING_MASTER_PLAYLIST,_masterPlaylistData)})}),eventBus=GGPlayer.models.EventBus.getInstance(),rootScope=GGPlayer.models.RootScope.getInstance(),streamKey=rootScope.config.get("streamkey"),sources=rootScope.config.get2("apidata","sources"),_masterPlaylistData=null,_interval=null,monitor=GGPlayer.modules.Monitoring.getInstance();return function(){window.DEV_PLAYER&&console.log("HlsTranscodingDetector init"),detectTranscoding(),_interval=setInterval(detectTranscoding,3e4)}(),{checkTranscoding:checkTranscoding,getMasterPlaylistData:function(){return _masterPlaylistData},destroy:destroy}},GGPlayer.modules.HlsTranscodingDetector.events={TRANSCODING_STATE:"transcoding_state",TRANSCODING_MASTER_PLAYLIST:"transcoding_master",TRANSCODING_MASTER_PLAYLIST_FAILED:"transcoding_master_failed"};var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[],_n=!0,_d=!1,_e=void 0;try{for(var _s,_i=arr[Symbol.iterator]();!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{!_n&&_i.return&&_i.return()}finally{if(_d)throw _e}}return _arr}return function(arr,i){if(Array.isArray(arr))return arr;if(Symbol.iterator in Object(arr))return sliceIterator(arr,i);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};GGPlayer.modules.Monitoring=function(createNew){var jitsuLocal=null;if(window.playerJitsuOnload=function(j){window.DEV_PLAYER_JITSU&&console.log("Jitsu onload",j),jitsuLocal=j},!createNew&&GGPlayer.modules.Monitoring._singletonInstance)return GGPlayer.modules.Monitoring._singletonInstance
22;var rootScope=GGPlayer.models.RootScope.getInstance(),lastSavedHeaders="",isRunning=!1,generateUUID=function(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)};!function(){var script=document.createElement("script");script.src="https://vmetrics.goodgame.ru:8081/p.js",script.setAttribute("data-write-key","poxZRQI1rxpy6MaqhZ4tQefpXAvu5
22H61:Xhovt10VStvUCiLzECzdjM3m9dOuIdDm"),script.setAttribute("data-namespace","playerJitsu"),script.setAttribute("data-debug",window.DEV_PLAYER_JITSU?"true":"false"),script.setAttribute("data-onload","playerJitsuOnload"),document.head.appendChild(script)}();var getOrCreateAnonymousUserId=function(){var anonymousUserId=localStorage.getItem("GG_ANONYMOUS_USER_ID");return anonymousUserId||(anonymousUserId="0_"+generateUUID(),localStorage.setItem("GG_ANONYMOUS_USER_ID",anonymousUserId)),anonymousUserId},monitorEvents=function(eventName,data){try{var _j=jitsuLocal||(window.playerJitsu?window.playerJitsu:null),userId=rootScope.apiData&&rootScope.apiData.user&&rootScope.apiData.user.user_id||getOrCreateAnonymousUserId();window.DEV_PLAYER_JITSU&&console.log("JITSU",eventName,data,userId,_j),_j&&_j.track(eventName,{data:removeCircularReferences(data||{}),headers:lastSavedHeaders,userId:userId})}catch(e){window.DEV_PLAYER_JITSU&&(console.error("JITSU ERROR",e,j),window.ggLog&&window.ggLog(e))}},removeCircularReferences=function(obj){function recursiveCopy(value){if("object"===(void 0===value?"undefined":_typeof(value))&&null!==value){if(seen.has(value))return"[Circular]";if(seen.add(value),Array.isArray(value))return value.map(recursiveCopy);var result={},_iteratorNormalCompletion=!0,_didIteratorError=!1,_iteratorError=void 0;try{for(var _step,_iterator=Object.entries(value)[Symbol.iterator]();!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=!0){var _step$value=_slicedToArray(_step.value,2),key=_step$value[0],val=_step$value[1];result[key]=recursiveCopy(val)}}catch(err){_didIteratorError=!0,_iteratorError=err}finally{try{!_iteratorNormalCompletion&&_iterator.return&&_iterator.return()}finally{if(_didIteratorError)throw _iteratorError}}return result}return value}var seen=new WeakSet;return recursiveCopy(obj)},postAfterStatusCheck=function(trackEventCallback){return isRunning?function(){return Promise.resolve()}:function(){return isRunning=!0,new Promise(function(resolve,reject){isRunning=setTimeout(function(){fetch("https://hls.goodgame.ru/onlineStreams").then(function(response){return response.text()}).then(function(text){var src=rootScope.config.get("streamkey");(text||"").split("\n").indexOf(src)>-1&&trackEventCallback&&trackEventCallback(),resolve()}).catch(function(e){console.error("Fetch error:",e),resolve()}).finally(function(){clearTimeout(isRunning),isRunning=null})},1e4)})}},saveLastHeaders=function(headers){lastSavedHeaders=headers};return GGPlayer.modules.Monitoring._singletonInstance={postEvent:function(eventName,data){return monitorEvents(eventName,data)},saveLastHeaders:saveLastHeaders,postAfterStatusCheck:postAfterStatusCheck},GGPlayer.modules.Monitoring._singletonInstance},GGPlayer.modules.Monitoring.getInstance=function(createNew){return new GGPlayer.modules.Monitoring(createNew)},GGPlayer.modules.Monitoring.events={HLS_MANIFEST_LOAD_ERROR:"hls_manifest_load_error",HLS_BUFFER_STALLED_ERROR:"hls_buffer_stalled_error",HLS_NETWORK_ERROR:"hls_network_error",HLS_MEDIA_ERROR:"hls_media_error",HLS_OTHER_ERROR:"hls_other_error",HLS_VIDEO_WAITING:"hls_video_waiting",HLS_VIDEO_STALLED:"hls_video_stalled",HLS_VIEWING_PARAMS:"hls_viewing_params",HLS_FATAL_ERROR:"hls_fatal_error",HLS_FRAG_LOADED:"hls_frag_loaded",HLS_AVERAGE_SPEED_LOADING:"hls_average_speed_loading",HLS_BUFFER_APPEND_ERROR:"hls_buffer_append_error",HLS_BUFFER_CRITICAL:"hls_buffer_critical",HLS_BUFFER_LOW:"hls_buffer_low",HLS_BUFFER_UPDATE:"hls_buffer_update",WS_CONNECT_ERROR:"ws_connect_error",WS_MEDIA_ERROR:"ws_media_error",WS_VIDEO_WAITING:"ws_video_waiting",WS_VIDEO_STALLED:"ws_video_stalled",WS_VIEWING_PARAMS:"ws_viewing_params"};var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),HLSSpeedMonitor=function(){function HLSSpeedMonitor(hlsInstance,monitor){_classCallCheck(this,HLSSpeedMonitor),this.hls=hlsInstance,this.monitor=monitor,this.downloadSpeeds=[],this.totalBytes=0,this.totalTime=0,this.statsInterval=null,this.statsIntervalTime=6e5,this.onFragLoadedHandler=this.onFragLoaded.bind(this),this.setupListeners(),this.startStatsReporting()}return _createClass(HLSSpeedMonitor,[{key:"setupListeners",value:function(){this.hls.on(Hls.Events.FRAG_LOADED,this.onFragLoadedHandler)}},{key:"startStatsReporting",value:function(){var _this=this;this.statsInterval||(this.statsInterval=setInterval(function(){var stats=_this.get
22Stats();_this.monitor.postAfterStatusCheck(function(){return _this.monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_AVERAGE_SPEED_LOADING,stats)})()},this.statsIntervalTime))}},{key:"onFragLoaded",value:function(event,data){try{var downloadTime=data.frag.stats.loading.end-data.frag.stats.loading.start,bytes=data.frag.stats.loaded,speedMbps=this.calculateSpeed(bytes,downloadTime);this.downloadSpeeds.push(speedMbps),this.totalBytes+=bytes,this.totalTime+=downloadTime}catch(e){console.error("onFragLoaded speed error",e)}}},{key:"calculateSpeed",value:function(bytes,milliseconds){return 8*bytes/1e6/(milliseconds/1e3)}},{key:"getAverageSpeed",value:function(){return 0===this.downloadSpeeds.length?0:this.downloadSpeeds.reduce(function(a,b){return a+b},0)/this.downloadSpeeds.length}},{key:"getOverallSpeed",value:function(){return 0===this.totalTime?0:this.calculateSpeed(this.totalBytes,this.totalTime)}},{key:"getStats",value:function(){return{averageSpeed:Math.round(this.getAverageSpeed()),overallSpeed:Math.round(this.getOverallSpeed()),totalBytes:Math.round(this.totalBytes),totalTime:Math.round(this.totalTime),measurements:this.downloadSpeeds.length}}},{key:"stopStatsReporting",value:function(){this.statsInterval&&(clearInterval(this.statsInterval),this.statsInterval=null)}},{key:"reset",value:function(){this.downloadSpeeds=[],this.totalBytes=0,this.totalTime=0}},{key:"destroy",value:function(){this.stopStatsReporting(),this.hls.off(Hls.Events.FRAG_LOADED,this.onFragLoadedHandler),this.reset(),this.hls=null}}]),HLSSpeedMonitor}();GGPlayer.modules.HLSSpeedMonitor=HLSSpeedMonitor,GGPlayer.modules.Premium=function(){var eventBus=GGPlayer.models.EventBus.getInstance(),checkCallback=(GGPlayer.models.RootScope.getInstance(),!1),getData=function(streamname,premium_key,uid){var body="streamname="+encodeURIComponent(streamname)+"&premium_key="+encodeURIComponent(premium_key)+"&uid="+encodeURIComponent(uid),xhr=new XMLHttpRequest;xhr.open("POST","/api/premium/xml/?all=1",!0),xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),xhr.responseType="text",x
22hr.send(body),xhr.onreadystatechange=function(){xhr.readyState==xhr.DONE&&xhr.response&&answer(parseXML(xhr.response))},xhr.addEventListener("error",function(e){eventBus.dispatchEvent(GGPlayer.modules.ApiResolver.events.ERROR)},!1)},parseXML=function(xml){for(var ret={},m=!1,params=xml.split(/<\/[^>]+>/),i=0;i<params.length;i++)(m=params[i].match(/<(.+)>(.+)/))&&(m[1].match(/activated="true"/)&&(m[1]=m[1].replace(/ activated="true"/,""),ret._activated=!0),ret[m[1]]=m[2]);return ret},answer=function(data){if("OK_ALL"==data.status||"OK"==data.status){if(checkCallback(!0,"OK_ALL"==data.status),data._activated)try{Utils.reachGoal("PREMIUM")}catch(e){}}else checkCallback(!1,!1)};return{checkKey:function(premiumkey,streamkey,uid,callback){checkCallback=callback,getData(streamkey,premiumkey,uid)},startTest:function(){return new Promise(function(resolve,reject){var xhr=new XMLHttpRequest;xhr.open("POST","/api/premium/trial/",!0),xhr.responseType="text",xhr.send(),xhr.onreadystatechange=function(){4==xhr.readyState&&xhr.response&&resolve(JSON.parse(xhr.response))},xhr.onerror=function(err){reject(err)}})}}},GGPlayer.modules.Premium.events={PREMIUM_OK:"premium_ok",PREMIUM_ERROR:"premium_error"},GGPlayer.modules.Reyden=function(){function parseInitData(){rootScope.config.set("autoplay",+InitData.autoplay),rootScope.config.set("volume",+InitData.volume/100),rootScope.config.set("muted",+InitData.mute)}function bindEvents(){eventBus.addEventListener(GGPlayer.modules.Playback.events.PLAYING,function(){return sendEvent("Play")}),eventBus.addEventListener(GGPlayer.modules.Playback.events.STOPPED,function(){return sendEvent("Pause")}),eventBus.addEventListener(GGPlayer.modules.Playback.events.ENDED,function(){return sendEvent("Stop")})}function bindInterval(){setInterval(function(){rootScope.isPlaying&&sendEvent("Playing")},1e3)}function sendEvent(event){try{window.parent.postMessage(JSON.stringify({event:event}),"*")}catch(e){}}var eventBus=GGPlayer.models.EventBus.getInstance(),rootScope=GGPlayer.models.RootScope.getInstance();return function(){if("undefined"==typeof InitData)return!1;parseInitData(),bindEvents(),bindInterval()}(),{}},GGPlayer.modules.View=function(){var _testPremiumTimout,announceTimer,eventBus=GGPlayer.models.EventBus.getInstance(),rootScope=GGPlayer.models.RootScope.getInstance(),hideAdultWarning=new GGPlayer.modules.HideAdultWarning,premiumChecker=new GGPlayer.modules.Premium,domain="https://goodgame.ru",gorodChannels=["127418","127419"],root={},dvrRange={},currentTime=0,quality="",_isFullscreen=0,_statusTimeout=!1,_isTestPremium=!1,_isInFeed=!1,_autoquality=!0,channelLink="",channelTitle="",cleanInnerHtml="",render=function(element,callback){if(root=element,cleanInnerHtml=element.cloneNode(!0).innerHTML,rootScope.premiumSecondsLeft=premiumSecondsLeft,window.DEV_PLAYER&&console.log("PLAYER","view render","previewmode = ",rootScope.config.get("previewmode")),rootScope.config.get("previewmode"))window.DEV_PLAYER&&console.log("PLAYER","view render","Режим превью - без шаблона старуем"),videoOnly(callback);else if(root.querySelector("#tplggplayer"))window.DEV_PLAYER&&console.log("PLAYER","view render","Использую инлайновый шаблон"),onload(callback);else{window.DEV_PLAYER&&console.log("PLAYER","view render","Шаблона нет, грузим");var xhr=new XMLHttpRequest;xhr.onreadystatechange=function(e){4==xhr.readyState&&200==xhr.status&&(root.innerHTML=xhr.responseText,onload(callback))},xhr.open("GET","/html/template/ggplayer.html?time="+ +new Date,!0),xhr.send()}},videoOnly=function(callback){bindEvents(),createMuteButton(),callback(root)},createMuteButton=function(){var btn=document.createElement("div");btn.classList.add("sound-wrap"),root.appendChild(btn),btn.addEventListener("click",setMute)},onload=function(callback){bindButtons(),bindEvents(),!!callback&&callback(q("#_video"))},q=function(selector,all){return all?Array.prototype.slice.call(root.querySelectorAll(selector)):root.querySelector(selector)||document.createElement("div")},bindEvents=function(){eventBus.addEventListener(GGPlayer.modules.Playback.events.PLAY,onPlaybackStart),eventBus.addEventListener(GGPlayer.modules.Playback.events.PLAYING,onPlaybackStarted),eventBus.addEventListener(GGPlayer.modules.Playback.events.STOPPED,onPlaybackStop),eventBus.addEventListener(GGPlayer.modules.Playback.events.STOP,onPlaybackStop),eventBus.addEventListener(GGPlayer.modules.Playback.events.QUALITY,onQualityChangeStart),eventBus.addEventListener(GGPlayer.modules.Playback.events.QUALITY_CHANGED,onQualityChangeEnd),eventBus.addEventListener(GGPlayer.modules.Playback.events.AUTOQUALITY_AVAILABLE,onQualityAvailable),eventBus.addEventListener(GGPlayer.modules.Playback.events.MUTED,onMutedChanged),eventBus.addEventListener(GGPlayer.modules.Playback.events.FULLSCREEN,onFullscreenChanged),eventBus.addEventListener(GGPlayer.modules.Playback.events.VOLUME,onVolumeChanged),eventBus.addEventListener(GGPlayer.modules.Playback.events.DVRINFO,onDvrInfo),eventBus.addEventListener(GGPlayer.modules.Playback.events.UPDATE,onVideoUpdate),eventBus.addEventListener(GGPlayer.modules.Playback.events.LOADING,onVideoLoading),eventBus.addEventListener(GGPlayer.modules.Websocket.events.VIEWERS,onViewersChanged),eventBus.addEventListener(GGPlayer.modules.ApiResolver.events.DATA,onApiData),eventBus.addEventListener(GGPlayer.modules.ApiResolver.events.USER_DATA,onApiUpdateUser),eventBus.addEventListener(GGPlayer.modules.View.events.STATUS,onDisplayStatus),eventBus.addEventListener(GGPlayer.modules.View.events.THEATRE_MODE,toggleTheatreMode),eventBus.addEventListener(GGPlayer.modules.Clips.events.AVAILABLE,onClipsAvailable),eventBus.addEventListener(GGPlayer.modules.Clips.events.DISABLED,onClipsDisabled),eventBus.addEventListener(GGPlayer.modules.HlsTranscodingDetector.events.TRANSCODING_STATE,onTranscodingState),document.addEventListener("webkitfullscreenchange",_fullscreenchange),document.addEventListener("mozfullscreenchange",_fullscreenchange),document.addEventListener("msfullscreenchange",_fullscreenchange),document.addEventListener("fullscreenchange",_fullscreenchange)},_fullscreenchange=function(e){onFullscreenChanged(document.webkitFullscreenElement||document.mozFullScreenElement)},onClipsAvailable=function(value){q("#_clipsBtn").style.display="block",q("#_clipsBtn").classList.toggle("disabled",!value)},onTranscodingState=function(state){showHideQualitySelector(state)},onClipsDisabled=function(value){q("#_clipsBtn").style.display="none"},_setStatus=function(value){var s=q(".stream-status-block .status");value?(rootScope.isOnline=!0,s.classList.add("statuslive"),s.textContent="в эфире"):(rootScope.isOnline=!1,s.classList.remove("statuslive"),s.textContent="офлайн",q(".player-block").classList.add("offline"))},onDisplayStatus=function(value){var statusBlock=q(".show-status");statusBlock.classList.add("active"),statusBlock.firstElementChild.textContent=value,clearTimeout(_statusTimeout),_statusTimeout=setTimeout(function(){statusBlock.classList.remove("active")},5e3)}
22,onApiUpdateUser=function(user){user&&user.user_id&&(q(".favorite-wrap").style.display="block"),rootScope.config.get("adult")&&user&&!1===user.subscribed?toggleAdultWarning(!0):(toggleAdultWarning(!1),user&&!0===user.subscribed&&rootScope.config.set("adult",!1))},toggleAdultWarning=function(show){show?(root.classList.add("adult-warning"),q(".stream-title").style.display="none"):(root.classList.remove("adult-warning"),q(".stream-title").style.display="block")},onApiData=function(data,forced){window.DEV_PLAYER&&console.log("PLAYER","view onApiData",data,forced);var announceData=data.broadcast;announceData&&0!==announceData.length&&"online"!==data.channel_status?_showAnnounce(announceData,data.streamer_name):setPoster("online"==data.channel_status?rootScope.config.get("poster"):data.channel_poster),channelTitle=data.channel_title+(data.streamer_name?" от "+data.streamer_name:""),channelLink="/channel/"+data.channel_key+"/",-1!=window.location.href.indexOf("utm_source")&&rootScope.config.set("adult",!1),q(".stream-title").style.display="block",q(".stream-title").addEventListener("click",function(e){window.open(domain+channelLink,"_blank")}),q("#_streamTitle").innerText=data.channel_title,q("#_streamStreamer").innerText=data.streamer_name,_setStatus("online"==data.channel_status);var displayPremium=data.channel_premium?"block":"none";if(rootScope.config.set("adult",data.adult),q(".right-panel .donation").style.display=displayPremium,q("#_qualitySwitch").style.display=displayPremium,q(".premium-wrap").style.display=displayPremium,q(".right-panel .donation").addEventListener("click",function(e){e.preventDefault();var link="https://goodgame.ru/channel/"+data.channel_key+"/support/";window.open(link,"donat","height=450,width=800,location=0,menubar=0,resizable=1,scrollbars=0,status=0")}),q(".player-control.player-in-window").addEventListener("click",function(e){e.preventDefault(),window.open(domain+"/player?"+rootScope.config.get("streamkey"),"player","height=450,width=800,location=0,menubar=0,resizable=1,scrollbars=0,status=0"),eventBus.dispatchEvent(GGPlayer.modules.View.events.STOP),onPlaybackStop()}),q(".right-panel .question").addEventListener("click",function(e){e.preventDefault(),window.open(domain+"/chat/"+data.channel_key+"/","chat","height=750,width=450,location=0,menubar=0,resizable=1,scrollbars=0,status=0")}),data.channel_premium){showHideQualitySelector(!0),q("#_qualitySwitch a[rel=auto]").style.display=_autoquality?"block":"none",q(".premium-wrap").style.display="none",q(".prem-button").style.display="none",rootScope.selectorOnly=!0;var quality=rootScope.config.get("previewmode")?"240":rootScope.config.get("quality");rootScope.isPlaying||eventBus.dispatchEvent(GGPlayer.modules.View.events.QUALITY,quality,!1)}else rootScope.isPlaying||eventBus.dispatchEvent(GGPlayer.modules.View.events.QUALITY,"",!1),q(".player-control.prem-button").style.display="none",showHideQualitySelector(!1);onApiUpdateUser(data.user),-1!=window.location.href.indexOf("utm_source")&&(log("Utm_source - отключаем 18+"),rootScope.config.set("adult",!1));var time=hideAdultWarning.get(rootScope.config.get("streamkey"));window.DEV_PLAYER&&console.log("PLAYER","hideAdultWarning.get",time),data.channel_start<time&&rootScope.config.set("adult",!1),!rootScope.config.get("autoplay")||forced||rootScope.config.get("adult")||(rootScope.windowIsActive?eventBus.dispatchEvent(GGPlayer.modules.View.events.PLAY):rootScope._startLater=!0),setVolume(rootScope.config.get("volume"),rootScope.config.get("muted")),(-1!=gorodChannels.indexOf(data.channel_id)||rootScope.config.get("hidechat"))&&hideRedundantControls()},showHideQualitySelector=function(show){q("#_qualitySwitch").style.display=show?"block":"none"},setPremiumHints=function setPremiumHints(userData){if(premiumSecondsLeft(userData.expire)){if(q("#_qualitySwitch a[rel=premium]").classList.remove("disabled"),!userData.test)return void(q(".player-control.prem-button").style.display="none");_isTestPremium=!0,q(".player-control.prem-button").style.display="block",q(".player-control.prem-button .popup-block.active").classList.remove("active"),q
22('.player-control.prem-button .popup-block[rel="active"]').classList.add("active");var counter=q('.player-control.prem-button b[rel="counter"]'),secondsLeft=premiumSecondsLeft(userData.expire);"undefined"!=typeof UserService&&(UserService.premium=!0),setInterval(function(){secondsLeft-=1;var minutes=Math.floor(secondsLeft/60),seconds=secondsLeft-60*minutes;counter.innerHTML=minutes+":"+_addLeadingZero(seconds)},1e3),clearTimeout(_testPremiumTimout),_testPremiumTimout=setTimeout(function(){setPremiumHints(userData),_isTestPremium&&(setQuality("720"),_isTestPremium=!1)},1e3*secondsLeft)}else q(".player-control.prem-button").style.display="block",q(".player-control.prem-button .popup-block.active").classList.remove("active"),q('.player-control.prem-button .popup-block[rel="try"]').classList.add("active"),q("#_qualitySwitch a[rel=premium]").classList.add("disabled"),"undefined"!=typeof UserService&&(UserService.premium=!1,Utils.rootScope().Reklama.loadData())},_showAnnounce=function(announceData,streamerName){var dateDiff,announceLogo=announceData.broadcast_logo,announceStartTime=announceData.broadcast_start;if(!announceStartTime)return void _hideAnnounceBlock();q(".announce-block .title").innerText=announceData.broadcast_title+" от "+streamerName,q(".announce-block .img-block").setAttribute("style","background: url('"+announceLogo+"') no-repeat; background-size: cover;"),q(".announce-block .blured").setAttribute("style","background: url('"+announceLogo+"') no-repeat; background-size: cover;"),_showAnnounceBlock(),announceTimer=setInterval(function(){dateDiff=getDateDiff("undefined"!=typeof Utils?new Date(Utils.moscowTime()):Date.now(),new Date(announceStartTime.replace(/-/g,"/"))),dateDiff.simple<=0?_hideAnnounceBlock():showAnnounceTime(dateDiff)},1e3),setTimeout(function(){q(".announce-block .timer-block").style.visibility="visible"},1e3)},showAnnounceTime=function(time){q(".timer-block .hours").innerHTML=_addLeadingZero(time.hours+24*time.days),q(".timer-block .minutes").innerHTML=_addLeadingZero(time.minutes),q(".timer-block .seconds").innerHTML=_addLeadingZero(time.seconds)},getDateDiff=function(dateFrom,dateTo){var delta,result={};return result.simple=dateTo-dateFrom,delta=Math.abs(result.simple)/1e3,result.days=Math.floor(delta/86400),delta-=86400*result.days,result.hours=Math.floor(delta/3600)%24,delta-=3600*result.hours,result.minutes=Math.floor(delta/60)%60,delta-=60*result.minutes,result.seconds=Math.floor(delta%60),result},_addLeadingZero=function(number){return number<10&&(number="0"+number),number},_hideAnnounceBlock=function(){q(".announce-block").style.display="none"},_showAnnounceBlock=function(){q(".announce-block").style.display="block"},setVolume=function(vol,muted){muted=muted||0==vol,eventBus.dispatchEvent(GGPlayer.modules.View.events.VOLUME,muted?0:vol),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.VOLUME,muted?0:vol),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.MUTED,muted?1:0),rootScope.config.set("muted",muted?1:0),rootScope.config.set("volume",vol)},onViewersChanged=function(newValue){q("#_viewers").textContent=parseInt(newValue)},onQualityChangeStart=function(newValue){},onQualityAvailable=function(value){_autoquality=!1,q("#_qualitySwitch a[rel=auto]").style.display=value?"block":"none"},onQualityChangeEnd=function(newValue){""==newValue&&(newValue="premium"),quality=newValue;var c=q('a[rel="'+newValue+'"]');q(".quality").textContent=c.getAttribute("data-letter"),q(".quality-block .icon").classList.remove("spin"),_isTestPremium&&"premium"!=newValue&&(log("stop on quality changed"),_isTestPremium=!1)},onMutedChanged=function(newValue){newValue?q(".sound-wrap").classList.add("active"):q(".sound-wrap").classList.remove("active")},onFullscreenChanged=function(newValue){_isFullscreen=newValue,newValue?q(".screen-wrap").classList.add("active"):q(".screen-wrap").classList.remove("active")},onVolumeChanged=function(newValue){q(".slider-wrap .slider-range-value").style.width=100*newValue+"%",q(".slider-wrap .slider-value").style.left=100*newValue+"%"},onPlaybackStart=function(){q("#_bigPlayBtn").style.display="none",_hideAnnounceBlock()},onPlaybackStarted=function(){var v=q("#_video"),p=q("#_poster");q("#_bigPlayBtn").style.display="none","audio"!=quality?(v.classList.add("on"),v.classList.remove("off"),p.classList.remove("on"),p.classList.add("off")):(v.classList.remove("on"),v.classList.add("off"),p.classList.add("on"),p.classList.remove("off")),q(".play-wrap").classList.add("active"),q
22(".player-block").classList.remove("hover"),jQuery(".channel-user-info-block .off").removeClass("off").addClass("on"),_setStatus(!0)},onPlaybackStop=function(){q(".play-wrap").classList.remove("active"),q("#_bigPlayBtn").style.display="block",q(".player-block").classList.add("hover")},onDvrInfo=function(range){return!1},onVideoLoading=function(value){q(".loading-bar").textContent=value<0?"Загружаю":value<100?value+"%":""},onVideoUpdate=function(pos){currentTime=pos},bindButtons=function(){bindPlay(),bindSound(),bindFullscreen(),bindQuality(),bindPremium(),bindTimeline(),bindHotKeys(),bindClips(),bindTheatreMode(),bindFavorite(),bindMouse(),bindTouchDevices()},resizeReset=function(theatre){if(!theatre){var left=document.querySelector(".main-inner-wrap"),right=document.querySelector(".feed-block"),chatBlock=document.querySelector(".chat .chat-container");left.style.right="",right.style.width="",chatBlock.style.width="",right.style.width="",right.classList.remove("closed"),right.classList.remove("close")}},toggleTheatreMode=function(){var body=document.getElementsByTagName("body")[0];body.classList.toggle("theatre"),resizeReset(body.classList.contains("theatre"))},bindTheatreMode=function(){setTimeout(function(){var theatreModeBtn=q("#_theatreMode"),dashTheatreModeBtn=q("#_dashTheatreMode");theatreModeBtn&&theatreModeBtn.addEventListener("click",toggleTheatreMode),dashTheatreModeBtn&&dashTheatreModeBtn.addEventListener("click",toggleTheatreMode)},0)},hideRedundantControls=function(){q(".stream-title").style.display="none",q(".favorite-wrap").style.display="none",q(".favorite-wrap").style.display="none",q(".create-clip-wrap").style.display="none",q(".right-panel").style.display="none"},bindFavorite=function(){var block=q(".favorite-wrap");block.addEventListener("click",function(e){block.classList.contains("on")?(block.classList.remove("on"),eventBus.dispatchEvent(GGPlayer.modules.ApiResolver.events.FAV,0)):(block.classList.add("on"),eventBus.dispatchEvent(GGPlayer.modules.ApiResolver.events.FAV,1,0,1))})},bindPlay=function(){q(".play-wrap .on").addEventListener("click",function(){q(".play-wrap").classList.add("active"),adultWarning(),eventBus.dispatchEvent(GGPlayer.modules.View.events.PLAY)}),q(".play-wrap .off").addEventListener("click",function(){q(".play-wrap").classList.add("active"),eventBus.dispatchEvent(GGPlayer.modules.View.events.STOP),onPlaybackStop()}),q("#_bigPlayBtn").addEventListener("click",function(){adultWarning(),eventBus.dispatchEvent(GGPlayer.modules.View.events.PLAY)}),q("#_warningBtn").addEventListener("click",function(e){e.preventDefault(),adultWarning(),eventBus.dispatchEvent(GGPlayer.modules.View.events.PLAY)})},adultWarning=function(){toggleAdultWarning(!1),rootScope.config.set("adult",!1),hideAdultWarning.set(rootScope.config.get("streamkey"),Date.now())},setMute=function(e){e.preventDefault(),e.stopImmediatePropagation();var newMute=!rootScope.config.get("muted");setVolume(rootScope.config.get("volume")||.5,newMute)},increaseVolume=function(volume){var currentVolume=rootScope.config.get("volume");1!==currentVolume&&setVolume(currentVolume+Math.min(1-currentVolume,volume))},decreaseVolume=function(volume){var currentVolume=rootScope.config.get("volume");0!==currentVolume&&setVolume(currentVolume-Math.min(currentVolume,volume))},bindSound=function(){q(".sound-wrap").addEventListener("click",setMute);var handle=q(".ui-slider-handle"),slider=q(".slider-wrap");handle.ondragstart=function(){return!1},slider.onmousedown=function(e){var moveAt=function(e){var offLeft=slider.getBoundingClientRect().left+20,left=e.clientX-offLeft-handle.offsetWidth/2,vol=Math.max(0,Math.min(85,left))/85;setVolume(vol,0)};moveAt(e),document.onmousemove=function(e){moveAt(e)},document.onmouseup=function(){document.onmousemove=null,handle.onmouseup=null}};var promise=null,mouseWheel=function(event){if(!_isFullscreen)return!0;var e=window.event||event;if(e.preventDefault(),!promise){var delta=(e.wheelDelta||-e.detail||-e.deltaY)>0?1:-1,vol=rootScope.config.get("volume"),newVol=Math.min(1,Math.max(0,vol+delta/25));setVolume(newVol,0),promise=setTimeout(function(){promise=null},15)}},elem=q("#_video");elem.addEventListener("wheel",mouseWheel),elem.addEventListener("DOMMouseScroll",mouseWheel)},bindFullscreen=function(){q(".screen-wrap .on").addEventListener("click",function(){q("#html5player").classList.add("full-screen"),_isInFeed&&document.querySelector(".player").classList.remove("in-feed"),eventBus.dispatchEvent(GGPlayer.modules.View.events.FULLSCREEN)}),q(".screen-wrap .off").addEventListener("click",function(){_isInFeed&&document.querySelector(".player").classList.add("in-feed"),q("#html5player").classList.remove("full-screen"),eventBus.dispatchEvent(GGPlayer.modules.View.events.FULLSCREEN)}),q("#_video").addEventListener("dblclick",function(){eventBus.dispatchEvent(GGPlayer.modules.View.events.FULLSCREEN)}),q(".detach-wrap").addEventListener("click",function(){window.StreamController.showPlayer(root,channelTitle,channelLink),rootScope._detaching=!0,_isInFeed=!0,eventBus.dispatchEvent(GGPlayer.modules.Advert.events.RELOAD),document.querySelector(".channel-name-block .full-size").classList.add("hide"),document.querySelector(".player").classList.add("in-feed")})},bindQuality=function(){q(".quality-wrap .quality-block").addEventListener("click",function(e){q(".quality-wrap").classList.toggle("active")}
22),q(".quality-list a",!0).forEach(function(elem){elem.addEventListener("click",function(e){e.preventDefault();var rel=this.getAttribute("rel");this.classList.contains("disabled")||("premium"!=this.getAttribute("rel")||rootScope.selectorOnly?setQuality(rel):premiumChecker.checkKey(rootScope.apiData.user.premium_key,rootScope.config.get("streamkey"),rootScope.apiData.user.user_id||0,function(result){result&&(rel="",setQuality(rel))}))})})},bindPremium=function(){var premwindow=q(".premium-key"),input=q(".premium-key-input");q(".player-control.prem-button").addEventListener("click",startTestPremium),q(".premium-block a").addEventListener("click",function(e){e.preventDefault(),window.playerCallbacks&&window.playerCallbacks.userClickPremium();try{if(window.parent!==window)var popup=window.parent.PremiumPopup;else var popup=window.PremiumPopup;popup.onSuccess(function(activate,key){activate&&(input.value=key,q(".premium-key .btn").click())}),popup.onStartTest(startTestPremium),popup.open(rootScope.apiData.channel_key,input.value)}catch(e){var link="https://goodgame.ru/payment/buypremium/?channel="+rootScope.apiData.channel_key;window.open(link,"donat","height=450,width=800,location=0,menubar=0,resizable=1,scrollbars=0,status=0")}}),q(".premium-key .close").addEventListener("click",function(e){e.preventDefault(),premwindow.style.display="none"}),q(".premium-key .btn").addEventListener("click",function(e){e.preventDefault(),premiumChecker.checkKey(input.value,rootScope.config.get("streamkey"),rootScope.apiData.user.user_id||0,function(result,all_channels){result?(q(".premium-key .error").style.display="none",q("#_qualitySwitch a[rel=premium]").classList.remove("disabled"),setQuality(""),premwindow.style.display="none"):(premwindow.style.display="block",q(".premium-key .error").style.display="block")})})},setQuality=function(quality){var chars={auto:"A","":"П",720:"В",480:"C",240:"М",audio:"3"};"premium"==quality&&(quality=""),q(".quality").textContent=chars[quality]||"",rootScope.config.set("quality",quality),eventBus.dispatchEvent(GGPlayer.modules.View.events.QUALITY,quality,!0)},startTestPremium=function(){if(!rootScope.apiData.user.user_id)return void(void 0!==window.openLogin?window.openLogin():onDisplayStatus("Чтобы активировать тестовый премиум, вам необходимо залогиниться"));premiumChecker.startTest().then(function(response){if(response.success){var userData={};userData.test=!0,userData.expire=response.expire,setPremiumHints(userData),setQuality(""),_isTestPremium=!0}else if(_isTestPremium&&(setQuality("720"),_isTestPremium=!1),"key_exists"==response.error){var diff=getDateDiff(0,1e3*response.remain);onDisplayStatus("Попробовать еще раз можно через "+diff.minutes+":"+_addLeadingZero(diff.seconds))}else onDisplayStatus("Ошибка "+response.error)})},bindTimeline=function(){q(".timeline .dvrlive").addEventListener("click",function(){eventBus.dispatchEvent(GGPlayer.modules.View.events.SEEKTO,"live")}),q(".values").addEventListener("click",function(e){var offset=(dvrRange.to-dvrRange.from)*(e.clientX/q(".values").offsetWidth),toSeek=dvrRange.from+offset;log("Мотаю на "+Math.round(toSeek)),eventBus.dispatchEvent(GGPlayer.modules.View.events.SEEKTO,toSeek)})},bindHotKeys=function(){document.addEventListener("keydown",onKeyPress)},bindClips=function(){q("#_clipsBtn").addEventListener("click",function(e){return rootScope.apiData.user.user_id||void 0===window.openLogin?!q("#_clipsBtn").classList.contains("disabled")&&void eventBus.dispatchEvent(GGPlayer.modules.View.events.CREATE_CLIP,e):void window.openLogin({
23message:"Чтобы создать клип, нужен аккаунт. Войдите или зарегистрируйтесь, и мы сохраним ваш клип.",eventSource:"auth_source_channel_create_clip"})})},bindMouse=function(){var promise,elem=q(".player-block"),handleHover=function(){elem.classList.add("hover"),promise&&clearTimeout(promise),promise=setTimeout(function(){_isHover(q(".right-panel"))||q("#_qualitySwitch").classList.contains("active")||q(".favorite-wrap").classList.contains("active")||elem.classList.remove("hover")},2e3)},handleLeave=function(){q("#_qualitySwitch").classList.contains("active")||q(".favorite-wrap").classList.contains("active")||elem.classList.remove("hover")};handleHover(),elem.addEventListener("mousemove",handleHover),elem.addEventListener("mouseleave",handleLeave)},_isHover=function(e){return!(!e.querySelector(":hover")&&(!e.parentNode||e.parentNode.querySelector(":hover")!==e&&e.parentNode.querySelector("div:hover")!==e))},bindTouchDevices=function(){var promise,elem=q(".player-block");elem.addEventListener("touchstart",function(e){elem.classList.add("hover"),"block"==q("#_bigPlayBtn").style.display&&(promise&&clearTimeout(promise),promise=setTimeout(function(){elem.classList.remove("hover")},3e3))})},onKeyPress=function(e){if(window.DEV_PLAYER&&console.log("PLAYER","view render","onKeyPress",e),["BODY"===e.target.tagName,"html5player"===e.target.id].some(function(option){return!!option}))switch(e.which){case 32:case 75:q(".play-wrap").classList.contains("active")?(eventBu
23s.dispatchEvent(GGPlayer.modules.View.events.STOP),onPlaybackStop()):(q(".play-wrap").classList.add("active"),eventBus.dispatchEvent(GGPlayer.modules.View.events.PLAY)),e.preventDefault();break;case 39:var delta=2;e.shiftKey&&(delta=.5),e.ctrlKey&&(delta=.1),eventBus.dispatchEvent(GGPlayer.modules.View.events.SEEK,delta),e.preventDefault();break;case 37:var delta=-2;e.shiftKey&&(delta=-.5),e.ctrlKey&&(delta=-.1),eventBus.dispatchEvent(GGPlayer.modules.View.events.SEEK,delta),e.preventDefault();break;case 38:increaseVolume(.2),e.preventDefault();break;case 40:decreaseVolume(.2),e.preventDefault();break;case 70:if(["Alt","AltGraph","Control","Shift","OS","Win","Meta","Super"].some(function(modifier){return e.getModifierState(modifier)}))return;eventBus.dispatchEvent(GGPlayer.modules.View.events.FULLSCREEN),e.preventDefault();break;case 77:setMute(e);break;case 84:_isFullscreen&&e.altKey&&eventBus.dispatchEvent(GGPlayer.modules.View.events.FULLSCREEN)}},setPoster=function(src){if(!src)return!1;q("#_poster").style.backgroundImage="url('"+src.replace("http://","//")+"')"},showNotAvailable=function(){q("#_notAvaliable").style.display="block",navigator.userAgent.toLowerCase().indexOf("firefox")>-1&&(q("#_notAvaliable .ff").style.display="block")},destroy=function(){document.removeEventListener("keydown",onKeyPress),root.innerHTML=cleanInnerHtml},checker=function(premiumKey,streamKey,id,callback){return premiumChecker.checkKey(premiumKey,streamKey,id,function(result,all_channels){result?(q(".premium-key .error").style.display="none",q("#_qualitySwitch a[rel=premium]").classList.remove("disabled"),setQuality(""),callback(!0)):(q(".premium-key .error").style.display="block",callback(!1))})},premiumSecondsLeft=function(date){var dateDiff=getDateDiff(Date.now(),new Date(1e3*date));return dateDiff.simple>0?Math.ceil(dateDiff.simple/1e3):0};return{render:render,setPoster:setPoster,showNotAvailable:showNotAvailable,destroy:destroy,premiumChecker:checker,startTestPremium:startTestPremium}},GGPlayer.modules.View.events={PLAY:"view_play_click",STOP:"view_stop_click",MUTE:"view_mute_click",SEEK:"view_seek_hotkey",SEEKTO:"view_seek_totime",VOLUME:"view_volume_set",STATUS:"view_set_status",QUALITY:"view_quality_set",AUTOQUALITY_AVAILABLE:"auto_quality_available",FULLSCREEN:"view_fullscreen_click",THEATRE_MODE:"view_theatre_mode",DETACH:"view_detach_click",CREATE_CLIP:"view_create_clip"},GGPlayer.modules.Websocket=function(){var sock,eventBus=GGPlayer.models.EventBus.getInstance(),rootScope=GGPlayer.models.RootScope.getInstance(),_bindOnce=!1,pingInterval=!1,waitingPong=!1,streamKey=!1,_testPremiumCallback=!1,init=function(){_bindOnce||_bindEvents();var CHAT=window.CHAT||"chat.goodgame.ru";return sock=new WebSocket((window.WS_SCHEMA||"wss")+"://"+CHAT+"/counter/"),sock.onmessage=_onMessage,sock.onclose=_onClose,pingInterval||(pingInterval=setInterval(ping,3e4)),!0},_bindEvents=function(){eventBus.addEventListener(GGPlayer.modules.Websocket.events.POSTEVENT,onEvent),eventBus.addEventListener(GGPlayer.modules.Websocket.events.STARTTESTPREMIUM,onTestPremium),eventBus.addEventListener(GGPlayer.modules.Websocket.events.STOPTESTPREMIUM,onTestPremiumEnd),eventBus.addEventListener(GGPlayer.modules.Playback.events.PLAYING,onPlaybackStart),eventBus.addEventListener(GGPlayer.modules.Playback.events.STOP,onPlaybackStop),eventBus.addEventListener(GGPlayer.modules.Playback.events.STOPPED,onPlaybackStopped),_bindOnce=!0},onTestPremium=function(callback){_testPremiumCallback=callback,_send("start_test_premium")},onTestPremiumEnd=function(){_testPremiumCallback=!1,_send("stop_test_premium")},setStreamKey=function(value){streamKey=value,getViewers()},onPlaybackStart=function(){var data={};data.channel=streamKey,rootScope.apiData&&rootScope.apiData.user&&(data.userId=rootScope.apiData.user.user_id||""),window.DEV_EVENTS,data.v=2,window.channelCommonInfo&&(data.streamerId=window.channelCommonInfo.streamerId,data.gameId=window.channelCommonInfo.gameId),_sendWithActive("viewing",data)},onPlaybackStop=function(){_sendWithActive("unview",{channel:streamKey})},onPlaybackStopped=function(){_sendWithActive("ping",{channel:streamKey})},ping=function(){if(!sock||1!=sock.readyState)return!1;waitingPong=!0;var data={};return data.channel=streamKey,data.state=rootScope.isPlaying?1:0,_sendWithActive("ping",data),setTimeout(function(){waitingPong&&(console.warn("No pong in 5 seconds. Closing."),_onClose())},3e3),!0},getViewers=function(){_sendWithActive("get_all_viewers",{channel:streamKey})},onEvent=function(eventName,eventData){_send("player_event_3",{name:eventName,data:eventData})},_onMessage=function(event){try{var msg=JSON.parse(event.data)}catch(err){return log(err.toString()),void eventBus.dispatchEvent(GGPlayer.modules.Websocket.events.ERROR,err)}switch(msg.type){case"welcome":streamKey&&getViewers(),streamKey&&rootScope.isPlaying&&onPlaybackStart();break;case"pong":waitingPong=!1;break;case"viewers":rootScope.isOnline&&eventBus.dispatchEvent(GGPlayer.modules.Websocket.events.VIEWERS,msg.data.count);break;
23case"remaining":_testPremiumCallback&&_testPremiumCallback(msg.data),_testPremiumCallback=!1;break;case"commercial":eventBus.dispatchEvent(GGPlayer.modules.Advert.events.SHOW,msg.data)}},_onClose=function(){sock&&(sock.onclose=function(){},sock.close()),console.warn("Websocket closed, reconnecting..."),setTimeout(init,3e3)},startCommercial=function(key,pwd){_send("commercial",{action:"show",key:key,pwd:pwd})},_sendWithActive=function(type,data){data=data||{},data.active=rootScope.isPlaying?1:0,_send(type,data)},_send=function(type,data){if(!sock||1!=sock.readyState)return void log("Cant send websocket "+type);void 0===data&&(data={});try{sock.send(JSON.stringify({type:type,data:data}))}catch(e){console.log(e.toString())}};return{init:init,setStreamKey:setStreamKey,startCommercial:startCommercial,destroy:function(){sock&&(sock.onclose=function(){},sock.close(),sock=null)}}},GGPlayer.modules.Websocket.isAvailable=function(){return!!window.WebSocket},GGPlayer.modules.Websocket.events={ERROR:"websockets_error",VIEWERS:"websockets_viewers",POSTEVENT:"websockets_postevent",STARTTESTPREMIUM:"websockets_start_test_premium",STOPTESTPREMIUM:"websockets_stop_test_premium"},GGPlayer.models.EventBus=function(createNew){if(!createNew&&GGPlayer.models.EventBus._singletonInstance)return GGPlayer.models.EventBus._singletonInstance;GGPlayer.models.EventBus._singletonInstance=this,this.events=[],this.addEventListener=function(eventName,callback){this.events[eventName]||(this.events[eventName]=[]),this.events[eventName].push(callback)},this.addEventListenerUniq=function(eventName,callback){this.events[eventName]||(this.events[eventName]=[]),this.events[eventName]=[callback]},this.dispatchEvent=function(eventName){if(this.events[eventName]&&this.events[eventName].length)for(var i=0;i<this.events[eventName].length;i++)this.events[eventName][i].apply(this,Array.prototype.slice.call(arguments).splice(1))}},GGPlayer.models.EventBus.getInstance=function(createNew){return new GGPlayer.models.EventBus(createNew)},GGPlayer.models.RootScope=function(createNew){if(!createNew&&GGPlayer.models.RootScope._singletonInstance)return GGPlayer.models.RootScope._singletonInstance;GGPlayer.models.RootScope._singletonInstance=this},GGPlayer.models.RootScope.getInstance=function(createNew){return new GGPlayer.models.RootScope(createNew)},GGPlayer.protocols.Dash=function(){var videoSource,audioSource,eventBus=GGPlayer.models.EventBus.getInstance(),rootScope=GGPlayer.models.RootScope.getInstance(),PLAY_SEGMENTS=2,DVR_LIMIT=300,video={},quality=!1,playlist=!1,sourcePath=!1,container=!1,mediaSource=!1,qualitySwitching=!1,qualitySwitchStarted=0,playlistData={},lastLoaded=0,_chunkloading=!1,_xhrQueue=[],_secure=!0,buffer=0,_maxBuffer=0,timer=0,_droppedFrames=0,_lags=0,_loadingProgress=0,_playOnOpen=!1,_retryTimeout=null,_speedAvg={count:0,sum:0},allevents=["play","stalled","suspend","emptied","suspend","waiting","seeking","seeked","ratechange","loadstart","loadeddata","pause","playing","progress","timeupdate","ended","error","abort","canplay"],_createVideoElement=function(){video=document.createElement("video"),video.setAttribute("width","100%"),video.setAttribute("height","100%"),video.setAttribute("webkit-playsinline","webkit-playsinline"),video.setAttribute("playsinline","playsinline"),container.appendChild(video)},_setupMediaSource=function(){MediaSource?mediaSource=new MediaSource:(log("MediaSource not supported"),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.ERROR)),mediaSource.addEventListener("sourceopen",_sourceOpen);var url=URL.createObjectURL(mediaSource);video.src=url},_bindVideoEvents=function(){for(var i=0;i<allevents.length;i++)video.addEventListener(allevents[i],_videoEvent);setInterval(_playListUpdate,1e3),rootScope.config.get("previewmode")||(setInterval(_monitorDroppedFrames,1e3),setInterval(_submitBuffer,3e5))},_submitBuffer=function(){if(rootScope.isPlaying){var data={},speed=_speedAvg.count?(_speedAvg.sum/_speedAvg.count).toFixed(2):0;speed&&!isNaN(speed)&&(data.speed=speed),_speedAvg={count:0,sum:0};var _premium=0;rootScope.apiData.user&&rootScope.apiData.user.premium_key&&(_premium="all"==rootScope.apiData.user.premium_channel?2:1),data.adblock="passed"!=window._ggAdblockDetect,data.premium=_premium,data.delay=rootScope._delay,data.ch=rootScope.channel?rootScope.channel:"",_postEvent("viewing_params",data)}},onApiData=function(data){rootScope.channel=data.channel_id,(_secure=!0)&&log("Использую HTTPS соединение")},_videoEvent=function(e){switch(buffer=video.currentTime?(lastLoaded+playlistData.chunkLe
23ngth)/1e3-video.currentTime:0,("waiting"==e.type||video.buffered.length&&video.buffered.end(video.buffered.length-1)<video.currentTime)&&(++_lags%20||(log("Sending lag event"),_postEvent("lags",{type:"event",value:_lags}))),e.type){case"loadstart":break;case"playing":log(e.type),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.PLAYING),timer&&(_submitBuffer(),log("Время старта: "+((new Date-timer)/1e3).toFixed(3)+"с"),timer=!1);break;case"waiting":log(e.type),_safariFix();break;case"seeked":log("seeked"),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.UPDATE,video.currentTime);break;case"progress":case"timeupdate":eventBus.dispatchEvent(GGPlayer.modules.Playback.events.UPDATE,video.currentTime);break;case"pause":rootScope._detaching?(rootScope._detaching=!1,video.play()):(log("stop on pause"),stop());break;default:log(e.type)}qualitySwitchStarted&&video.currentTime>qualitySwitchStarted/1e3&&(eventBus.dispatchEvent(GGPlayer.modules.Playback.events.QUALITY_CHANGED,quality),qualitySwitchStarted=!1)},_postEvent=function(event,data){data instanceof Object||(data={0:data}),data.server=rootScope.cdnServer?rootScope.cdnServer.ip:"noip",data.server_name=rootScope.cdnServer?rootScope.cdnServer.name:"noname",data.q=quality,eventBus.dispatchEvent(GGPlayer.modules.Websocket.events.POSTEVENT,event,data)},restart=function(){stop(),_cleanup(),play()},_safariFix=function(){video.currentTime&&rootScope.isPlaying&&(log("sf fix"),video.currentTime+=.1)},_cleanup=function(callback){rootScope.isPlaying=!1,playlistData={},lastLoaded=0,video.currentTime=0,buffer=0,_maxBuffer=0,(qualitySwitching||qualitySwitchStarted)&&eventBus.dispatchEvent(GGPlayer.modules.Playback.events.QUALITY_CHANGED,quality),qualitySwitching=!1,qualitySwitchStarted=!1;try{videoSource&&videoSource.removeEventListener("updateend",_finishBufferUpdate),videoSource&&videoSource.abort(),audioSource.abort()}catch(e){log("notice",e.message)}videoSource=!1,audioSource=!1,_cancelXhr(),_setupMediaSource(),"function"==typeof callback&&callback()},destroy=function(){_cleanup(),mediaSource=null,video.remove()},_cancelXhr=function(){for(var i=0;i<_xhrQueue.length;i++)_xhrQueue[i].abort();_xhrQueue=[],_chunkloading=!1},_sourceOpen=function(){eventBus.dispatchEvent(GGPlayer.modules.Playback.events.INIT),_playOnOpen&&(log("_playOnOpened"),play(),_playOnOpen=!1)},_loadPlaylist=function(callback){var file=playlist.substr(sourcePath.length+1);_loadFile(file+"?time="+(Date.now()/1e3).toFixed(0),"text",function(data){qualitySwitching||(_parsePlaylist(data),rootScope._queue=playlistData.segments?playlistData.segments.length:0,!!callback&&callback())})},_playListUpdate=function(){if(!qualitySwitching){if(!rootScope.isPlaying)return!1;if(_retryTimeout)return!1}_loadPlaylist(_playLoop)},_monitorDroppedFrames=function(){if(!video.webkitDroppedFrameCount)return!1;var limit=playlistData.video.fps?playlistData.video.fps/1.5:30;return video.webkitDroppedFrameCount-_droppedFrames>limit&&(buffer<16?(log("! Слишком много дропов, увеличиваю задержку на 1s","total="+video.webkitDroppedFrameCount,"d="+(video.webkitDroppedFrameCount-_droppedFrames)),video.currentTime-=1):log("Dropped frames","total="+video.webkitDroppedFrameCount,"d="+(video.webkitDroppedFrameCount-_droppedFrames)),_postEvent("dropped_frames",{value:video.webkitDroppedFrameCount-_droppedFrames})),_droppedFrames=video.webkitDroppedFrameCount,!0},_loadInit=function(callback){if(videoSource)return void callback();var _initLoaded=0,_VBufferCallback=!1,_ABufferCallback=!1,loaded=function(){2!=++_initLoaded&&"audio"!=quality||(callback(),audioSource.removeEventListener("updateend",_ABufferCallback),"audio"!=quality&&videoSource.removeEventListener("updateend",_VBufferCallback))};try{"audio"!=quality&&(videoSource=mediaSource.addSourceBuffer(playlistData.video.mtype+';codecs="'+playlistData.video.codec+'"'),_loadFile(playlistData.video.initFile,function(bytes){videoSource&&(_VBufferCallback=loaded.bind(self),videoSource.addEventListener("updateend",_VBufferCallback),_appendBuffer(videoSource,bytes))})),audioSource=mediaSource.addSourceBuffer(playlistData.audio.mtype+';
23codecs="'+playlistData.audio.codec+'"'),_loadFile(playlistData.audio.initFile,function(bytes){audioSource&&(_ABufferCallback=loaded.bind(self),audioSource.addEventListener("updateend",_ABufferCallback),_appendBuffer(audioSource,bytes))})}catch(e){log("Error",e.toString()),restart()}},_appendBuffer=function _appendBuffer(source,bytes){if(!source)return!1;if(source.updating)return log("Source updating!!"),void setTimeout(function(){_appendBuffer(source,bytes)},10);qualitySwitching&&log("Пишу в буфер во время смены качества!");var ret=!1;try{ret=source.appendBuffer(bytes)}catch(e){log("Error",e.toString()),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.ERROR,{action:"restart"})}return ret},_parsePlaylist=function(data){var data=(new DOMParser).parseFromString(data,"text/xml");try{var rep=data.querySelectorAll("Representation"),segTemplateV=rep[0].querySelector("SegmentTemplate"),segTemplateA=rep[1].querySelector("SegmentTemplate"),segs=segTemplateV.querySelectorAll("S"),added=[];playlistData.startTime||(playlistData.startTime=data.querySelector("MPD").getAttribute("availabilityStartTime")),"0"==segs[0].getAttribute("t")&&playlistData.startTime<data.querySelector("MPD").getAttribute("availabilityStartTime")&&(log("Стоп-старт! Начинаем все с начала"),playlistData={},restart());for(var i=0;i<segs.length;i++){var s=parseInt(segs[i].getAttribute("t"));playlistData.chunkLength=parseInt(segs[i].getAttribute("d")),playlistData.segments||(playlistData.segments=[]),-1==playlistData.segments.indexOf(s)&&s>lastLoaded&&(playlistData.segments.push(s),added.push(s)),playlistData._lastSegment=s}playlistData.video={mtype:rep[0].getAttribute("mimeType"),codec:rep[0].getAttribute("codecs"),initFile:segTemplateV.getAttribute("initialization"),fps:rep[0].getAttribute("frameRate")},playlistData.audio={mtype:rep[1].getAttribute("mimeType"),codec:rep[1].getAttribute("codecs"),initFile:segTemplateA.getAttribute("initialization")}}catch(er){return void log(er.toString())}return playlistData},_loadFile=function _loadFile(file,type,callback,ntry){var _tmpQualy=quality,qdir=quality?"_"+("audio"==quality?"720":quality):"",path=(_secure?"https://":"http://")+sourcePath+qdir+"/";if("function"==typeof type&&(callback=type,type="arraybuffer"),(ntry=void 0===ntry?0:ntry)>10)return void(!rootScope.isPlaying||-1==file.indexOf(".m4v")&&-1==file.indexOf(".mpd")||eventBus.dispatchEvent(GGPlayer.modules.Playback.events.ERROR,{action:"restart"}));if(""!==file){var xhr=new XMLHttpRequest,speedChecker=Date.now();xhr.open("GET",path+file,!0),xhr.responseType=type||"arraybuffer",xhr.timeout="arraybuffer"==xhr.responseType?2e4:1e4,xhr.send(),_xhrQueue.push(xhr),xhr.onreadystatechange=function(event){if(4==this.readyState&&this.response){if(speedChecker&&-1!=file.indexOf("m4v")&&-1==file.indexOf("init")){var timeStamp=event.timeStamp>2e12?event.timeStamp/1e3:event.timeStamp,time=(timeStamp-speedChecker)/1e3,bytes=this.response.byteLength/1024,speed=8*bytes/time/1024;_speedAvg.sum+=speed,_speedAvg.count+=1,rootScope._speed=speed.toFixed(2)}if(_tmpQualy!=quality)return log(_tmpQualy+"!="+quality+" "+file),restart(),!1;if(clearTimeout(_retryTimeout),_retryTimeout=null,rootScope.cdnServer=getEgdeIp(this.getAllResponseHeaders()),-1==_xhrQueue.indexOf(this))return void log("xhr canceled!");
23200==this.status?callback(this.response):this.onerror();try{delete this.response}catch(e){}this.onreadystatechange=null,this.onerror=null,_xhrQueue.splice(_xhrQueue.indexOf(this),1)}},xhr.onprogress=function(event){-1!=file.indexOf("m4v")&&-1==file.indexOf("init")&&(_loadingProgress=(event.loaded/event.total*100).toFixed(0),(buffer<=.2||100==_loadingProgress)&&eventBus.dispatchEvent(GGPlayer.modules.Playback.events.LOADING,_loadingProgress))},xhr.onerror=function(e){log(ntry+" Ошибка загрузки "+path+file,this.statusText),rootScope.config.get("previewmode")||(rootScope.isPlaying||"text"!=type?(log(ntry+" Ошибка загрузки "+path+file,this.statusText),clearTimeout(_retryTimeout),_retryTimeout=setTimeout(function(){_loadFile(file,type,callback,++ntry)},200)):(clearTimeout(_retryTimeout),_retryTimeout=setTimeout(function(){_loadFile(file,type,callback,0)},5e3)),this.onreadystatechange=null,this.onerror=null)},xhr.ontimeout=function(e){log("Таймаут загрузки "+path+file),_postEvent("lags",{type:"timeout",file:file}),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.ERROR,{action:"restart"})},xhr=null}},getEgdeIp=function(headers){for(var server={name:"noname",ip:"noip"},all=headers.split("\r\n"),i=0;i<all.length;i++){var d=all[i].split(": ");"X-EDGE-IP"==d[0]&&(server.ip=d[1]),"X-EDGE-FQDN"==d[0]&&(server.name=d[1])}return server},_finishBufferUpdate=function(){if(!rootScope.isPlaying)return!1;video.currentTime<=0&&lastLoaded&&(log("starting"),video.currentTime=lastLoaded/1e3,video.play()),cleanupBufferedRange();var range=_getAvailableRange();return eventBus.dispatchEvent(GGPlayer.modules.Playback.events.DVRINFO,range),_maxBuffer=video.currentTime?Math.round(range.to-video.currentTime):0,rootScope._delay=((playlistData._lastSegment+2*playlistData.chunkLength-1e3*video.currentTime)/1e3).toFixed(2),_playLoop(),!0},cleanupBufferedRange=function(all){var saveLimit=!1;all&&(console.warn("Cleaning all buffers..."),saveLimit=DVR_LIMIT,DVR_LIMIT=2);var range=_getAvailableRange();if(range.to-range.from<=DVR_LIMIT)return!1;try{videoSource&&videoSource.remove(0,range.to-DVR_LIMIT),audioSource&&audioSource.remove(0,range.to-DVR_LIMIT)}catch(e){}saveLimit&&(DVR_LIMIT=saveLimit)},onError=function(e){log("Fatal error"),e.action&&"restart"==e.action&&(log("Restarting"),restart())},_getAvailableRange=function(){var source="audio"==quality?audioSource:videoSource;return{from:source.buffered.start(0),to:source.buffered.end(source.buffered.length-1)}},_playLoop=function _playLoop(){if(qualitySwitching)return log("Грузим инит, пока нельзя чанки грузить"),!1;if(_chunkloading)return!1;if(playlistData.segments.length>10)return log("Слишком длинная очередь загрузки - рестартим"),_postEvent("too_long_queue",{}),void restart();var file=playlistData.segments.shift();if(file){if(file<=lastLoaded)return void _playLoop();video.currentTime&&file-lastLoaded>playlistData.chunkLength&&log("q:"+(quality||"prem"),"d:"+(file-lastLoaded)),"audio"!=quality&&(videoSource&&(_chunkloading=+new Date),_loadFile(file+".m4v",function(bytes){if(lastLoaded=file,qualitySwitching)return _chunkloading=!1,!1;_chunkloading&&_checkSpeed(+new Date-_chunkloading,bytes.byteLength),_chunkloading=!1,_appendBuffer(videoSource,bytes)})),_loadFile(file+".m4a",function(bytes){if(lastLoaded=file,qualitySwitching)return!1;_appendBuffer(audioSource,bytes)})}},_checkSpeed=function(time,size){if(time>playlistData.chunkLength){var speed=(8*size/time).toFixed(2);log("Низкая скорость доставки!",time+" мс"," - ",speed+" kbps")}},setupVideo=function(element){container=element,_createVideoElement(),_setupMediaSource(),_bindVideoEvents()},setPlaylist=function(url){playlist=url.replace(/https?:\/\//,""),sourcePath=playlist.replace(/^(.+)\/([^\/]+)/,"$1")},play=function(){if("open"!=mediaSource.readyState)return _playOnOpen=!0,!1;PLAY_SEGMENTS=rootScope.config.get("PLAY_SEGMENTS")||PLAY_SEGMENTS,-1!=navigator.userAgent.toLowerCase().indexOf("android")&&(video.webkitEnterFullScreen(),video.play()),timer=+new Date,eventBus.dispatchEvent(GGPlayer.modules.Playback.events.PLAY),video.currentTime&&_cleanup(),_loadPlaylist(function(){eventBus.dispatchEvent(GGPlayer.modules.Playback.events.LOADING,0),log("Видео",playlistData.video.mtype,playlistData.video.codec),log("Аудио",playlistData.audio.mtype,playlistData.audio.codec),log("Воспроизводим сегментов: "+PLAY_SEGMENTS),playlistData.segments=playlistData.segments.slice(-PLAY_SEGMENTS),_loadInit(function(){rootScope.isPlaying=!0,("audio"!=quality?videoSource:audioSource).addEventListener("update",_finishBufferUpdate),_playLoop()})})},stop=function(callback){rootScope.isPlaying=!1,video.pause(),callback||eventBus.dispatchEvent(GGPlayer.modules.Playback.events.STOPPED)},setFullscreen=function(){var elem=rootScope.config.get("container");document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement?(document.exitFullscreen?document.exitFullscreen():document.msExitFullscreen?document.msExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen(),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.FULLSCREEN,!1)):(elem.requestFullscreen?elem.requestFullscreen():elem.msRequestFullscreen?elem.msRequestFullscreen():elem.mozRequestFullScreen?elem.mozRequestFullScreen():elem.webkitRequestFullscreen&&elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.FULLSCREEN,!0))},setVolume=function(value){video.volume=value},setSeek=function(value){var range=_getAvailableRange(),toSeek=Math.max(range.from,Math.min(range.to,video.currentTime+value));video.currentTime=toSeek,eventBus.dispatchEvent(GGPlayer.modules.Playback.events.UPDATE,toSeek),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.DVRINFO,range)},setSeekToTime=function(value){var range=_getAvailableRange(),toSeek="live"==value?range.to-1:Math.max(range.from,Math.min(range.to-1,value));toSeek<video.currentTime&&_postEvent("seek_time",{d:range.to-toSeek}),video.currentTime=toSeek,eventBus.dispatchEvent(GGPlayer.modules.Playback.events.UPDATE,toSeek),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.DVRINFO,range)},setQuality=function(q,startPlay){quality=q,qualitySwitching=!0,eventBus.dispatchEvent(GGPlayer.modules.Playback.events.QUALITY,q),rootScope.isPlaying?restart():(qualitySwitching=!1,eventBus.dispatchEvent(GGPlayer.modules.Playback.events.QUALITY_CHANGED,quality),startPlay&&play())};return function(){eventBus.addEventListener(GGPlayer.modules.View.events.PLAY,play),eventBus.addEventListener(GGPlayer.modules.View.events.STOP,stop),eventBus.addEventListener(GGPlayer.modules.View.events.QUALITY,setQuality),eventBus.addEventListener(GGPlayer.modules.View.events.FULLSCREEN,setFullscreen),eventBus.addEventListener(GGPlayer.modules.View.events.VOLUME,setVolume),eventBus.addEventListener(GGPlayer.modules.View.events.SEEK,setSeek),eventBus.addEventListener(GGPlayer.modules.View.events.SEEKTO,setSeekToTime),eventBus.addEventListener(GGPlayer.modules.Playback.events.ERROR,onError),eventBus.addEventListener(GGPlayer.modules.ApiResolver.events.DATA,onApiData),navigator.userAgent.toLowerCase().indexOf("firefox")>-1&&PLAY_SEGMENTS<2&&(log("Firefox - играем два сегмента"),PLAY_SEGMENTS=2),rootScope.playlistData=playlistData,rootScope.canAudioOnly=!0}(),{setupVideo:setupVideo,setPlaylist:setPlaylist,setQuality:setQuality,setVolume:setVolume,play:play,stop:stop,destroy:destroy}},GGPlayer.protocols.Dash.isAvailable=function(){try{return!(-1!=navigator.userAgent.indexOf("YaBrowser")||!MediaSource||Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0)}catch(e){}return!1},GGPlayer.modules.Playback={},GGPlayer.modules.Playback.events={INIT:"playback_init_complete",PLAY:"playback_play_start",PLAYING:"playback_playing",UPDATE:"playback_update",LOADING:"playback_loading",STOPPED:"playback_stopped",ENDED:"playback_ended",MUTED:"playback_muted",VOLUME:"playback_volume_set",QUALITY:"playback_quality_set",QUALITY_CHANGED:"playback_quality_changed",FULLSCREEN:"playback_fullscreen_click",ERROR:"playback_error",DVRINFO:"playback_dvr_info",CLEANBUFFERS:"playback_clear_buffers",APPEND_DATA:"playback_append_data",APPEND_INIT_DATA:"playback_append_init_data",APPEND_FRAG_DATA:"playback_append_frag_data"},GGPlayer.protocols.HLS=function(){var container,video,quality,src,_volume,_promisePlay,_promiseQuality,eventBus=GGPlayer.models.EventBus.getInstance(),_createVideoElement=(GGPlayer.models.RootScope.getInstance(),function(){_setupCallbacks();var elem=document.createElement("div");elem.setAttribute("id","ggPlayerFlashContent"),container.appendChild(elem)}),loadFlash=function(smilFile){var flashvars={src:smilFile},params={};params.quality="high",params.wmode="opaque",params.allowscriptaccess="always",params.allowfullscreen="true",params.bgcolor="000000";var attributes={};attributes.id="hlsModule",attributes.name="hlsModule",attributes.align="middle",swfobject.embedSWF("/files/PlaybackModule.swf?time="+ +new Date,"ggPlayerFlashContent","100%","100%","0.0.0","",flashvars,params,attributes,onFlashLoaded)},onFlashLoaded=function(data){video=data.ref},onInitComplete=function(){video.volume(_volume),_promiseQuality&&(video.quality(_promiseQuality),_promiseQuality=!1),_promisePlay&&play()},_setupCallbacks=function(){window.player=function(){var obj={};return obj.inited=function(){onInitComplete()},obj.updatePlaybackState=function(state){console.warn("updatePlaybackState",state),"playing"==state.toLocaleStr
23ing()&&eventBus.dispatchEvent(GGPlayer.modules.Playback.events.PLAYING),"idle"==state.toLocaleString()&&eventBus.dispatchEvent(GGPlayer.modules.Playback.events.STOPPED)},obj}()},setupVideo=function(element){container=element,_createVideoElement()},play=function(){video&&video.start?(eventBus.dispatchEvent(GGPlayer.modules.Playback.events.PLAY),video.start(),_promisePlay=!1):_promisePlay=!0},stop=function(callback){video.stop(),callback||eventBus.dispatchEvent(GGPlayer.modules.Playback.events.STOPPED)},_setVolume=function(value){video&&video.volume&&video.volume(value),_volume=value},setFullscreen=function(){document.webkitFullscreenElement?(video.webkitExitFullscreen(),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.FULLSCREEN,!1)):(video.webkitEnterFullscreen(),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.FULLSCREEN,!0))},setVolume=function(value){_setVolume(value)},setQuality=function(q,startPlay){if(quality!=q){eventBus.dispatchEvent(GGPlayer.modules.Playback.events.QUALITY,q),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.QUALITY_CHANGED,q),quality=q;var quas={"":"premium",720:"high",480:"medium",240:"low",audio:"medium"};video&&video.quality?(video.quality(quas[q]),_promiseQuality=!1):_promiseQuality=quas[q],startPlay&&play()}},setPlaylist=function(file){log("setPlaylist"),file&&(src=file.replace(/.+dash\/(.+)\/index.+/,"$1")),loadFlash("http://hls.goodgame.ru/hls/"+src+".smil")};return function(){eventBus.addEventListener(GGPlayer.modules.View.events.PLAY,play),eventBus.addEventListener(GGPlayer.modules.View.events.STOP,stop),eventBus.addEventListener(GGPlayer.modules.View.events.QUALITY,setQuality),eventBus.addEventListener(GGPlayer.modules.View.events.FULLSCREEN,setFullscreen),eventBus.addEventListener(GGPlayer.modules.View.events.VOLUME,setVolume)}(),{setupVideo:setupVideo,setPlaylist:setPlaylist,setQuality:setQuality,setVolume:setVolume,play:play,stop:stop}},GGPlayer.protocols.HLS.isAvailable=function(){return!0},GGPlayer.protocols.GGWs=function(){var video,ws,container,sourceBuffer,quality,mediaSource,eventBus=GGPlayer.models.EventBus.getInstance(),rootScope=GGPlayer.models.RootScope.getInstance(),monitor=GGPlayer.modules.Monitoring.getInstance(),bufferQueue=new Uint8Array(0),_lags=0,_seeked=0,qualityChanging=!1,checkBufferTimer=0,_started=!1,_restartTimer=0,MAX_BUFFER=2,allevents=["play","stalled","suspend","emptied","suspend","waiting","seeking","seeked","ratechange","loadstart","loadeddata","pause","playing","progress","timeupdate","ended","error","abort","canplay"],setSeek=function(value){try{var range=_getAvailableRange()}catch(e){return!1}rootScope.isPlaying=!1;var toSeek=Math.max(range.from,Math.min(range.to,video.currentTime+value));video.currentTime=toSeek,_seeked=toSeek<range.to-2,eventBus.dispatchEvent(GGPlayer.modules.Playback.events.UPDATE,toSeek),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.DVRINFO,range)},_getAvailableRange=function(){var source=video;return{from:source.buffered.start(0),to:source.buffered.end(source.buffered.length-1)}},_createVideoElement=function(){video=document.createElement("video"),video.setAttribute("width","100%"),video.setAttribute("height","100%"),video.setAttribute("webkit-playsinline","webkit-playsinline"),video.setAttribute("playsinline","playsinline"),container.appendChild(video);for(var i=0;i<allevents.length;i++)video.addEventListener(allevents[i],_videoEvent);setInterval(_submitBuffer,3e5)},_submitBuffer=function(){var data={};data.ch=rootScope.apiData.channel_id,data.streamer_id=rootScope.apiData.streamer_id||0,_postEvent("viewing_params",data),monitor.postEvent(GGPlayer.modules.Monitoring.events.WS_VIEWING_PARAMS,data)},_postEvent=function(event,data){data instanceof Object||(data={0:data}),data.server="5",data.server_name="ggws",data.q=quality,
24eventBus.dispatchEvent(GGPlayer.modules.Websocket.events.POSTEVENT,event,data)},_videoEvent=function(e){switch(e.type){case"loadstart":break;case"playing":log(e.type),_submitBuffer(),_started=!0,rootScope.isPlaying=!0,clearTimeout(_restartTimer),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.PLAYING),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.LOADING,100);break;
24case"waiting":eventBus.dispatchEvent(GGPlayer.modules.Playback.events.LOADING,-1),_started&&(MAX_BUFFER=Math.min(MAX_BUFFER+.5,5),log("Buffer increased:",MAX_BUFFER,"s"),monitor.postEvent(GGPlayer.modules.Monitoring.events.WS_VIDEO_WAITING,{started:_started,maxbufer:MAX_BUFFER}));case"stalled":if(log(e.type),0==video.currentTime||!_started||!rootScope.isPlaying)return;_lags+="stalled"==e.type?10:1,_lags>=10&&(log("Sending lag event"),_postEvent("lags",{type:"ggws"}),monitor.postEvent(GGPlayer.modules.Monitoring.events.WS_VIDEO_STALLED,{lags:_lags}),_lags=0),clearTimeout(_restartTimer),_restartTimer=setTimeout(function(){_started&&rootScope.isPlaying&&(log("Fired restart timer"),restart())},5e3);break;case"progress":case"timeupdate":eventBus.dispatchEvent(GGPlayer.modules.Playback.events.UPDATE,video.currentTime);break;case"pause":qualityChanging||(log("stop on pause"),stop());break;default:log(e.type)}},buffer=function(){return video.buffered.length?video.buffered.end(video.buffered.length-1)-video.currentTime:0},wsConnect=function(channel){ws&&(ws.close(),ws=null),ws=new WebSocket("wss://ggws.goodgame.ru:1443/"+channel),ws.binaryType="arraybuffer",ws.onopen=function(){wsSend("hello")},ws.onerror=function(error){monitor.postEvent(GGPlayer.modules.Monitoring.events.WS_CONNECT_ERROR,{error:error})},ws.onmessage=onWsHelloMessage},onWsHelloMessage=function(){wsSend("change",{quality:rootScope.config.get("streamkey")+quality}),ws.onmessage=onWsMessage},_appendBuffer=function(buffer1,buffer2){var tmp=new Uint8Array(buffer1.byteLength+buffer2.byteLength);return tmp.set(buffer1,0),tmp.set(buffer2,buffer1.byteLength),tmp},waitForStart=function(){setTimeout(function(){onWsHelloMessage()},5e3)},parseResponse=function(json){var data=JSON.parse(json);log(data.error),"Stream not found"==data.error&&waitForStart(),"Stream ended"==data.error&&(rootScope.isPlaying=!1,eventBus.dispatchEvent(GGPlayer.modules.Playback.events.STOPPED),waitForStart())},lastMessage=0,onWsMessage=function(event){if("string"==typeof event.data)return void parseResponse(event.data);var data=new Uint8Array(event.data);lastMessage&&Date.now()-lastMessage>1e3&&log("slow req:",Date.now()-lastMessage,"ms"),lastMessage=Date.now(),bufferQueue=0==bufferQueue.byteLength?data:_appendBuffer(bufferQueue,data),sourceBuffer.updating||(sourceBuffer.appendBuffer(bufferQueue),bufferQueue=new Uint8Array(0)),video.paused&&(eventBus.dispatchEvent(GGPlayer.modules.Playback.events.PLAY),rootScope.isPlaying=!0,qualityChanging=!1,video.play())},checkBuffer=function(){checkBufferTimer=1;var isFF=navigator.userAgent.toLowerCase().indexOf("firefox")>-1,ffFix=isFF?2:0,_buffer=buffer().toFixed(2);if(video.buffered.length&&(!_seeked&&_buffer>MAX_BUFFER+ffFix||0==video.currentTime)){log("Buffer",_buffer,"ffFix",ffFix);var start=video.buffered.start(0),end=video.buffered.end(video.buffered.length-1),to=0;(to=end-start<.5?start:end-.5)-ffFix>start&&(log("Seeking to ",to-ffFix,end),video.currentTime=to-ffFix)}setTimeout(function(){checkBufferTimer=0},1e3)},wsSend=function(cmd,data){var send=data||{};send.url="stream/"+cmd,send.version="0.0.1",ws.send(JSON.stringify(send))},setupVideo=function(element){container=element,_createVideoElement()},_setupMediaSource=function(){MediaSource?mediaSource=new MediaSource:(log("MediaSource not supported"),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.ERROR)),mediaSource.addEventListener("sourceopen",_sourceOpen),mediaSource.addEventListener("error",function(e){monitor.postEvent(GGPlayer.modules.Monitoring.events.WS_MEDIA_ERROR,{error:e}),console.log(e),restart()}),video.src=URL.createObjectURL(mediaSource)},_sourceOpen=function(){sourceBuffer=mediaSource.addSourceBuffer('video/mp4; codecs="avc1.424020, mp4a.40.2"'),sourceBuffer.addEventListener("updateend",sourceBufferUpdateEnd),sourceBuffer.addEventListener("error",function(e){console.log(e),monitor.postEvent(GGPlayer.modules.Monitoring.events.WS_MEDIA_ERROR,{error:e}),restart()})},sourceBufferUpdateEnd=function(){checkBufferTimer&&0!=video.currentTime||checkBuffer()},setPlaylist=function(file){log("setPlaylist")},play=function(){_setupMediaSource(),wsConnect(rootScope.config.get("streamkey"))},stop=function(){ws&&(ws.close(),ws=null),rootScope.isPlaying=!1,video.pause(),_seeked=!1,_started=!1},setQuality=function(q,startPlay){var _q=q;"audio"==q&&(_q="480"),"auto"==q&&(_q=""),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.QUALITY,q),quality=_q?"_"+_q:"",rootScope.isPlaying?(qualityChanging=!0,restart()):(eventBus.dispatchEvent(GGPlayer.modules.Playback.events.QUALITY_CHANGED,q),startPlay&&play())},restart=function(){MAX_BUFFER=1,stop(),play()},setVolume=function(value){video.volume=value},setFullscreen=function(){var elem=rootScope.config.get("container");document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement?(document.exitFullscreen?document.exitFullscreen():document.msExitFullscreen?document.msExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen(),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.FULLSCREEN,!1)):(elem.requestFullscreen?elem.requestFullscreen():elem.msRequestFullscreen?elem.msRequestFullscreen():elem.mozRequestFullScreen?elem.mozRequestFullScreen():elem.webkitRequestFullscreen&&elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.FULLSCREEN,!0))},destroy=function(){stop()};return function(){eventBus.addEventListener(GGPlayer.modules.View.events.PLAY,play),eventBus.addEventListener(GGPlayer.modules.View.events.STOP,stop),eventBus.addEventListener(GGPlayer.modules.View.events.QUALITY,setQuality),eventBus.addEventListener(GGPlayer.modules.View.events.FULLSCREEN,setFullscreen),eventBus.addEventListener(GGPlayer.modules.View.events.VOLUME,setVolume),eventBus.addEventListener(GGPlayer.modules.View.events.SEEK,setSeek),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.AUTOQUALITY_AVAILABLE,!1)}(),{setupVideo:setupVideo,setPlaylist:setPlaylist,setQuality:setQuality,setVolume:setVolume,play:play,stop:stop,destroy:destroy}};var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();GGPlayer.protocols.hlsjs=function(){var container,video,candy,buffer,hls,src,quality,mediaUrl,_lastFrag,intervalSpeed,restartTimeout,speedMonitor,eventBus=GGPlayer.models.EventBus.getInstance(),rootScope=GGPlayer.models.RootScope.getInstance(),trDetector=new GGPlayer.modules.HlsTranscodingDetector,monitor=GGPlayer.modules.Monitoring.getInstance(),playerQuality2Hls=null,CustomPlaylistLoader=function(){function CustomPlaylistLoader(config){_classCallCheck(this,CustomPlaylistLoader),this.loader=new Hls.DefaultConfig.loader(config)}
24return _createClass(CustomPlaylistLoader,[{key:"load",value:function(context,config,callbacks){!context.url.includes("?")&&getParams&&(context.url+="?"+getParams),window.DEV_PLAYER&&log("[pLoader] Loading:",context.url),this.loader.load(context,config,callbacks)}},{key:"abort",value:function(){this.loader.abort()}},{key:"destroy",value:function(){this.loader.destroy()}}]),CustomPlaylistLoader}(),_fragDuration=0,_loadingProgress=0,_speedAvg={count:0,sum:0},autoPlay=!1,getParams="",allevents=["play","stalled","suspend","emptied","suspend","waiting","seeking","seeked","ratechange","loadstart","loadeddata","pause","playing","progress","timeupdate","ended","error","abort","canplay"],onApiData=function(data){if(window.DEV_PLAYER&&console.log("hlsjs::onApiData",data),data&&data.sources)return setPlaylist(null,null,data.sources),void __play();autoPlay&&(autoPlay=!1,__play())},onTranscodingState=function(state){state||""==quality||setQuality("",rootScope.isPlaying)},_setupHls=function(){var config={};config.liveSyncDurationCount=3,config.startFragPrefetch=!0,config.autoStartLoad=!1,config.debug=window.DEV_PLAYER||!1,config.manifestLoadingMaxRetry=18e3,config.manifestLoadingRetryDelay=5e3,config.manifestLoadingMaxRetryTimeout=5e3,config.levelLoadingMaxRetry=18e3,config.levelLoadingRetryDelay=5e3,config.levelLoadingMaxRetryTimeout=2e3,config.maxBufferHole=0,config.lowLatencyMode=!0,window.DEV_PLAYER&&console.log("PLAYER","_setupHls",config);var isCandy=!1;if(isCandy=window.CANDY_FORCE?"on"==window.CANDY_FORCE||"off"!=window.CANDY_FORCE&&"undefined"!=typeof __isCandy&&__isCandy(src,quality,rootScope.apiData||{}):"undefined"!=typeof __isCandy&&__isCandy(src,quality,rootScope.apiData||{}),log("Candy: ",isCandy,"/ force: ",window.CANDY_FORCE),isCandy){config.liveSyncDurationCount=4;var clientId=322;try{5==(rootScope&&rootScope.apiData&&rootScope.apiData.channel_id)?clientId=323:rootScope&&rootScope.apiData&&rootScope.apiData.hidden?clientId=322:rootScope.apiData&&rootScope.apiData.viewers&&rootScope.apiData.viewers>5&&(clientId=324)}catch(e){console.log("Candy clientId exception",e),log("Candy clientId exception",e),clientId=322}log("Candy clientId = ",clientId);var comment="?";try{comment=rootScope&&rootScope.apiData.streamer_name}catch(e){console.log("CandyCommentError",e)}var data={};data.label=comment,data.video=video,data.clientId=clientId,data.streamKey=src,data.swarm={peersLimit:10};try{candy&&candy.config&&candy.config.streamKey!==data.streamKey&&(candy.destroy(),candy=null),candy||(candy=new Candy(data)),config.fLoader=candy.hlsJsLoader()}catch(e){var _log="?";_log=e.stack?e.stack:e.message?e.message:e.toString?e.toString():e,window.ggLog&&window.ggLog(_log)}}config.pLoader=CustomPlaylistLoader,config.xhrSetup=function(xhr,url){xhr.addEventListener("readystatechange",function(event){2===this.readyState&&(rootScope.cdnServer=getEgdeIp(this.getAllResponseHeaders()))})},hls&&hls.destroy(),hls=new Hls(config),playerQuality2Hls=new GGPlayerModulesHlsPlayerQuality2Hls(hls),speedMonitor&&speedMonitor.destroy(),speedMonitor=new GGPlayer.modules.HLSSpeedMonitor(hls,monitor),window.DEV_PLAYER&&(window.playerHls=hls),_bindHlsEvents(),hls.attachMedia(video),clearInterval(intervalSpeed),intervalSpeed=setInterval(function(){return rootScope._speed=(hls.bandwidthEstimate/1024/1024).toFixed(3)},1500)},_bindHlsEvents=function(){var _currentBuffer=0,_lastBufferCheck=0;hls.on("hlsManifestParsed",function(event){hls.startLoad(),video.play().catch(function(e){return console.log(e.message),eventBus.dispatchEvent(GGPlayer.modules.View.events.VOLUME,0),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.VOLUME,0),video.play()})}),hls.on(Hls.Events.LEVEL_UPDATED,function(event,data){_lastFrag=data.details.endSN;var totalDuration=0;data.details.fragments.forEach(function(fragment){totalDuration+=fragment.duration}),_fragDuration=totalDuration/data.details.fragments.length*1e3}),hls.on(Hls.Events.ERROR,function(event,data){if(rootScope.isPlaying&&video.currentTime>30&&"bufferStalledError"==data.details)return log("sending lag event"),monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_BUFFER_STALLED_ERROR,{data:data,src:src,quality:quality}),void _postEvent("lags",{type:"hlsjs",lagver2:1,speed:rootScope._speed,loaded:_loadingProgress});
24switch(data.type){case Hls.ErrorTypes.NETWORK_ERROR:monitor.postAfterStatusCheck(function(){return monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_NETWORK_ERROR,{error:data,src:src,quality:quality})})();break;case Hls.ErrorTypes.MEDIA_ERROR:monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_MEDIA_ERROR,{error:data,src:src,quality:quality});break;case Hls.ErrorTypes.OTHER_ERROR:monitor.postAfterStatusCheck(function(){return monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_OTHER_ERROR,{error:data,src:src,quality:quality})})()}if(data.fatal){var timeout="networkError"===data.type&&data.response&&404===data.response.code?5e3:500;return monitor.postAfterStatusCheck(function(){return monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_FATAL_ERROR,{error:data,src:src,quality:quality,restartIn:timeout})})(),restartTimeout&&clearTimeout(restartTimeout),restartTimeout=setTimeout(restart,timeout)}}),hls.on(Hls.Events.FRAG_LOADING,function(event,data){_loadingProgress=0,_currentBuffer<.5&&monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_BUFFER_CRITICAL,{bufferLength:_currentBuffer,currentTime:video.currentTime,fragmentLevel:data.frag.level,fragmentSN:data.frag.sn,src:src,quality:quality})}),hls.on(Hls.Events.FRAG_LOAD_PROGRESS,function(event,data){window.DEV_PLAYER&&console.log("PLAYER","HLS FRAG_LOAD_PROGRESS",data.stats),_loadingProgress=(data.stats.loaded/data.stats.total*100).toFixed(0),console.log("123 intervalId FRAG_LOAD_PROGRESS"),(buffer<=.2||100==_loadingProgress)&&eventBus.dispatchEvent(GGPlayer.modules.Playback.events.LOADING,_loadingProgress)}),hls.on(Hls.Events.FRAG_BUFFERED,function(event,data){for(var videoBuffer={currentTime:video.currentTime,bufferLength:0,targetDuration:data.frag.duration,fragDuration:data.frag.duration,timeToLoad:data.stats.loading.end-data.stats.loading.start,bandwidth:Math.round(8*data.stats.total/(data.stats.buffering.end-data.stats.loading.start))},i=0;i<video.buffered.length;i++){var start=video.buffered.start(i),end=video.buffered.end(i);if(video.currentTime>=start&&video.currentTime<=end){videoBuffer.bufferLength=end-video.currentTime;break}}(_currentBuffer=videoBuffer.bufferLength)<2&&monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_BUFFER_LOW,{bufferLength:_currentBuffer,currentTime:video.currentTime,bandwidth:videoBuffer.bandwidth,targetDuration:videoBuffer.targetDuration,timeToLoad:videoBuffer.timeToLoad,src:src,quality:quality});var now=Date.now();now-_lastBufferCheck>=12e4&&(_lastBufferCheck=now,monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_BUFFER_UPDATE,videoBuffer))}),hls.on(Hls.Events.BUFFER_APPENDING_ERROR,function(event,data){monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_BUFFER_APPEND_ERROR,{type:data.type,start:data.start,end:data.end,error:data.error,src:src,quality:quality})});var lastEventTimestamp=0;hls.on(Hls.Events.FRAG_LOADED,function(event,data){rootScope.isPlaying=!0;var networkDetails=data.networkDetails;if(networkDetails&&networkDetails.getAllResponseHeaders){var allHeaders=networkDetails.getAllResponseHeaders(),headers={};allHeaders.trim().split(/[\r\n]+/).forEach(function(line){var parts=line.split(": "),header=parts.shift(),value=parts.join(": ");header&&(headers[header.toLowerCase()]=value)}),monitor.saveLastHeaders(headers)}else console.warn("No networkDetails or unable to get response headers");var currentTime=Date.now();if(currentTime-lastEventTimestamp>=12e4){lastEventTimestamp=currentTime;var safeData={sn:data.frag&&data.frag.sn,level:data.frag&&data.frag.level,bitrate:data.frag&&data.frag.bitrate,duration:data.frag&&data.frag.duration,size:data.stats&&data.stats.total,loadTime:data.stats?data.stats.tload-data.stats.trequest:void 0,src:src,quality:quality,part:data.part||void 0,payloadSize:data.payload?data.payload.byteLength:void 0,networkDetails:{responseURL:data.networkDetails&&data.networkDetails.responseURL,url:data.networkDetails&&data.networkDetails.url,status:data.networkDetails&&data.networkDetails.status}};monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_FRAG_LOADED,safeData)}})},_createVideoElement=function(){video=document.createElement("video"),video.setAttribute("width","100%"),video.setAttribute("height","100%"),video.setAttribute("webkit-playsinline","webkit-playsinline"),video.setAttribute("playsinline","playsinline"),container.appendChild(video)},_bindVideoEvents=function(){for(var i=0;i<allevents.length;i++)video.addEventListener(allevents[i],_videoEvent);setInterval(_submitBuffer,3e5)},_videoEvent=function(e){switch(buffer=video.currentTime&&video.buffered.length?Math.round(video.buffered.end(video.buffered.length-1)-video.currentTime):0,rootScope.isPlaying=video&&!video.paused,e.type){case"waiting":case"stalled":for(var duration=video.duration,networkState=video.networkState,readyState=video.readyState,bufferedRanges=[],i=0;i<video.buffered.length;i++)bufferedRanges.push({start:video.buffered.start(i),end:video.buffered.end(i)});var networkStateDescriptions={0:"NETWORK_EMPTY",1:"NETWORK_IDLE",2:"NETWORK_LOADING",3:"NETWORK_NO_SOURCE"},readyStateDescriptions={0:"HAVE_NOTHING",1:"HAVE_METADATA",2:"HAVE_CURRENT_DATA",3:"HAVE_FUTURE_DATA",4:"HAVE_ENOUGH_DATA"},eventMetrics={src:src,quality:quality,duration:duration,networkState:networkState,networkStateDescription:networkStateDescriptions[networkState]||"Unknown",readyState:readyState,readyStateDescription:readyStateDescriptions[readyState]||"Unknown",bufferedRanges:bufferedRanges},eventMap={waiting:GGPlayer.modules.Monitoring.events.HLS_VIDEO_WAITING,stalled:GGPlayer.modules.Monitoring.events.HLS_VIDEO_STALLED};if("waiting"===e.type&&bufferedRanges.length>0){var lastBufferedEnd=bufferedRanges[bufferedRanges.length-1].end;eventMetrics.bufferTime=lastBufferedEnd-video.currentTime}monitor.postEvent(eventMap[e.type],eventMetrics);break;
24case"playing":eventBus.dispatchEvent(GGPlayer.modules.Playback.events.PLAYING);try{ym(11385799,"reachGoal","stream_start")}catch(e){}_submitBuffer(!0);break;case"progress":case"timeupdate":eventBus.dispatchEvent(GGPlayer.modules.Playback.events.UPDATE,video.currentTime);break;case"pause":rootScope._detaching?(rootScope._detaching=!1,video.play()):(log("stop on pause"),stop());break;default:log(e.type)}},restart=function(){stop(),play()},setupVideo=function(element){container=element||container,_createVideoElement(),_bindVideoEvents()},play=function(){rootScope.apiData?__play():autoPlay=!0},__play=function(){try{_setupHls(),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.PLAY),hls.loadSource(mediaUrl),playerQuality2Hls&&playerQuality2Hls.changeLevel(quality)}catch(e){window.ggLog&&window.ggLog(e)}},stop=function(callback){hls&&hls.stopLoad(),video.pause(),rootScope.isPlaying=!1,callback||eventBus.dispatchEvent(GGPlayer.modules.Playback.events.STOPPED)},setFullscreen=function(){var elem=rootScope.config.get("container");document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement?(document.exitFullscreen?document.exitFullscreen():document.msExitFullscreen?document.msExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen(),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.FULLSCREEN,!1)):(elem.requestFullscreen?elem.requestFullscreen({navigationUI:"hide"}):elem.msRequestFullscreen?elem.msRequestFullscreen():elem.mozRequestFullScreen?elem.mozRequestFullScreen():elem.webkitRequestFullscreen&&elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.FULLSCREEN,!0))},setVolume=function(value){video.volume=value,video.muted=0==value},setQuality=function(q,startPlay){window.DEV_PLAYER&&console.log("setQuality",q,startPlay),quality=q,eventBus.dispatchEvent(GGPlayer.modules.Playback.events.QUALITY,q),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.QUALITY_CHANGED,q),startPlay&&hls?playerQuality2Hls?(playerQuality2Hls.changeLevel(quality),video.style.visibility="audio"==quality?"hidden":"visible"):hls.currentLevel=-1:restart()},setPlaylist=function(file,streamkey,sources){return window.DEV_PLAYER,sources&&(sources.master||sources.source)?(mediaUrl=sources.master||sources.source,getParams=_getQueryParams(mediaUrl),src=streamkey||(window.DEV_HLS?mediaUrl.replace("https://speedtest.goodgame.ru/manifest/","").replace("https://speedtest.goodgame.ru/hls/").match(/^[^\_]+/,"")[0]:mediaUrl.replace("https://hls.goodgame.ru/manifest/","").replace("https://hls.goodgame.ru/hls/").match(/^[^\_]+/,"")[0]),mediaUrl):(src=null,file&&(src=file.replace(/.+dash\/(.+)\/index.+/,"$1")),void 0===quality&&(quality=""),video.style.visibility="audio"==quality?"hidden":"visible",mediaUrl=window.DEV_HLS?"https://speedtest.goodgame.ru/manifest/"+src+"_master.m3u8":"https://hls.goodgame.ru/manifest/"+src+"_master.m3u8",getParams=_getQueryParams(mediaUrl),mediaUrl)},_submitBuffer=function(noSpeed){if(!video.paused){var data={},speed=_speedAvg.count?(_speedAvg.sum/_speedAvg.count).toFixed(2):0;noSpeed||!speed||isNaN(speed)||(data.speed=speed),_speedAvg={count:0,sum:0};var _premium=0;rootScope.apiData.user&&rootScope.apiData.user.premium_key&&(_premium="all"==rootScope.apiData.user.premium_channel?2:1),data.adblock="passed"!=window._ggAdblockDetect,data.premium=_premium,data.ch=rootScope.apiData.channel_id,data.streamer_id=rootScope.apiData.streamer_id||0,_postEvent("viewing_params",data),monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_VIEWING_PARAMS,data)}},_postEvent=function(event,data){data instanceof Object||(data={0:data}),data.server=rootScope.cdnServer?rootScope.cdnServer.ip:"noip",data.server_name=rootScope.cdnServer?rootScope.cdnServer.name:"noname",data.q=quality,window.DEV&&console.log("_postEvent",event,data),eventBus.dispatchEvent(GGPlayer.modules.Websocket.events.POSTEVENT,event,data)},getEgdeIp=function(headers){for(var server={name:"noname",ip:"noip"},all=headers.split("\r\n"),i=0;i<all.length;i++){var d=all[i].split(": ");"X-EDGE-IP"==d[0].toUpperCase()&&(server.ip=d[1]),"X-EDGE-FQDN"==d[0].toUpperCase()&&(server.name=d[1])}return server},setSeek=function(value){try{var range=_getAvailableRange()}catch(e){return!1}rootScope.isPlaying=!1;var toSeek=Math.max(range.from,Math.min(range.to,video.currentTime+value));video.currentTime=toSeek,eventBus.dispatchEvent(GGPlayer.modules.Playback.events.UPDATE,toSeek),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.DVRINFO,range)},_getAvailableRange=function(){var source=video;return{from:source.buffered.start(0),to:source.buffered.end(source.buffered.length-1)}}
24,destroy=function(){hls&&(window.DEV&&console.log("hls destroy"),hls.destroy()),candy&&(candy.destroy(),candy=null),trDetector&&trDetector.destroy(),intervalSpeed&&clearInterval(intervalSpeed),playerQuality2Hls&&(playerQuality2Hls=null),restartTimeout&&clearTimeout(restartTimeout),speedMonitor&&speedMonitor.destroy()},clean=function(){},_getQueryParams=function(url){return url.split("?")[1]||""};return function(){eventBus.addEventListener(GGPlayer.modules.View.events.PLAY,play),eventBus.addEventListener(GGPlayer.modules.View.events.STOP,stop),eventBus.addEventListener(GGPlayer.modules.View.events.QUALITY,setQuality),eventBus.addEventListener(GGPlayer.modules.View.events.FULLSCREEN,setFullscreen),eventBus.addEventListener(GGPlayer.modules.View.events.VOLUME,setVolume),eventBus.addEventListener(GGPlayer.modules.View.events.SEEK,setSeek),eventBus.addEventListener(GGPlayer.modules.ApiResolver.events.DATA,onApiData),eventBus.addEventListener(GGPlayer.modules.HlsTranscodingDetector.events.TRANSCODING_STATE,onTranscodingState)}(),{setupVideo:setupVideo,setPlaylist:setPlaylist,setQuality:setQuality,setVolume:setVolume,play:play,stop:stop,destroy:destroy,clean:clean}},GGPlayer.protocols.hlsjs.isAvailable=function(){try{return Hls.isSupported()}catch(e){}return!1};var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();GGPlayer.protocols.hlsjsll=function(){var container,video,candy,buffer,hls,src,quality,mediaUrl,_lastFrag,intervalSpeed,restartTimeout,speedMonitor,eventBus=GGPlayer.models.EventBus.getInstance(),rootScope=GGPlayer.models.RootScope.getInstance(),trDetector=new GGPlayer.modules.HlsTranscodingDetector,monitor=GGPlayer.modules.Monitoring.getInstance(),playerQuality2Hls=null,CustomPlaylistLoader=function(){function CustomPlaylistLoader(config){_classCallCheck(this,CustomPlaylistLoader),this.loader=new Hls.DefaultConfig.loader(config)}return _createClass(CustomPlaylistLoader,[{key:"load",value:function(context,config,callbacks){!context.url.includes("?")&&getParams&&(context.url+="?"+getParams),window.DEV_PLAYER&&log("[pLoader] Loading:",context.url),this.loader.load(context,config,callbacks)}},{key:"abort",value:function(){this.loader.abort()}},{key:"destroy",value:function(){this.loader.destroy()}}]),CustomPlaylistLoader}(),_fragDuration=0,_loadingProgress=0,_speedAvg={count:0,sum:0},autoPlay=!1,getParams="",allevents=["play","stalled","suspend","emptied","suspend","waiting","seeking","seeked","ratechange","loadstart","loadeddata","pause","playing","progress","timeupdate","ended","error","abort","canplay"],onApiData=function(data){if(window.DEV_PLAYER&&console.log("hlsjsll::onApiData",data),data&&data.sources)return setPlaylist(null,null,data.sources),void __play();autoPlay&&(autoPlay=!1,__play())},onTranscodingState=function(state){state||""==quality||setQuality("",rootScope.isPlaying)},_setupHls=function(){var config={};window.ggPlayerConfigLL?config=window.ggPlayerConfigLL:(config.liveSyncDurationCount=1.5,config.liveMaxLatencyDurationCount=4,config.maxLiveSyncPlaybackRate=1.2,config.startFragPrefetch=!0,config.autoStartLoad=!1,config.maxBufferHole=.1,config.backBufferLength=30,config.manifestLoadingMaxRetry=10,config.manifestLoadingRetryDelay=2e3,config.levelLoadingMaxRetry=20,config.levelLoadingRetryDelay=1e3,config.levelLoadingMaxRetryTimeout=1e3,config.lowLatencyMode=!0,config.debug=window.DEV_PLAYER||!1),console.log("PLAYER","_setupHls",config),config.pLoader=CustomPlaylistLoader,config.xhrSetup=function(xhr,url){xhr.addEventListener("readystatechange",function(event){2===this.readyState&&(rootScope.cdnServer=getEgdeIp(this.getAllResponseHeaders()))})},hls&&hls.destroy(),hls=new Hls(config),playerQuality2Hls=new GGPlayerModulesHlsPlayerQuality2Hls(hls),speedMonitor&&speedMonitor.destroy(),speedMonitor=new GGPlayer.modules.HLSSpeedMonitor(hls,monitor),window.playerHls=hls,_bindHlsEvents(),hls.attachMedia(video),clearInterval(intervalSpeed),intervalSpeed=setInterval(function(){return rootScope._speed=(hls.bandwidthEstimate/1024/1024).toFixed(3)},1500)},_bindHlsEvents=function(){var _currentBuffer=0,_lastBufferCheck=0;
24hls.on("hlsManifestParsed",function(event){hls.startLoad(),video.play().catch(function(e){return console.log(e.message),eventBus.dispatchEvent(GGPlayer.modules.View.events.VOLUME,0),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.VOLUME,0),video.play()})}),hls.on(Hls.Events.LEVEL_UPDATED,function(event,data){_lastFrag=data.details.endSN;var totalDuration=0;data.details.fragments.forEach(function(fragment){totalDuration+=fragment.duration}),_fragDuration=totalDuration/data.details.fragments.length*1e3}),hls.on(Hls.Events.ERROR,function(event,data){if(rootScope.isPlaying&&video.currentTime>30&&"bufferStalledError"==data.details)return log("sending lag event"),monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_BUFFER_STALLED_ERROR,{data:data,src:src,quality:quality}),void _postEvent("lags",{type:"hlsjs",lagver2:1,speed:rootScope._speed,loaded:_loadingProgress});switch(data.type){case Hls.ErrorTypes.NETWORK_ERROR:monitor.postAfterStatusCheck(function(){return monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_NETWORK_ERROR,{error:data,src:src,quality:quality})})();break;case Hls.ErrorTypes.MEDIA_ERROR:monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_MEDIA_ERROR,{error:data,src:src,quality:quality});break;case Hls.ErrorTypes.OTHER_ERROR:monitor.postAfterStatusCheck(function(){return monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_OTHER_ERROR,{error:data,src:src,quality:quality})})()}if(data.fatal){var timeout="networkError"===data.type&&data.response&&404===data.response.code?5e3:500;return monitor.postAfterStatusCheck(function(){return monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_FATAL_ERROR,{error:data,src:src,quality:quality,restartIn:timeout})})(),restartTimeout&&clearTimeout(restartTimeout),restartTimeout=setTimeout(restart,timeout)}}),hls.on(Hls.Events.FRAG_LOADING,function(event,data){_loadingProgress=0,_currentBuffer<.5&&monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_BUFFER_CRITICAL,{bufferLength:_currentBuffer,currentTime:video.currentTime,fragmentLevel:data.frag.level,fragmentSN:data.frag.sn,src:src,quality:quality})}),hls.on(Hls.Events.FRAG_LOAD_PROGRESS,function(event,data){window.DEV_PLAYER&&console.log("PLAYER","HLS FRAG_LOAD_PROGRESS",data.stats),_loadingProgress=(data.stats.loaded/data.stats.total*100).toFixed(0),console.log("123 intervalId FRAG_LOAD_PROGRESS"),(buffer<=.2||100==_loadingProgress)&&eventBus.dispatchEvent(GGPlayer.modules.Playback.events.LOADING,_loadingProgress)}),hls.on(Hls.Events.FRAG_BUFFERED,function(event,data){for(var videoBuffer={currentTime:video.currentTime,bufferLength:0,targetDuration:data.frag.duration,fragDuration:data.frag.duration,timeToLoad:data.stats.loading.end-data.stats.loading.start,bandwidth:Math.round(8*data.stats.total/(data.stats.buffering.end-data.stats.loading.start))},i=0;i<video.buffered.length;i++){var start=video.buffered.start(i),end=video.buffered.end(i);if(video.currentTime>=start&&video.currentTime<=end){videoBuffer.bufferLength=end-video.currentTime;break}}(_currentBuffer=videoBuffer.bufferLength)<2&&monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_BUFFER_LOW,{bufferLength:_currentBuffer,currentTime:video.currentTime,bandwidth:videoBuffer.bandwidth,targetDuration:videoBuffer.targetDuration,timeToLoad:videoBuffer.timeToLoad,src:src,quality:quality});var now=Date.now();now-_lastBufferCheck>=12e4&&(_lastBufferCheck=now,monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_BUFFER_UPDATE,videoBuffer))}),hls.on(Hls.Events.BUFFER_APPENDING_ERROR,function(event,data){monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_BUFFER_APPEND_ERROR,{type:data.type,start:data.start,end:data.end,error:data.error,src:src,quality:quality})});var lastEventTimestamp=0;hls.on(Hls.Events.FRAG_LOADED,function(event,data){rootScope.isPlaying=!0;var networkDetails=data.networkDetails;if(networkDetails&&networkDetails.getAllResponseHeaders){var allHeaders=networkDetails.getAllResponseHeaders(),headers={};allHeaders.trim().split(/[\r\n]+/).forEach(function(line){var parts=line.split(": "),header=parts.shift(),value=parts.join(": ");header&&(headers[header.toLowerCase()]=value)}),monitor.saveLastHeaders(headers)}else console.warn("No networkDetails or unable to get response headers");
24var currentTime=Date.now();if(currentTime-lastEventTimestamp>=12e4){lastEventTimestamp=currentTime;var safeData={sn:data.frag&&data.frag.sn,level:data.frag&&data.frag.level,bitrate:data.frag&&data.frag.bitrate,duration:data.frag&&data.frag.duration,size:data.stats&&data.stats.total,loadTime:data.stats?data.stats.tload-data.stats.trequest:void 0,src:src,quality:quality,part:data.part||void 0,payloadSize:data.payload?data.payload.byteLength:void 0,networkDetails:{responseURL:data.networkDetails&&data.networkDetails.responseURL,url:data.networkDetails&&data.networkDetails.url,status:data.networkDetails&&data.networkDetails.status}}
25;monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_FRAG_LOADED,safeData)}})},_createVideoElement=function(){video=document.createElement("video"),video.setAttribute("width","100%"),video.setAttribute("height","100%"),video.setAttribute("webkit-playsinline","webkit-playsinline"),video.setAttribute("playsinline","playsinline"),container.appendChild(video)},_bindVideoEvents=function(){for(var i=0;i<allevents.length;i++)video.addEventListener(allevents[i],_videoEvent);setInterval(_submitBuffer,3e5)},_videoEvent=function(e){switch(buffer=video.currentTime&&video.buffered.length?Math.round(video.buffered.end(video.buffered.length-1)-video.currentTime):0,rootScope.isPlaying=video&&!video.paused,e.type){case"waiting":case"stalled":for(var duration=video.duration,networkState=video.networkState,readyState=video.readyState,bufferedRanges=[],i=0;i<video.buffered.length;i++)bufferedRanges.push({start:video.buffered.start(i),end:video.buffered.end(i)});var networkStateDescriptions={0:"NETWORK_EMPTY",1:"NETWORK_IDLE",2:"NETWORK_LOADING",3:"NETWORK_NO_SOURCE"},readyStateDescriptions={0:"HAVE_NOTHING",1:"HAVE_METADATA",2:"HAVE_CURRENT_DATA",3:"HAVE_FUTURE_DATA",4:"HAVE_ENOUGH_DATA"},eventMetrics={src:src,quality:quality,duration:duration,networkState:networkState,networkStateDescription:networkStateDescriptions[networkState]||"Unknown",readyState:readyState,readyStateDescription:readyStateDescriptions[readyState]||"Unknown",bufferedRanges:bufferedRanges},eventMap={waiting:GGPlayer.modules.Monitoring.events.HLS_VIDEO_WAITING,stalled:GGPlayer.modules.Monitoring.events.HLS_VIDEO_STALLED};if("waiting"===e.type&&bufferedRanges.length>0){var lastBufferedEnd=bufferedRanges[bufferedRanges.length-1].end;eventMetrics.bufferTime=lastBufferedEnd-video.currentTime}monitor.postEvent(eventMap[e.type],eventMetrics);break;case"playing":eventBus.dispatchEvent(GGPlayer.modules.Playback.events.PLAYING);try{ym(11385799,"reachGoal","stream_start")}catch(e){}_submitBuffer(!0);break;case"progress":case"timeupdate":eventBus.dispatchEvent(GGPlayer.modules.Playback.events.UPDATE,video.currentTime);break;case"pause":rootScope._detaching?(rootScope._detaching=!1,video.play()):(log("stop on pause"),stop());break;default:log(e.type)}},restart=function(){stop(),play()},setupVideo=function(element){container=element||container,_createVideoElement(),_bindVideoEvents()},play=function(){rootScope.apiData?__play():autoPlay=!0},__play=function(){try{_setupHls(),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.PLAY),hls.loadSource(mediaUrl),playerQuality2Hls&&playerQuality2Hls.changeLevel(quality)}catch(e){window.ggLog&&window.ggLog(e)}},stop=function(callback){hls&&hls.stopLoad(),video.pause(),rootScope.isPlaying=!1,callback||eventBus.dispatchEvent(GGPlayer.modules.Playback.events.STOPPED)},setFullscreen=function(){var elem=rootScope.config.get("container");document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement?(document.exitFullscreen?document.exitFullscreen():document.msExitFullscreen?document.msExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen(),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.FULLSCREEN,!1)):(elem.requestFullscreen?elem.requestFullscreen({navigationUI:"hide"}):elem.msRequestFullscreen?elem.msRequestFullscreen():elem.mozRequestFullScreen?elem.mozRequestFullScreen():elem.webkitRequestFullscreen&&elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.FULLSCREEN,!0))},setVolume=function(value){video.volume=value,video.muted=0==value},setQuality=function(q,startPlay){window.DEV_PLAYER&&console.log("setQuality",q,startPlay),quality=q,eventBus.dispatchEvent(GGPlayer.modules.Playback.events.QUALITY,q),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.QUALITY_CHANGED,q),startPlay&&hls?playerQuality2Hls?(playerQuality2Hls.changeLevel(quality),video.style.visibility="audio"==quality?"hidden":"visible"):hls.currentLevel=-1:restart()},setPlaylist=function(file,streamkey,sources){return window.DEV_PLAYER,sources&&(sources.master||sources.source)?(mediaUrl=sources.master||sources.source,getParams=_getQueryParams(mediaUrl),src=streamkey||(window.DEV_HLS?mediaUrl.replace("https://speedtest.goodgame.ru/manifest/","").replace("https://speedtest.goodgame.ru/hls/").match(/^[^\_]+/,"")[0]:mediaUrl.replace("https://hls.goodgame.ru/manifest/","").replace("https://hls.goodgame.ru/hls/").match(/^[^\_]+/,"")[0]),mediaUrl):(src=null,file&&(src=file.replace(/.+dash\/(.+)\/index.+/,"$1")),void 0===quality&&(quality=""),video.style.visibility="audio"==quality?"hidden":"visible",mediaUrl=window.DEV_HLS?"https://speedtest.goodgame.ru/manifest/"+src+"_master.m3u8":"https://hls.goodgame.ru/manifest/"+src+"_master.m3u8",getParams=_getQueryParams(mediaUrl),mediaUrl)},_submitBuffer=function(noSpeed){if(!video.paused){var data={},speed=_speedAvg.count?(_speedAvg.sum/_speedAvg.count).toFixed(2):0;noSpeed||!speed||isNaN(speed)||(data.speed=speed),_speedAvg={count:0,sum:0};var _premium=0;rootScope.apiData.user&&rootScope.apiData.user.premium_key&&(_premium="all"==rootScope.apiData.user.premium_channel?2:1),data.adblock="passed"!=window._ggAdblockDetect,data.premium=_premium,data.ch=rootScope.apiData.channel_id,data.streamer_id=rootScope.apiData.streamer_id||0,_postEvent("viewing_params",data),monitor.postEvent(GGPlayer.modules.Monitoring.events.HLS_VIEWING_PARAMS,data)}},_postEvent=function(event,data){data instanceof Object||(data={0:data}),data.server=rootScope.cdnServer?rootScope.cdnServer.ip:"noip",data.server_name=rootScope.cdnServer?rootScope.cdnServer.name:"noname",data.q=quality,window.DEV&&
25console.log("_postEvent",event,data),eventBus.dispatchEvent(GGPlayer.modules.Websocket.events.POSTEVENT,event,data)},getEgdeIp=function(headers){for(var server={name:"noname",ip:"noip"},all=headers.split("\r\n"),i=0;i<all.length;i++){var d=all[i].split(": ");"X-EDGE-IP"==d[0].toUpperCase()&&(server.ip=d[1]),"X-EDGE-FQDN"==d[0].toUpperCase()&&(server.name=d[1])}return server},setSeek=function(value){try{var range=_getAvailableRange()}catch(e){return!1}rootScope.isPlaying=!1;var toSeek=Math.max(range.from,Math.min(range.to,video.currentTime+value));video.currentTime=toSeek,eventBus.dispatchEvent(GGPlayer.modules.Playback.events.UPDATE,toSeek),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.DVRINFO,range)},_getAvailableRange=function(){var source=video;return{from:source.buffered.start(0),to:source.buffered.end(source.buffered.length-1)}},destroy=function(){hls&&(window.DEV&&console.log("hls destroy"),hls.destroy()),candy&&(candy.destroy(),candy=null),trDetector&&trDetector.destroy(),intervalSpeed&&clearInterval(intervalSpeed),playerQuality2Hls&&(playerQuality2Hls=null),restartTimeout&&clearTimeout(restartTimeout),speedMonitor&&speedMonitor.destroy()},clean=function(){},_getQueryParams=function(url){return url.split("?")[1]||""};return function(){eventBus.addEventListener(GGPlayer.modules.View.events.PLAY,play),eventBus.addEventListener(GGPlayer.modules.View.events.STOP,stop),eventBus.addEventListener(GGPlayer.modules.View.events.QUALITY,setQuality),eventBus.addEventListener(GGPlayer.modules.View.events.FULLSCREEN,setFullscreen),eventBus.addEventListener(GGPlayer.modules.View.events.VOLUME,setVolume),eventBus.addEventListener(GGPlayer.modules.View.events.SEEK,setSeek),eventBus.addEventListener(GGPlayer.modules.ApiResolver.events.DATA,onApiData),eventBus.addEventListener(GGPlayer.modules.HlsTranscodingDetector.events.TRANSCODING_STATE,onTranscodingState)}(),{setupVideo:setupVideo,setPlaylist:setPlaylist,setQuality:setQuality,setVolume:setVolume,play:play,stop:stop,destroy:destroy,clean:clean}},GGPlayer.protocols.hlsjs.isAvailable=function(){try{return Hls.isSupported()}catch(e){}return!1},GGPlayer.protocols.iOS=function(){var video,container,src,buffer,_maxBuffer,quality,_sources,eventBus=GGPlayer.models.EventBus.getInstance(),rootScope=GGPlayer.models.RootScope.getInstance(),allevents=["play","stalled","suspend","emptied","suspend","waiting","seeking","seeked","ratechange","loadstart","loadeddata","pause","playing","progress","timeupdate","ended","error","abort","canplay"],_createVideoElement=function(){video=document.createElement("video"),video.setAttribute("width","100%"),video.setAttribute("height","100%"),video.setAttribute("webkit-playsinline","webkit-playsinline"),video.setAttribute("playsinline","playsinline"),container.appendChild(video)},_bindVideoEvents=function(){for(var i=0;i<allevents.length;i++)video.addEventListener(allevents[i],_videoEvent)},_videoEvent=function(e){switch(buffer=video.currentTime&&video.buffered.length?Math.round(video.buffered.end(video.buffered.length-1)-video.currentTime):0,buffer>_maxBuffer&&(_maxBuffer=buffer),e.type){case"playing":eventBus.dispatchEvent(GGPlayer.modules.Playback.events.PLAYING);break;case"progress":case"timeupdate":eventBus.dispatchEvent(GGPlayer.modules.Playback.events.UPDATE,video.currentTime);break;default:log(e.type)}},_getAvailableRange=function(){var source="audio"==quality?audioSource:videoSource;return{from:source.buffered.start(0),to:source.buffered.end(source.buffered.length-1)-playlistData.chunkLength*PLAY_SEGMENTS/1e3}},setupVideo=function(element){container=element,_createVideoElement(),_bindVideoEvents()},play=function(){eventBus.dispatchEvent(GGPlayer.modules.Playback.events.PLAY),video.play()},stop=function(callback){video.pause(),callback||eventBus.dispatchEvent(GGPlayer.modules.Playback.events.STOPPED)},setFullscreen=function(){var elem=rootScope.config.get("container");void 0!==elem.webkitRequestFullScreen?document.webkitIsFullScreen?(document.webkitCancelFullScreen(),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.FULLSCREEN,!1)):(elem.webkitRequestFullScreen(),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.FULLSCREEN,!0)):document.webkitFullscreenElement?(video.webkitExitFullscreen(),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.FULLSCREEN,!1)):(video.webkitEnterFullscreen(),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.FULLSCREEN,!0))},setVolume=function(value){video.volume=value},setSeek=function(value){var range=_getAvailableRange(),toSeek=Math.max(range.from,Math.min(range.to,video.currentTime+value));video.currentTime=toSeek,eventBus.dispatchEvent(GGPlayer.modules.Playback.events.UPDATE,toSeek),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.DVRINFO,range)},setSeekToTime=function(value){var range=_getAvailableRange(),toSeek="live"==value?range.to:Math.max(range.from,Math.min(range.to,value));toSeek<video.currentTime&&_postEvent("seek_time",{d:range.to-toSeek}),video.currentTime=toSeek,eventBus.dispatchEvent(GGPlayer.modules.Playback.events.UPDATE,toSeek),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.DVRINFO,range)},setQuality=function(q,startPlay){quality=q,setPlaylist(),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.QUALITY,q),eventBus.dispatchEvent(GGPlayer.modules.Playback.events.QUALITY_CHANGED,q),startPlay&&play()},setPlaylist=function(file,streamkey,sources){if(window.DEV_PLAYER,log("setPlaylist"),sources&&(sources.master||sources.source))return _sources=sources,void(quality&&sources[quality]?video.src=sources[quality]:video.src=sources.source);file&&(src=file.replace(/.+dash\/(.+)\/index.+/,"$1")),void 0!==quality&&(!src&&_sources?quality&&_sources[quality]?video.src=_sources[quality]:video.src=_sources.source:video.src="https://hls.goodgame.ru/hls/"+src+(""==quality?"":"_"+quality)+".m3u8")};return function(){eventBus.addEventListener(GGPlayer.modules.View.events.PLAY,play),eventBus.addEventListener(GGPlayer.modules.View.events.STOP,stop),eventBus.addEventListener(GGPlayer.modules.View.events.QUALITY,setQuality),eventBus.addEventListener(GGPlayer.modules.View.events.FULLSCREEN,setFullscreen),eventBus.addEventListener(GGPlayer.modules.View.events.VOLUME,setVolume),eventBus.addEventListener(GGPlayer.modules.View.events.SEEK,setSeek),eventBus.addEventListener(GGPlayer.modules.View.events.SEEKTO,setSeekToTime)}
25(),{setupVideo:setupVideo,setPlaylist:setPlaylist,setQuality:setQuality,setVolume:setVolume,play:play,stop:stop}},GGPlayer.protocols.iOS.isAvailable=function(){if(window.DEV_PLAYER)return!0;try{return document.createElement("video").canPlayType("application/vnd.apple.mpegURL")}catch(e){}return!1};
26angular.module("GG").run(["$templateCache",function($templateCache){$templateCache.put("/html/header-profile.html",'<div ng-if="!$root.User.placeholder">\n    <gg-login-btn ng-if="!$root.User.logged()"></gg-login-btn>\n\n    <div class="user-panel"\n         gg-click-outside="vm.clickOutside()"\n         ng-click="vm.togleShowMenu()"\n         ng-controller="ggProfileNavigation as vm"\n         ng-if="$root.User.logged()"\n         ng-mouseleave="vm.mouseLeave()"\n         ng-mouseover="vm.mouseOver()"\n    >\n        <span class="avatar" style="background-image:url({{ vm.gg4UserService.user.avatar }});"></span>\n        <span class="sign">{{ $root.User.nickname }}</span>\n        <ul class="sub-menu" ng-class="{\'active\': vm.isSubmenuOpened}">\n            <li>\n                <a href="/user/{{ $root.User.id }}">\n                    <span class="icon icon-User-24px"></span>\n                    Профиль\n                </a>\n            </li>\n            <li>\n                <a href="/channel/new" ng-if="!$root.User.channel">\n                    <span class="icon icon-Camera-24px1"></span>\n                    Создать канал\n                </a>\n            </li>\n            <li>\n                <a href="{{ $root.User.channel.links.stream }}" ng-if="$root.User.channel" title="">\n                    <span class="icon icon-Camera-24px1"></span>\n                    Канал\n                </a>\n            </li>\n            <li>\n                <a href="{{ $root.User.channel.links.dashboard }}" ng-if="$root.User.channel" title="">\n                    <span class="icon icon-Settings-24px1"></span>\n                    Дашборд стримера\n                </a>\n            </li>\n            <li>\n                <a href="/cups">\n                    <span class="icon icon-CupNew24px"></span>\n                    Турниры\n                </a>\n\n                <ul class="sub-menu inner">\n                    <li>\n                        <a href="/cups/bracket/generator"><span class="icon icon-Bracket-24px"></span>Генератор сеток</a>\n                    </li>\n                    <li>\n                        <a href="/cups/new"><span class="icon icon-Swords-24px1"></span>Создать турнир</a>\n                    </li>\n                    <li>\n                        <a href="/cups/teams/new"><span class="icon icon-Viewers-24px"></span>Создать команду</a>\n                    </li>\n                </ul>\n            </li>\n            <li>\n                <a href="/user/{{ $root.User.id }}/achievements">\n                    <span class="icon icon-Diamond-24px"></span>\n                    Трофеи и достижения\n                </a>\n            </li>\n            <li>\n                <a href="/user/finance/premium/">\n                    <span class="icon icon-Donate-24px"></span>\n                    Подписки и донаты\n                </a>\n            </li>\n            <li><a href="/user/beta/"><span class="icon icon-Wrench-24px1"></span> Бета профиль</a></li>\n            <li ng-if="$root.User.hasAccess(\'MATERIALS\') || $root.User.hasAccess(\'EVENTS\') || $root.User.hasAccess(\'SUPER_MODERATOR\')">\n            <span class="link"><span class="icon icon-Add-24px1"></span>\n                Добавить\n            </span>\n                <ul class="sub-menu inner">\n                    <li ng-if="$root.User.hasAccess(\'MATERIALS\') || $root.User.hasAccess(\'SUPER_MODERATOR\')">\n                        <a href="/materials/new/" ><span class="icon icon-File-24px1"></span>Новость</a>\n                    </li>\n                    <li>\n                        <a href="/cup/new/?type=1" ng-if="$root.User.hasAccess(\'EVENTS\') || $root.User.hasAccess(\'SUPER_MODERATOR\')"><span class="icon icon-Calendar-24px1"></span>Событие</a>\n                    </li>\n                    <li ng-if="$root.User.hasAccess(\'SUPER_MODERATOR\')">\n                        <a href="/help/new-type"><span class="icon icon-report-comment"></span>
26Раздел помощи</a>\n                    </li>\n                </ul>\n            </li>\n            <li class="child"\n                ng-if="$root.User.hasAccess(\'ANY_MODERATOR\') ||\n                $root.User.hasAccess(\'SUPER_MODERATOR\') ||\n                $root.User.hasAccess(\'SELLER\') ||\n                $root.User.hasAccess(\'SUPPORT\') ||\n                $root.User.hasAccess(\'MATERIALS\')"\n            >\n            <span class="link">\n                <span class="icon icon-SwordNew24px"></span>\n                Админу\n            </span>\n                <ul class="sub-menu inner">\n                    <li ng-if="$root.User.hasAccess(\'ANY_MODERATOR\')"><a href="/moderation/"><span class="icon icon-Swords-24px1"></span>Модерация</a></li>\n                    <li ng-if="$root.User.hasAccess(\'MATERIALS\') || $root.User.hasAccess(\'EVENTS\') || $root.User.hasAccess(\'SUPER_MODERATOR\')"><a href="/moderation/materials/"><span class="icon icon-File-24px1"></span>Редакция</a></li>\n                    <li ng-if="$root.User.hasAccess(\'SUPER_MODERATOR\')"><a href="/notify/admin/"><span class="icon icon-Bell-Full-24px"></span>Уведомления</a></li>\n                    <li ng-if="$root.User.hasAccess(\'SUPER_MODERATOR\')"><a href="/emailsystem/"><span class="icon icon-Letter-24px"></span>Email</a></li>\n                    <li ng-if="$root.User.hasAccess(\'SUPER_MODERATOR\') || $root.User.hasAccess(\'SUPPORT\')"><a href="/admin/shop/"><span class="icon icon-Gamepad-24px"></span>Магазин</a></li>\n                    <li ng-if="$root.User.hasAccess(\'SUPER_MODERATOR\')"><a href="/admin/premiums/"><span class="icon icon-month-18px"></span>Плюс и премиум</a></li>\n                    <li ng-if="$root.User.hasAccess(\'SUPER_MODERATOR\') || $root.User.hasAccess(\'SUPPORT\')"><a href="/admin/games/"><span class="icon icon-Invader-24px"></span>Игры и жанры</a></li>\n                    <li ng-if="$root.User.hasAccess(\'SUPER_MODERATOR\') || $root.User.hasAccess(\'SUPPORT\')"><a href="/admin/smiles/"><span class="icon icon-Smile-24px"></span>Смайлы</a></li>\n                    <li ng-if="$root.User.hasAccess(\'SUPER_MODERATOR\')"><a href="/statistics/player/"><span class="icon icon-GG-Money-24px1"></span>Статистика</a></li>\n                    <li ng-if="$root.User.hasAccess(\'SUPER_MODERATOR\')"><a href="/admin/rutony/"><span class="icon icon-GG-Money-24px1"></span>Рутони</a></li>\n                    <li ng-if="$root.User.hasAccess(\'SUPER_MODERATOR\')"><a href="/admin/premiums_notifies/"><span class="icon icon-GG-Money-24px1"></span>Прем.Оповещения</a></li>\n                    <li ng-if="$root.User.hasAccess(\'SELLER\') || $root.User.hasAccess(\'SUPER_MODERATOR\')">\n                        <a href="/webpanel-all-statistics/">\n                            <span class="icon icon-Globe-24px"></span>Стат. партнеров</a>\n                    </li>\n                    \x3c!-- <li ng-if="$root.User.hasAccess(\'SUPER_MODERATOR\')"><a href=""\n                                                                           onclick="localStorage.setItem(\'lang\', localStorage.getItem(\'lang\') === \'en\' ? \'ru\' : \'en\'); window.location.reload();">RU/EN</a>\n                    </li> --\x3e\n                </ul>\n            </li>\n            <li><a href="/user/{{ $root.User.id }}/webpanel" ng-if="$root.User.webmaster || vm.isWebmaster()"><span class="icon icon-Globe-24px"></span>Панель вебмастера</a></li>\n            <li>\n                <a onclick="alert(\'Да, ты тестер\')" ng-if="$root.User.hasAccess(\'TESTER\')">\n                    <span class="icon icon-nilfgaard-24"></span>Тестер\n                </a>\n\n                <ul class="sub-menu inner">\n                    <li ng-if="$root.User.hasAccess(\'TESTER\')"><a href="/tools/ca2">\n                        <span class="icon icon-Swords-24px1"></span>Сброс кэша</a>\n                    </li>\n                </ul>\n            </li>\n            <li><a data-action="logout" href="" ng-click="vm.logOut()"><span class="icon icon-logout-24px"></span>\n                Выйти</a></li>\n        </ul>\n    </div>\n</div>\n'),$templateCache.put("/html/footer.html",'<div class="footer">\n    <span class="footer__topline"></span>\n    <section class="footer__main-wrapper">\n        <div class="footer__sub-wrapper">\n            <article class="footer__main-info">\n                <img class="footer__logo" src="/images/svg/new-logo.svg" alt="Логотип" width="72" height="32">\n                <p>\n                    Первая киберспортивная стриминговая платформа в СНГ. Стримы игр и IRL,\n                    турниры по популярным играм, околоигровые и киберспортивные новости.\n                </p>\n                <ul>\n                    <li>\n                        <a href="http://vk.com/goodgameru" target="_blank">\n                            <img src="/images/svg/social/VKFooter34new.svg" alt="ВКонтакте" width="34" height="34">\n                        </a>\n                    </li>\n                    <li>\n                        <a href="http://www.youtube.com/user/TheAsperanT" target="_blank">\n                            <img src="/images/svg/social/Youtube-34-px.svg" alt="YouTube" width="34" height="34">\n                        </a>\n                    </li>\n                    <li>\n                        <a href="https://t.me/GoodGame_Ru" target="_blank">\n                            <img src="/images/svg/social/Telegram-34-px.svg" alt="Telegram" width="34" height="34">\n                        </a>\n                    </li>\n                    <li>\n                        <a href="https://discord.gg/BMsGPdQ" target="_blank">\n                            <img src="/images/svg/social/discord-34-px.svg" alt="Discord" width="34" height="34">\n                        </a>\n                    </li>\n                </ul>\n            </article>\n            <article class="footer__secondary-info"> \n\n                <div class="footer__info">\n                    <h2>Информация</h2>\n                    <ul>\n                        <li><a href="https://goodgame.ru/html/advert.html" target="_blank">
26Рекламные возможности</a></li>\n                        <li><a href="https://goodgame.ru/html/user-agreement.html" target="_blank">Пользовательское соглашение</a></li>\n                        <li><a href="https://goodgame.ru/html/privacy-policy.html" target="_blank">Политика конфиденциальности</a></li>\n                        <li><a href="/personal-data-consent" target="_blank">Согласие на обработку персональных данных</a></li>\n                        <li><a href="https://goodgame.ru/help/5/53" target="_blank">API разработчикам</a></li>\n                        <li><a href="/landingforstreamers" target="_blank">Стримерам</a></li>\n                        <li><a href="/candy/docs" target="_blank">Документация Candy</a></li>\n                        <li><a href="/cups/docs" target="_blank">Документация ТМ</a></li>\n                        <li><a href="/avtomodul/docs" target="_blank">Документация PM</a></li>\n                    </ul>\n                </div>\n\n                <div class="footer__contacts">\n                    <h2>Контакты</h2>\n                    <ul>\n                        <li><a href="mailto:[email protected]">[email protected]</a></li>\n                        <li><a href="mailto:[email protected]">[email protected]</a></li>\n                        <li><a href="mailto:[email protected]">[email protected]</a></li>\n                    </ul>\n                </div>\n\n                <div class="footer__apps">\n                    <h2>Приложения</h2>\n                    <ul>\n                        <li>\n                            <a href="https://goodgame.ru/a/googleplay" target="_blank">\n                                <img src="/images/PlayMarket.svg" alt="PlayMarket">\n                            </a>\n                        </li>\n                        <li>\n                            <a href="https://goodgame.ru/a/apk" target="_blank">\n                                <img src="/images/DirectDownload.svg" alt="DirectDownload">\n                            </a>\n                        </li>\n                        <li>\n                            <a href="https://goodgame.ru/a/appstore" target="_blank">\n                                <img src="/images/AppStore.svg" alt="AppStore">\n                            </a>\n                        </li>\n                        <li>\n                            <a href="https://goodgame.ru/a/huawei" target="_blank">\n                                <img src="/images/AppGallery.svg" alt="AppGallery" width="136px">\n                            </a>\n                        </li>\n                        <li>\n                            <a href="https://www.rustore.ru/catalog/app/ru.goodgame.goodgame2" target="_blank">\n                                <img src="/images/svg/RuStoreOption.svg" alt="RuStore">\n                            </a>\n                        </li>\n                    </ul>\n                </div>\n\n                <div class="footer__adress">\n                    <p class="footer__documents footer__years">\n                        <span class="INN">ИНН 7805457709</span>\n                        <span class="OGRN">ОГРН 1089847129283</span>\n                        <span class="codes">Коды видов деятельности: 1.01, 1.05</span>\n                        <span class="adress">308015, г. Белгород, ул. Чапаева, д. 24</span>\n                        <span class="OOO">© 2008–2026, Общество с ограниченной ответственностью «Мидиан»</span>\n                    </p>\n                    <img src="/images/svg/18-Plus.svg" alt="18+" width="50" height="50">\n                </div>\n\n            </article>\n\n            <article class="footer__last-info__medium">\n                <div class="footer__adress footer__adress-max__width">\n                    <p class="footer__documents">
26\n                        <span class="INN">ИНН 7805457709</span>\n                        <span class="OGRN">ОГРН 1089847129283</span>\n                        <span class="codes">Коды видов деятельности: 1.01, 1.05</span>\n                        <span class="adress">308015, г. Белгород, ул. Чапаева, д. 24</span>\n                    </p>\n                </div>\n                <div class="footer__adress">\n                    <p class="footer__documents footer__years">\n                        <span class="OOO">© 2008–2026, Общество с ограниченной ответственностью «Мидиан»</span>\n                    </p>\n                </div>\n                <img src="/images/svg/18-Plus.svg" alt="18+" width="50" height="50">\n            </article>\n        </div>\n\n\n        <article class="footer__last-info">\n            <div class="footer__adress">\n                <p class="footer__documents footer__years">\n                    <span class="INN">ИНН 7805457709</span>\n                    <span class="OGRN">ОГРН 1089847129283</span>\n                    <span class="codes">Коды видов деятельности: 1.01, 1.05</span>\n                    <span class="adress">308015, г. Белгород, ул. Чапаева, д. 24</span>\n                    <span class="OOO" style="text-align: center;">© 2008–2026, Общество с ограниченной ответственностью «Мидиан»</span>\n                </p>\n                <img src="/images/svg/18-Plus.svg" alt="18+" width="50" height="50">\n            </div>\n        </article>\n    </section>\n    <script>\n        const footer = document.querySelectorAll(\'.footer__years\')\n            .forEach((elem) => {\n                elem.querySelector(\'.OOO\')\n                    .textContent = `© 2008 — ${new Date().getFullYear()}, Общество с ограниченной ответственностью «Мидиан»`;\n            })\n    <\/script>\n</div>\n'),
27$templateCache.put("/html/feed/index.html",'<div ng-controller="ggFloatingEventsCtrl as flEvents">\n    <div class="floating-events" ng-class="{show: flEvents.isVisible(), down: feed.stream.player}">\n        <div class="event-list-block floating">\n\n            <div class="event-block"\n                 ng-if="flEvents.list[0]"\n                 ng-include="flEvents.getTemplate(event)"\n                 ng-init="event = flEvents.list[0]">\n            </div>\n\n            <div ng-click="flEvents.showFullFeed();" class="other" ng-class="{show: flEvents.list.length>1}">\n                <div class="inner">\n                    <a href="" class="btn btn-transparent">\n                        +{{ flEvents.list.length - 1 | decl: [\'новое сообщение\', \'новых сообщения\', \'новых сообщений\'] }} в ленте\n                    </a>\n                </div>\n            </div>\n\n        </div>\n    </div>\n</div>\n\n<div class="tab-panel head-container">\n    <ul class="nav nav-tabs nav-justified">\n        <li class="stream" ng-class="{active:!$root.hideFeed&&feed.currentTab==\'stream\'}" ng-if="feed.stream.visible">\n            <a href="" class="" ng-click="feed.showTab(\'stream\')">\n                <span class="icon" ng-class="{\'icon-playerchat\': feed.stream.player, \'icon-Chat-New-Messages-24px\': !feed.stream.player}"></span>\n            </a>\n        </li>\n\n        <li class="favorites" ng-class="{active:!$root.hideFeed&&feed.currentTab==\'favorites\'}" ng-if="$root.User.logged()">\n            <a class="favorites" href="" ng-click="feed.showTab(\'favorites\')">\n                <span class="icon icon-Heart-24px">\n                    <span class="count">{{ feed.favoritesNum || \'\' }}</span>\n                </span>\n            </a>\n        </li>\n\n        <li class="mails" ng-class="{active:!$root.hideFeed&&feed.currentTab==\'mails\'}" ng-if="$root.User.logged()">\n            <a class="mails" href="" ng-click="feed.showTab(\'mails\')">
27\n                <span class="icon icon-Letter-24px">\n                    <span class="count">{{ $root.User.dialogs || \'\' }}</span>\n                </span>\n            </a>\n        </li>\n\n        <li class="newsfeed" ng-class="{active:!$root.hideFeed&&feed.currentTab==\'newsfeed\'}" ng-if="$root.User.logged()">\n            <a class="newsfeed" href="" ng-click="feed.showTab(\'newsfeed\')">\n                <span class="icon icon-Bell-Full-24px">\n                    <span class="count" ng-class="{\'show\':feed.newsfeedCnt}">{{ feed.newsfeedCnt }}</span>\n                </span>\n            </a>\n        </li>\n    </ul>\n</div>\n<div class="tab-panel content-container" ng-class="{loading:!feed.currentTab}">\n    <div class="tab-content">\n        <div class="tab-pane stream-block"\n             ng-class="{active:feed.currentTab==\'stream\',\'hide-player\':!stream.player, \'has-game\':stream.game}"\n             ng-controller="ggFeedStreamCtrl as stream">\n\n            <div class="player">\n                <div class="player-container">\n                    <div class="player-wrap">\n                        <div class="player-controls">\n                            <a href="" ng-click="stream.goToChannel()" class="channel-link">\n                                <span class="icon icon-chevron-left"></span>\n                                Назад к {{ stream.streamTitle }}\n                            </a>\n                            <a href="" ng-click="stream.closePlayer()" class="close icon icon-close2"></a>\n                        </div>\n                        <div class="player-tab" id="player-feed-root">\n                        </div>\n                    </div>\n                </div>\n            </div>\n\n            <div class="game" ng-if="stream.game">\n                <iframe width="100%" height="100%" frameborder="0" scrolling="0" ng-src="/files/game/fb2/index.html"></iframe>\n            </div>\n\n            <div ng-if="feed.hasChat()" class="chat" ng-include="\'/html/feed/chat.html\'"></div>\n\n\n        </div>\n\n        <div class="tab-pane active" ng-if="feed.currentTab==\'mails\'">\n            <div class="dialog-wrap" ng-class="{loading: !dialogs.loaded}" ng-controller="ggDialogsCtrl as dialogs">\n                <ng-include src="\'/html/feed/dialogs.html\'"></ng-include>\n            </div>\n        </div>\n\n        <div class="tab-pane favorites-block" gg-scrollable ng-class="{active:feed.currentTab==\'favorites\'}"\n             ng-if="$root.User.logged()">\n            <div class="tab-pane-inner loaded" ng-controller="ggFeedFavoritesCtrl as favorites">\n\n                <div ng-if="!favorites.loaded">\n                    <div class="inner-block"></div>\n\n                    <div class="streams-wrapper dummy">\n                        <div class="title-block"></div>\n                        <div class="stream-info-wrap">\n                            <a href="" class="stream-info-block">\n                                <span class="avatar"></span>\n                                <span class="streamer-block">\n                                            <span class="streamer pull-left"></span>\n                                            <span class="info-block pull-right">\n                                                <span class="icon icon-eye"></span>\n                                                <span class="viewers"></span>\n                                            </span>\n                                            <span class="streamer-plays ov">\n                                                <span class="svg-icon-gamepad14px"></span>\n                                                <span class="game"></span>\n                                            </span>\n                                        </span>\n                                <span class="channel-title">\n                                        </span>\n                            </a>\n                        </div>\n                        <div class="stream-info-wrap">\n                            <a href="" class="stream-info-block">
27\n                                <span class="avatar"></span>\n                                <span class="streamer-block">\n                                            <span class="streamer pull-left"></span>\n                                            <span class="info-block pull-right">\n                                                <span class="icon icon-eye"></span>\n                                                <span class="viewers"></span>\n                                            </span>\n                                            <span class="streamer-plays ov">\n                                                <span class="svg-icon-gamepad14px"></span>\n                                                <span class="game"></span>\n                                            </span>\n                                        </span>\n                                <span class="channel-title">\n                                        </span>\n                            </a>\n                        </div>\n                        <div class="stream-info-wrap">\n                            <a href="" class="stream-info-block">\n                                <span class="avatar"></span>\n                                <span class="streamer-block">\n                                            <span class="streamer pull-left"></span>\n                                            <span class="info-block pull-right">\n                                                <span class="icon icon-eye"></span>\n                                                <span class="viewers"></span>\n                                            </span>\n                                            <span class="streamer-plays ov">\n                                                <span class="svg-icon-gamepad14px"></span>\n                                                <span class="game"></span>\n                                            </span>\n                                        </span>\n                                <span class="channel-title">\n                                        </span>\n                            </a>\n                        </div>\n                    </div>\n                </div>\n\n                <div ng-if="!favorites.isReady()" style="margin:15px 15px 5px 15px;width:calc(100% - 30px);"\n                     class="system-message warning">Подключаюсь к серверу...\n                </div>\n\n                <div class="no-events-block big-smiles" ng-if="favorites.isReady() && favorites.isEmpty">\n                    <smile name="grumpy"></smile>\n\n                    <div class="text">Вы пока не добавили ни один стрим в избранное.</div>\n\n                    <div class="example text">\n                        Добавьте канал в избранное, нажав на кнопку под плеером слева.\n                    </div>\n\n                </div>\n\n                <div class="inner-block" ng-show="favorites.channelsCount > 11">\n                    <input type="text" placeholder="Быстрый поиск" ng-model="search.streamer.nickname">\n                </div>\n\n                <div class="streams-wrapper" ng-show="online_filtered.length">\n                    <div class="title-block">Каналы онлайн</div>\n                    <div class="stream-info-wrap"\n                         ng-repeat="channel in favorites.online | filter:search as online_filtered"\n                         ng-click="feed.showTab(false)"\n                    >\n                        <a href="{{ channel.link }}#autoplay" class="stream-info-block">\n                            <span class="avatar" gg-user="channel.streamer" ng-class="{online: channel.streamer.online}">\n                                <img ng-src="{{ channel.streamer.avatar }}">\n                            </span>\n                            <span class="streamer-block">\n                                <span class="tip">{{ channel.game }}</span>
27\n                                <span class="streamer pull-left">{{ channel.streamer.nickname }}</span>\n                                <span class="info-block pull-right">\n                                    <span class="icon icon-eye"></span>\n                                    <span class="viewers">{{ channel.viewers }}</span>\n                                </span>\n                                <span class="streamer-plays ov">\n                                    <span class="svg-icon-gamepad14px"></span>\n                                    <span class="game">{{ channel.game }}</span>\n                                </span>\n                            </span>\n                            <span class="channel-title">\n                                <span class="tip">{{ channel.stream_title }}</span>\n                                    {{ channel.stream_title }}\n                            </span>\n                        </a>\n                    </div>\n                </div>\n\n                <div class="streams-wrapper" ng-show="soon_filtered.length" ng-click>\n                    <div class="title-block">Скоро в эфире</div>\n                    <div class="stream-info-wrap"\n                         ng-repeat="channel in favorites.soon | filter:search as soon_filtered"\n                         ng-click="feed.showTab(false)"\n                    >\n                        <a href="{{ channel.link }}" class="stream-info-block">\n                            <span class="avatar" gg-user="channel.streamer" ng-class="{online: channel.streamer.online}">\n                                <img ng-src="{{ channel.streamer.avatar }}">\n                            </span>\n                            <span class="streamer-block">\n                                <span class="tip">{{ channel.broadcast.game }}</span>\n                                <span class="streamer pull-left">{{ channel.streamer.nickname }}</span>\n                                <span class="info-block pull-right">\n                                    <span class="start-date">{{ favorites.formatDate(channel.broadcast.startDate)  }}</span>\n                                </span>\n                                <span class="streamer-plays ov">\n                                    <span class="svg-icon-gamepad14px"></span>\n                                    <span class="game">{{ channel.broadcast.game }}</span>\n                                </span>\n                            </span>\n                            <span class="channel-title">\n                                <span class="tip">{{ channel.broadcast.title }}</span>\n                                {{ channel.broadcast.title }}\n                            </span>\n\n                        </a>\n                    </div>\n                </div>\n\n                <div class="streams-wrapper" ng-show="hosts_filtered.length">\n                    <div class="title-block">Ретрансляции</div>\n                    <div class="stream-info-wrap"\n                         ng-repeat="channel in favorites.hosting | filter:search as hosts_filtered"\n                         ng-click="feed.showTab(false)"\n                    >\n                        <a href="{{ channel.link }}" class="stream-info-block flex">\n                            <span class="avatar" gg-user="channel.streamer" ng-class="{online: channel.streamer.online}">\n                                <img ng-src="{{ channel.streamer.avatar }}">\n                            </span>\n                            <span class="streamer-block">\n                                <span class="pull-left">\n                                    <span class="streamer">{{ channel.streamer.nickname }}</span>\n                                    <span class="icon icon-Host-24px"></span>\n                                    <span class="streamer">{{ channel.hosting.streamer.nickname }}</span>\n                                </span>\n                                \x3c!--<span class="info-block pull-right">
27\n                                    <span class="icon icon-eye"></span>\n                                    <span class="viewers">{{ channel.hosting.viewers }}</span>\n                                </span>--\x3e\n                            </span>\n                        </a>\n                    </div>\n                </div>\n\n                <div class="streams-wrapper" ng-show="recently_filtered.length">\n                    <div class="title-block">Недавно смотрели</div>\n                    <div class="stream-info-wrap" ng-repeat="channel in favorites.recently | filter:search as recently_filtered">\n                        <a href="{{ channel.link }}#autoplay" class="stream-info-block">\n                            <span class="avatar" gg-user="channel.streamer" ng-class="{online: channel.streamer.online}">\n                                <img ng-src="{{ channel.streamer.avatar }}">\n                            </span>\n                            <span class="streamer-block">\n                                <span class="streamer pull-left">{{ channel.streamer.nickname }}</span>\n                                <span class="info-block pull-right">\n                                    <span class="icon icon-eye"></span>\n                                    <span class="viewers">{{ channel.viewers }}</span>\n                                </span>\n                                <span class="streamer-plays ov">\n                                    <span class="svg-icon-gamepad14px"></span>\n                                    <span class="game">{{ channel.game }}</span></span>\n                            </span>\n                            <span class="channel-title">\n                                <span class="tip">{{ channel.stream_title }}</span>\n                                    {{ channel.stream_title }}\n                            </span>\n                        </a>\n                    </div>\n                </div>\n\n                \x3c!--<div class="streams-wrapper">\n                    <div class="title-block">Избранное с Twitch</div>\n                    <div class="stream-info-wrap">\n                        <div class="stream-info-block">\n                            <a href="#">\n                                <span class="avatar">\n                                    <img ng-src="/files/avatars/av_141472_yenv.jpg">\n                                </span>\n                            </a>\n                            <span class="streamer-block twitch">\n                                <a href="#">\n                                    <span class="info-block pull-left">\n                                        <span class="streamer">Farkem</span>\n                                        <span class="channel-title">Название игры тут</span>\n                                    </span>\n                                </a>\n                                <span class="icons-block pull-right">\n                                    <a href="" class="icon icon-heart">\n                                        <span class="tip">В избранное</span>\n                                    </a>\n                                    <a href="" class="icon icon-close">\n                                        <span class="tip">Скрыть</span>\n                                    </a>\n                                </span>\n                            </span>\n                        </div>\n                    </div>\n                </div>--\x3e\n\n                <div class="streams-wrapper" ng-show="twitch_filtered.length">\n                    <div class="title-block">Избранное с Twitch</div>\n                    <div class="stream-info-wrap" ng-repeat="channel in favorites.twitch | filter:search as twitch_filtered">\n                        <div class="stream-info-block">\n                            <a href="{{ channel.link }}#autoplay">\n                                <span class="avatar" gg-user="channel.streamer"\n                                      ng-class="{online: channel.streamer.online}">\n                                    <img ng-src="{{ channel.streamer.avatar }}">\n                                </span>\n                            </a>
27\n                            <span class="streamer-block twitch">\n                                <span class="info-block pull-left">\n                                    <a href="{{ channel.link }}#autoplay">\n                                        <span class="streamer">{{ channel.streamer.nickname }}</span>\n                                        <span class="channel-title">{{ channel.game }}</span>\n                                    </a>\n                                </span>\n                                <span class="icons-block pull-right">\n                                    <span class="icon icon-heart2" ng-click="favorites.addToFavorites(channel)">\n                                        <span class="tip">В избранное</span>\n                                    </span>\n                                    <span class="icon icon-close" ng-click="favorites.hideTwitch(channel)">\n                                        <span class="tip">Скрыть</span>\n                                    </span>\n                                </span>\n                            </span>\n                        </div>\n                    </div>\n                </div>\n\n                <div class="streams-wrapper" ng-show="offline_filtered.length">\n                    <div class="title-block">Офлайн</div>\n                    <div class="stream-info-wrap"\n                         ng-repeat="channel in favorites.offline | filter:search as offline_filtered"\n                         ng-click="feed.showTab(false)"\n                    >\n                        <a href="{{ channel.link }}" class="stream-info-block">\n                            <span class="avatar" gg-user="channel.streamer" ng-class="{online: channel.streamer.online}">\n                                <img ng-src="{{ channel.streamer.avatar }}">\n                            </span>\n                            <span class="streamer-block">\n                                <span class="streamer streamer-offline">{{ channel.streamer.nickname }}</span>\n                            </span>\n                        </a>\n                    </div>\n                </div>\n\n                <div class="blacklist-block" ng-if="$root.User.bl">\n                    <div class="spoiler-block" ng-class="{\'active\': favorites._blacklist}">\n                        <div class="spoiler-head" data-show="показать" data-hide="скрыть" ng-click="favorites.showBlacklist()">\n                            Черный список\n                        </div>\n                        <div class="spoiler-content">\n                            <div class="stream-info-wrap" ng-repeat="channel in favorites.blacklist">\n                                <a href="{{ channel.link }}" class="stream-info-block">\n                                    <span class="avatar">\n                                        <img ng-src="{{ channel.streamer.avatar }}">\n                                    </span>\n                                    <span class="streamer streamer-offline">{{ channel.streamer.nickname }}</span>\n                                </a>\n                                <a href="" ng-click="favorites.deleteFromBlacklist(channel)" class="icon icon-close2"></a>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n            </div>\n        </div>\n\n        <div class="tab-pane event-list-block" gg-scrollable ng-class="{active:feed.currentTab==\'newsfeed\'}"\n             ng-if="$root.User.logged()">\n\n            <div class="container" ng-class="{loaded: events.loaded}" ng-controller="ggEventsCtrl as events">\n                <div class="control-block" ng-if="events.list.length">\n                    \x3c!--a href="" class="control icon icon-cog" ng-click="settings=!settings"></a--\x3e\n                    <a href="" ng-click="events.markAllAsRead()">Отм. как прочитанное</a>\n                    <a href="" ng-click="events.deleteAll()">Очистить ленту</a>\n                    <div class="settings-block" ng-class="{\'show\':sett
27ings}">\n                        <div class="title">Что отображать в ленте</div>\n                        <a href="" class="close icon icon-close2" ng-click="settings=!settings"></a>\n                        <div class="checkbox-list">\n                            <div class="checkbox">\n                                <input id="checkbox1" type="checkbox">\n                                <label for="checkbox1" ng-click="disabled=!disabled">Ничего, отключить ленту</label>\n                            </div>\n                            <div class="checkbox" ng-class="{\'disabled\': disabled}">\n                                <input id="checkbox2" type="checkbox">\n                                <label for="checkbox2">Звуковой сигнал при новом событии</label>\n                            </div>\n                        </div>\n                        <div class="checkbox-list">\n                            <div class="checkbox" ng-class="{\'disabled\': disabled}">\n                                <input id="checkbox1" type="checkbox">\n                                <label for="checkbox1">Старт стрима</label>\n                            </div>\n                            <div class="checkbox" ng-class="{\'disabled\': disabled}">\n                                <input id="checkbox2" type="checkbox">\n                                <label for="checkbox2">Новый анонс</label>\n                            </div>\n                            <div class="checkbox" ng-class="{\'disabled\': disabled}">\n                                <input id="checkbox2" type="checkbox">\n                                <label for="checkbox2">Ответ на ваш комментарий</label>\n                            </div>\n                            <div class="checkbox" ng-class="{\'disabled\': disabled}">\n                                <input id="checkbox2" type="checkbox">\n                                <label for="checkbox2">Достижения</label>\n                            </div>\n                            <div class="checkbox" ng-class="{\'disabled\': disabled}">\n                                <input id="checkbox2" type="checkbox">\n                                <label for="checkbox2">Сообщения о дружбе</label>\n                            </div>\n                            <div class="checkbox" ng-class="{\'disabled\': disabled}">\n                                <input id="checkbox2" type="checkbox">\n                                <label for="checkbox2">Уведомления стримера</label>\n                            </div>\n                            <div class="checkbox" ng-class="{\'disabled\': disabled}">\n                                <input id="checkbox2" type="checkbox">\n                                <label for="checkbox2">Новый анонс</label>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n                \x3c!--<div class="event-block">\n                    <a href="" class="close icon icon-close2" ng-click="events.list.length = 0"></a>\n                    <div class="icon-block" href="{{ event.data.obj.link }}">\n                        <img ng-src="{{ event.data.obj.streamer.avatar }}">\n                    </div>\n                    <div class="info-block">\n                        <div class="date">Дата </div>\n                        <div class="text">\n                            <a href="">Happa_</a> создал анонс по игре DOOM, начало 27.08 в 15:00\n                        </div>\n                        <div class="announce-block">\n                            <div class="timer">16:53:13</div>\n                            <img src="/images/ico_tv.png" alt="">\n                        </div>\n                    </div>\n                </div>\n                <div class="event-block">\n                    <a href="" class="close icon icon-close2" ng-click="events.list.length = 0"></a>\n                    \x3c!-- Все иконки, в завимисти от типа уведомления\n                        <div class="icon-block info-status"></div>\n                        <div class="icon-block ban-status"></div>\n                        <div class="icon-block streamer-notify"></div>\n                        <div class="icon-block tournament-confirmation"></div>\n                        <div class="icon-block premium-status"></div>\n                        <div class="icon-block claim-status"></div>\n                        <div class="icon-block finance-notify"></div>\n                        <div class="icon-block friends-notify"></div>\n                        <div class="icon-block achievement-notify"></div>\n                        <div class="icon-block comment-notify"></div>\n                    <div class="icon-block comment-notify">\n                    </div>\n                    <div class="info-block">\n                        <div class="date">
27Дата </div>\n                        <div class="text">\n                            Сообщение удалено из ленты\n                        </div>\n                        <a href="" class="btn btn-transparent">Не показывать подобное</a>\n                    </div>\n                </div>\n                <div class="event-block">\n                    <a href="" class="close icon icon-close2" ng-click="events.list.length = 0"></a>\n                    <div class="icon-block achievement-notify"></div>\n                    <div class="info-block">\n                        <div class="date">Сегодня в 14:22 </div>\n                        <div class="text">\n                            Вы заработали достижение «Красавчик StarCraft 2» и открыли новый предмет:\n                        </div>\n                        <div class="achievement-block">\n                            тут будут награды\n                        </div>\n\n                        2 кнопки подряд идут в турнирах когда приглашают\n                        <a href="" class="btn btn-transparent">Вступить</a>\n                        <a href="" class="btn btn-transparent reject">Отклонить</a>\n                    </div>\n                </div>\n            --\x3e\n                <div ng-if="feed.currentTab==\'newsfeed\'">\n                    <div class="event-block"\n                         ng-if="events.list.length"\
27n                         ng-class="{unread: !event.read}"\n                         ng-repeat="event in events.list track by event.time"\n                         ng-include="events.getTemplate(event)"\n                         ng-mouseenter="events.setRead(event)">\n                    </div>\n                    <div class="no-events-block" ng-if="!events.list.length">\n                        <div class="big-smiles">\n                            <img src="/images/chat/blank.gif" class="smile goodnews" alt="">\n                        </div>\n                        <div class="text">У вас нет новых событий.</div>\n                    </div>\n                </div>\n            </div>\n\n\n        </div>\n\n    </div>\n</div>\n\n\n'),
28$templateCache.put("/html/feed/chat.html",'\x3c!--\n<div class="restream-block flex">\n    <div class="streamer flex">\n        <img src="/images/svg/ic-lightning.svg" alt="">\n        <span class="nick">Abver</span>\n    </div>\n    <div class="btn-block flex">\n        <button class="btn btn-blue">Перейти на канал</button>\n        <div class="icon icon-close3"></div>\n    </div>\n</div>\n<div class="teleport-notify">\n    <button class="icon icon-close"></button>\n    <div class="title">Только что</div>\n    <div class="flex">\n        <div class="avatar" style="background-image:url(\'/files/avatars/av_91633_2XB4.png\');"></div>\n        <div class="text-block">\n            Вы телепортируетесь на канал <a href="">Happa_</a> через 00:15\n        </div>\n    </div>\n    <button class="btn btn-transparent wide">Отменить</button>\n</div>\n--\x3e\n\n<div class="chat-container premium-icon-{{vm.room.id}}"\n     ng-controller="ggChat as vm"\n     ng-class="{\n     \'big-smiles\':vm.settings.smilesType > 1,\n     \'animated-smiles\':vm.settings.smilesType == 4,\n     \'task-one\': vm.countPinnedQuest === 1,\n     \'task-two\': vm.countPinnedQuest === 2,\n     \'task-three\': vm.countPinnedQuest >= 3,\n     \'prem-shout\': vm.room.notify,\n     \'chat-container_new-guy\': !vm.room.user.id\n     }">\n\n    <gg-pinned-quest\n            [user]="vm.room.streamer.id"\n            [tasks]="vm.pinnedQuests"\n            (count-pin-task)="vm.setCountPinnedQuest($event)"\n            (replenish)="vm.replenish($event)"\n            (paste-nick)="vm.pasteNick($event)"></gg-pinned-quest>\n\n    <div class="sub-announce-block" ng-if="vm.room.notify">\n        <div class="text-block">\n            <span class="text">Вы подписаны {{ vm.room.notify }} мес. подряд!</span>\n        </div>\n        <div class="close-block">\n            <button\n                ng-click="vm.room.sendNotify()"\n                ng-disabled="vm.room.isNotifyDisabled"\n                class="btn-like">\n                Пошуметь\n            </button>\n            <span class="close icon icon-close3" ng-click="vm.room.discardNotify()"></span>\n        </div>\n    </div>\n\n    <div class="help-block">\n        Бан VineWood\n    </div>\n    <div class="user-context-menu" ng-show="vm.view.user" ng-click="vm.view.user=false"\n         gg-click-outside="vm.view.user=false">\n        <a href="" ng-click="vm.view.message.remove()"\n           ng-if="(vm.room.user.rights || vm.view.message.user.id == vm.room.user.id) && vm.view.message && !vm.view.message.donateValue">Удалить\n            сообщение</a>\n        <a href="" ng-click="vm.warnUser(vm.view.user.id)" ng-if="vm.room.user.rights">Предупреждение</a>\n        <a href="" ng-click="vm.banUser(vm.view.user)" ng-if="vm.room.user.rights && !vm.view.user.banned && !vm.view.message.donateValue">Забанить</a>\n        <a href="" ng-click="vm.banUserTillStreamEnd(vm.view.user)" ng-if="vm.room.user.rights && !vm.view.user.banned && !vm.view.message.donateValue">Забанить\n            до конца стрима</a>\n        <a href="" ng-click="vm.unBanUser(vm.view.user)"\n           ng-if="vm.room.user.rights && vm.view.user.banned && vm.view.user.banned!=undefined">Разбанить</a>\n        <a href="" ng-click="vm.room.addHelper(vm.view.user.id)"\n           ng-if="vm.room.user.rights>10 && vm.view.user.rights < 10">Выдать права</a>\n        <a href="" ng-click="vm.room.deleteHelper(vm.view.user.id)"\n           ng-if="vm.room.user.rights>10 && vm.view.user.rights == 10">Забрать права</a>\n        <gg4-chat-premium-btn\n                [user-id]="vm.view.user.id"\n                [streamkey]="vm.room.streamKey"\n                [premium]="vm.room.room_premium"\n        ></gg4-chat-premium-btn>\n        <a href="" ng-click="vm.view.pasteNick(vm.view.user.nickname, 1)">
28Написать лично</a>\n        <a href="" ng-click="vm.view.user.showInGrid()" ng-if="vm.view.user.isCup">Показать в сетке</a>\n        <a ng-href="/user/{{ vm.view.user.id }}/" ng-click="vm.profileClick($event)">Профиль</a>\n        <a href="" ng-click="vm.Chat.rooms.addToIgnoreList(vm.view.user.id, vm.room.user.id)">В игнор-лист</a>\n        <a ng-href="/user/{{ vm.view.user.id }}/nicknamehistory" ng-click="vm.nicknamehistoryClick($event)">Прошлые\n            ники</a>\n    </div>\n    <div class="content-window" ng-class="{loading: !vm.room.messages.loaded}" chat-messages>\n        <div class="bg-block"></div>\n        <canvas id="snow"></canvas>\n        <div class="tse-scrollable" gg-scrollable>\n            <div class="chat-section"\n                 ng-class="{\'ban-icon\': vm.room.user.rights && vm.settings.quickBan,\'delete-icon\':vm.room.user.rights && vm.settings.quickDelete, format: vm.settings.alignType > 0}">\n                <div class="message-block {{ ::message.color }}"\n                     ng-if="(!message.deleted || vm.room.user.rights || vm.room.user.id == message.user.id) && !message.hide"\n                     ng-class="{\n                        deleted: message.deleted,\n                        private: message.mine,\n                        bubble: message.private,\n                        gift: message.gift,\n                        \'donate-message\': message.donateValue,\n                        \'private-message\': message.private || message.mine\n                        }"\n                     ng-repeat="message in vm.room.messages" tooltip="{{ ::message.time }}">\n\n                    <div ng-class="{\'new-donate\': message.donateValue, \'commission\': message.is_commission_covered}">\n                        <div ng-if="message.donateValue" class="sum">\n                            <span ng-if="message.is_commission_covered" class="icon icon-heart-24"></span>\n                            {{message.donateValue}}\n                        </div>\n\n                        <div class="user" ng-if="message.user.nickname && !message.anonymous">\n                            <span class="pretext" ng-if="message.mine && message.private">лично</span>\n                            <span class="pretext" ng-if="message.private && !message.mine">от</span>\n                            <a href="" ng-if="!message.donateValue" ng-click="message.remove()" class="delete icon icon-trash-chat"\n                               tooltip="Удалить сообщение"></a>\n                            <a href="" ng-if="!message.donateValue" ng-click="vm.banUser(message.user, message)"\n                               class="ban icon icon-ban-chat" tooltip="Бан {{message.user.nickname}}"></a>\n                            <chat-user user-obj="::message.user" message="::message"></chat-user>\n                        </div>\n\n                        <div class="message" parse-message="message.text" preserve-html="message.html"\n                             event-data="vm.parseEvent"></div>\n\n                    </div>\n\n                    <span ng-if="message.adminName" class="system">&mdash; удалил {{ message.adminName }}</span>\n                </div>\n                <div class="new-message-block"\n                     ng-class="{\'active\':vm.room.newmsg}"\n                     ng-click="vm.view.justScroll()">Новые сообщения ниже\n                </div>\n            </div>\n        </div>\n        <div class="autocomplete-window" id="username-autocomplete"\n             ng-class="{\'additional-margin\': vm.view.nickAdditionalMargin}"\n             ng-if="vm.view.suggest && vm.view.suggest.value.length">\n            <ul>\n                <li ng-if="vm.view.suggest.type === \'user\'" ng-repeat="u in vm.view.suggest.value">\n                    <a href=""\n                       ng-class="{hover:vm.view.suggestSelected==$index+1}"\n                       ng-click="vm.view.pasteNick(u.nickname, false, true)">\n                        {{ u.nickname }}\n                    </a>\n                </li>\n                <li ng-if="vm.view.suggest.type === \'command\'" ng-repeat="c in vm.view.suggest.value">\n                    <a href=""\n                       ng-class="{hover:vm.view.suggestSelected==$index+1}"\n                       ng-click="vm.view.pasteCommand(c)">\n                        {{ c }}\n                    </a>\n                </li>\n            </ul>\n        </div>\n    </div>\n    <div class="chat-control-block" ng-show="vm.room">
28\n\n        <span class="chat__newguy-msg" ng-if="vm.newUserPopup === 0" ng-click="vm.startGreeting()">\n            Поприветствовать стримера\n            <img src="/images/brofist-gif.gif" width="75" height="36" alt="">\n        </span>\n\n        <div class="prem-only-block" ng-class="{hidden: vm.premHide}"\n             ng-if="vm.room.premiumOnly && !vm.room.user.canwrite && vm.room.streamer">\n            <div class="toggle-block" ng-click="vm.premHide = !vm.premHide">\n                <sapn class="icon icon-Down-24px"></sapn>\n                <span class="icon icon-Up-24px"></span>\n            </div>\n            <div class="text">\n                <p class="text-header">Премиум-чат включен</p>\n                Подпишитесь на премиум или отправьте донат от 100 рублей, чтобы продолжить общение в чате\n            </div>\n            <div class="btn-block clearfix">\n                <div class="btn-wrapper">\n                    <div ng-click="vm.trackEvent(\'pc_premium_click\')">\n                        <gg4-premium-btn\n                                [user]="vm.room.user.id"\n                                [icon]="\'premium-icon-\' + vm.room.id"\n                                [streamkey]="vm.room.streamer.name">\n                        </gg4-premium-btn>\n                    </div>\n                    <div ng-click="vm.trackEvent(\'pc_donate_click\')" class="donate-block__wrapper">\n                        <gg4-donate-btn\n                                [user]="vm.room.user.id"\n                                [premiumchat]="true"\n                                [streamer]="vm.room.streamer.id"\n                                [streamkey]="vm.room.streamer.name">\n                        </gg4-donate-btn>\n                    </div>\n                </div>\n            </div>\n        </div>\n\n        <div class="control-wrap">\n            <div class="control-panel clearfix" ng-if="!vm.room.user">\n                <div class="pull-right">\n                    <a href="" class="donate-block"\n                       ng-if="vm.room.isStream()"\n                       ng-init="vm.donateRng()"\n                       ng-mouseover="vm.donateRng()"\n                       ng-class="{\'active\': vm.view.donate}"\n                       ng-click="vm.toggleDonat()">Донат</a>\n\n                </div>\n            </div>\n\n            <div class="text-block" ng-if="vm.room.user.canwrite || !vm.room.user">\n                <a class="control streamer"\n                   ng-click="vm.view.pasteNick(vm.room.streamer.name, false, false, \'streamer\')">\n                    <span class="icon icon-mention-streamer reply"></span>\n                </a>\n                <span class="tooltip tooltip_mention">Упомянуть стримера</span>\n                <a id=\'chat-gg-smiles-show-button\' class="control icon icon-smilemenu-icon smiles" ng-class="{active: vm.view.smiles}"\n                   ng-click="vm.toggleSmiles()"></a>\n                <span class="tooltip tooltip_smiles">Вставить смайл</span>\n                <div id="chat-gg-message-input" class="textarea" ng-class="{\'safari-styles\': vm.isSafari}" contenteditable="true" chat-input\n                     placeholder="Написать сообщение..."></div>\n                <gg4-smile-suggestion\n                        (paste-smile)="vm.view.pasteSmile($event)"\n                        (paste-smile-replace)="vm.view.replaceStrWithImage($event)"\n                ></gg4-smile-suggestion>\n            </div>\n\n            <div class="control-panel clearfix" ng-if="vm.room.user.canwrite">\n\n                <div class="control__wrapper">\n\n                    <a class="donate-block icon icon-plus" style="margin-right: 15px;"\n                       ng-if="vm.room.donateButtons"\n                       ng-class="{\'active\': vm.showCustomDonate}"\n                       ng-click="vm.showCustomDonate = !vm.showCustomDonate">
28\n                        <span class="tip">Интерактив</span>\n                    </a>\n\n                    <div class="donate-block__wrapper">\n                        <button class="donate-block"\n                           ng-if="vm.room.isStream()"\n                           ng-init="vm.donateRng()"\n                           ng-mouseover="vm.donateRng()"\n                           ng-class="{\'active\': vm.view.donate}"\n                           ng-click="vm.toggleDonat()">Донат</button>\n                        <span class="tooltip tooltip_donate">Поддержать стримера</span>\n                    </div>\n\n                    <div class="control__wrapper-right">\n                        <div ng-if="false" class="user-block__wrapper">\n                            <a class="user-block" ng-click="vm.toggleFriendInvite()">\n                                <span class="control task">\n                                    <span class="icon icon-retroghost"></span>\n                                </span>\n                            </a>\n                        </div>\n\n                        <div ng-class="{\'display_none\': !vm.room.jobs}" class="user-block__wrapper">\n                            <a ng-if="vm.room.jobs" class="user-block" ng-click="vm.toggleTaskList()">\n                                <span class="control task">\n                                    <span class="icon icon-chat-task"></span>\n                                </span>\n                            </a>\n                            <span class="tooltip tooltip_tasks">Журнал заданий</span>\n                        </div>\n\n                        <div class="user-block__wrapper">\n                            <a class="user-block" ng-click="vm.toggleUsersList()">\n                                <span class="control user icon icon-user-24"></span>\n                            </a>\n                            <span class="tooltip tooltip_users">Список зрителей</span>\n                        </div>\n\n                        <div class="control-settings__wrapper">\n                            <div class="control settings"\n                                 ng-class="{show: vm.chatShow == \'menu\'}"\n                                 gg-click-outside="vm.chatShow = \'0\'"\n                                 ng-click="vm.chatShow = {\'menu\' : \'0\', \'0\' : \'menu\'}[vm.chatShow]">\n                                <span class="icon icon-menu-20px"></span>\n                                <div class="settings-popup">\n                                    <a href="" ng-click="vm.openPoll()" class="element">\n                                        <span class="icon icon-Charts-24px"></span>\n                                        Голосование\n                                    </a>\n                                    <a href="" ng-click="vm.openRandomizer()" ng-if="vm.room.user.rights"\n                                       class="element">\n                                        <span class="icon icon-random-24"></span>\n                                        Рандомайзер\n                                    </a>\n                                    <a href="" ng-click="vm.showIgnoreList()" class="element">\n                                        <span class="icon icon-Ignore-24px"></span>\n                                        Игнор-лист\n                                    </a>\n                                    <a href="" ng-click="vm.showHelpersList()" ng-if="vm.room.user.rights>=20"\n                                       class="element">\n                                        <span class="icon icon-Helper-24px"></span>\n                                        Помощники\n                                    </a>\n                                    <a href="" ng-click="vm.showBanned()" ng-if="vm.room.user.rights" class="element">\n                                        <span class="icon icon-Sword-24px"></span>\n                                        Список забаненых\n                                    </a>\n                                    <a href="" class="element" ng-click="vm.openSettings()">
28\n                                        <span class="icon icon-Settings-24px1"></span>\n                                        Настройки чата\n                                    </a>\n                                    <a href="" class="element" ng-click="vm.chatInWindow()">\n                                        <span class="icon icon-Up-Right-24px"></span>\n                                        Чат в окне\n                                    </a>\n                                </div>\n                            </div>\n                            <span class="tooltip tooltip_menu">Меню чата</span>\n                        </div>\n\n                    </div>\n\n\n                </div>\n            </div>\n        </div>\n\n    </div>\n    <div class="popup-wrap" ng-if="vm.room">\n        <gg-motd room="vm.room"></gg-motd>\n\n        <gg-popup id="smiles" class="popup-block smiles" ng-if="vm.room">\n            <div class="smiles-panel" gg-scrollable>\n                <gg-smiles2 [room]="vm.room" [admin]="!!vm.room.user.rights"\n                            (paste-smile)="vm.selectedSmile($event)"\n                            (close)="vm.toggleSmiles()"></gg-smiles2>\n            </div>\n        </gg-popup>\n\n        <gg-popup id="poll" class="poll-windows" ng-if="vm.view.pollWindow" ng-controller="ggChatPoll as poll">\n            <div class="popup-block scrollable poll vote-block" gg-scrollable\n                 ng-class="{show: !poll.data.voted && !poll.data.mine}">\n                <div class="title-block">\n                    <div class="control-block">\n                        <a href="" class="icon icon-close2" ng-click="closePopup($event)"></a>\n                    </div>\n                    <div class="title ov">{{ poll.data.title }}</div>\n                </div>\n                <div class="poll-list">\n                    <div class="form-group" ng-repeat="answer in poll.data.answers">\n                        <div class="radio">\n                            <input id="radio{{ answer.id }}" type="radio" ng-model="poll.myvote"\n                                   ng-value="{{ answer.id }}">\n                            <label for="radio{{ answer.id }}">{{ answer.text }}</label>\n                        </div>\n                    </div>\n                </div>\n                <div class="btn-block">\n                    <a href="" class="btn btn-blue" ng-if="vm.room.user.id" ng-click="poll.vote()">Проголосовать</a>\n                    <a href="" class="btn btn-gray" ng-if="vm.room.user.rights"\n                       ng-click="poll.edit = true">Создать новое</a>\n                </div>\n            </div>\n            <div class="popup-block scrollable poll vote-edit" ng-class="{show: poll.edit}" gg-scrollable>\n                <div class="title-block">\n                    <div class="title">Новое голосование</div>\n                    <div class="control-block">\n                        <a href="" class="icon icon-close2" ng-click="closePopup($event)"></a>\n                    </div>\n                </div>\n                <div class="form-group">\n                    <label class="title small" for="question">Вопрос</label>\n                    <textarea id="question" ng-model="poll.data.title"></textarea>\n                </div>\n                <div class="polls-list">\n                    <div class="title small">Ответы</div>\n\n                    <div class="form-group" ng-repeat="answer in poll.data.answers">\n                        <input type="text" ng-model="answer.text">\n                        <a href="" class="icon icon-close2" ng-click="poll.deleteAnswer(answer)"></a>\n                    </div>\n\n                </div>\n                <div class="btn-block">\n                    <a href="" class="btn btn-blue" ng-click="poll.back()">Назад</a>\n                    <a href="" class="btn btn-blue" ng-click="poll.create()">Создать голосование</a>\n                </div>\n            </div>\n            <div class="popup-block scrollable poll vote-results" ng-class="{show: poll.isResults()}" gg-scrollable>\n                <div class="title-block">\n                    <div class="title">Результаты</div>\n                    <div class="control-block">\n                        <a href="" class="icon icon-close2" ng-click="closePopup($event)"></a>\n                    </div>\n                </div>\n                <div class="result-block">\n                    <div class="text">{{ poll.data.title }}</div>\n                    <div class="result-list">\n                        <div class="result" ng-repeat="answer in poll.data.answers track by $index">\n                            <div class="bar" style="width: {{ poll.percentages[answer.id] }}%;"></div>\n                            <div class="name" title="{{ answer.text }}">{{ answer.text }}</div>\n                            <div class="percent">{{ poll.percentages[answer.id] }}%</div>\n                        </div>\n                    </div>\n                    <div class="text">{{ poll.data.voters | decl: [\'человек проголосовал\', \'человека проголосовало\',\n                        \'человек проголосовало\'] }}\n                    </div>\n                    <div class="btn-block">\n                        <a href="" class="btn btn-gray" ng-if="vm.room.user.rights"\n                           ng-click="poll.edit = true">Новое голосование</a>\n                    </div>\n                </div>\n            </div>\n        </gg-popup>\n\n        <gg-popup id="users-list" class="popup-block scrollable users-count show" gg-scrollable\n                  ng-if="vm.view.usersList">\n            <div ng-controller="ggChatUsersList as list">\n                <div class="fixed-block">\n                    <div class="title-block">\n                        <div class="title">\n                            {{ list.users.length || vm.room.usersCnt | decl: [\'зритель\', \'зрителя\',\'зрителей\'] }} в чате\n                        </div>\n                    </div>\n                    <div class="search-block">\n                        <input type="text" ng-model="list.userSearch" placeholder="Поиск зрителей в чате"\n                               gg-catch-focus>\n                    </div>\n                    <div class="control-block">\n                        <a href="" ng-click="closePopup($event)" class="icon icon-close2"></a>\n                    </div>\n                </div>\n                <div class="user-list-block">\n                    <div class="list-block" ng-if="list.streamers.length">\n                        <div class="title">Стример</div>\n                        <ul class="user-list">\n                            <li ng-repeat="user in list.streamers track by user.id">\n                                <chat-user user-obj="::user"></chat-user>
28\n                                <span ng-if="user.cup">({{::user.cup.contact}})</span>\n                            </li>\n                        </ul>\n                    </div>\n                    <div class="list-block" ng-if="list.moders.length">\n                        <div class="title">Модераторы</div>\n                        <ul class="user-list">\n                            <li ng-repeat="user in list.moders track by user.id">\n                                <chat-user user-obj="::user"></chat-user>\n                                <span ng-if="::user.hidden"> (скрытый)</span>\n                                <span ng-if="user.cup">({{::user.cup.contact}})</span>\n                            </li>\n                        </ul>\n                    </div>\n                    <div class="list-block" ng-if="list.judges.length">\n                        <div class="title">Судьи</div>\n                        <ul class="user-list">\n                            <li ng-repeat="user in list.judges track by user.id">\n                                <chat-user user-obj="::user"></chat-user>\n                            </li>\n                        </ul>\n                    </div>\n                    <div class="list-block" ng-if="list.helpers.length">\n                        <div class="title">Помощники стримера</div>\n                        <ul class="user-list">\n                            <li ng-repeat="user in list.helpers track by user.id">\n                                <chat-user user-obj="::user"></chat-user>\n                                <span ng-if="user.cup">({{::user.cup.contact}})</span>\n                            </li>\n                        </ul>\n                    </div>\n\n                    <div class="list-block" ng-if="list.customs.size">\n                        <div ng-repeat="key in list.customKeys" class="custom-role__wrapper">\n                            <div class="title">{{ key }}</div>\n                            <ul class="user-list">\n                                <li ng-repeat="user in list.customs.get(key) track by user.id">\n                                    <chat-user user-obj="::user"></chat-user>\n                                    <span ng-if="user.cup">({{::user.cup.contact}})</span>\n                                </li>\n                            </ul>\n                        </div>\n                    </div>\n\n                    <div class="list-block" ng-if="list.others.length">\n                        <div class="title">Зрители</div>\n                        <ul class="user-list">\n                            <li ng-repeat="user in list.others | limitTo: list.othersLimit track by user.id">\n                                <chat-user user-obj="::user"></chat-user>\n                                <span ng-if="user.cup">({{::user.cup.contact}})</span>\n                            </li>\n                            <li class="show-more" ng-if="list.others.length > list.othersLimit"\n                                ng-click="list.othersLimit=list.othersLimit+100">\n                                <a href="">Показать еще...</a>\n                            </li>\n                        </ul>\n                    </div>\n                    <div class="list-block" ng-if="list.banned.length">\n                        <div class="title">Забаненные</div>\n                        <ul class="user-list">\n                            <li ng-repeat="user in list.banned track by user.id">\n                                <chat-user user-obj="::user"></chat-user>\n                                <span ng-if="user.cup">({{::user.cup.contact}})</span>\n                            </li>\n                        </ul>\n                    </div>\n                </div>\n            </div>\n        </gg-popup>\n\n        <gg-popup id="ban-user" class="popup-block user-ban-block scrollable" gg-scrollable\n                  ng-class="{\'mod\': vm.room.user.rights > 20}"\n                  ng-if="vm.view.banUser && vm.room.user.rights">\n            <div ng-controller="ggChatBan as ban">\n                <div ng-if="vm.room.user.rights <= 20">\n                    <div class="title-block">\n                        <div class="title">\n                            Забанить {{ user.nickname }}\n                        </div>\n                        <div class="control-block">\n                            <a href="" class="icon icon-close2" ng-click="vm.view.banUser=false"></a>\n                        </div>\n                    </div>\n                    <div class="radio-list">\n                        <div class="radio">\n                            <input id="radio-ban1" type="radio" ng-model="ban.duration2" value="20min">\n                            <label for="radio-ban1">На 20 минут</label>\n                        </div>\n                        <div class="radio">\n                            <input id="radio-ban2" type="radio" ng-model="ban.duration2" value="stream">\n                            <label for="radio-ban2">До конца стрима</label>\n                        </div>\n                        <div class="radio">\n                            <input id="radio-ban3" type="radio" ng-model="ban.duration2" value="month">\n                            <label for="radio-ban3">На месяц</label>\n                        </div>\n                        <div class="radio">\n                            <input id="radio-ban4" type="radio" ng-model="ban.duration2" value="unlim">\n                            <label for="radio-ban4">
28Бессрочно</label>\n                        </div>\n                    </div>\n                    <div class="checkbox-list">\n                        <div class="checkbox">\n                            <input id="checkbox_delete_message" type="checkbox" ng-model="ban.deleteMessage">\n                            <label for="checkbox_delete_message">Удалить сообщение</label>\n                        </div>\n                    </div>\n                    <div class="btn-block">\n                        <a href="" ng-click="makeBan()" class="btn btn-red">Забанить</a>\n                    </div>\n                </div>\n                <div ng-if="vm.room.user.rights > 20">\n                    <div class="title-block">\n                        <div class="title">\n                            Забанить {{ user.nickname }}\n                        </div>\n                        <div class="control-block">\n                            <a href="" class="icon icon-close2" ng-click="vm.view.banUser=false"></a>\n                        </div>\n                    </div>\n                    <div class="radio-list">\n                        <div class="radio">\n                            <input id="radio-mod1" type="radio" ng-model="ban.reason" value="1">\n                            <label for="radio-mod1">Смайлабуз, флуд</label>\n                        </div>\n                        <div class="radio">\n                            <input id="radio-mod2" type="radio" ng-model="ban.reason" value="2">\n                            <label for="radio-mod2">Провоцирование</label>\n                        </div>\n                        <div class="radio">\n                            <input id="radio-mod3" type="radio" ng-model="ban.reason" value="3">\n                            <label for="radio-mod3">Маты, оскорбления</label>\n                        </div>\n                        <div class="radio">\n                            <input id="radio-mod4" type="radio" ng-model="ban.reason" value="4">\n                            <label for="radio-mod4">Другая причина</label>\n                        </div>\n                        <div class="input-block">\n                            <input type="text" placeholder="Введите причину" ng-model="ban.comment">\n                        </div>\n                    </div>\n\n                    <div class="scroll-block" ng-if="vm.view.banUserTillStreamEnd">\n                        <div class="title"><strong>Бан до конца стрима</strong></div>\n                    </div>\n\n                    <div class="scroll-block" ng-if="!vm.view.banUserTillStreamEnd">\n                        <div class="title">Бан на {{ ban.textValue }}</div>\n                        <div class="clickable">\n                            <slider\n                                    min="ban.reasons[ban.reason].min"\n                                    max="ban.reasons[ban.reason].max"\n                                    value="ban.customValue"\n                                    text-value="ban.textValue">\n                            </slider>\n                        </div>\n                    </div>\n                    <div class="checkbox-list">\n                        <div class="checkbox">\n                            <input id="checkbox-mod1" type="checkbox" ng-model="ban.deleteMessage">\n                            <label for="checkbox-mod1">Удалить сообщение</label>\n                        </div>\n                        <div class="checkbox">\n                            <input id="checkbox-mod2" type="checkbox" ng-model="ban.showBan">\n                            <label for="checkbox-mod2">Не показывать бан</label>\n                        </div>\n                        <div class="checkbox" ng-if="!vm.view.banUserTillStreamEnd">\n                            <input id="checkbox-mod3" type="checkbox" ng-model="ban.allChats">\n                            <label for="checkbox-mod3">На все чаты</label>\n                        </div>\n                    </div>\n                    <div class="btn-block">\n                        <a href="" ng-click="makeBan()" class="btn btn-red">Забанить</a>\n                    </div>\n                </div>\n            </div>\n        </gg-popup>\n\n        <gg-popup id="ignore-list" class="popup-block scrollable ignore-list-block show" ng-if="vm.view.igroneList"\n                  gg-scrollable>\n            <div ng-controller="ggChatIgnoreList as list">\n                <div class="fixed-block">\n                    <div class="title-block">\n                        <div class="title">Игнор-лист</div>\n                    </div>\n                    <div class="search-block"><input type="text" ng-model="list.search" placeholder="Поиск"></div>\n                    <div class="control-block">\n                        <a href="" ng-click="closePopup($event)" class="icon icon-close2"></a>\n                    </div>\n                </div>\n                <ul class="ignore-list">\n                    <li ng-repeat="user in list.users">\n                        <chat-user user-obj="user"></chat-user>\n                        <a href="" ng-click="list.delete(user)" class="icon icon-trashcan"></a>\n                    </li>\n                </ul>\n            </div>\n        </gg-popup>\n\n        <gg-popup id="banned-list" class="popup-block scrollable banned-list-block" ng-if="vm.view.bannedList"\n                  gg-scrollable>\n            <div ng-controller="ggChatBannedList as list">\n                <div class="fixed-block">\n                    <div class="title-block">\n                        <div class="title">Забанены</div>\n                    </div>\n                    <div class="search-block"><input type="text" ng-model="list.search" placeholder="Поиск"></div>\n                    <div class="control-block">\n                        <a href="" ng-click="closePopup($event)" class="icon icon-close2"></a>\n                    </div>\n                </div>\n                <div class="banned-list">\n                    <ul>\n                        <li ng-repeat="user in list.banned">\n                            <chat-user user-obj="user"></chat-user>
28\n                            <span ng-if="user.baninfo.type == 0">- до {{(user.baninfo.till*1000)|ggDate:\'dd.MM.yy HH:mm\'}}</span>\n                            <span ng-if="user.baninfo.type == 1">- до конца стрима</span>\n                            <span ng-if="user.baninfo.type == 2">- бессрочно</span>\n                            <a href="" ng-click="list.unban(user)" class="icon icon-trashcan"></a>\n                        </li>\n                    </ul>\n                </div>\n            </div>\n        </gg-popup>\n\n        <gg-popup id="helpers-list" class="popup-block scrollable ignore-list-block show"\n                  ng-if="vm.view.helpersList" gg-scrollable>\n            <div ng-controller="ggChatHelpersList as list">\n                <div class="fixed-block">\n                    <div class="title-block">\n                        <div class="title">Помощники стримера</div>\n                    </div>\n                    <div class="search-block">\n                        <input type="text" ng-model="list.search" placeholder="Поиск">\n                    </div>\n                    <div class="control-block">\n                        <a href="" ng-click="closePopup($event)" class="icon icon-close2"></a>\n                    </div>\n                </div>\n                <ul class="ignore-list">\n                    <li ng-repeat="user in list.users | filter:list.search">\n                        <chat-user user-obj="user"></chat-user>\n                        <a href="" ng-click="list.delete(user)" class="icon icon-trashcan"></a>\n                    </li>\n                </ul>\n            </div>\n        </gg-popup>\n\n        <gg-popup id="randomizer" class="popup-block scrollable randomize-block" ng-if="vm.view.randomizer"\n                  gg-scrollable>\n            <div ng-controller="ggRandomizer as randomizer">\n                <div class="title-block">\n                    <div class="title">Рандомайзер</div>\n                    <div class="control-block">\n                        <a href="" class="icon icon-close2" ng-click="closePopup($event)"></a>\n                    </div>\n                </div>\n                <div class="checkbox-list">\n                    <div class="checkbox">\n                        <input id="premiums" name="premiums" type="checkbox" ng-model="randomizer.params.premiums">\n                        <label for="premiums">Премиум-зрители</label>\n                    </div>\n                    <div class="checkbox">\n                        <input id="donaters" name="donaters" type="checkbox" ng-model="randomizer.params.donaters">\n                        <label for="donaters">Поддержавшие</label>\n                    </div>\n                    <div class="checkbox">\n                        <input id="others" name="others" type="checkbox" ng-model="randomizer.params.others">\n                        <label for="others">Простые зрители</label>\n                    </div>\n                    <div class="checkbox">\n                        <input id="noModers" name="noModers" type="checkbox" ng-model="randomizer.params.noModers">\n                        <label for="noModers">Не выбирать модераторов</label>\n                    </div>\n                </div>\n                <div class="randomize-block" gg-scrollable>\n                    <chat-user class="randomize-user user" ng-repeat="(key, user) in randomizer.users"\n                               user-obj="user"></chat-user>\n                </div>\n                <div class="btn-block">\n                    <a href="" ng-click="randomizer.choose()" class="btn btn-blue">Выбрать</a>\n                    <a href="" ng-click="randomizer.clean()" class="btn btn-red">Очистить</a>\n                </div>\n            </div>\n        </gg-popup>\n\n        <gg-popup id="chat-settings" class="chat-settings" ng-if="vm.room.user" style="">\n            <gg4-chat-settings ng-if="vm.view.settings" [room]="vm.room" [user]="user"\n                               (close)="vm.openSettings()"></gg4-chat-settings>\n        </gg-popup>\n\n        <gg-popup id="task-list" ng-if="vm.view.taskList">\n            <gg-quest-log [user]="vm.room.streamer.id"\n                          [quest-id]="vm.questId"\n                          (close)="vm.toggleTaskList()"\n                          (paste-nick)="vm.pasteNick($event)"></gg-quest-log>\n        </gg-popup>\n\n        <gg-popup id="friend-invite" ng-if="vm.view.friendInvite">\n            <gg4-friend-invite-popup\n                (close)="vm.toggleFriendInvite()"\n                [streamer]="vm.room.streamer"\n                [key]="vm.room.streamer.username"\n                [user]="vm.room.user"\n            ></gg4-friend-invite-popup>\n        </gg-popup>\n\n        <gg-popup id="free-premium" ng-if="vm.room.freeprem">\n            <gg-free-premium-activation [room]="vm.room"></gg-free-premium-activation>\n        </gg-popup>\n\n        <gg-popup id="donat">\n            <div ng-if="vm.view.donat">\n                <gg-donate-chat-window\n                    [opened-from-chat]="true"\n                    [streamer]="vm.room.streamer.id"\n                    [key]="vm.room.streamer.name"\n                    [logged]="vm.room.user.id"\n                    (close)="vm.toggleDonat()"\n                ></gg-donate-chat-window>\n            </div>\n        </gg-popup>\n\n        <div ng-if="vm.showCustomDonate">\n            <gg-chat-custom-donate show-donate="vm.showCustomDonate" channel-id="vm.room.id"\n                                   buttons="vm.room.donateButtons"></gg-chat-custom-donate>\n        </div>\n    </div>\n\n    <div ng-if="vm.newUserPopup === 1">\n        <gg-newbie-greeting [streamer]="vm.room.streamer.name" (done)="vm.greetingDone($event)"\n                            (close)="vm.closeGreeting()">
28</gg-newbie-greeting>\n    </div>\n\n    <gg4-invited-auth-flow\n        [streamer]="vm.room.streamer.name"\n        (done)="vm.inviteAuthDone($event)"\n        (off-greeting)="vm.newUserPopup = null"\n    ></gg4-invited-auth-flow>\n\n</div>\n\n\n'),
29$templateCache.put("/html/channels/featured-streams.html",'<div class="featured-streams-wrap" ng-if="$ctrl.streams.length">\n    <div class="title">В центре внимания</div>\n    <div class="featured-streams-list" ng-if="$ctrl.streams.length == 3">\n        <div class="stream-block" ng-class="{\'orange warrior\': $index == 0, \'green thief\': $index == 1, \'purple mage\': $index == 2}" ng-repeat="stream in $ctrl.streams">\n            <div class="title">{{ stream.title }}</div>\n            <div class="flex-block">\n                <a class="stream-inner" href="{{ stream.channelObj.link }}#autoplay">\n                    <span class="inner-wrap">\n                        <span class="viewers-shade"></span>\n                        <img src="" alt="" ng-src="{{ stream.channelObj.preview.replace(\'http://\', \'//\') }}" gg-no-preview="{{ stream.channelObj.poster }}" class="feature-preview__img">\n                        <video src="https://hls.goodgame.ru/videopreviews/{{stream.channelObj.streamkey}}
29.mp4" nocontrols preload="auto" loop playsinline autoplay muted class="stream-preview feature-preview"></video>\n                        \x3c!--<span class="viewers"><span class="icon icon-users2"></span> {{ stream.channelObj.viewers }}</span>--\x3e\n                        <span class="stream-info">\n                            <span class="streamer-block">\n                                <span class="avatar">\n                                    <img src="" ng-src="{{ stream.channelObj.avatar }}" alt="">\n                                </span>\n                                <span class="name">{{ stream.channelObj.streamer }}</span>\n                            </span>\n                        </span>\n                    </span>\n                </a>\n                <div class="description-block" ng-bind-html="stream.description | nl2br"></div>\n            </div>\n        </div>\n    </div>\n    <div class="featured-streams-list" ng-if="$ctrl.streams.length == 1">\n        <div class="stream-block single orange warrior" ng-repeat="stream in $ctrl.streams">\n            <div class="title">{{ stream.title }}</div>\n            <div class="flex-block">\n                <a class="stream-inner" href="{{ stream.channelObj.link }}#autoplay">\n                    <span class="inner-wrap">\n                        <span class="viewers-shade"></span>\n                        <img src="" alt="" ng-src="{{ stream.channelObj.preview.replace(\'http://\', \'//\') }}" gg-no-preview="{{ stream.channelObj.poster }}" class="feature-preview__img">\n                        <video src="https://hls.goodgame.ru/videopreviews/{{stream.channelObj.streamkey}}
29.mp4" nocontrols preload="auto" loop playsinline autoplay muted class="stream-preview feature-preview"></video>\n                        \x3c!--<span class="viewers"><span class="icon icon-users2"></span> {{ stream.channelObj.viewers }}</span>--\x3e\n                        <span class="stream-info">\n                            <span class="streamer-block">\n                                <span class="avatar">\n                                    <img src="" ng-src="{{ stream.channelObj.avatar }}" alt="">\n                                </span>\n                                <span class="name">{{ stream.channelObj.streamer }}</span>\n                            </span>\n                        </span>\n                    </span>\n                </a>\n                <div class="description-block" ng-bind-html="stream.description | nl2br"></div>\n            </div>\n        </div>\n    </div>\n    <div class="featured-streams-list" ng-if="$ctrl.streams.length == 2">\n        <div class="stream-block double" ng-class="{\'green thief\': $index == 0, \'purple mage\': $index == 1}" ng-repeat="stream in $ctrl.streams">\n            <div class="title">{{ stream.title }}</div>\n            <div class="flex-block">\n                <a class="stream-inner" href="{{ stream.channelObj.link }}#autoplay">\n                    <span class="inner-wrap">\n                        <span class="viewers-shade"></span>\n                        <img src="" alt="" ng-src="{{ stream.channelObj.preview.replace(\'http://\', \'//\') }}" gg-no-preview="{{ stream.channelObj.poster }}" class="feature-preview__img">\n                        <video src="https://hls.goodgame.ru/videopreviews/{{stream.channelObj.streamkey}}
29.mp4" nocontrols preload="auto" loop playsinline autoplay muted class="stream-preview feature-preview"></video>\n                        \x3c!--<span class="viewers"><span class="icon icon-users2"></span> {{ stream.channelObj.viewers }}</span>--\x3e\n                        <span class="stream-info">\n                            <span class="streamer-block">\n                                <span class="avatar">\n                                    <img src="" ng-src="{{ stream.channelObj.avatar }}" alt="">\n                                </span>\n                                <span class="name">{{ stream.channelObj.streamer }}</span>\n                            </span>\n                        </span>\n                    </span>\n                </a>\n                <div class="description-block" ng-bind-html="stream.description | nl2br"></div>\n            </div>\n        </div>\n    </div>\n</div>')}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.